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/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
36 #include "llvm/Support/Debug.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "sancov"
45 
46 static const char *const SanCovTracePCIndirName =
47  "__sanitizer_cov_trace_pc_indir";
48 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
49 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
50 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
51 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
52 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
53 static const char *const SanCovTraceConstCmp1 =
54  "__sanitizer_cov_trace_const_cmp1";
55 static const char *const SanCovTraceConstCmp2 =
56  "__sanitizer_cov_trace_const_cmp2";
57 static const char *const SanCovTraceConstCmp4 =
58  "__sanitizer_cov_trace_const_cmp4";
59 static const char *const SanCovTraceConstCmp8 =
60  "__sanitizer_cov_trace_const_cmp8";
61 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
62 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
63 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
64 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
65 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
66 static const uint64_t SanCtorAndDtorPriority = 2;
67 
68 static const char *const SanCovTracePCGuardName =
69  "__sanitizer_cov_trace_pc_guard";
70 static const char *const SanCovTracePCGuardInitName =
71  "__sanitizer_cov_trace_pc_guard_init";
72 static const char *const SanCov8bitCountersInitName =
73  "__sanitizer_cov_8bit_counters_init";
74 static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
75 
76 static const char *const SanCovGuardsSectionName = "sancov_guards";
77 static const char *const SanCovCountersSectionName = "sancov_cntrs";
78 static const char *const SanCovPCsSectionName = "sancov_pcs";
79 
80 static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
81 
83  "sanitizer-coverage-level",
84  cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
85  "3: all blocks and critical edges"),
86  cl::Hidden, cl::init(0));
87 
88 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
89  cl::desc("Experimental pc tracing"), cl::Hidden,
90  cl::init(false));
91 
92 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
93  cl::desc("pc tracing with a guard"),
94  cl::Hidden, cl::init(false));
95 
96 // If true, we create a global variable that contains PCs of all instrumented
97 // BBs, put this global into a named section, and pass this section's bounds
98 // to __sanitizer_cov_pcs_init.
99 // This way the coverage instrumentation does not need to acquire the PCs
100 // at run-time. Works with trace-pc-guard and inline-8bit-counters.
101 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
102  cl::desc("create a static PC table"),
103  cl::Hidden, cl::init(false));
104 
105 static cl::opt<bool>
106  ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
107  cl::desc("increments 8-bit counter for every edge"),
108  cl::Hidden, cl::init(false));
109 
110 static cl::opt<bool>
111  ClCMPTracing("sanitizer-coverage-trace-compares",
112  cl::desc("Tracing of CMP and similar instructions"),
113  cl::Hidden, cl::init(false));
114 
115 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
116  cl::desc("Tracing of DIV instructions"),
117  cl::Hidden, cl::init(false));
118 
119 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
120  cl::desc("Tracing of GEP instructions"),
121  cl::Hidden, cl::init(false));
122 
123 static cl::opt<bool>
124  ClPruneBlocks("sanitizer-coverage-prune-blocks",
125  cl::desc("Reduce the number of instrumented blocks"),
126  cl::Hidden, cl::init(true));
127 
128 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
129  cl::desc("max stack depth tracing"),
130  cl::Hidden, cl::init(false));
131 
132 namespace {
133 
134 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
136  switch (LegacyCoverageLevel) {
137  case 0:
139  break;
140  case 1:
142  break;
143  case 2:
145  break;
146  case 3:
148  break;
149  case 4:
151  Res.IndirectCalls = true;
152  break;
153  }
154  return Res;
155 }
156 
157 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
158  // Sets CoverageType and IndirectCalls.
159  SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
160  Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
161  Options.IndirectCalls |= CLOpts.IndirectCalls;
162  Options.TraceCmp |= ClCMPTracing;
163  Options.TraceDiv |= ClDIVTracing;
164  Options.TraceGep |= ClGEPTracing;
165  Options.TracePC |= ClTracePC;
166  Options.TracePCGuard |= ClTracePCGuard;
168  Options.PCTable |= ClCreatePCTable;
169  Options.NoPrune |= !ClPruneBlocks;
170  Options.StackDepth |= ClStackDepth;
171  if (!Options.TracePCGuard && !Options.TracePC &&
172  !Options.Inline8bitCounters && !Options.StackDepth)
173  Options.TracePCGuard = true; // TracePCGuard is default.
174  return Options;
175 }
176 
177 class SanitizerCoverageModule : public ModulePass {
178 public:
179  SanitizerCoverageModule(
181  : ModulePass(ID), Options(OverrideFromCL(Options)) {
183  }
184  bool runOnModule(Module &M) override;
185  bool runOnFunction(Function &F);
186  static char ID; // Pass identification, replacement for typeid
187  StringRef getPassName() const override { return "SanitizerCoverageModule"; }
188 
189  void getAnalysisUsage(AnalysisUsage &AU) const override {
192  }
193 
194 private:
195  void InjectCoverageForIndirectCalls(Function &F,
196  ArrayRef<Instruction *> IndirCalls);
197  void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
198  void InjectTraceForDiv(Function &F,
199  ArrayRef<BinaryOperator *> DivTraceTargets);
200  void InjectTraceForGep(Function &F,
201  ArrayRef<GetElementPtrInst *> GepTraceTargets);
202  void InjectTraceForSwitch(Function &F,
203  ArrayRef<Instruction *> SwitchTraceTargets);
204  bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
205  bool IsLeafFunc = true);
206  GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
207  Function &F, Type *Ty,
208  const char *Section);
209  GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210  void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
211  void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
212  bool IsLeafFunc = true);
213  Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
214  Type *Ty, const char *Section);
215  std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
216  Type *Ty);
217 
218  void SetNoSanitizeMetadata(Instruction *I) {
219  I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
220  MDNode::get(*C, None));
221  }
222 
223  std::string getSectionName(const std::string &Section) const;
224  std::string getSectionStart(const std::string &Section) const;
225  std::string getSectionEnd(const std::string &Section) const;
226  Function *SanCovTracePCIndir;
227  Function *SanCovTracePC, *SanCovTracePCGuard;
228  Function *SanCovTraceCmpFunction[4];
229  Function *SanCovTraceConstCmpFunction[4];
230  Function *SanCovTraceDivFunction[2];
231  Function *SanCovTraceGepFunction;
232  Function *SanCovTraceSwitchFunction;
233  GlobalVariable *SanCovLowestStack;
234  InlineAsm *EmptyAsm;
235  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
236  *Int16Ty, *Int8Ty, *Int8PtrTy;
237  Module *CurModule;
238  std::string CurModuleUniqueId;
239  Triple TargetTriple;
240  LLVMContext *C;
241  const DataLayout *DL;
242 
243  GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
244  GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
245  GlobalVariable *FunctionPCsArray; // for pc-table.
246  SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
247  SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
248 
249  SanitizerCoverageOptions Options;
250 };
251 
252 } // namespace
253 
254 std::pair<Value *, Value *>
255 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
256  Type *Ty) {
257  GlobalVariable *SecStart =
258  new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
259  getSectionStart(Section));
261  GlobalVariable *SecEnd =
263  nullptr, getSectionEnd(Section));
265  IRBuilder<> IRB(M.getContext());
266  Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
267  if (TargetTriple.getObjectFormat() != Triple::COFF)
268  return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
269 
270  // Account for the fact that on windows-msvc __start_* symbols actually
271  // point to a uint64_t before the start of the array.
272  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
273  auto GEP = IRB.CreateGEP(SecStartI8Ptr,
274  ConstantInt::get(IntptrTy, sizeof(uint64_t)));
275  return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
276 }
277 
278 Function *SanitizerCoverageModule::CreateInitCallsForSections(
279  Module &M, const char *InitFunctionName, Type *Ty,
280  const char *Section) {
281  auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
282  auto SecStart = SecStartEnd.first;
283  auto SecEnd = SecStartEnd.second;
284  Function *CtorFunc;
285  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
286  M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
287 
288  if (TargetTriple.supportsCOMDAT()) {
289  // Use comdat to dedup CtorFunc.
290  CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
291  appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
292  } else {
294  }
295 
296  if (TargetTriple.getObjectFormat() == Triple::COFF) {
297  // In COFF files, if the contructors are set as COMDAT (they are because
298  // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
299  // functions and data) is used, the constructors get stripped. To prevent
300  // this, give the constructors weak ODR linkage and tell the linker to
301  // always include the sancov constructor. This way the linker can
302  // deduplicate the constructors but always leave one copy.
304  SmallString<20> PartialIncDirective("/include:");
305  // Get constructor's mangled name in order to support i386.
306  SmallString<40> MangledName;
307  Mangler().getNameWithPrefix(MangledName, CtorFunc, true);
308  Twine IncDirective = PartialIncDirective + MangledName;
309  Metadata *Args[1] = {MDString::get(*C, IncDirective.str())};
310  MDNode *MetadataNode = MDNode::get(*C, Args);
311  NamedMDNode *NamedMetadata =
312  M.getOrInsertNamedMetadata("llvm.linker.options");
313  NamedMetadata->addOperand(MetadataNode);
314  }
315  return CtorFunc;
316 }
317 
318 bool SanitizerCoverageModule::runOnModule(Module &M) {
320  return false;
321  C = &(M.getContext());
322  DL = &M.getDataLayout();
323  CurModule = &M;
324  CurModuleUniqueId = getUniqueModuleId(CurModule);
325  TargetTriple = Triple(M.getTargetTriple());
326  FunctionGuardArray = nullptr;
327  Function8bitCounterArray = nullptr;
328  FunctionPCsArray = nullptr;
329  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
330  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
331  Type *VoidTy = Type::getVoidTy(*C);
332  IRBuilder<> IRB(*C);
333  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
334  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
335  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
336  Int64Ty = IRB.getInt64Ty();
337  Int32Ty = IRB.getInt32Ty();
338  Int16Ty = IRB.getInt16Ty();
339  Int8Ty = IRB.getInt8Ty();
340 
341  SanCovTracePCIndir = checkSanitizerInterfaceFunction(
342  M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
343  SanCovTraceCmpFunction[0] =
345  SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
346  SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
347  M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
348  IRB.getInt16Ty()));
349  SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
350  M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
351  IRB.getInt32Ty()));
352  SanCovTraceCmpFunction[3] =
354  SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
355 
356  SanCovTraceConstCmpFunction[0] =
358  SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
359  SanCovTraceConstCmpFunction[1] =
361  SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
362  SanCovTraceConstCmpFunction[2] =
364  SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
365  SanCovTraceConstCmpFunction[3] =
367  SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
368 
369  SanCovTraceDivFunction[0] =
371  SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
372  SanCovTraceDivFunction[1] =
374  SanCovTraceDiv8, VoidTy, Int64Ty));
375  SanCovTraceGepFunction =
377  SanCovTraceGep, VoidTy, IntptrTy));
378  SanCovTraceSwitchFunction =
380  SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
381 
382  Constant *SanCovLowestStackConstant =
383  M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
384  SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
385  SanCovLowestStack->setThreadLocalMode(
386  GlobalValue::ThreadLocalMode::InitialExecTLSModel);
387  if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
388  SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
389 
390  // Make sure smaller parameters are zero-extended to i64 as required by the
391  // x86_64 ABI.
392  if (TargetTriple.getArch() == Triple::x86_64) {
393  for (int i = 0; i < 3; i++) {
394  SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
395  SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
396  SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
397  SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
398  }
399  SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
400  }
401 
402 
403  // We insert an empty inline asm after cov callbacks to avoid callback merge.
404  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
405  StringRef(""), StringRef(""),
406  /*hasSideEffects=*/true);
407 
408  SanCovTracePC = checkSanitizerInterfaceFunction(
409  M.getOrInsertFunction(SanCovTracePCName, VoidTy));
411  SanCovTracePCGuardName, VoidTy, Int32PtrTy));
412 
413  for (auto &F : M)
414  runOnFunction(F);
415 
416  Function *Ctor = nullptr;
417 
418  if (FunctionGuardArray)
419  Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
420  SanCovGuardsSectionName);
421  if (Function8bitCounterArray)
422  Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
423  SanCovCountersSectionName);
424  if (Ctor && Options.PCTable) {
425  auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
426  Function *InitFunction = declareSanitizerInitFunction(
427  M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
428  IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
429  IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
430  }
431  // We don't reference these arrays directly in any of our runtime functions,
432  // so we need to prevent them from being dead stripped.
433  if (TargetTriple.isOSBinFormatMachO())
434  appendToUsed(M, GlobalsToAppendToUsed);
435  appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
436  return true;
437 }
438 
439 // True if block has successors and it dominates all of them.
440 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
441  if (succ_begin(BB) == succ_end(BB))
442  return false;
443 
444  for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
445  if (!DT->dominates(BB, SUCC))
446  return false;
447  }
448 
449  return true;
450 }
451 
452 // True if block has predecessors and it postdominates all of them.
453 static bool isFullPostDominator(const BasicBlock *BB,
454  const PostDominatorTree *PDT) {
455  if (pred_begin(BB) == pred_end(BB))
456  return false;
457 
458  for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
459  if (!PDT->dominates(BB, PRED))
460  return false;
461  }
462 
463  return true;
464 }
465 
466 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
467  const DominatorTree *DT,
468  const PostDominatorTree *PDT,
469  const SanitizerCoverageOptions &Options) {
470  // Don't insert coverage for unreachable blocks: we will never call
471  // __sanitizer_cov() for them, so counting them in
472  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
473  // percentage. Also, unreachable instructions frequently have no debug
474  // locations.
475  if (isa<UnreachableInst>(BB->getTerminator()))
476  return false;
477 
478  // Don't insert coverage into blocks without a valid insertion point
479  // (catchswitch blocks).
480  if (BB->getFirstInsertionPt() == BB->end())
481  return false;
482 
483  if (Options.NoPrune || &F.getEntryBlock() == BB)
484  return true;
485 
487  &F.getEntryBlock() != BB)
488  return false;
489 
490  // Do not instrument full dominators, or full post-dominators with multiple
491  // predecessors.
492  return !isFullDominator(BB, DT)
493  && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
494 }
495 
497  if (F.empty())
498  return false;
499  if (F.getName().find(".module_ctor") != std::string::npos)
500  return false; // Should not instrument sanitizer init functions.
501  if (F.getName().startswith("__sanitizer_"))
502  return false; // Don't instrument __sanitizer_* callbacks.
503  // Don't touch available_externally functions, their actual body is elewhere.
505  return false;
506  // Don't instrument MSVC CRT configuration helpers. They may run before normal
507  // initialization.
508  if (F.getName() == "__local_stdio_printf_options" ||
509  F.getName() == "__local_stdio_scanf_options")
510  return false;
511  if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
512  return false;
513  // Don't instrument functions using SEH for now. Splitting basic blocks like
514  // we do for coverage breaks WinEHPrepare.
515  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
516  if (F.hasPersonalityFn() &&
518  return false;
522  SmallVector<BasicBlock *, 16> BlocksToInstrument;
523  SmallVector<Instruction *, 8> CmpTraceTargets;
524  SmallVector<Instruction *, 8> SwitchTraceTargets;
525  SmallVector<BinaryOperator *, 8> DivTraceTargets;
526  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
527 
528  const DominatorTree *DT =
529  &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
530  const PostDominatorTree *PDT =
531  &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
532  bool IsLeafFunc = true;
533 
534  for (auto &BB : F) {
535  if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
536  BlocksToInstrument.push_back(&BB);
537  for (auto &Inst : BB) {
538  if (Options.IndirectCalls) {
539  CallSite CS(&Inst);
540  if (CS && !CS.getCalledFunction())
541  IndirCalls.push_back(&Inst);
542  }
543  if (Options.TraceCmp) {
544  if (isa<ICmpInst>(&Inst))
545  CmpTraceTargets.push_back(&Inst);
546  if (isa<SwitchInst>(&Inst))
547  SwitchTraceTargets.push_back(&Inst);
548  }
549  if (Options.TraceDiv)
550  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
551  if (BO->getOpcode() == Instruction::SDiv ||
552  BO->getOpcode() == Instruction::UDiv)
553  DivTraceTargets.push_back(BO);
554  if (Options.TraceGep)
555  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
556  GepTraceTargets.push_back(GEP);
557  if (Options.StackDepth)
558  if (isa<InvokeInst>(Inst) ||
559  (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
560  IsLeafFunc = false;
561  }
562  }
563 
564  InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
565  InjectCoverageForIndirectCalls(F, IndirCalls);
566  InjectTraceForCmp(F, CmpTraceTargets);
567  InjectTraceForSwitch(F, SwitchTraceTargets);
568  InjectTraceForDiv(F, DivTraceTargets);
569  InjectTraceForGep(F, GepTraceTargets);
570  return true;
571 }
572 
573 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
574  size_t NumElements, Function &F, Type *Ty, const char *Section) {
575  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
576  auto Array = new GlobalVariable(
577  *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
578  Constant::getNullValue(ArrayTy), "__sancov_gen_");
579 
580  if (TargetTriple.supportsCOMDAT())
581  if (auto Comdat =
582  GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
583  Array->setComdat(Comdat);
584  Array->setSection(getSectionName(Section));
585  Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
586  : Ty->getPrimitiveSizeInBits() / 8);
587  GlobalsToAppendToUsed.push_back(Array);
588  GlobalsToAppendToCompilerUsed.push_back(Array);
590  Array->addMetadata(LLVMContext::MD_associated, *MD);
591 
592  return Array;
593 }
594 
596 SanitizerCoverageModule::CreatePCArray(Function &F,
597  ArrayRef<BasicBlock *> AllBlocks) {
598  size_t N = AllBlocks.size();
599  assert(N);
602  for (size_t i = 0; i < N; i++) {
603  if (&F.getEntryBlock() == AllBlocks[i]) {
604  PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
605  PCs.push_back((Constant *)IRB.CreateIntToPtr(
606  ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
607  } else {
608  PCs.push_back((Constant *)IRB.CreatePointerCast(
609  BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
610  PCs.push_back((Constant *)IRB.CreateIntToPtr(
611  ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
612  }
613  }
614  auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
615  SanCovPCsSectionName);
616  PCArray->setInitializer(
617  ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
618  PCArray->setConstant(true);
619 
620  return PCArray;
621 }
622 
623 void SanitizerCoverageModule::CreateFunctionLocalArrays(
624  Function &F, ArrayRef<BasicBlock *> AllBlocks) {
625  if (Options.TracePCGuard)
626  FunctionGuardArray = CreateFunctionLocalArrayInSection(
627  AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
628 
629  if (Options.Inline8bitCounters)
630  Function8bitCounterArray = CreateFunctionLocalArrayInSection(
631  AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
632 
633  if (Options.PCTable)
634  FunctionPCsArray = CreatePCArray(F, AllBlocks);
635 }
636 
637 bool SanitizerCoverageModule::InjectCoverage(Function &F,
638  ArrayRef<BasicBlock *> AllBlocks,
639  bool IsLeafFunc) {
640  if (AllBlocks.empty()) return false;
641  CreateFunctionLocalArrays(F, AllBlocks);
642  for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
643  InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
644  return true;
645 }
646 
647 // On every indirect call we call a run-time function
648 // __sanitizer_cov_indir_call* with two parameters:
649 // - callee address,
650 // - global cache array that contains CacheSize pointers (zero-initialized).
651 // The cache is used to speed up recording the caller-callee pairs.
652 // The address of the caller is passed implicitly via caller PC.
653 // CacheSize is encoded in the name of the run-time function.
654 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
655  Function &F, ArrayRef<Instruction *> IndirCalls) {
656  if (IndirCalls.empty())
657  return;
658  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
659  for (auto I : IndirCalls) {
660  IRBuilder<> IRB(I);
661  CallSite CS(I);
662  Value *Callee = CS.getCalledValue();
663  if (isa<InlineAsm>(Callee))
664  continue;
665  IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
666  }
667 }
668 
669 // For every switch statement we insert a call:
670 // __sanitizer_cov_trace_switch(CondValue,
671 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
672 
673 void SanitizerCoverageModule::InjectTraceForSwitch(
674  Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
675  for (auto I : SwitchTraceTargets) {
676  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
677  IRBuilder<> IRB(I);
678  SmallVector<Constant *, 16> Initializers;
679  Value *Cond = SI->getCondition();
680  if (Cond->getType()->getScalarSizeInBits() >
681  Int64Ty->getScalarSizeInBits())
682  continue;
683  Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
684  Initializers.push_back(
685  ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
686  if (Cond->getType()->getScalarSizeInBits() <
687  Int64Ty->getScalarSizeInBits())
688  Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
689  for (auto It : SI->cases()) {
690  Constant *C = It.getCaseValue();
691  if (C->getType()->getScalarSizeInBits() <
692  Int64Ty->getScalarSizeInBits())
693  C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
694  Initializers.push_back(C);
695  }
696  llvm::sort(Initializers.begin() + 2, Initializers.end(),
697  [](const Constant *A, const Constant *B) {
698  return cast<ConstantInt>(A)->getLimitedValue() <
699  cast<ConstantInt>(B)->getLimitedValue();
700  });
701  ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
702  GlobalVariable *GV = new GlobalVariable(
703  *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
704  ConstantArray::get(ArrayOfInt64Ty, Initializers),
705  "__sancov_gen_cov_switch_values");
706  IRB.CreateCall(SanCovTraceSwitchFunction,
707  {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
708  }
709  }
710 }
711 
712 void SanitizerCoverageModule::InjectTraceForDiv(
713  Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
714  for (auto BO : DivTraceTargets) {
715  IRBuilder<> IRB(BO);
716  Value *A1 = BO->getOperand(1);
717  if (isa<ConstantInt>(A1)) continue;
718  if (!A1->getType()->isIntegerTy())
719  continue;
720  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
721  int CallbackIdx = TypeSize == 32 ? 0 :
722  TypeSize == 64 ? 1 : -1;
723  if (CallbackIdx < 0) continue;
724  auto Ty = Type::getIntNTy(*C, TypeSize);
725  IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
726  {IRB.CreateIntCast(A1, Ty, true)});
727  }
728 }
729 
730 void SanitizerCoverageModule::InjectTraceForGep(
731  Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
732  for (auto GEP : GepTraceTargets) {
733  IRBuilder<> IRB(GEP);
734  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
735  if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
736  IRB.CreateCall(SanCovTraceGepFunction,
737  {IRB.CreateIntCast(*I, IntptrTy, true)});
738  }
739 }
740 
741 void SanitizerCoverageModule::InjectTraceForCmp(
742  Function &, ArrayRef<Instruction *> CmpTraceTargets) {
743  for (auto I : CmpTraceTargets) {
744  if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
745  IRBuilder<> IRB(ICMP);
746  Value *A0 = ICMP->getOperand(0);
747  Value *A1 = ICMP->getOperand(1);
748  if (!A0->getType()->isIntegerTy())
749  continue;
750  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
751  int CallbackIdx = TypeSize == 8 ? 0 :
752  TypeSize == 16 ? 1 :
753  TypeSize == 32 ? 2 :
754  TypeSize == 64 ? 3 : -1;
755  if (CallbackIdx < 0) continue;
756  // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
757  auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
758  bool FirstIsConst = isa<ConstantInt>(A0);
759  bool SecondIsConst = isa<ConstantInt>(A1);
760  // If both are const, then we don't need such a comparison.
761  if (FirstIsConst && SecondIsConst) continue;
762  // If only one is const, then make it the first callback argument.
763  if (FirstIsConst || SecondIsConst) {
764  CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
765  if (SecondIsConst)
766  std::swap(A0, A1);
767  }
768 
769  auto Ty = Type::getIntNTy(*C, TypeSize);
770  IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
771  IRB.CreateIntCast(A1, Ty, true)});
772  }
773  }
774 }
775 
776 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
777  size_t Idx,
778  bool IsLeafFunc) {
780  bool IsEntryBB = &BB == &F.getEntryBlock();
781  DebugLoc EntryLoc;
782  if (IsEntryBB) {
783  if (auto SP = F.getSubprogram())
784  EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
785  // Keep static allocas and llvm.localescape calls in the entry block. Even
786  // if we aren't splitting the block, it's nice for allocas to be before
787  // calls.
788  IP = PrepareToSplitEntryBlock(BB, IP);
789  } else {
790  EntryLoc = IP->getDebugLoc();
791  }
792 
793  IRBuilder<> IRB(&*IP);
794  IRB.SetCurrentDebugLocation(EntryLoc);
795  if (Options.TracePC) {
796  IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
797  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
798  }
799  if (Options.TracePCGuard) {
800  auto GuardPtr = IRB.CreateIntToPtr(
801  IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
802  ConstantInt::get(IntptrTy, Idx * 4)),
803  Int32PtrTy);
804  IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
805  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
806  }
807  if (Options.Inline8bitCounters) {
808  auto CounterPtr = IRB.CreateGEP(
809  Function8bitCounterArray,
810  {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
811  auto Load = IRB.CreateLoad(CounterPtr);
812  auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
813  auto Store = IRB.CreateStore(Inc, CounterPtr);
814  SetNoSanitizeMetadata(Load);
815  SetNoSanitizeMetadata(Store);
816  }
817  if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
818  // Check stack depth. If it's the deepest so far, record it.
819  Function *GetFrameAddr =
820  Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
821  auto FrameAddrPtr =
822  IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
823  auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
824  auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
825  auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
826  auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
827  IRBuilder<> ThenIRB(ThenTerm);
828  auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
829  SetNoSanitizeMetadata(LowestStack);
830  SetNoSanitizeMetadata(Store);
831  }
832 }
833 
834 std::string
835 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
836  if (TargetTriple.getObjectFormat() == Triple::COFF) {
837  if (Section == SanCovCountersSectionName)
838  return ".SCOV$CM";
839  if (Section == SanCovPCsSectionName)
840  return ".SCOVP$M";
841  return ".SCOV$GM"; // For SanCovGuardsSectionName.
842  }
843  if (TargetTriple.isOSBinFormatMachO())
844  return "__DATA,__" + Section;
845  return "__" + Section;
846 }
847 
848 std::string
849 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
850  if (TargetTriple.isOSBinFormatMachO())
851  return "\1section$start$__DATA$__" + Section;
852  return "__start___" + Section;
853 }
854 
855 std::string
856 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
857  if (TargetTriple.isOSBinFormatMachO())
858  return "\1section$end$__DATA$__" + Section;
859  return "__stop___" + Section;
860 }
861 
862 
864 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
865  "SanitizerCoverage: TODO."
866  "ModulePass",
867  false, false)
870 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
871  "SanitizerCoverage: TODO."
872  "ModulePass",
873  false, false)
875  const SanitizerCoverageOptions &Options) {
876  return new SanitizerCoverageModule(Options);
877 }
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
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:1764
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
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:54
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:454
static const char *const SanCovPCsInitName
Available for inspection, not emission.
Definition: GlobalValue.h:50
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
void addOperand(MDNode *M)
Definition: Metadata.cpp:1087
static const char *const SanCovGuardsSectionName
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:254
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
const Instruction * 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
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
A tuple of MDNodes.
Definition: Metadata.h:1326
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:364
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
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:743
static const char *const SanCovLowestStackName
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:974
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:1333
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1636
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
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
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:843
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:1317
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:419
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:219
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:236
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
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:978
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1386
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:265
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:1710
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
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 setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:445
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
Comdat * GetOrCreateFunctionComdat(Function &F, Triple &T, const std::string &ModuleId)
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:1687
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
Instruction * 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 ...
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:581
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
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:18
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:1631
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 &)
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable&#39;s name.
Definition: Mangler.cpp:112
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
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
Root of the metadata hierarchy.
Definition: Metadata.h:58
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
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:1883