LLVM  8.0.0svn
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/Constant.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DebugInfo.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InlineAsm.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/MDBuilder.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Type.h"
35 #include "llvm/Support/Debug.h"
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "sancov"
44 
45 static const char *const SanCovTracePCIndirName =
46  "__sanitizer_cov_trace_pc_indir";
47 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
48 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
52 static const char *const SanCovTraceConstCmp1 =
53  "__sanitizer_cov_trace_const_cmp1";
54 static const char *const SanCovTraceConstCmp2 =
55  "__sanitizer_cov_trace_const_cmp2";
56 static const char *const SanCovTraceConstCmp4 =
57  "__sanitizer_cov_trace_const_cmp4";
58 static const char *const SanCovTraceConstCmp8 =
59  "__sanitizer_cov_trace_const_cmp8";
60 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
63 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
65 static const uint64_t SanCtorAndDtorPriority = 2;
66 
67 static const char *const SanCovTracePCGuardName =
68  "__sanitizer_cov_trace_pc_guard";
69 static const char *const SanCovTracePCGuardInitName =
70  "__sanitizer_cov_trace_pc_guard_init";
71 static const char *const SanCov8bitCountersInitName =
72  "__sanitizer_cov_8bit_counters_init";
73 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
74 
75 static const char *const SanCovGuardsSectionName = "sancov_guards";
76 static const char *const SanCovCountersSectionName = "sancov_cntrs";
77 static const char *const SanCovPCsSectionName = "sancov_pcs";
78 
79 static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
80 
82  "sanitizer-coverage-level",
83  cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
84  "3: all blocks and critical edges"),
85  cl::Hidden, cl::init(0));
86 
87 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
88  cl::desc("Experimental pc tracing"), cl::Hidden,
89  cl::init(false));
90 
91 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
92  cl::desc("pc tracing with a guard"),
93  cl::Hidden, cl::init(false));
94 
95 // If true, we create a global variable that contains PCs of all instrumented
96 // BBs, put this global into a named section, and pass this section's bounds
97 // to __sanitizer_cov_pcs_init.
98 // This way the coverage instrumentation does not need to acquire the PCs
99 // at run-time. Works with trace-pc-guard and inline-8bit-counters.
100 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
101  cl::desc("create a static PC table"),
102  cl::Hidden, cl::init(false));
103 
104 static cl::opt<bool>
105  ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
106  cl::desc("increments 8-bit counter for every edge"),
107  cl::Hidden, cl::init(false));
108 
109 static cl::opt<bool>
110  ClCMPTracing("sanitizer-coverage-trace-compares",
111  cl::desc("Tracing of CMP and similar instructions"),
112  cl::Hidden, cl::init(false));
113 
114 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
115  cl::desc("Tracing of DIV instructions"),
116  cl::Hidden, cl::init(false));
117 
118 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
119  cl::desc("Tracing of GEP instructions"),
120  cl::Hidden, cl::init(false));
121 
122 static cl::opt<bool>
123  ClPruneBlocks("sanitizer-coverage-prune-blocks",
124  cl::desc("Reduce the number of instrumented blocks"),
125  cl::Hidden, cl::init(true));
126 
127 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
128  cl::desc("max stack depth tracing"),
129  cl::Hidden, cl::init(false));
130 
131 namespace {
132 
133 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
135  switch (LegacyCoverageLevel) {
136  case 0:
138  break;
139  case 1:
141  break;
142  case 2:
144  break;
145  case 3:
147  break;
148  case 4:
150  Res.IndirectCalls = true;
151  break;
152  }
153  return Res;
154 }
155 
156 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
157  // Sets CoverageType and IndirectCalls.
158  SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
159  Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
160  Options.IndirectCalls |= CLOpts.IndirectCalls;
161  Options.TraceCmp |= ClCMPTracing;
162  Options.TraceDiv |= ClDIVTracing;
163  Options.TraceGep |= ClGEPTracing;
164  Options.TracePC |= ClTracePC;
165  Options.TracePCGuard |= ClTracePCGuard;
167  Options.PCTable |= ClCreatePCTable;
168  Options.NoPrune |= !ClPruneBlocks;
169  Options.StackDepth |= ClStackDepth;
170  if (!Options.TracePCGuard && !Options.TracePC &&
171  !Options.Inline8bitCounters && !Options.StackDepth)
172  Options.TracePCGuard = true; // TracePCGuard is default.
173  return Options;
174 }
175 
176 class SanitizerCoverageModule : public ModulePass {
177 public:
178  SanitizerCoverageModule(
180  : ModulePass(ID), Options(OverrideFromCL(Options)) {
182  }
183  bool runOnModule(Module &M) override;
184  bool runOnFunction(Function &F);
185  static char ID; // Pass identification, replacement for typeid
186  StringRef getPassName() const override { return "SanitizerCoverageModule"; }
187 
188  void getAnalysisUsage(AnalysisUsage &AU) const override {
191  }
192 
193 private:
194  void InjectCoverageForIndirectCalls(Function &F,
195  ArrayRef<Instruction *> IndirCalls);
196  void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
197  void InjectTraceForDiv(Function &F,
198  ArrayRef<BinaryOperator *> DivTraceTargets);
199  void InjectTraceForGep(Function &F,
200  ArrayRef<GetElementPtrInst *> GepTraceTargets);
201  void InjectTraceForSwitch(Function &F,
202  ArrayRef<Instruction *> SwitchTraceTargets);
203  bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
204  bool IsLeafFunc = true);
205  GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
206  Function &F, Type *Ty,
207  const char *Section);
208  GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
209  void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
211  bool IsLeafFunc = true);
212  Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
213  Type *Ty, const char *Section);
214  std::pair<GlobalVariable *, GlobalVariable *>
215  CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
216 
217  void SetNoSanitizeMetadata(Instruction *I) {
218  I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
219  MDNode::get(*C, None));
220  }
221 
222  Comdat *GetOrCreateFunctionComdat(Function &F);
223 
224  std::string getSectionName(const std::string &Section) const;
225  std::string getSectionStart(const std::string &Section) const;
226  std::string getSectionEnd(const std::string &Section) const;
227  Function *SanCovTracePCIndir;
228  Function *SanCovTracePC, *SanCovTracePCGuard;
229  Function *SanCovTraceCmpFunction[4];
230  Function *SanCovTraceConstCmpFunction[4];
231  Function *SanCovTraceDivFunction[2];
232  Function *SanCovTraceGepFunction;
233  Function *SanCovTraceSwitchFunction;
234  GlobalVariable *SanCovLowestStack;
235  InlineAsm *EmptyAsm;
236  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
237  *Int16Ty, *Int8Ty, *Int8PtrTy;
238  Module *CurModule;
239  std::string CurModuleUniqueId;
240  Triple TargetTriple;
241  LLVMContext *C;
242  const DataLayout *DL;
243 
244  GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
245  GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
246  GlobalVariable *FunctionPCsArray; // for pc-table.
247  SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
248  SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
249 
250  SanitizerCoverageOptions Options;
251 };
252 
253 } // namespace
254 
255 std::pair<GlobalVariable *, GlobalVariable *>
256 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
257  Type *Ty) {
258  GlobalVariable *SecStart =
259  new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
260  getSectionStart(Section));
262  GlobalVariable *SecEnd =
264  nullptr, getSectionEnd(Section));
266 
267  return std::make_pair(SecStart, SecEnd);
268 }
269 
270 
271 Function *SanitizerCoverageModule::CreateInitCallsForSections(
272  Module &M, const char *InitFunctionName, Type *Ty,
273  const char *Section) {
274  IRBuilder<> IRB(M.getContext());
275  auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
276  auto SecStart = SecStartEnd.first;
277  auto SecEnd = SecStartEnd.second;
278  Function *CtorFunc;
279  Value *SecStartPtr = nullptr;
280  // Account for the fact that on windows-msvc __start_* symbols actually
281  // point to a uint64_t before the start of the array.
282  if (TargetTriple.getObjectFormat() == Triple::COFF) {
283  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
284  auto GEP = IRB.CreateGEP(SecStartI8Ptr,
285  ConstantInt::get(IntptrTy, sizeof(uint64_t)));
286  SecStartPtr = IRB.CreatePointerCast(GEP, Ty);
287  } else {
288  SecStartPtr = IRB.CreatePointerCast(SecStart, Ty);
289  }
290  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
291  M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
292  {SecStartPtr, IRB.CreatePointerCast(SecEnd, Ty)});
293 
294  if (TargetTriple.supportsCOMDAT()) {
295  // Use comdat to dedup CtorFunc.
296  CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
297  appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
298  } else {
300  }
301  return CtorFunc;
302 }
303 
304 bool SanitizerCoverageModule::runOnModule(Module &M) {
306  return false;
307  C = &(M.getContext());
308  DL = &M.getDataLayout();
309  CurModule = &M;
310  CurModuleUniqueId = getUniqueModuleId(CurModule);
311  TargetTriple = Triple(M.getTargetTriple());
312  FunctionGuardArray = nullptr;
313  Function8bitCounterArray = nullptr;
314  FunctionPCsArray = nullptr;
315  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
316  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
317  Type *VoidTy = Type::getVoidTy(*C);
318  IRBuilder<> IRB(*C);
319  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
320  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
321  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
322  Int64Ty = IRB.getInt64Ty();
323  Int32Ty = IRB.getInt32Ty();
324  Int16Ty = IRB.getInt16Ty();
325  Int8Ty = IRB.getInt8Ty();
326 
327  SanCovTracePCIndir = checkSanitizerInterfaceFunction(
328  M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
329  SanCovTraceCmpFunction[0] =
331  SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
332  SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
333  M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
334  IRB.getInt16Ty()));
335  SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
336  M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
337  IRB.getInt32Ty()));
338  SanCovTraceCmpFunction[3] =
340  SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
341 
342  SanCovTraceConstCmpFunction[0] =
344  SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
345  SanCovTraceConstCmpFunction[1] =
347  SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
348  SanCovTraceConstCmpFunction[2] =
350  SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
351  SanCovTraceConstCmpFunction[3] =
353  SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
354 
355  SanCovTraceDivFunction[0] =
357  SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
358  SanCovTraceDivFunction[1] =
360  SanCovTraceDiv8, VoidTy, Int64Ty));
361  SanCovTraceGepFunction =
363  SanCovTraceGep, VoidTy, IntptrTy));
364  SanCovTraceSwitchFunction =
366  SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
367 
368  Constant *SanCovLowestStackConstant =
369  M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
370  SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
371  SanCovLowestStack->setThreadLocalMode(
372  GlobalValue::ThreadLocalMode::InitialExecTLSModel);
373  if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
374  SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
375 
376  // Make sure smaller parameters are zero-extended to i64 as required by the
377  // x86_64 ABI.
378  if (TargetTriple.getArch() == Triple::x86_64) {
379  for (int i = 0; i < 3; i++) {
380  SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
381  SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
382  SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
383  SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
384  }
385  SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
386  }
387 
388 
389  // We insert an empty inline asm after cov callbacks to avoid callback merge.
390  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
391  StringRef(""), StringRef(""),
392  /*hasSideEffects=*/true);
393 
394  SanCovTracePC = checkSanitizerInterfaceFunction(
395  M.getOrInsertFunction(SanCovTracePCName, VoidTy));
397  SanCovTracePCGuardName, VoidTy, Int32PtrTy));
398 
399  for (auto &F : M)
400  runOnFunction(F);
401 
402  Function *Ctor = nullptr;
403 
404  if (FunctionGuardArray)
405  Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
406  SanCovGuardsSectionName);
407  if (Function8bitCounterArray)
408  Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
409  SanCovCountersSectionName);
410  if (Ctor && Options.PCTable) {
411  auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
412  Function *InitFunction = declareSanitizerInitFunction(
413  M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
414  IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
415  Value *SecStartPtr = nullptr;
416  // Account for the fact that on windows-msvc __start_pc_table actually
417  // points to a uint64_t before the start of the PC table.
418  if (TargetTriple.getObjectFormat() == Triple::COFF) {
419  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy);
420  auto GEP = IRB.CreateGEP(SecStartI8Ptr,
421  ConstantInt::get(IntptrTy, sizeof(uint64_t)));
422  SecStartPtr = IRB.CreatePointerCast(GEP, IntptrPtrTy);
423  } else {
424  SecStartPtr = IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy);
425  }
426  IRBCtor.CreateCall(
427  InitFunction,
428  {SecStartPtr, IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
429  }
430  // We don't reference these arrays directly in any of our runtime functions,
431  // so we need to prevent them from being dead stripped.
432  if (TargetTriple.isOSBinFormatMachO())
433  appendToUsed(M, GlobalsToAppendToUsed);
434  appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
435  return true;
436 }
437 
438 // True if block has successors and it dominates all of them.
439 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
440  if (succ_begin(BB) == succ_end(BB))
441  return false;
442 
443  for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
444  if (!DT->dominates(BB, SUCC))
445  return false;
446  }
447 
448  return true;
449 }
450 
451 // True if block has predecessors and it postdominates all of them.
452 static bool isFullPostDominator(const BasicBlock *BB,
453  const PostDominatorTree *PDT) {
454  if (pred_begin(BB) == pred_end(BB))
455  return false;
456 
457  for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
458  if (!PDT->dominates(BB, PRED))
459  return false;
460  }
461 
462  return true;
463 }
464 
465 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
466  const DominatorTree *DT,
467  const PostDominatorTree *PDT,
468  const SanitizerCoverageOptions &Options) {
469  // Don't insert coverage for unreachable blocks: we will never call
470  // __sanitizer_cov() for them, so counting them in
471  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
472  // percentage. Also, unreachable instructions frequently have no debug
473  // locations.
474  if (isa<UnreachableInst>(BB->getTerminator()))
475  return false;
476 
477  // Don't insert coverage into blocks without a valid insertion point
478  // (catchswitch blocks).
479  if (BB->getFirstInsertionPt() == BB->end())
480  return false;
481 
482  if (Options.NoPrune || &F.getEntryBlock() == BB)
483  return true;
484 
486  &F.getEntryBlock() != BB)
487  return false;
488 
489  // Do not instrument full dominators, or full post-dominators with multiple
490  // predecessors.
491  return !isFullDominator(BB, DT)
492  && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
493 }
494 
496  if (F.empty())
497  return false;
498  if (F.getName().find(".module_ctor") != std::string::npos)
499  return false; // Should not instrument sanitizer init functions.
500  if (F.getName().startswith("__sanitizer_"))
501  return false; // Don't instrument __sanitizer_* callbacks.
502  // Don't touch available_externally functions, their actual body is elewhere.
504  return false;
505  // Don't instrument MSVC CRT configuration helpers. They may run before normal
506  // initialization.
507  if (F.getName() == "__local_stdio_printf_options" ||
508  F.getName() == "__local_stdio_scanf_options")
509  return false;
510  if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
511  return false;
512  // Don't instrument functions using SEH for now. Splitting basic blocks like
513  // we do for coverage breaks WinEHPrepare.
514  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
515  if (F.hasPersonalityFn() &&
517  return false;
521  SmallVector<BasicBlock *, 16> BlocksToInstrument;
522  SmallVector<Instruction *, 8> CmpTraceTargets;
523  SmallVector<Instruction *, 8> SwitchTraceTargets;
524  SmallVector<BinaryOperator *, 8> DivTraceTargets;
525  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
526 
527  const DominatorTree *DT =
528  &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
529  const PostDominatorTree *PDT =
530  &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
531  bool IsLeafFunc = true;
532 
533  for (auto &BB : F) {
534  if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
535  BlocksToInstrument.push_back(&BB);
536  for (auto &Inst : BB) {
537  if (Options.IndirectCalls) {
538  CallSite CS(&Inst);
539  if (CS && !CS.getCalledFunction())
540  IndirCalls.push_back(&Inst);
541  }
542  if (Options.TraceCmp) {
543  if (isa<ICmpInst>(&Inst))
544  CmpTraceTargets.push_back(&Inst);
545  if (isa<SwitchInst>(&Inst))
546  SwitchTraceTargets.push_back(&Inst);
547  }
548  if (Options.TraceDiv)
549  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
550  if (BO->getOpcode() == Instruction::SDiv ||
551  BO->getOpcode() == Instruction::UDiv)
552  DivTraceTargets.push_back(BO);
553  if (Options.TraceGep)
554  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
555  GepTraceTargets.push_back(GEP);
556  if (Options.StackDepth)
557  if (isa<InvokeInst>(Inst) ||
558  (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
559  IsLeafFunc = false;
560  }
561  }
562 
563  InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
564  InjectCoverageForIndirectCalls(F, IndirCalls);
565  InjectTraceForCmp(F, CmpTraceTargets);
566  InjectTraceForSwitch(F, SwitchTraceTargets);
567  InjectTraceForDiv(F, DivTraceTargets);
568  InjectTraceForGep(F, GepTraceTargets);
569  return true;
570 }
571 
572 Comdat *SanitizerCoverageModule::GetOrCreateFunctionComdat(Function &F) {
573  if (auto Comdat = F.getComdat()) return Comdat;
574  if (!TargetTriple.isOSBinFormatELF()) return nullptr;
575  assert(F.hasName());
576  std::string Name = F.getName();
577  if (F.hasLocalLinkage()) {
578  if (CurModuleUniqueId.empty()) return nullptr;
579  Name += CurModuleUniqueId;
580  }
581  auto Comdat = CurModule->getOrInsertComdat(Name);
582  F.setComdat(Comdat);
583  return Comdat;
584 }
585 
586 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
587  size_t NumElements, Function &F, Type *Ty, const char *Section) {
588  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
589  auto Array = new GlobalVariable(
590  *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
591  Constant::getNullValue(ArrayTy), "__sancov_gen_");
592  if (auto Comdat = GetOrCreateFunctionComdat(F))
593  Array->setComdat(Comdat);
594  Array->setSection(getSectionName(Section));
595  Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
596  : Ty->getPrimitiveSizeInBits() / 8);
597  GlobalsToAppendToCompilerUsed.push_back(Array);
599  Array->addMetadata(LLVMContext::MD_associated, *MD);
600 
601  return Array;
602 }
603 
605 SanitizerCoverageModule::CreatePCArray(Function &F,
606  ArrayRef<BasicBlock *> AllBlocks) {
607  size_t N = AllBlocks.size();
608  assert(N);
611  for (size_t i = 0; i < N; i++) {
612  if (&F.getEntryBlock() == AllBlocks[i]) {
613  PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
614  PCs.push_back((Constant *)IRB.CreateIntToPtr(
615  ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
616  } else {
617  PCs.push_back((Constant *)IRB.CreatePointerCast(
618  BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
619  PCs.push_back((Constant *)IRB.CreateIntToPtr(
620  ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
621  }
622  }
623  auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
624  SanCovPCsSectionName);
625  PCArray->setInitializer(
626  ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
627  PCArray->setConstant(true);
628 
629  return PCArray;
630 }
631 
632 void SanitizerCoverageModule::CreateFunctionLocalArrays(
633  Function &F, ArrayRef<BasicBlock *> AllBlocks) {
634  if (Options.TracePCGuard) {
635  FunctionGuardArray = CreateFunctionLocalArrayInSection(
636  AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
637  GlobalsToAppendToUsed.push_back(FunctionGuardArray);
638  }
639  if (Options.Inline8bitCounters)
640  Function8bitCounterArray = CreateFunctionLocalArrayInSection(
641  AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
642  if (Options.PCTable)
643  FunctionPCsArray = CreatePCArray(F, AllBlocks);
644 }
645 
646 bool SanitizerCoverageModule::InjectCoverage(Function &F,
647  ArrayRef<BasicBlock *> AllBlocks,
648  bool IsLeafFunc) {
649  if (AllBlocks.empty()) return false;
650  CreateFunctionLocalArrays(F, AllBlocks);
651  for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
652  InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
653  return true;
654 }
655 
656 // On every indirect call we call a run-time function
657 // __sanitizer_cov_indir_call* with two parameters:
658 // - callee address,
659 // - global cache array that contains CacheSize pointers (zero-initialized).
660 // The cache is used to speed up recording the caller-callee pairs.
661 // The address of the caller is passed implicitly via caller PC.
662 // CacheSize is encoded in the name of the run-time function.
663 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
664  Function &F, ArrayRef<Instruction *> IndirCalls) {
665  if (IndirCalls.empty())
666  return;
667  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
668  for (auto I : IndirCalls) {
669  IRBuilder<> IRB(I);
670  CallSite CS(I);
671  Value *Callee = CS.getCalledValue();
672  if (isa<InlineAsm>(Callee))
673  continue;
674  IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
675  }
676 }
677 
678 // For every switch statement we insert a call:
679 // __sanitizer_cov_trace_switch(CondValue,
680 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
681 
682 void SanitizerCoverageModule::InjectTraceForSwitch(
683  Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
684  for (auto I : SwitchTraceTargets) {
685  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
686  IRBuilder<> IRB(I);
687  SmallVector<Constant *, 16> Initializers;
688  Value *Cond = SI->getCondition();
689  if (Cond->getType()->getScalarSizeInBits() >
690  Int64Ty->getScalarSizeInBits())
691  continue;
692  Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
693  Initializers.push_back(
694  ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
695  if (Cond->getType()->getScalarSizeInBits() <
696  Int64Ty->getScalarSizeInBits())
697  Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
698  for (auto It : SI->cases()) {
699  Constant *C = It.getCaseValue();
700  if (C->getType()->getScalarSizeInBits() <
701  Int64Ty->getScalarSizeInBits())
702  C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
703  Initializers.push_back(C);
704  }
705  llvm::sort(Initializers.begin() + 2, Initializers.end(),
706  [](const Constant *A, const Constant *B) {
707  return cast<ConstantInt>(A)->getLimitedValue() <
708  cast<ConstantInt>(B)->getLimitedValue();
709  });
710  ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
711  GlobalVariable *GV = new GlobalVariable(
712  *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
713  ConstantArray::get(ArrayOfInt64Ty, Initializers),
714  "__sancov_gen_cov_switch_values");
715  IRB.CreateCall(SanCovTraceSwitchFunction,
716  {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
717  }
718  }
719 }
720 
721 void SanitizerCoverageModule::InjectTraceForDiv(
722  Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
723  for (auto BO : DivTraceTargets) {
724  IRBuilder<> IRB(BO);
725  Value *A1 = BO->getOperand(1);
726  if (isa<ConstantInt>(A1)) continue;
727  if (!A1->getType()->isIntegerTy())
728  continue;
729  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
730  int CallbackIdx = TypeSize == 32 ? 0 :
731  TypeSize == 64 ? 1 : -1;
732  if (CallbackIdx < 0) continue;
733  auto Ty = Type::getIntNTy(*C, TypeSize);
734  IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
735  {IRB.CreateIntCast(A1, Ty, true)});
736  }
737 }
738 
739 void SanitizerCoverageModule::InjectTraceForGep(
740  Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
741  for (auto GEP : GepTraceTargets) {
742  IRBuilder<> IRB(GEP);
743  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
744  if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
745  IRB.CreateCall(SanCovTraceGepFunction,
746  {IRB.CreateIntCast(*I, IntptrTy, true)});
747  }
748 }
749 
750 void SanitizerCoverageModule::InjectTraceForCmp(
751  Function &, ArrayRef<Instruction *> CmpTraceTargets) {
752  for (auto I : CmpTraceTargets) {
753  if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
754  IRBuilder<> IRB(ICMP);
755  Value *A0 = ICMP->getOperand(0);
756  Value *A1 = ICMP->getOperand(1);
757  if (!A0->getType()->isIntegerTy())
758  continue;
759  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
760  int CallbackIdx = TypeSize == 8 ? 0 :
761  TypeSize == 16 ? 1 :
762  TypeSize == 32 ? 2 :
763  TypeSize == 64 ? 3 : -1;
764  if (CallbackIdx < 0) continue;
765  // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
766  auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
767  bool FirstIsConst = isa<ConstantInt>(A0);
768  bool SecondIsConst = isa<ConstantInt>(A1);
769  // If both are const, then we don't need such a comparison.
770  if (FirstIsConst && SecondIsConst) continue;
771  // If only one is const, then make it the first callback argument.
772  if (FirstIsConst || SecondIsConst) {
773  CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
774  if (SecondIsConst)
775  std::swap(A0, A1);
776  }
777 
778  auto Ty = Type::getIntNTy(*C, TypeSize);
779  IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
780  IRB.CreateIntCast(A1, Ty, true)});
781  }
782  }
783 }
784 
785 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
786  size_t Idx,
787  bool IsLeafFunc) {
789  bool IsEntryBB = &BB == &F.getEntryBlock();
790  DebugLoc EntryLoc;
791  if (IsEntryBB) {
792  if (auto SP = F.getSubprogram())
793  EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
794  // Keep static allocas and llvm.localescape calls in the entry block. Even
795  // if we aren't splitting the block, it's nice for allocas to be before
796  // calls.
797  IP = PrepareToSplitEntryBlock(BB, IP);
798  } else {
799  EntryLoc = IP->getDebugLoc();
800  }
801 
802  IRBuilder<> IRB(&*IP);
803  IRB.SetCurrentDebugLocation(EntryLoc);
804  if (Options.TracePC) {
805  IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
806  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
807  }
808  if (Options.TracePCGuard) {
809  auto GuardPtr = IRB.CreateIntToPtr(
810  IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
811  ConstantInt::get(IntptrTy, Idx * 4)),
812  Int32PtrTy);
813  IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
814  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
815  }
816  if (Options.Inline8bitCounters) {
817  auto CounterPtr = IRB.CreateGEP(
818  Function8bitCounterArray,
819  {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
820  auto Load = IRB.CreateLoad(CounterPtr);
821  auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
822  auto Store = IRB.CreateStore(Inc, CounterPtr);
823  SetNoSanitizeMetadata(Load);
824  SetNoSanitizeMetadata(Store);
825  }
826  if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
827  // Check stack depth. If it's the deepest so far, record it.
828  Function *GetFrameAddr =
829  Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
830  auto FrameAddrPtr =
831  IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
832  auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
833  auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
834  auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
835  auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
836  IRBuilder<> ThenIRB(ThenTerm);
837  auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
838  SetNoSanitizeMetadata(LowestStack);
839  SetNoSanitizeMetadata(Store);
840  }
841 }
842 
843 std::string
844 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
845  if (TargetTriple.getObjectFormat() == Triple::COFF) {
846  if (Section == SanCovCountersSectionName)
847  return ".SCOV$CM";
848  if (Section == SanCovPCsSectionName)
849  return ".SCOVP$M";
850  return ".SCOV$GM"; // For SanCovGuardsSectionName.
851  }
852  if (TargetTriple.isOSBinFormatMachO())
853  return "__DATA,__" + Section;
854  return "__" + Section;
855 }
856 
857 std::string
858 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
859  if (TargetTriple.isOSBinFormatMachO())
860  return "\1section$start$__DATA$__" + Section;
861  return "__start___" + Section;
862 }
863 
864 std::string
865 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
866  if (TargetTriple.isOSBinFormatMachO())
867  return "\1section$end$__DATA$__" + Section;
868  return "__stop___" + Section;
869 }
870 
871 
873 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
874  "SanitizerCoverage: TODO."
875  "ModulePass",
876  false, false)
879 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
880  "SanitizerCoverage: TODO."
881  "ModulePass",
882  false, false)
884  const SanitizerCoverageOptions &Options) {
885  return new SanitizerCoverageModule(Options);
886 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:239
static const char *const SanCovPCsSectionName
uint64_t CallInst * C
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.compiler.used list.
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:239
Function * declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type *> InitArgTypes)
bool empty() const
Definition: Function.h:662
static const uint64_t SanCtorAndDtorPriority
bool hasLocalLinkage() const
Definition: GlobalValue.h:436
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:22
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)
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
static const char *const SanCovTraceConstCmp1
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1752
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:64
static const char *const SanCovPCsInitName
Available for inspection, not emission.
Definition: GlobalValue.h:50
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
static const char *const SanCovGuardsSectionName
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Externally visible function.
Definition: GlobalValue.h:49
static cl::opt< bool > ClStackDepth("sanitizer-coverage-stack-depth", cl::desc("max stack depth tracing"), cl::Hidden, cl::init(false))
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:864
F(f)
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
static const char *const SanCovTraceConstCmp2
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:960
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:268
static const char *const SanCov8bitCountersInitName
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:364
static const char *const SanCovTraceCmp2
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:243
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:731
static const char *const SanCovLowestStackName
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:962
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))
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:103
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1321
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1624
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:100
static const char *const SanCovTraceGep
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:267
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
void appendToUsed(Module &M, ArrayRef< GlobalValue *> Values)
Adds global values to the llvm.used list.
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
void setComdat(Comdat *C)
Definition: GlobalObject.h:103
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))
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:702
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:151
LinkageTypes getLinkage() const
Definition: GlobalValue.h:451
static const char *const SanCovTracePCGuardName
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:145
amdgpu Simplify well known AMD library false Value * Callee
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1021
INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov", "SanitizerCoverage: TODO." "ModulePass", false, false) INITIALIZE_PASS_END(SanitizerCoverageModule
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:106
const BasicBlock & getEntryBlock() const
Definition: Function.h:640
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:841
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool&#39; fo...
Definition: IRBuilder.h:1305
static const char *const SanCovTracePCIndirName
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1166
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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:218
static const char *const SanCovTraceCmp1
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:235
bool hasName() const
Definition: Value.h:251
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
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&#39;s init function from it.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1508
Constant * getOrInsertGlobal(StringRef Name, Type *Ty)
Look up the specified global in the module symbol table.
Definition: Module.cpp:205
static cl::opt< bool > ClCreatePCTable("sanitizer-coverage-pc-table", cl::desc("create a static PC table"), cl::Hidden, cl::init(false))
static const char *const SanCovTraceDiv4
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Definition: Constants.cpp:1411
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:149
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:129
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:224
static const char *const SanCovTraceConstCmp8
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:113
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.
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
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
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
static Constant * getAllOnesValue(Type *Ty)
Definition: Constants.cpp:322
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module&#39;s strong...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:194
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:477
static const char *const SanCovTraceCmp8
size_t size() const
Definition: SmallVector.h:53
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1226
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:972
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1374
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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
iterator end()
Definition: BasicBlock.h:266
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
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:1698
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:349
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:249
Module.h This file contains the declarations for the Module class.
static const char *const SanCovCountersSectionName
TerminatorInst * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
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:621
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
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:941
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1507
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static cl::opt< bool > ClTracePC("sanitizer-coverage-trace-pc", cl::desc("Experimental pc tracing"), cl::Hidden, cl::init(false))
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1675
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
const Comdat * getComdat() const
Definition: GlobalObject.h:101
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:133
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
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
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
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
static cl::opt< bool > ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters", cl::desc("increments 8-bit counter for every edge"), cl::Hidden, cl::init(false))
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1619
FunTy * getCalledFunction() const
Return the function being called if this is a direct call, otherwise return null (if it&#39;s an indirect...
Definition: CallSite.h:107
Multiway switch.
unsigned getMDKindID(StringRef Name) const
Return a unique non-zero ID for the specified metadata kind.
Definition: Module.cpp:119
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
aarch64 promote const
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition: Type.cpp:115
static const char *const SanCovTracePCGuardInitName
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1302
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:260
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:138
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
static const char *const SanCovTraceConstCmp4
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:144
IntegerType * Int32Ty
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1871