xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 5971f18133cbdece6012b3e0f54ae85877e4306f)
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 that works with AddressSanitizer
11 // and potentially with other Sanitizers.
12 //
13 // We create a Guard variable with the same linkage
14 // as the function and inject this code into the entry block (SCK_Function)
15 // or all blocks (SCK_BB):
16 // if (Guard < 0) {
17 //    __sanitizer_cov(&Guard);
18 // }
19 // The accesses to Guard are atomic. The rest of the logic is
20 // in __sanitizer_cov (it's fine to call it more than once).
21 //
22 // With SCK_Edge we also split critical edges this effectively
23 // instrumenting all edges.
24 //
25 // This coverage implementation provides very limited data:
26 // it only tells if a given function (block) was ever executed. No counters.
27 // But for many use cases this is what we need and the added slowdown small.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/IR/CFG.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/DebugInfo.h"
38 #include "llvm/IR/Dominators.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/MDBuilder.h"
44 #include "llvm/IR/Module.h"
45 #include "llvm/IR/Type.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Transforms/Instrumentation.h"
50 #include "llvm/Transforms/Scalar.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/ModuleUtils.h"
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "sancov"
57 
58 static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
59 static const char *const kSanCovName = "__sanitizer_cov";
60 static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
61 static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
62 static const char *const kSanCovTracePCIndir = "__sanitizer_cov_trace_pc_indir";
63 static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
64 static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
65 static const char *const kSanCovTracePC = "__sanitizer_cov_trace_pc";
66 static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
67 static const char *const kSanCovTraceSwitch = "__sanitizer_cov_trace_switch";
68 static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
69 static const uint64_t    kSanCtorAndDtorPriority = 2;
70 
71 static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
72        cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
73                 "3: all blocks and critical edges, "
74                 "4: above plus indirect calls"),
75        cl::Hidden, cl::init(0));
76 
77 static cl::opt<unsigned> ClCoverageBlockThreshold(
78     "sanitizer-coverage-block-threshold",
79     cl::desc("Use a callback with a guard check inside it if there are"
80              " more than this number of blocks."),
81     cl::Hidden, cl::init(500));
82 
83 static cl::opt<bool>
84     ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
85                           cl::desc("Experimental basic-block tracing: insert "
86                                    "callbacks at every basic block"),
87                           cl::Hidden, cl::init(false));
88 
89 static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
90                                            cl::desc("Experimental pc tracing"),
91                                            cl::Hidden, cl::init(false));
92 
93 static cl::opt<bool>
94     ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
95                              cl::desc("Experimental tracing of CMP and similar "
96                                       "instructions"),
97                              cl::Hidden, cl::init(false));
98 
99 static cl::opt<bool> ClPruneBlocks(
100     "sanitizer-coverage-prune-blocks",
101     cl::desc("Reduce the number of instrumented blocks (experimental)"),
102     cl::Hidden, cl::init(false));
103 
104 // Experimental 8-bit counters used as an additional search heuristic during
105 // coverage-guided fuzzing.
106 // The counters are not thread-friendly:
107 //   - contention on these counters may cause significant slowdown;
108 //   - the counter updates are racy and the results may be inaccurate.
109 // They are also inaccurate due to 8-bit integer overflow.
110 static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
111                                        cl::desc("Experimental 8-bit counters"),
112                                        cl::Hidden, cl::init(false));
113 
114 namespace {
115 
116 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
117   SanitizerCoverageOptions Res;
118   switch (LegacyCoverageLevel) {
119   case 0:
120     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
121     break;
122   case 1:
123     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
124     break;
125   case 2:
126     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
127     break;
128   case 3:
129     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
130     break;
131   case 4:
132     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
133     Res.IndirectCalls = true;
134     break;
135   }
136   return Res;
137 }
138 
139 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
140   // Sets CoverageType and IndirectCalls.
141   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
142   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
143   Options.IndirectCalls |= CLOpts.IndirectCalls;
144   Options.TraceBB |= ClExperimentalTracing;
145   Options.TraceCmp |= ClExperimentalCMPTracing;
146   Options.Use8bitCounters |= ClUse8bitCounters;
147   Options.TracePC |= ClExperimentalTracePC;
148   return Options;
149 }
150 
151 class SanitizerCoverageModule : public ModulePass {
152  public:
153   SanitizerCoverageModule(
154       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
155       : ModulePass(ID), Options(OverrideFromCL(Options)) {}
156   bool runOnModule(Module &M) override;
157   bool runOnFunction(Function &F);
158   static char ID;  // Pass identification, replacement for typeid
159   const char *getPassName() const override {
160     return "SanitizerCoverageModule";
161   }
162 
163  private:
164   void InjectCoverageForIndirectCalls(Function &F,
165                                       ArrayRef<Instruction *> IndirCalls);
166   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
167   void InjectTraceForSwitch(Function &F,
168                             ArrayRef<Instruction *> SwitchTraceTargets);
169   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
170   void SetNoSanitizeMetadata(Instruction *I);
171   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
172   unsigned NumberOfInstrumentedBlocks() {
173     return SanCovFunction->getNumUses() +
174            SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
175            SanCovTraceEnter->getNumUses();
176   }
177   Function *SanCovFunction;
178   Function *SanCovWithCheckFunction;
179   Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
180   Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC;
181   Function *SanCovTraceCmpFunction;
182   Function *SanCovTraceSwitchFunction;
183   InlineAsm *EmptyAsm;
184   Type *IntptrTy, *Int64Ty, *Int64PtrTy;
185   Module *CurModule;
186   LLVMContext *C;
187   const DataLayout *DL;
188 
189   GlobalVariable *GuardArray;
190   GlobalVariable *EightBitCounterArray;
191 
192   SanitizerCoverageOptions Options;
193 };
194 
195 }  // namespace
196 
197 bool SanitizerCoverageModule::runOnModule(Module &M) {
198   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
199     return false;
200   C = &(M.getContext());
201   DL = &M.getDataLayout();
202   CurModule = &M;
203   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
204   Type *VoidTy = Type::getVoidTy(*C);
205   IRBuilder<> IRB(*C);
206   Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
207   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
208   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
209   Int64Ty = IRB.getInt64Ty();
210 
211   SanCovFunction = checkSanitizerInterfaceFunction(
212       M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
213   SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
214       M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
215   SanCovTracePCIndir =
216       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
217           kSanCovTracePCIndir, VoidTy, IntptrTy, nullptr));
218   SanCovIndirCallFunction =
219       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
220           kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
221   SanCovTraceCmpFunction =
222       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
223           kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
224   SanCovTraceSwitchFunction =
225       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
226           kSanCovTraceSwitch, VoidTy, Int64Ty, Int64PtrTy, nullptr));
227 
228   // We insert an empty inline asm after cov callbacks to avoid callback merge.
229   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
230                             StringRef(""), StringRef(""),
231                             /*hasSideEffects=*/true);
232 
233   SanCovTracePC = checkSanitizerInterfaceFunction(
234       M.getOrInsertFunction(kSanCovTracePC, VoidTy, nullptr));
235   SanCovTraceEnter = checkSanitizerInterfaceFunction(
236       M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
237   SanCovTraceBB = checkSanitizerInterfaceFunction(
238       M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
239 
240   // At this point we create a dummy array of guards because we don't
241   // know how many elements we will need.
242   Type *Int32Ty = IRB.getInt32Ty();
243   Type *Int8Ty = IRB.getInt8Ty();
244 
245   GuardArray =
246       new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
247                          nullptr, "__sancov_gen_cov_tmp");
248   if (Options.Use8bitCounters)
249     EightBitCounterArray =
250         new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
251                            nullptr, "__sancov_gen_cov_tmp");
252 
253   for (auto &F : M)
254     runOnFunction(F);
255 
256   auto N = NumberOfInstrumentedBlocks();
257 
258   // Now we know how many elements we need. Create an array of guards
259   // with one extra element at the beginning for the size.
260   Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
261   GlobalVariable *RealGuardArray = new GlobalVariable(
262       M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
263       Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
264 
265 
266   // Replace the dummy array with the real one.
267   GuardArray->replaceAllUsesWith(
268       IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
269   GuardArray->eraseFromParent();
270 
271   GlobalVariable *RealEightBitCounterArray;
272   if (Options.Use8bitCounters) {
273     // Make sure the array is 16-aligned.
274     static const int kCounterAlignment = 16;
275     Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, kCounterAlignment));
276     RealEightBitCounterArray = new GlobalVariable(
277         M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
278         Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
279     RealEightBitCounterArray->setAlignment(kCounterAlignment);
280     EightBitCounterArray->replaceAllUsesWith(
281         IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
282     EightBitCounterArray->eraseFromParent();
283   }
284 
285   // Create variable for module (compilation unit) name
286   Constant *ModNameStrConst =
287       ConstantDataArray::getString(M.getContext(), M.getName(), true);
288   GlobalVariable *ModuleName =
289       new GlobalVariable(M, ModNameStrConst->getType(), true,
290                          GlobalValue::PrivateLinkage, ModNameStrConst);
291 
292   Function *CtorFunc;
293   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
294       M, kSanCovModuleCtorName, kSanCovModuleInitName,
295       {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
296       {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
297        ConstantInt::get(IntptrTy, N),
298        Options.Use8bitCounters
299            ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
300            : Constant::getNullValue(Int8PtrTy),
301        IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
302 
303   appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
304 
305   return true;
306 }
307 
308 static bool shouldInstrumentBlock(const BasicBlock *BB,
309                                   const DominatorTree *DT) {
310   if (!ClPruneBlocks)
311     return true;
312   if (succ_begin(BB) == succ_end(BB))
313     return true;
314 
315   // Check if BB dominates all its successors.
316   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
317     if (!DT->dominates(BB, SUCC))
318       return true;
319   }
320 
321   return false;
322 }
323 
324 bool SanitizerCoverageModule::runOnFunction(Function &F) {
325   if (F.empty()) return false;
326   if (F.getName().find(".module_ctor") != std::string::npos)
327     return false;  // Should not instrument sanitizer init functions.
328   // Don't instrument functions using SEH for now. Splitting basic blocks like
329   // we do for coverage breaks WinEHPrepare.
330   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
331   if (F.hasPersonalityFn() &&
332       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
333     return false;
334   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
335     SplitAllCriticalEdges(F);
336   SmallVector<Instruction*, 8> IndirCalls;
337   SmallVector<BasicBlock *, 16> BlocksToInstrument;
338   SmallVector<Instruction*, 8> CmpTraceTargets;
339   SmallVector<Instruction*, 8> SwitchTraceTargets;
340 
341   DominatorTree DT;
342   DT.recalculate(F);
343   for (auto &BB : F) {
344     if (shouldInstrumentBlock(&BB, &DT))
345       BlocksToInstrument.push_back(&BB);
346     for (auto &Inst : BB) {
347       if (Options.IndirectCalls) {
348         CallSite CS(&Inst);
349         if (CS && !CS.getCalledFunction())
350           IndirCalls.push_back(&Inst);
351       }
352       if (Options.TraceCmp) {
353         if (isa<ICmpInst>(&Inst))
354           CmpTraceTargets.push_back(&Inst);
355         if (isa<SwitchInst>(&Inst))
356           SwitchTraceTargets.push_back(&Inst);
357       }
358     }
359   }
360 
361   InjectCoverage(F, BlocksToInstrument);
362   InjectCoverageForIndirectCalls(F, IndirCalls);
363   InjectTraceForCmp(F, CmpTraceTargets);
364   InjectTraceForSwitch(F, SwitchTraceTargets);
365   return true;
366 }
367 
368 bool SanitizerCoverageModule::InjectCoverage(Function &F,
369                                              ArrayRef<BasicBlock *> AllBlocks) {
370   switch (Options.CoverageType) {
371   case SanitizerCoverageOptions::SCK_None:
372     return false;
373   case SanitizerCoverageOptions::SCK_Function:
374     InjectCoverageAtBlock(F, F.getEntryBlock(), false);
375     return true;
376   default: {
377     bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
378     for (auto BB : AllBlocks)
379       InjectCoverageAtBlock(F, *BB, UseCalls);
380     return true;
381   }
382   }
383 }
384 
385 // On every indirect call we call a run-time function
386 // __sanitizer_cov_indir_call* with two parameters:
387 //   - callee address,
388 //   - global cache array that contains kCacheSize pointers (zero-initialized).
389 //     The cache is used to speed up recording the caller-callee pairs.
390 // The address of the caller is passed implicitly via caller PC.
391 // kCacheSize is encoded in the name of the run-time function.
392 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
393     Function &F, ArrayRef<Instruction *> IndirCalls) {
394   if (IndirCalls.empty()) return;
395   const int kCacheSize = 16;
396   const int kCacheAlignment = 64;  // Align for better performance.
397   Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
398   for (auto I : IndirCalls) {
399     IRBuilder<> IRB(I);
400     CallSite CS(I);
401     Value *Callee = CS.getCalledValue();
402     if (isa<InlineAsm>(Callee)) continue;
403     GlobalVariable *CalleeCache = new GlobalVariable(
404         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
405         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
406     CalleeCache->setAlignment(kCacheAlignment);
407     if (Options.TracePC)
408       IRB.CreateCall(SanCovTracePCIndir,
409                      IRB.CreatePointerCast(Callee, IntptrTy));
410     else
411       IRB.CreateCall(SanCovIndirCallFunction,
412                      {IRB.CreatePointerCast(Callee, IntptrTy),
413                        IRB.CreatePointerCast(CalleeCache, IntptrTy)});
414   }
415 }
416 
417 // For every switch statement we insert a call:
418 // __sanitizer_cov_trace_switch(CondValue,
419 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
420 
421 void SanitizerCoverageModule::InjectTraceForSwitch(
422     Function &F, ArrayRef<Instruction *> SwitchTraceTargets) {
423   for (auto I : SwitchTraceTargets) {
424     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
425       IRBuilder<> IRB(I);
426       SmallVector<Constant *, 16> Initializers;
427       Value *Cond = SI->getCondition();
428       if (Cond->getType()->getScalarSizeInBits() >
429           Int64Ty->getScalarSizeInBits())
430         continue;
431       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
432       Initializers.push_back(
433           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
434       if (Cond->getType()->getScalarSizeInBits() <
435           Int64Ty->getScalarSizeInBits())
436         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
437       for (auto It: SI->cases()) {
438         Constant *C = It.getCaseValue();
439         if (C->getType()->getScalarSizeInBits() <
440             Int64Ty->getScalarSizeInBits())
441           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
442         Initializers.push_back(C);
443       }
444       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
445       GlobalVariable *GV = new GlobalVariable(
446           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
447           ConstantArray::get(ArrayOfInt64Ty, Initializers),
448           "__sancov_gen_cov_switch_values");
449       IRB.CreateCall(SanCovTraceSwitchFunction,
450                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
451     }
452   }
453 }
454 
455 
456 void SanitizerCoverageModule::InjectTraceForCmp(
457     Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
458   for (auto I : CmpTraceTargets) {
459     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
460       IRBuilder<> IRB(ICMP);
461       Value *A0 = ICMP->getOperand(0);
462       Value *A1 = ICMP->getOperand(1);
463       if (!A0->getType()->isIntegerTy()) continue;
464       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
465       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
466       IRB.CreateCall(
467           SanCovTraceCmpFunction,
468           {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
469            IRB.CreateIntCast(A0, Int64Ty, true),
470            IRB.CreateIntCast(A1, Int64Ty, true)});
471     }
472   }
473 }
474 
475 void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
476   I->setMetadata(
477       I->getModule()->getMDKindID("nosanitize"), MDNode::get(*C, None));
478 }
479 
480 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
481                                                     bool UseCalls) {
482   // Don't insert coverage for unreachable blocks: we will never call
483   // __sanitizer_cov() for them, so counting them in
484   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
485   // percentage. Also, unreachable instructions frequently have no debug
486   // locations.
487   if (isa<UnreachableInst>(BB.getTerminator()))
488     return;
489   BasicBlock::iterator IP = BB.getFirstInsertionPt();
490 
491   bool IsEntryBB = &BB == &F.getEntryBlock();
492   DebugLoc EntryLoc;
493   if (IsEntryBB) {
494     if (auto SP = getDISubprogram(&F))
495       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
496     // Keep static allocas and llvm.localescape calls in the entry block.  Even
497     // if we aren't splitting the block, it's nice for allocas to be before
498     // calls.
499     IP = PrepareToSplitEntryBlock(BB, IP);
500   } else {
501     EntryLoc = IP->getDebugLoc();
502   }
503 
504   IRBuilder<> IRB(&*IP);
505   IRB.SetCurrentDebugLocation(EntryLoc);
506   Value *GuardP = IRB.CreateAdd(
507       IRB.CreatePointerCast(GuardArray, IntptrTy),
508       ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
509   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
510   GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
511   if (Options.TracePC) {
512     IRB.CreateCall(SanCovTracePC);
513   } else if (Options.TraceBB) {
514     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
515   } else if (UseCalls) {
516     IRB.CreateCall(SanCovWithCheckFunction, GuardP);
517   } else {
518     LoadInst *Load = IRB.CreateLoad(GuardP);
519     Load->setAtomic(Monotonic);
520     Load->setAlignment(4);
521     SetNoSanitizeMetadata(Load);
522     Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
523     Instruction *Ins = SplitBlockAndInsertIfThen(
524         Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
525     IRB.SetInsertPoint(Ins);
526     IRB.SetCurrentDebugLocation(EntryLoc);
527     // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
528     IRB.CreateCall(SanCovFunction, GuardP);
529     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
530   }
531 
532   if (Options.Use8bitCounters) {
533     IRB.SetInsertPoint(&*IP);
534     Value *P = IRB.CreateAdd(
535         IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
536         ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
537     P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
538     LoadInst *LI = IRB.CreateLoad(P);
539     Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
540     StoreInst *SI = IRB.CreateStore(Inc, P);
541     SetNoSanitizeMetadata(LI);
542     SetNoSanitizeMetadata(SI);
543   }
544 }
545 
546 char SanitizerCoverageModule::ID = 0;
547 INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
548     "SanitizerCoverage: TODO."
549     "ModulePass", false, false)
550 ModulePass *llvm::createSanitizerCoverageModulePass(
551     const SanitizerCoverageOptions &Options) {
552   return new SanitizerCoverageModule(Options);
553 }
554