LLVM  5.0.0
SanitizerCoverage.cpp
Go to the documentation of this file.
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/CallSite.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/MDBuilder.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
34 #include "llvm/Transforms/Scalar.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "sancov"
41 
42 static const char *const SanCovTracePCIndirName =
43  "__sanitizer_cov_trace_pc_indir";
44 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
45 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
46 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
47 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
48 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
49 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
50 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
51 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
52 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
53 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
54 static const uint64_t SanCtorAndDtorPriority = 2;
55 
56 static const char *const SanCovTracePCGuardName =
57  "__sanitizer_cov_trace_pc_guard";
58 static const char *const SanCovTracePCGuardInitName =
59  "__sanitizer_cov_trace_pc_guard_init";
60 static const char *const SanCov8bitCountersInitName =
61  "__sanitizer_cov_8bit_counters_init";
62 
63 static const char *const SanCovGuardsSectionName = "sancov_guards";
64 static const char *const SanCovCountersSectionName = "sancov_cntrs";
65 
67  "sanitizer-coverage-level",
68  cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
69  "3: all blocks and critical edges"),
70  cl::Hidden, cl::init(0));
71 
72 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
73  cl::desc("Experimental pc tracing"), cl::Hidden,
74  cl::init(false));
75 
76 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
77  cl::desc("pc tracing with a guard"),
78  cl::Hidden, cl::init(false));
79 
80 static cl::opt<bool> ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
81  cl::desc("increments 8-bit counter for every edge"),
82  cl::Hidden, cl::init(false));
83 
84 static cl::opt<bool>
85  ClCMPTracing("sanitizer-coverage-trace-compares",
86  cl::desc("Tracing of CMP and similar instructions"),
87  cl::Hidden, cl::init(false));
88 
89 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
90  cl::desc("Tracing of DIV instructions"),
91  cl::Hidden, cl::init(false));
92 
93 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
94  cl::desc("Tracing of GEP instructions"),
95  cl::Hidden, cl::init(false));
96 
97 static cl::opt<bool>
98  ClPruneBlocks("sanitizer-coverage-prune-blocks",
99  cl::desc("Reduce the number of instrumented blocks"),
100  cl::Hidden, cl::init(true));
101 
102 namespace {
103 
104 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
106  switch (LegacyCoverageLevel) {
107  case 0:
109  break;
110  case 1:
112  break;
113  case 2:
115  break;
116  case 3:
118  break;
119  case 4:
121  Res.IndirectCalls = true;
122  break;
123  }
124  return Res;
125 }
126 
127 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
128  // Sets CoverageType and IndirectCalls.
129  SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
130  Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
131  Options.IndirectCalls |= CLOpts.IndirectCalls;
132  Options.TraceCmp |= ClCMPTracing;
133  Options.TraceDiv |= ClDIVTracing;
134  Options.TraceGep |= ClGEPTracing;
135  Options.TracePC |= ClTracePC;
136  Options.TracePCGuard |= ClTracePCGuard;
138  if (!Options.TracePCGuard && !Options.TracePC && !Options.Inline8bitCounters)
139  Options.TracePCGuard = true; // TracePCGuard is default.
140  Options.NoPrune |= !ClPruneBlocks;
141  return Options;
142 }
143 
144 class SanitizerCoverageModule : public ModulePass {
145 public:
146  SanitizerCoverageModule(
148  : ModulePass(ID), Options(OverrideFromCL(Options)) {
150  }
151  bool runOnModule(Module &M) override;
152  bool runOnFunction(Function &F);
153  static char ID; // Pass identification, replacement for typeid
154  StringRef getPassName() const override { return "SanitizerCoverageModule"; }
155 
156  void getAnalysisUsage(AnalysisUsage &AU) const override {
159  }
160 
161 private:
162  void InjectCoverageForIndirectCalls(Function &F,
163  ArrayRef<Instruction *> IndirCalls);
164  void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
165  void InjectTraceForDiv(Function &F,
166  ArrayRef<BinaryOperator *> DivTraceTargets);
167  void InjectTraceForGep(Function &F,
168  ArrayRef<GetElementPtrInst *> GepTraceTargets);
169  void InjectTraceForSwitch(Function &F,
170  ArrayRef<Instruction *> SwitchTraceTargets);
171  bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
172  GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
173  Function &F, Type *Ty,
174  const char *Section);
175  void CreateFunctionLocalArrays(size_t NumGuards, Function &F);
176  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
177  void CreateInitCallForSection(Module &M, const char *InitFunctionName,
178  Type *Ty, const std::string &Section);
179 
180  void SetNoSanitizeMetadata(Instruction *I) {
181  I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
182  MDNode::get(*C, None));
183  }
184 
185  std::string getSectionName(const std::string &Section) const;
186  std::string getSectionStart(const std::string &Section) const;
187  std::string getSectionEnd(const std::string &Section) const;
188  Function *SanCovTracePCIndir;
189  Function *SanCovTracePC, *SanCovTracePCGuard;
190  Function *SanCovTraceCmpFunction[4];
191  Function *SanCovTraceDivFunction[2];
192  Function *SanCovTraceGepFunction;
193  Function *SanCovTraceSwitchFunction;
194  InlineAsm *EmptyAsm;
195  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
196  *Int8Ty, *Int8PtrTy;
197  Module *CurModule;
198  Triple TargetTriple;
199  LLVMContext *C;
200  const DataLayout *DL;
201 
202  GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
203  GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
204 
205  SanitizerCoverageOptions Options;
206 };
207 
208 } // namespace
209 
210 void SanitizerCoverageModule::CreateInitCallForSection(
211  Module &M, const char *InitFunctionName, Type *Ty,
212  const std::string &Section) {
213  IRBuilder<> IRB(M.getContext());
214  Function *CtorFunc;
215  GlobalVariable *SecStart =
216  new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
217  getSectionStart(Section));
219  GlobalVariable *SecEnd =
221  nullptr, getSectionEnd(Section));
223 
224  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
225  M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
226  {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
227 
228  if (TargetTriple.supportsCOMDAT()) {
229  // Use comdat to dedup CtorFunc.
230  CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
231  appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
232  } else {
234  }
235 }
236 
237 bool SanitizerCoverageModule::runOnModule(Module &M) {
239  return false;
240  C = &(M.getContext());
241  DL = &M.getDataLayout();
242  CurModule = &M;
243  TargetTriple = Triple(M.getTargetTriple());
244  FunctionGuardArray = nullptr;
245  Function8bitCounterArray = nullptr;
246  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
247  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
248  Type *VoidTy = Type::getVoidTy(*C);
249  IRBuilder<> IRB(*C);
250  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
251  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
252  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
253  Int64Ty = IRB.getInt64Ty();
254  Int32Ty = IRB.getInt32Ty();
255  Int8Ty = IRB.getInt8Ty();
256 
257  SanCovTracePCIndir = checkSanitizerInterfaceFunction(
258  M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
259  SanCovTraceCmpFunction[0] =
261  SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
262  SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
264  IRB.getInt16Ty()));
265  SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
267  IRB.getInt32Ty()));
268  SanCovTraceCmpFunction[3] =
270  SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
271 
272  SanCovTraceDivFunction[0] =
274  SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
275  SanCovTraceDivFunction[1] =
277  SanCovTraceDiv8, VoidTy, Int64Ty));
278  SanCovTraceGepFunction =
280  SanCovTraceGep, VoidTy, IntptrTy));
281  SanCovTraceSwitchFunction =
283  SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
284  // Make sure smaller parameters are zero-extended to i64 as required by the
285  // x86_64 ABI.
286  if (TargetTriple.getArch() == Triple::x86_64) {
287  for (int i = 0; i < 3; i++) {
288  SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
289  SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
290  }
291  SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
292  }
293 
294 
295  // We insert an empty inline asm after cov callbacks to avoid callback merge.
296  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
297  StringRef(""), StringRef(""),
298  /*hasSideEffects=*/true);
299 
300  SanCovTracePC = checkSanitizerInterfaceFunction(
303  SanCovTracePCGuardName, VoidTy, Int32PtrTy));
304 
305  for (auto &F : M)
306  runOnFunction(F);
307 
308  if (FunctionGuardArray)
309  CreateInitCallForSection(M, SanCovTracePCGuardInitName, Int32PtrTy,
311  if (Function8bitCounterArray)
312  CreateInitCallForSection(M, SanCov8bitCountersInitName, Int8PtrTy,
314 
315  return true;
316 }
317 
318 // True if block has successors and it dominates all of them.
319 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
320  if (succ_begin(BB) == succ_end(BB))
321  return false;
322 
323  for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
324  if (!DT->dominates(BB, SUCC))
325  return false;
326  }
327 
328  return true;
329 }
330 
331 // True if block has predecessors and it postdominates all of them.
332 static bool isFullPostDominator(const BasicBlock *BB,
333  const PostDominatorTree *PDT) {
334  if (pred_begin(BB) == pred_end(BB))
335  return false;
336 
337  for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
338  if (!PDT->dominates(BB, PRED))
339  return false;
340  }
341 
342  return true;
343 }
344 
345 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
346  const DominatorTree *DT,
347  const PostDominatorTree *PDT,
348  const SanitizerCoverageOptions &Options) {
349  // Don't insert coverage for unreachable blocks: we will never call
350  // __sanitizer_cov() for them, so counting them in
351  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
352  // percentage. Also, unreachable instructions frequently have no debug
353  // locations.
354  if (isa<UnreachableInst>(BB->getTerminator()))
355  return false;
356 
357  // Don't insert coverage into blocks without a valid insertion point
358  // (catchswitch blocks).
359  if (BB->getFirstInsertionPt() == BB->end())
360  return false;
361 
362  if (Options.NoPrune || &F.getEntryBlock() == BB)
363  return true;
364 
365  // Do not instrument full dominators, or full post-dominators with multiple
366  // predecessors.
367  return !isFullDominator(BB, DT)
368  && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
369 }
370 
371 bool SanitizerCoverageModule::runOnFunction(Function &F) {
372  if (F.empty())
373  return false;
374  if (F.getName().find(".module_ctor") != std::string::npos)
375  return false; // Should not instrument sanitizer init functions.
376  if (F.getName().startswith("__sanitizer_"))
377  return false; // Don't instrument __sanitizer_* callbacks.
378  // Don't instrument MSVC CRT configuration helpers. They may run before normal
379  // initialization.
380  if (F.getName() == "__local_stdio_printf_options" ||
381  F.getName() == "__local_stdio_scanf_options")
382  return false;
383  // Don't instrument functions using SEH for now. Splitting basic blocks like
384  // we do for coverage breaks WinEHPrepare.
385  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
386  if (F.hasPersonalityFn() &&
388  return false;
392  SmallVector<BasicBlock *, 16> BlocksToInstrument;
393  SmallVector<Instruction *, 8> CmpTraceTargets;
394  SmallVector<Instruction *, 8> SwitchTraceTargets;
395  SmallVector<BinaryOperator *, 8> DivTraceTargets;
396  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
397 
398  const DominatorTree *DT =
399  &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
400  const PostDominatorTree *PDT =
401  &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
402 
403  for (auto &BB : F) {
404  if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
405  BlocksToInstrument.push_back(&BB);
406  for (auto &Inst : BB) {
407  if (Options.IndirectCalls) {
408  CallSite CS(&Inst);
409  if (CS && !CS.getCalledFunction())
410  IndirCalls.push_back(&Inst);
411  }
412  if (Options.TraceCmp) {
413  if (isa<ICmpInst>(&Inst))
414  CmpTraceTargets.push_back(&Inst);
415  if (isa<SwitchInst>(&Inst))
416  SwitchTraceTargets.push_back(&Inst);
417  }
418  if (Options.TraceDiv)
419  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
420  if (BO->getOpcode() == Instruction::SDiv ||
421  BO->getOpcode() == Instruction::UDiv)
422  DivTraceTargets.push_back(BO);
423  if (Options.TraceGep)
424  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
425  GepTraceTargets.push_back(GEP);
426  }
427  }
428 
429  InjectCoverage(F, BlocksToInstrument);
430  InjectCoverageForIndirectCalls(F, IndirCalls);
431  InjectTraceForCmp(F, CmpTraceTargets);
432  InjectTraceForSwitch(F, SwitchTraceTargets);
433  InjectTraceForDiv(F, DivTraceTargets);
434  InjectTraceForGep(F, GepTraceTargets);
435  return true;
436 }
437 
438 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
439  size_t NumElements, Function &F, Type *Ty, const char *Section) {
440  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
441  auto Array = new GlobalVariable(
442  *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
443  Constant::getNullValue(ArrayTy), "__sancov_gen_");
444  if (auto Comdat = F.getComdat())
445  Array->setComdat(Comdat);
446  Array->setSection(getSectionName(Section));
447  return Array;
448 }
449 void SanitizerCoverageModule::CreateFunctionLocalArrays(size_t NumGuards,
450  Function &F) {
451  if (Options.TracePCGuard)
452  FunctionGuardArray = CreateFunctionLocalArrayInSection(
453  NumGuards, F, Int32Ty, SanCovGuardsSectionName);
454  if (Options.Inline8bitCounters)
455  Function8bitCounterArray = CreateFunctionLocalArrayInSection(
456  NumGuards, F, Int8Ty, SanCovCountersSectionName);
457 }
458 
459 bool SanitizerCoverageModule::InjectCoverage(Function &F,
460  ArrayRef<BasicBlock *> AllBlocks) {
461  if (AllBlocks.empty()) return false;
462  switch (Options.CoverageType) {
464  return false;
466  CreateFunctionLocalArrays(1, F);
467  InjectCoverageAtBlock(F, F.getEntryBlock(), 0);
468  return true;
469  default: {
470  CreateFunctionLocalArrays(AllBlocks.size(), F);
471  for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
472  InjectCoverageAtBlock(F, *AllBlocks[i], i);
473  return true;
474  }
475  }
476 }
477 
478 // On every indirect call we call a run-time function
479 // __sanitizer_cov_indir_call* with two parameters:
480 // - callee address,
481 // - global cache array that contains CacheSize pointers (zero-initialized).
482 // The cache is used to speed up recording the caller-callee pairs.
483 // The address of the caller is passed implicitly via caller PC.
484 // CacheSize is encoded in the name of the run-time function.
485 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
486  Function &F, ArrayRef<Instruction *> IndirCalls) {
487  if (IndirCalls.empty())
488  return;
489  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
490  for (auto I : IndirCalls) {
491  IRBuilder<> IRB(I);
492  CallSite CS(I);
493  Value *Callee = CS.getCalledValue();
494  if (isa<InlineAsm>(Callee))
495  continue;
496  IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
497  }
498 }
499 
500 // For every switch statement we insert a call:
501 // __sanitizer_cov_trace_switch(CondValue,
502 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
503 
504 void SanitizerCoverageModule::InjectTraceForSwitch(
505  Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
506  for (auto I : SwitchTraceTargets) {
507  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
508  IRBuilder<> IRB(I);
509  SmallVector<Constant *, 16> Initializers;
510  Value *Cond = SI->getCondition();
511  if (Cond->getType()->getScalarSizeInBits() >
512  Int64Ty->getScalarSizeInBits())
513  continue;
514  Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
515  Initializers.push_back(
516  ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
517  if (Cond->getType()->getScalarSizeInBits() <
518  Int64Ty->getScalarSizeInBits())
519  Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
520  for (auto It : SI->cases()) {
521  Constant *C = It.getCaseValue();
522  if (C->getType()->getScalarSizeInBits() <
523  Int64Ty->getScalarSizeInBits())
524  C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
525  Initializers.push_back(C);
526  }
527  std::sort(Initializers.begin() + 2, Initializers.end(),
528  [](const Constant *A, const Constant *B) {
529  return cast<ConstantInt>(A)->getLimitedValue() <
530  cast<ConstantInt>(B)->getLimitedValue();
531  });
532  ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
533  GlobalVariable *GV = new GlobalVariable(
534  *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
535  ConstantArray::get(ArrayOfInt64Ty, Initializers),
536  "__sancov_gen_cov_switch_values");
537  IRB.CreateCall(SanCovTraceSwitchFunction,
538  {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
539  }
540  }
541 }
542 
543 void SanitizerCoverageModule::InjectTraceForDiv(
544  Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
545  for (auto BO : DivTraceTargets) {
546  IRBuilder<> IRB(BO);
547  Value *A1 = BO->getOperand(1);
548  if (isa<ConstantInt>(A1)) continue;
549  if (!A1->getType()->isIntegerTy())
550  continue;
551  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
552  int CallbackIdx = TypeSize == 32 ? 0 :
553  TypeSize == 64 ? 1 : -1;
554  if (CallbackIdx < 0) continue;
555  auto Ty = Type::getIntNTy(*C, TypeSize);
556  IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
557  {IRB.CreateIntCast(A1, Ty, true)});
558  }
559 }
560 
561 void SanitizerCoverageModule::InjectTraceForGep(
562  Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
563  for (auto GEP : GepTraceTargets) {
564  IRBuilder<> IRB(GEP);
565  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
566  if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
567  IRB.CreateCall(SanCovTraceGepFunction,
568  {IRB.CreateIntCast(*I, IntptrTy, true)});
569  }
570 }
571 
572 void SanitizerCoverageModule::InjectTraceForCmp(
573  Function &, ArrayRef<Instruction *> CmpTraceTargets) {
574  for (auto I : CmpTraceTargets) {
575  if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
576  IRBuilder<> IRB(ICMP);
577  Value *A0 = ICMP->getOperand(0);
578  Value *A1 = ICMP->getOperand(1);
579  if (!A0->getType()->isIntegerTy())
580  continue;
581  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
582  int CallbackIdx = TypeSize == 8 ? 0 :
583  TypeSize == 16 ? 1 :
584  TypeSize == 32 ? 2 :
585  TypeSize == 64 ? 3 : -1;
586  if (CallbackIdx < 0) continue;
587  // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
588  auto Ty = Type::getIntNTy(*C, TypeSize);
589  IRB.CreateCall(
590  SanCovTraceCmpFunction[CallbackIdx],
591  {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
592  }
593  }
594 }
595 
596 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
597  size_t Idx) {
599  bool IsEntryBB = &BB == &F.getEntryBlock();
600  DebugLoc EntryLoc;
601  if (IsEntryBB) {
602  if (auto SP = F.getSubprogram())
603  EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
604  // Keep static allocas and llvm.localescape calls in the entry block. Even
605  // if we aren't splitting the block, it's nice for allocas to be before
606  // calls.
607  IP = PrepareToSplitEntryBlock(BB, IP);
608  } else {
609  EntryLoc = IP->getDebugLoc();
610  }
611 
612  IRBuilder<> IRB(&*IP);
613  IRB.SetCurrentDebugLocation(EntryLoc);
614  if (Options.TracePC) {
615  IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
616  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
617  }
618  if (Options.TracePCGuard) {
619  auto GuardPtr = IRB.CreateIntToPtr(
620  IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
621  ConstantInt::get(IntptrTy, Idx * 4)),
622  Int32PtrTy);
623  IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
624  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
625  }
626  if (Options.Inline8bitCounters) {
627  auto CounterPtr = IRB.CreateGEP(
628  Function8bitCounterArray,
629  {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
630  auto Load = IRB.CreateLoad(CounterPtr);
631  auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
632  auto Store = IRB.CreateStore(Inc, CounterPtr);
633  SetNoSanitizeMetadata(Load);
634  SetNoSanitizeMetadata(Store);
635  }
636 }
637 
638 std::string
639 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
640  if (TargetTriple.getObjectFormat() == Triple::COFF)
641  return ".SCOV$M";
642  if (TargetTriple.isOSBinFormatMachO())
643  return "__DATA,__" + Section;
644  return "__" + Section;
645 }
646 
647 std::string
648 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
649  if (TargetTriple.isOSBinFormatMachO())
650  return "\1section$start$__DATA$__" + Section;
651  return "__start___" + Section;
652 }
653 
654 std::string
655 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
656  if (TargetTriple.isOSBinFormatMachO())
657  return "\1section$end$__DATA$__" + Section;
658  return "__stop___" + Section;
659 }
660 
661 
663 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
664  "SanitizerCoverage: TODO."
665  "ModulePass",
666  false, false)
669 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
670  "SanitizerCoverage: TODO."
671  "ModulePass",
672  false, false)
674  const SanitizerCoverageOptions &Options) {
675  return new SanitizerCoverageModule(Options);
676 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:226
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
static const uint64_t SanCtorAndDtorPriority
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
Function * checkSanitizerInterfaceFunction(Constant *FuncOrBitcast)
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:142
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
adds the attribute to the list of attributes for the given arg.
Definition: Function.cpp:365
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
DataLayout DL
static const char *const SanCovGuardsSectionName
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
A debug info location.
Definition: DebugLoc.h:34
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:177
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
Loop over all of the edges in the CFG, breaking critical edges as they are found. ...
static const char *const SanCovTracePCName
Hexagon Common GEP
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:175
static const char *const SanCovTraceSwitchName
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:233
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:207
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
static const char *const SanCov8bitCountersInitName
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
static cl::opt< int > ClCoverageLevel("sanitizer-coverage-level", cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, ""3: all blocks and critical edges"), cl::Hidden, cl::init(0))
static const char *const SanCovTraceCmp2
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:664
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1255
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:106
static const char *const SanCovTraceGep
#define F(x, y, z)
Definition: MD5.cpp:55
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
static cl::opt< bool > ClDIVTracing("sanitizer-coverage-trace-divs", cl::desc("Tracing of DIV instructions"), cl::Hidden, cl::init(false))
Class to represent array types.
Definition: DerivedTypes.h:369
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:297
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
static cl::opt< bool > ClCMPTracing("sanitizer-coverage-trace-compares", cl::desc("Tracing of CMP and similar instructions"), cl::Hidden, cl::init(false))
static const char *const SanCovTracePCGuardName
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:134
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:109
SanitizerCoverage false
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:837
static const char *const SanCovTracePCIndirName
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
static const char *const SanCovTraceCmp1
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:298
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition: DataLayout.h:396
static const char *const SanCovTraceDiv4
const Comdat * getComdat() const
Definition: GlobalObject.h:101
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:200
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:888
#define A
Definition: LargeTest.cpp:12
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:116
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:626
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:161
This instruction compares its operands according to the predicate given to the constructor.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:119
static cl::opt< bool > ClPruneBlocks("sanitizer-coverage-prune-blocks", cl::desc("Reduce the number of instrumented blocks"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClTracePCGuard("sanitizer-coverage-trace-pc-guard", cl::desc("pc tracing with a guard"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceCmp4
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:467
static const char *const SanCovTraceCmp8
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1214
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:234
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::pair< Function *, Function * > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef())
Creates sanitizer constructor function, and calls sanitizer's init function from it.
Iterator for intrusive lists based on ilist_node.
static const char *const SanCovModuleCtorName
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
Definition: DerivedTypes.h:482
#define B
Definition: LargeTest.cpp:24
iterator end()
Definition: BasicBlock.h:254
static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT)
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:130
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:57
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static const char *const SanCovCountersSectionName
const size_t N
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition: Type.cpp:180
enum llvm::SanitizerCoverageOptions::Type CoverageType
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:560
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:84
const BasicBlock & getEntryBlock() const
Definition: Function.h:564
static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB, const DominatorTree *DT, const PostDominatorTree *PDT, const SanitizerCoverageOptions &Options)
BasicBlock::iterator PrepareToSplitEntryBlock(BasicBlock &BB, BasicBlock::iterator IP)
Instrumentation passes often insert conditional checks into entry blocks.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:217
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1498
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1435
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
bool empty() const
Definition: Function.h:586
static cl::opt< bool > ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden, cl::init(false))
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1164
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:361
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
#define C
Definition: LargeTest.cpp:25
static cl::opt< bool > ClGEPTracing("sanitizer-coverage-trace-geps", cl::desc("Tracing of GEP instructions"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceDiv8
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
Definition: DataLayout.h:346
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:568
ModulePass * createSanitizerCoverageModulePass(const SanitizerCoverageOptions &Options=SanitizerCoverageOptions())
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
INITIALIZE_PASS_BEGIN(SanitizerCoverageModule,"sancov","SanitizerCoverage: TODO.""ModulePass", false, false) INITIALIZE_PASS_END(SanitizerCoverageModule
static cl::opt< bool > ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden, cl::init(false))
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
aarch64 promote const
static const char *const SanCovTracePCGuardInitName
LLVM Value Representation.
Definition: Value.h:73
void initializeSanitizerCoverageModulePass(PassRegistry &)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:261
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
Definition: Module.cpp:118
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
IntegerType * Int32Ty
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237