LLVM  9.0.0svn
SanitizerCoverage.cpp
Go to the documentation of this file.
1 //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/IR/CFG.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Constant.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/InlineAsm.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Mangler.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<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
215  Type *Ty);
216 
217  void SetNoSanitizeMetadata(Instruction *I) {
218  I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
219  MDNode::get(*C, None));
220  }
221 
222  std::string getSectionName(const std::string &Section) const;
223  std::string getSectionStart(const std::string &Section) const;
224  std::string getSectionEnd(const std::string &Section) const;
225  Function *SanCovTracePCIndir;
226  Function *SanCovTracePC, *SanCovTracePCGuard;
227  Function *SanCovTraceCmpFunction[4];
228  Function *SanCovTraceConstCmpFunction[4];
229  Function *SanCovTraceDivFunction[2];
230  Function *SanCovTraceGepFunction;
231  Function *SanCovTraceSwitchFunction;
232  GlobalVariable *SanCovLowestStack;
233  InlineAsm *EmptyAsm;
234  Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
235  *Int16Ty, *Int8Ty, *Int8PtrTy;
236  Module *CurModule;
237  std::string CurModuleUniqueId;
238  Triple TargetTriple;
239  LLVMContext *C;
240  const DataLayout *DL;
241 
242  GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
243  GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
244  GlobalVariable *FunctionPCsArray; // for pc-table.
245  SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
246  SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
247 
248  SanitizerCoverageOptions Options;
249 };
250 
251 } // namespace
252 
253 std::pair<Value *, Value *>
254 SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
255  Type *Ty) {
256  GlobalVariable *SecStart =
257  new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
258  getSectionStart(Section));
260  GlobalVariable *SecEnd =
262  nullptr, getSectionEnd(Section));
264  IRBuilder<> IRB(M.getContext());
265  Value *SecEndPtr = IRB.CreatePointerCast(SecEnd, Ty);
266  if (!TargetTriple.isOSBinFormatCOFF())
267  return std::make_pair(IRB.CreatePointerCast(SecStart, Ty), SecEndPtr);
268 
269  // Account for the fact that on windows-msvc __start_* symbols actually
270  // point to a uint64_t before the start of the array.
271  auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
272  auto GEP = IRB.CreateGEP(SecStartI8Ptr,
273  ConstantInt::get(IntptrTy, sizeof(uint64_t)));
274  return std::make_pair(IRB.CreatePointerCast(GEP, Ty), SecEndPtr);
275 }
276 
277 Function *SanitizerCoverageModule::CreateInitCallsForSections(
278  Module &M, const char *InitFunctionName, Type *Ty,
279  const char *Section) {
280  auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
281  auto SecStart = SecStartEnd.first;
282  auto SecEnd = SecStartEnd.second;
283  Function *CtorFunc;
284  std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
285  M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty}, {SecStart, SecEnd});
286 
287  if (TargetTriple.supportsCOMDAT()) {
288  // Use comdat to dedup CtorFunc.
289  CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
290  appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
291  } else {
293  }
294 
295  if (TargetTriple.isOSBinFormatCOFF()) {
296  // In COFF files, if the contructors are set as COMDAT (they are because
297  // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
298  // functions and data) is used, the constructors get stripped. To prevent
299  // this, give the constructors weak ODR linkage and ensure the linker knows
300  // to include the sancov constructor. This way the linker can deduplicate
301  // the constructors but always leave one copy.
303  appendToUsed(M, CtorFunc);
304  }
305  return CtorFunc;
306 }
307 
308 bool SanitizerCoverageModule::runOnModule(Module &M) {
310  return false;
311  C = &(M.getContext());
312  DL = &M.getDataLayout();
313  CurModule = &M;
314  CurModuleUniqueId = getUniqueModuleId(CurModule);
315  TargetTriple = Triple(M.getTargetTriple());
316  FunctionGuardArray = nullptr;
317  Function8bitCounterArray = nullptr;
318  FunctionPCsArray = nullptr;
319  IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
320  IntptrPtrTy = PointerType::getUnqual(IntptrTy);
321  Type *VoidTy = Type::getVoidTy(*C);
322  IRBuilder<> IRB(*C);
323  Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
324  Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
325  Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
326  Int64Ty = IRB.getInt64Ty();
327  Int32Ty = IRB.getInt32Ty();
328  Int16Ty = IRB.getInt16Ty();
329  Int8Ty = IRB.getInt8Ty();
330 
331  SanCovTracePCIndir = checkSanitizerInterfaceFunction(
332  M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
333  SanCovTraceCmpFunction[0] =
335  SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
336  SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
337  M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
338  IRB.getInt16Ty()));
339  SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
340  M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
341  IRB.getInt32Ty()));
342  SanCovTraceCmpFunction[3] =
344  SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
345 
346  SanCovTraceConstCmpFunction[0] =
348  SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
349  SanCovTraceConstCmpFunction[1] =
351  SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
352  SanCovTraceConstCmpFunction[2] =
354  SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
355  SanCovTraceConstCmpFunction[3] =
357  SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
358 
359  SanCovTraceDivFunction[0] =
361  SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
362  SanCovTraceDivFunction[1] =
364  SanCovTraceDiv8, VoidTy, Int64Ty));
365  SanCovTraceGepFunction =
367  SanCovTraceGep, VoidTy, IntptrTy));
368  SanCovTraceSwitchFunction =
370  SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
371 
372  Constant *SanCovLowestStackConstant =
373  M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
374  SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
375  SanCovLowestStack->setThreadLocalMode(
376  GlobalValue::ThreadLocalMode::InitialExecTLSModel);
377  if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
378  SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
379 
380  // Make sure smaller parameters are zero-extended to i64 as required by the
381  // x86_64 ABI.
382  if (TargetTriple.getArch() == Triple::x86_64) {
383  for (int i = 0; i < 3; i++) {
384  SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
385  SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
386  SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
387  SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
388  }
389  SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
390  }
391 
392 
393  // We insert an empty inline asm after cov callbacks to avoid callback merge.
394  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
395  StringRef(""), StringRef(""),
396  /*hasSideEffects=*/true);
397 
398  SanCovTracePC = checkSanitizerInterfaceFunction(
399  M.getOrInsertFunction(SanCovTracePCName, VoidTy));
401  SanCovTracePCGuardName, VoidTy, Int32PtrTy));
402 
403  for (auto &F : M)
404  runOnFunction(F);
405 
406  Function *Ctor = nullptr;
407 
408  if (FunctionGuardArray)
409  Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
410  SanCovGuardsSectionName);
411  if (Function8bitCounterArray)
412  Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
413  SanCovCountersSectionName);
414  if (Ctor && Options.PCTable) {
415  auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
416  Function *InitFunction = declareSanitizerInitFunction(
417  M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
418  IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
419  IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
420  }
421  // We don't reference these arrays directly in any of our runtime functions,
422  // so we need to prevent them from being dead stripped.
423  if (TargetTriple.isOSBinFormatMachO())
424  appendToUsed(M, GlobalsToAppendToUsed);
425  appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
426  return true;
427 }
428 
429 // True if block has successors and it dominates all of them.
430 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
431  if (succ_begin(BB) == succ_end(BB))
432  return false;
433 
434  for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
435  if (!DT->dominates(BB, SUCC))
436  return false;
437  }
438 
439  return true;
440 }
441 
442 // True if block has predecessors and it postdominates all of them.
443 static bool isFullPostDominator(const BasicBlock *BB,
444  const PostDominatorTree *PDT) {
445  if (pred_begin(BB) == pred_end(BB))
446  return false;
447 
448  for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
449  if (!PDT->dominates(BB, PRED))
450  return false;
451  }
452 
453  return true;
454 }
455 
456 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
457  const DominatorTree *DT,
458  const PostDominatorTree *PDT,
459  const SanitizerCoverageOptions &Options) {
460  // Don't insert coverage for unreachable blocks: we will never call
461  // __sanitizer_cov() for them, so counting them in
462  // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
463  // percentage. Also, unreachable instructions frequently have no debug
464  // locations.
465  if (isa<UnreachableInst>(BB->getTerminator()))
466  return false;
467 
468  // Don't insert coverage into blocks without a valid insertion point
469  // (catchswitch blocks).
470  if (BB->getFirstInsertionPt() == BB->end())
471  return false;
472 
473  if (Options.NoPrune || &F.getEntryBlock() == BB)
474  return true;
475 
477  &F.getEntryBlock() != BB)
478  return false;
479 
480  // Do not instrument full dominators, or full post-dominators with multiple
481  // predecessors.
482  return !isFullDominator(BB, DT)
483  && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
484 }
485 
487  if (F.empty())
488  return false;
489  if (F.getName().find(".module_ctor") != std::string::npos)
490  return false; // Should not instrument sanitizer init functions.
491  if (F.getName().startswith("__sanitizer_"))
492  return false; // Don't instrument __sanitizer_* callbacks.
493  // Don't touch available_externally functions, their actual body is elewhere.
495  return false;
496  // Don't instrument MSVC CRT configuration helpers. They may run before normal
497  // initialization.
498  if (F.getName() == "__local_stdio_printf_options" ||
499  F.getName() == "__local_stdio_scanf_options")
500  return false;
501  if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
502  return false;
503  // Don't instrument functions using SEH for now. Splitting basic blocks like
504  // we do for coverage breaks WinEHPrepare.
505  // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
506  if (F.hasPersonalityFn() &&
508  return false;
512  SmallVector<BasicBlock *, 16> BlocksToInstrument;
513  SmallVector<Instruction *, 8> CmpTraceTargets;
514  SmallVector<Instruction *, 8> SwitchTraceTargets;
515  SmallVector<BinaryOperator *, 8> DivTraceTargets;
516  SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
517 
518  const DominatorTree *DT =
519  &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
520  const PostDominatorTree *PDT =
521  &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
522  bool IsLeafFunc = true;
523 
524  for (auto &BB : F) {
525  if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
526  BlocksToInstrument.push_back(&BB);
527  for (auto &Inst : BB) {
528  if (Options.IndirectCalls) {
529  CallSite CS(&Inst);
530  if (CS && !CS.getCalledFunction())
531  IndirCalls.push_back(&Inst);
532  }
533  if (Options.TraceCmp) {
534  if (isa<ICmpInst>(&Inst))
535  CmpTraceTargets.push_back(&Inst);
536  if (isa<SwitchInst>(&Inst))
537  SwitchTraceTargets.push_back(&Inst);
538  }
539  if (Options.TraceDiv)
540  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
541  if (BO->getOpcode() == Instruction::SDiv ||
542  BO->getOpcode() == Instruction::UDiv)
543  DivTraceTargets.push_back(BO);
544  if (Options.TraceGep)
545  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
546  GepTraceTargets.push_back(GEP);
547  if (Options.StackDepth)
548  if (isa<InvokeInst>(Inst) ||
549  (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
550  IsLeafFunc = false;
551  }
552  }
553 
554  InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
555  InjectCoverageForIndirectCalls(F, IndirCalls);
556  InjectTraceForCmp(F, CmpTraceTargets);
557  InjectTraceForSwitch(F, SwitchTraceTargets);
558  InjectTraceForDiv(F, DivTraceTargets);
559  InjectTraceForGep(F, GepTraceTargets);
560  return true;
561 }
562 
563 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
564  size_t NumElements, Function &F, Type *Ty, const char *Section) {
565  ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
566  auto Array = new GlobalVariable(
567  *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
568  Constant::getNullValue(ArrayTy), "__sancov_gen_");
569 
570  if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
571  if (auto Comdat =
572  GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
573  Array->setComdat(Comdat);
574  Array->setSection(getSectionName(Section));
575  Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
576  : Ty->getPrimitiveSizeInBits() / 8);
577  GlobalsToAppendToUsed.push_back(Array);
578  GlobalsToAppendToCompilerUsed.push_back(Array);
580  Array->addMetadata(LLVMContext::MD_associated, *MD);
581 
582  return Array;
583 }
584 
586 SanitizerCoverageModule::CreatePCArray(Function &F,
587  ArrayRef<BasicBlock *> AllBlocks) {
588  size_t N = AllBlocks.size();
589  assert(N);
592  for (size_t i = 0; i < N; i++) {
593  if (&F.getEntryBlock() == AllBlocks[i]) {
594  PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
595  PCs.push_back((Constant *)IRB.CreateIntToPtr(
596  ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
597  } else {
598  PCs.push_back((Constant *)IRB.CreatePointerCast(
599  BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
600  PCs.push_back((Constant *)IRB.CreateIntToPtr(
601  ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
602  }
603  }
604  auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
605  SanCovPCsSectionName);
606  PCArray->setInitializer(
607  ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
608  PCArray->setConstant(true);
609 
610  return PCArray;
611 }
612 
613 void SanitizerCoverageModule::CreateFunctionLocalArrays(
614  Function &F, ArrayRef<BasicBlock *> AllBlocks) {
615  if (Options.TracePCGuard)
616  FunctionGuardArray = CreateFunctionLocalArrayInSection(
617  AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
618 
619  if (Options.Inline8bitCounters)
620  Function8bitCounterArray = CreateFunctionLocalArrayInSection(
621  AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
622 
623  if (Options.PCTable)
624  FunctionPCsArray = CreatePCArray(F, AllBlocks);
625 }
626 
627 bool SanitizerCoverageModule::InjectCoverage(Function &F,
628  ArrayRef<BasicBlock *> AllBlocks,
629  bool IsLeafFunc) {
630  if (AllBlocks.empty()) return false;
631  CreateFunctionLocalArrays(F, AllBlocks);
632  for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
633  InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
634  return true;
635 }
636 
637 // On every indirect call we call a run-time function
638 // __sanitizer_cov_indir_call* with two parameters:
639 // - callee address,
640 // - global cache array that contains CacheSize pointers (zero-initialized).
641 // The cache is used to speed up recording the caller-callee pairs.
642 // The address of the caller is passed implicitly via caller PC.
643 // CacheSize is encoded in the name of the run-time function.
644 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
645  Function &F, ArrayRef<Instruction *> IndirCalls) {
646  if (IndirCalls.empty())
647  return;
648  assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
649  for (auto I : IndirCalls) {
650  IRBuilder<> IRB(I);
651  CallSite CS(I);
652  Value *Callee = CS.getCalledValue();
653  if (isa<InlineAsm>(Callee))
654  continue;
655  IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
656  }
657 }
658 
659 // For every switch statement we insert a call:
660 // __sanitizer_cov_trace_switch(CondValue,
661 // {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
662 
663 void SanitizerCoverageModule::InjectTraceForSwitch(
664  Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
665  for (auto I : SwitchTraceTargets) {
666  if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
667  IRBuilder<> IRB(I);
668  SmallVector<Constant *, 16> Initializers;
669  Value *Cond = SI->getCondition();
670  if (Cond->getType()->getScalarSizeInBits() >
671  Int64Ty->getScalarSizeInBits())
672  continue;
673  Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
674  Initializers.push_back(
675  ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
676  if (Cond->getType()->getScalarSizeInBits() <
677  Int64Ty->getScalarSizeInBits())
678  Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
679  for (auto It : SI->cases()) {
680  Constant *C = It.getCaseValue();
681  if (C->getType()->getScalarSizeInBits() <
682  Int64Ty->getScalarSizeInBits())
683  C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
684  Initializers.push_back(C);
685  }
686  llvm::sort(Initializers.begin() + 2, Initializers.end(),
687  [](const Constant *A, const Constant *B) {
688  return cast<ConstantInt>(A)->getLimitedValue() <
689  cast<ConstantInt>(B)->getLimitedValue();
690  });
691  ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
692  GlobalVariable *GV = new GlobalVariable(
693  *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
694  ConstantArray::get(ArrayOfInt64Ty, Initializers),
695  "__sancov_gen_cov_switch_values");
696  IRB.CreateCall(SanCovTraceSwitchFunction,
697  {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
698  }
699  }
700 }
701 
702 void SanitizerCoverageModule::InjectTraceForDiv(
703  Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
704  for (auto BO : DivTraceTargets) {
705  IRBuilder<> IRB(BO);
706  Value *A1 = BO->getOperand(1);
707  if (isa<ConstantInt>(A1)) continue;
708  if (!A1->getType()->isIntegerTy())
709  continue;
710  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
711  int CallbackIdx = TypeSize == 32 ? 0 :
712  TypeSize == 64 ? 1 : -1;
713  if (CallbackIdx < 0) continue;
714  auto Ty = Type::getIntNTy(*C, TypeSize);
715  IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
716  {IRB.CreateIntCast(A1, Ty, true)});
717  }
718 }
719 
720 void SanitizerCoverageModule::InjectTraceForGep(
721  Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
722  for (auto GEP : GepTraceTargets) {
723  IRBuilder<> IRB(GEP);
724  for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
725  if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
726  IRB.CreateCall(SanCovTraceGepFunction,
727  {IRB.CreateIntCast(*I, IntptrTy, true)});
728  }
729 }
730 
731 void SanitizerCoverageModule::InjectTraceForCmp(
732  Function &, ArrayRef<Instruction *> CmpTraceTargets) {
733  for (auto I : CmpTraceTargets) {
734  if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
735  IRBuilder<> IRB(ICMP);
736  Value *A0 = ICMP->getOperand(0);
737  Value *A1 = ICMP->getOperand(1);
738  if (!A0->getType()->isIntegerTy())
739  continue;
740  uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
741  int CallbackIdx = TypeSize == 8 ? 0 :
742  TypeSize == 16 ? 1 :
743  TypeSize == 32 ? 2 :
744  TypeSize == 64 ? 3 : -1;
745  if (CallbackIdx < 0) continue;
746  // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
747  auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
748  bool FirstIsConst = isa<ConstantInt>(A0);
749  bool SecondIsConst = isa<ConstantInt>(A1);
750  // If both are const, then we don't need such a comparison.
751  if (FirstIsConst && SecondIsConst) continue;
752  // If only one is const, then make it the first callback argument.
753  if (FirstIsConst || SecondIsConst) {
754  CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
755  if (SecondIsConst)
756  std::swap(A0, A1);
757  }
758 
759  auto Ty = Type::getIntNTy(*C, TypeSize);
760  IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
761  IRB.CreateIntCast(A1, Ty, true)});
762  }
763  }
764 }
765 
766 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
767  size_t Idx,
768  bool IsLeafFunc) {
770  bool IsEntryBB = &BB == &F.getEntryBlock();
771  DebugLoc EntryLoc;
772  if (IsEntryBB) {
773  if (auto SP = F.getSubprogram())
774  EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
775  // Keep static allocas and llvm.localescape calls in the entry block. Even
776  // if we aren't splitting the block, it's nice for allocas to be before
777  // calls.
778  IP = PrepareToSplitEntryBlock(BB, IP);
779  } else {
780  EntryLoc = IP->getDebugLoc();
781  }
782 
783  IRBuilder<> IRB(&*IP);
784  IRB.SetCurrentDebugLocation(EntryLoc);
785  if (Options.TracePC) {
786  IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
787  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
788  }
789  if (Options.TracePCGuard) {
790  auto GuardPtr = IRB.CreateIntToPtr(
791  IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
792  ConstantInt::get(IntptrTy, Idx * 4)),
793  Int32PtrTy);
794  IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
795  IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
796  }
797  if (Options.Inline8bitCounters) {
798  auto CounterPtr = IRB.CreateGEP(
799  Function8bitCounterArray,
800  {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
801  auto Load = IRB.CreateLoad(CounterPtr);
802  auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
803  auto Store = IRB.CreateStore(Inc, CounterPtr);
804  SetNoSanitizeMetadata(Load);
805  SetNoSanitizeMetadata(Store);
806  }
807  if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
808  // Check stack depth. If it's the deepest so far, record it.
809  Function *GetFrameAddr =
810  Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
811  auto FrameAddrPtr =
812  IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
813  auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
814  auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
815  auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
816  auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
817  IRBuilder<> ThenIRB(ThenTerm);
818  auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
819  SetNoSanitizeMetadata(LowestStack);
820  SetNoSanitizeMetadata(Store);
821  }
822 }
823 
824 std::string
825 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
826  if (TargetTriple.isOSBinFormatCOFF()) {
827  if (Section == SanCovCountersSectionName)
828  return ".SCOV$CM";
829  if (Section == SanCovPCsSectionName)
830  return ".SCOVP$M";
831  return ".SCOV$GM"; // For SanCovGuardsSectionName.
832  }
833  if (TargetTriple.isOSBinFormatMachO())
834  return "__DATA,__" + Section;
835  return "__" + Section;
836 }
837 
838 std::string
839 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
840  if (TargetTriple.isOSBinFormatMachO())
841  return "\1section$start$__DATA$__" + Section;
842  return "__start___" + Section;
843 }
844 
845 std::string
846 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
847  if (TargetTriple.isOSBinFormatMachO())
848  return "\1section$end$__DATA$__" + Section;
849  return "__stop___" + Section;
850 }
851 
852 
854 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
855  "SanitizerCoverage: TODO."
856  "ModulePass",
857  false, false)
860 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
861  "SanitizerCoverage: TODO."
862  "ModulePass",
863  false, false)
865  const SanitizerCoverageOptions &Options) {
866  return new SanitizerCoverageModule(Options);
867 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:238
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:110
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:661
static const uint64_t SanCtorAndDtorPriority
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:21
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)
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static const char *const SanCovTraceConstCmp1
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1854
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1356
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:53
static const char *const SanCovPCsInitName
Available for inspection, not emission.
Definition: GlobalValue.h:49
static bool isFullPostDominator(const BasicBlock *BB, const PostDominatorTree *PDT)
static const char *const SanCovGuardsSectionName
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
Externally visible function.
Definition: GlobalValue.h:48
bool isInterposable() const
Return true if this global&#39;s definition can be substituted with an arbitrary definition at link time...
Definition: GlobalValue.h:419
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:33
Metadata node.
Definition: Metadata.h:863
F(f)
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:176
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:137
static IntegerType * getInt16Ty(LLVMContext &C)
Definition: Type.cpp:174
static const char *const SanCovTraceSwitchName
static const char *const SanCovTraceConstCmp2
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:982
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:264
static const char *const SanCov8bitCountersInitName
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:370
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:196
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
static const char *const SanCovLowestStackName
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1013
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:102
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1385
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1726
ValTy * getCalledValue() const
Return the pointer to function that is being called.
Definition: CallSite.h:99
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:266
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
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:368
void setComdat(Comdat *C)
Definition: GlobalObject.h:102
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
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:701
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
Definition: IRBuilder.h:150
LinkageTypes getLinkage() const
Definition: GlobalValue.h:450
static const char *const SanCovTracePCGuardName
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
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:1019
INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov", "SanitizerCoverage: TODO." "ModulePass", false, false) INITIALIZE_PASS_END(SanitizerCoverageModule
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:105
const BasicBlock & getEntryBlock() const
Definition: Function.h:639
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:873
static const char *const SanCovTracePCIndirName
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1165
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:422
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:216
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:233
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
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:68
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1507
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:1433
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
This is an important base class in LLVM.
Definition: Constant.h:41
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:128
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:223
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:112
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:160
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:296
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
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:318
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:192
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:483
static const char *const SanCovTraceCmp8
size_t size() const
Definition: SmallVector.h:52
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:1225
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:43
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1115
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1457
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:481
iterator end()
Definition: BasicBlock.h:270
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:129
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:1800
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:348
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:845
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:248
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:179
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:83
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:444
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
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:1529
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:1777
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:132
Constant * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition: Module.cpp:205
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
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:213
#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:224
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:580
ModulePass * createSanitizerCoverageModulePass(const SanitizerCoverageOptions &Options=SanitizerCoverageOptions())
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1973
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:42
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:1721
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:106
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:114
static const char *const SanCovTracePCGuardInitName
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
LLVM Value Representation.
Definition: Value.h:72
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1298
void initializeSanitizerCoverageModulePass(PassRegistry &)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:259
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:297
static const char *const SanCovTraceConstCmp4
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:173
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
IntegerType * Int32Ty