xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 8ad415574543c5ee4de98678fbe7452f60a086e3)
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/Analysis/PostDominators.h"
35 #include "llvm/IR/CFG.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/Dominators.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/InlineAsm.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/MDBuilder.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Instrumentation.h"
51 #include "llvm/Transforms/Scalar.h"
52 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
53 #include "llvm/Transforms/Utils/ModuleUtils.h"
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "sancov"
58 
59 static const char *const SanCovModuleInitName = "__sanitizer_cov_module_init";
60 static const char *const SanCovName = "__sanitizer_cov";
61 static const char *const SanCovWithCheckName = "__sanitizer_cov_with_check";
62 static const char *const SanCovIndirCallName = "__sanitizer_cov_indir_call16";
63 static const char *const SanCovTracePCIndirName =
64     "__sanitizer_cov_trace_pc_indir";
65 static const char *const SanCovTraceEnterName =
66     "__sanitizer_cov_trace_func_enter";
67 static const char *const SanCovTraceBBName =
68     "__sanitizer_cov_trace_basic_block";
69 static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
70 static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
71 static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
72 static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
73 static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
74 static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
75 static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
76 static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
77 static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
78 static const char *const SanCovModuleCtorName = "sancov.module_ctor";
79 static const uint64_t SanCtorAndDtorPriority = 2;
80 
81 static const char *const SanCovTracePCGuardSection = "__sancov_guards";
82 static const char *const SanCovTracePCGuardName =
83     "__sanitizer_cov_trace_pc_guard";
84 static const char *const SanCovTracePCGuardInitName =
85     "__sanitizer_cov_trace_pc_guard_init";
86 
87 static cl::opt<int> ClCoverageLevel(
88     "sanitizer-coverage-level",
89     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
90              "3: all blocks and critical edges, "
91              "4: above plus indirect calls"),
92     cl::Hidden, cl::init(0));
93 
94 static cl::opt<unsigned> ClCoverageBlockThreshold(
95     "sanitizer-coverage-block-threshold",
96     cl::desc("Use a callback with a guard check inside it if there are"
97              " more than this number of blocks."),
98     cl::Hidden, cl::init(500));
99 
100 static cl::opt<bool>
101     ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
102                           cl::desc("Experimental basic-block tracing: insert "
103                                    "callbacks at every basic block"),
104                           cl::Hidden, cl::init(false));
105 
106 static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
107                                            cl::desc("Experimental pc tracing"),
108                                            cl::Hidden, cl::init(false));
109 
110 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
111                                     cl::desc("pc tracing with a guard"),
112                                     cl::Hidden, cl::init(false));
113 
114 static cl::opt<bool>
115     ClCMPTracing("sanitizer-coverage-trace-compares",
116                  cl::desc("Tracing of CMP and similar instructions"),
117                  cl::Hidden, cl::init(false));
118 
119 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
120                                   cl::desc("Tracing of DIV instructions"),
121                                   cl::Hidden, cl::init(false));
122 
123 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
124                                   cl::desc("Tracing of GEP instructions"),
125                                   cl::Hidden, cl::init(false));
126 
127 static cl::opt<bool>
128     ClPruneBlocks("sanitizer-coverage-prune-blocks",
129                   cl::desc("Reduce the number of instrumented blocks"),
130                   cl::Hidden, cl::init(true));
131 
132 // Experimental 8-bit counters used as an additional search heuristic during
133 // coverage-guided fuzzing.
134 // The counters are not thread-friendly:
135 //   - contention on these counters may cause significant slowdown;
136 //   - the counter updates are racy and the results may be inaccurate.
137 // They are also inaccurate due to 8-bit integer overflow.
138 static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
139                                        cl::desc("Experimental 8-bit counters"),
140                                        cl::Hidden, cl::init(false));
141 
142 namespace {
143 
144 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
145   SanitizerCoverageOptions Res;
146   switch (LegacyCoverageLevel) {
147   case 0:
148     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
149     break;
150   case 1:
151     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
152     break;
153   case 2:
154     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
155     break;
156   case 3:
157     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
158     break;
159   case 4:
160     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
161     Res.IndirectCalls = true;
162     break;
163   }
164   return Res;
165 }
166 
167 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
168   // Sets CoverageType and IndirectCalls.
169   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
170   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
171   Options.IndirectCalls |= CLOpts.IndirectCalls;
172   Options.TraceBB |= ClExperimentalTracing;
173   Options.TraceCmp |= ClCMPTracing;
174   Options.TraceDiv |= ClDIVTracing;
175   Options.TraceGep |= ClGEPTracing;
176   Options.Use8bitCounters |= ClUse8bitCounters;
177   Options.TracePC |= ClExperimentalTracePC;
178   Options.TracePCGuard |= ClTracePCGuard;
179   return Options;
180 }
181 
182 class SanitizerCoverageModule : public ModulePass {
183 public:
184   SanitizerCoverageModule(
185       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
186       : ModulePass(ID), Options(OverrideFromCL(Options)) {
187     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
188   }
189   bool runOnModule(Module &M) override;
190   bool runOnFunction(Function &F);
191   static char ID; // Pass identification, replacement for typeid
192   const char *getPassName() const override { return "SanitizerCoverageModule"; }
193 
194   void getAnalysisUsage(AnalysisUsage &AU) const override {
195     AU.addRequired<DominatorTreeWrapperPass>();
196     AU.addRequired<PostDominatorTreeWrapperPass>();
197   }
198 
199 private:
200   void InjectCoverageForIndirectCalls(Function &F,
201                                       ArrayRef<Instruction *> IndirCalls);
202   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
203   void InjectTraceForDiv(Function &F,
204                          ArrayRef<BinaryOperator *> DivTraceTargets);
205   void InjectTraceForGep(Function &F,
206                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
207   void InjectTraceForSwitch(Function &F,
208                             ArrayRef<Instruction *> SwitchTraceTargets);
209   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210   void SetNoSanitizeMetadata(Instruction *I);
211   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
212   unsigned NumberOfInstrumentedBlocks() {
213     return SanCovFunction->getNumUses() +
214            SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
215            SanCovTraceEnter->getNumUses();
216   }
217   Function *SanCovFunction;
218   Function *SanCovWithCheckFunction;
219   Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
220   Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC, *SanCovTracePCGuard;
221   Function *SanCovTraceCmpFunction[4];
222   Function *SanCovTraceDivFunction[2];
223   Function *SanCovTraceGepFunction;
224   Function *SanCovTraceSwitchFunction;
225   InlineAsm *EmptyAsm;
226   Type *IntptrTy, *Int64Ty, *Int64PtrTy;
227   Module *CurModule;
228   LLVMContext *C;
229   const DataLayout *DL;
230 
231   GlobalVariable *GuardArray;
232   GlobalVariable *EightBitCounterArray;
233 
234   SanitizerCoverageOptions Options;
235 };
236 
237 } // namespace
238 
239 bool SanitizerCoverageModule::runOnModule(Module &M) {
240   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
241     return false;
242   C = &(M.getContext());
243   DL = &M.getDataLayout();
244   CurModule = &M;
245   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
246   Type *VoidTy = Type::getVoidTy(*C);
247   IRBuilder<> IRB(*C);
248   Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
249   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
250   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
251   Int64Ty = IRB.getInt64Ty();
252 
253   SanCovFunction = checkSanitizerInterfaceFunction(
254       M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
255   SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
256       M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
257   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
258       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
259   SanCovIndirCallFunction =
260       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
261           SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
262   SanCovTraceCmpFunction[0] =
263       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
264           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty(), nullptr));
265   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
266       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
267                             IRB.getInt16Ty(), nullptr));
268   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
269       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
270                             IRB.getInt32Ty(), nullptr));
271   SanCovTraceCmpFunction[3] =
272       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
273           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty, nullptr));
274 
275   SanCovTraceDivFunction[0] =
276       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
277           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty(), nullptr));
278   SanCovTraceDivFunction[1] =
279       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
280           SanCovTraceDiv8, VoidTy, Int64Ty, nullptr));
281   SanCovTraceGepFunction =
282       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
283           SanCovTraceGep, VoidTy, IntptrTy, nullptr));
284   SanCovTraceSwitchFunction =
285       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
286           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
287 
288   // We insert an empty inline asm after cov callbacks to avoid callback merge.
289   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
290                             StringRef(""), StringRef(""),
291                             /*hasSideEffects=*/true);
292 
293   SanCovTracePC = checkSanitizerInterfaceFunction(
294       M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
295   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
296       SanCovTracePCGuardName, VoidTy, Int64PtrTy, nullptr));
297   SanCovTraceEnter = checkSanitizerInterfaceFunction(
298       M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
299   SanCovTraceBB = checkSanitizerInterfaceFunction(
300       M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
301 
302   // At this point we create a dummy array of guards because we don't
303   // know how many elements we will need.
304   Type *Int32Ty = IRB.getInt32Ty();
305   Type *Int8Ty = IRB.getInt8Ty();
306 
307   GuardArray =
308       new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
309                          nullptr, "__sancov_gen_cov_tmp");
310   if (Options.Use8bitCounters)
311     EightBitCounterArray =
312         new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
313                            nullptr, "__sancov_gen_cov_tmp");
314 
315   for (auto &F : M)
316     runOnFunction(F);
317 
318   auto N = NumberOfInstrumentedBlocks();
319 
320   // Now we know how many elements we need. Create an array of guards
321   // with one extra element at the beginning for the size.
322   Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
323   GlobalVariable *RealGuardArray = new GlobalVariable(
324       M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
325       Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
326 
327   // Replace the dummy array with the real one.
328   GuardArray->replaceAllUsesWith(
329       IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
330   GuardArray->eraseFromParent();
331 
332   GlobalVariable *RealEightBitCounterArray;
333   if (Options.Use8bitCounters) {
334     // Make sure the array is 16-aligned.
335     static const int CounterAlignment = 16;
336     Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
337     RealEightBitCounterArray = new GlobalVariable(
338         M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
339         Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
340     RealEightBitCounterArray->setAlignment(CounterAlignment);
341     EightBitCounterArray->replaceAllUsesWith(
342         IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
343     EightBitCounterArray->eraseFromParent();
344   }
345 
346   // Create variable for module (compilation unit) name
347   Constant *ModNameStrConst =
348       ConstantDataArray::getString(M.getContext(), M.getName(), true);
349   GlobalVariable *ModuleName =
350       new GlobalVariable(M, ModNameStrConst->getType(), true,
351                          GlobalValue::PrivateLinkage, ModNameStrConst);
352   if (Options.TracePCGuard) {
353     Function *CtorFunc;
354     std::string SectionName(SanCovTracePCGuardSection);
355     GlobalVariable *Bounds[2];
356     const char *Prefix[2] = {"__start_", "__stop_"};
357     for (int i = 0; i < 2; i++) {
358       Bounds[i] = new GlobalVariable(M, Int64PtrTy, false,
359                                      GlobalVariable::ExternalLinkage, nullptr,
360                                      Prefix[i] + SectionName);
361       Bounds[i]->setVisibility(GlobalValue::HiddenVisibility);
362     }
363     std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
364         M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
365         {Int64PtrTy, Int64PtrTy}, {IRB.CreatePointerCast(Bounds[0], Int64PtrTy),
366                                  IRB.CreatePointerCast(Bounds[1], Int64PtrTy)});
367 
368     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
369 
370   } else if (!Options.TracePC) {
371     Function *CtorFunc;
372     std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
373         M, SanCovModuleCtorName, SanCovModuleInitName,
374         {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
375         {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
376          ConstantInt::get(IntptrTy, N),
377          Options.Use8bitCounters
378              ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
379              : Constant::getNullValue(Int8PtrTy),
380          IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
381 
382     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
383   }
384 
385   return true;
386 }
387 
388 // True if block has successors and it dominates all of them.
389 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
390   if (succ_begin(BB) == succ_end(BB))
391     return false;
392 
393   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
394     if (!DT->dominates(BB, SUCC))
395       return false;
396   }
397 
398   return true;
399 }
400 
401 // True if block has predecessors and it postdominates all of them.
402 static bool isFullPostDominator(const BasicBlock *BB,
403                                 const PostDominatorTree *PDT) {
404   if (pred_begin(BB) == pred_end(BB))
405     return false;
406 
407   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
408     if (!PDT->dominates(BB, PRED))
409       return false;
410   }
411 
412   return true;
413 }
414 
415 static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
416                                   const PostDominatorTree *PDT) {
417   if (!ClPruneBlocks || &F.getEntryBlock() == BB)
418     return true;
419 
420   return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
421 }
422 
423 bool SanitizerCoverageModule::runOnFunction(Function &F) {
424   if (F.empty())
425     return false;
426   if (F.getName().find(".module_ctor") != std::string::npos)
427     return false; // Should not instrument sanitizer init functions.
428   if (F.getName().startswith("__sanitizer_"))
429     return false;  // Don't instrument __sanitizer_* callbacks.
430   // Don't instrument functions using SEH for now. Splitting basic blocks like
431   // we do for coverage breaks WinEHPrepare.
432   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
433   if (F.hasPersonalityFn() &&
434       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
435     return false;
436   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
437     SplitAllCriticalEdges(F);
438   SmallVector<Instruction *, 8> IndirCalls;
439   SmallVector<BasicBlock *, 16> BlocksToInstrument;
440   SmallVector<Instruction *, 8> CmpTraceTargets;
441   SmallVector<Instruction *, 8> SwitchTraceTargets;
442   SmallVector<BinaryOperator *, 8> DivTraceTargets;
443   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
444 
445   const DominatorTree *DT =
446       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
447   const PostDominatorTree *PDT =
448       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
449 
450   for (auto &BB : F) {
451     if (shouldInstrumentBlock(F, &BB, DT, PDT))
452       BlocksToInstrument.push_back(&BB);
453     for (auto &Inst : BB) {
454       if (Options.IndirectCalls) {
455         CallSite CS(&Inst);
456         if (CS && !CS.getCalledFunction())
457           IndirCalls.push_back(&Inst);
458       }
459       if (Options.TraceCmp) {
460         if (isa<ICmpInst>(&Inst))
461           CmpTraceTargets.push_back(&Inst);
462         if (isa<SwitchInst>(&Inst))
463           SwitchTraceTargets.push_back(&Inst);
464       }
465       if (Options.TraceDiv)
466         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
467           if (BO->getOpcode() == Instruction::SDiv ||
468               BO->getOpcode() == Instruction::UDiv)
469             DivTraceTargets.push_back(BO);
470       if (Options.TraceGep)
471         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
472           GepTraceTargets.push_back(GEP);
473    }
474   }
475 
476   InjectCoverage(F, BlocksToInstrument);
477   InjectCoverageForIndirectCalls(F, IndirCalls);
478   InjectTraceForCmp(F, CmpTraceTargets);
479   InjectTraceForSwitch(F, SwitchTraceTargets);
480   InjectTraceForDiv(F, DivTraceTargets);
481   InjectTraceForGep(F, GepTraceTargets);
482   return true;
483 }
484 
485 bool SanitizerCoverageModule::InjectCoverage(Function &F,
486                                              ArrayRef<BasicBlock *> AllBlocks) {
487   switch (Options.CoverageType) {
488   case SanitizerCoverageOptions::SCK_None:
489     return false;
490   case SanitizerCoverageOptions::SCK_Function:
491     InjectCoverageAtBlock(F, F.getEntryBlock(), false);
492     return true;
493   default: {
494     bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
495     for (auto BB : AllBlocks)
496       InjectCoverageAtBlock(F, *BB, UseCalls);
497     return true;
498   }
499   }
500 }
501 
502 // On every indirect call we call a run-time function
503 // __sanitizer_cov_indir_call* with two parameters:
504 //   - callee address,
505 //   - global cache array that contains CacheSize pointers (zero-initialized).
506 //     The cache is used to speed up recording the caller-callee pairs.
507 // The address of the caller is passed implicitly via caller PC.
508 // CacheSize is encoded in the name of the run-time function.
509 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
510     Function &F, ArrayRef<Instruction *> IndirCalls) {
511   if (IndirCalls.empty())
512     return;
513   const int CacheSize = 16;
514   const int CacheAlignment = 64; // Align for better performance.
515   Type *Ty = ArrayType::get(IntptrTy, CacheSize);
516   for (auto I : IndirCalls) {
517     IRBuilder<> IRB(I);
518     CallSite CS(I);
519     Value *Callee = CS.getCalledValue();
520     if (isa<InlineAsm>(Callee))
521       continue;
522     GlobalVariable *CalleeCache = new GlobalVariable(
523         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
524         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
525     CalleeCache->setAlignment(CacheAlignment);
526     if (Options.TracePC || Options.TracePCGuard)
527       IRB.CreateCall(SanCovTracePCIndir,
528                      IRB.CreatePointerCast(Callee, IntptrTy));
529     else
530       IRB.CreateCall(SanCovIndirCallFunction,
531                      {IRB.CreatePointerCast(Callee, IntptrTy),
532                       IRB.CreatePointerCast(CalleeCache, IntptrTy)});
533   }
534 }
535 
536 // For every switch statement we insert a call:
537 // __sanitizer_cov_trace_switch(CondValue,
538 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
539 
540 void SanitizerCoverageModule::InjectTraceForSwitch(
541     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
542   for (auto I : SwitchTraceTargets) {
543     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
544       IRBuilder<> IRB(I);
545       SmallVector<Constant *, 16> Initializers;
546       Value *Cond = SI->getCondition();
547       if (Cond->getType()->getScalarSizeInBits() >
548           Int64Ty->getScalarSizeInBits())
549         continue;
550       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
551       Initializers.push_back(
552           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
553       if (Cond->getType()->getScalarSizeInBits() <
554           Int64Ty->getScalarSizeInBits())
555         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
556       for (auto It : SI->cases()) {
557         Constant *C = It.getCaseValue();
558         if (C->getType()->getScalarSizeInBits() <
559             Int64Ty->getScalarSizeInBits())
560           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
561         Initializers.push_back(C);
562       }
563       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
564       GlobalVariable *GV = new GlobalVariable(
565           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
566           ConstantArray::get(ArrayOfInt64Ty, Initializers),
567           "__sancov_gen_cov_switch_values");
568       IRB.CreateCall(SanCovTraceSwitchFunction,
569                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
570     }
571   }
572 }
573 
574 void SanitizerCoverageModule::InjectTraceForDiv(
575     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
576   for (auto BO : DivTraceTargets) {
577     IRBuilder<> IRB(BO);
578     Value *A1 = BO->getOperand(1);
579     if (isa<ConstantInt>(A1)) continue;
580     if (!A1->getType()->isIntegerTy())
581       continue;
582     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
583     int CallbackIdx = TypeSize == 32 ? 0 :
584         TypeSize == 64 ? 1 : -1;
585     if (CallbackIdx < 0) continue;
586     auto Ty = Type::getIntNTy(*C, TypeSize);
587     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
588                    {IRB.CreateIntCast(A1, Ty, true)});
589   }
590 }
591 
592 void SanitizerCoverageModule::InjectTraceForGep(
593     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
594   for (auto GEP : GepTraceTargets) {
595     IRBuilder<> IRB(GEP);
596     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
597       if (!isa<ConstantInt>(*I))
598         IRB.CreateCall(SanCovTraceGepFunction,
599                        {IRB.CreateIntCast(*I, IntptrTy, true)});
600   }
601 }
602 
603 void SanitizerCoverageModule::InjectTraceForCmp(
604     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
605   for (auto I : CmpTraceTargets) {
606     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
607       IRBuilder<> IRB(ICMP);
608       Value *A0 = ICMP->getOperand(0);
609       Value *A1 = ICMP->getOperand(1);
610       if (!A0->getType()->isIntegerTy())
611         continue;
612       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
613       int CallbackIdx = TypeSize == 8 ? 0 :
614                         TypeSize == 16 ? 1 :
615                         TypeSize == 32 ? 2 :
616                         TypeSize == 64 ? 3 : -1;
617       if (CallbackIdx < 0) continue;
618       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
619       auto Ty = Type::getIntNTy(*C, TypeSize);
620       IRB.CreateCall(
621           SanCovTraceCmpFunction[CallbackIdx],
622           {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
623     }
624   }
625 }
626 
627 void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
628   I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
629                  MDNode::get(*C, None));
630 }
631 
632 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
633                                                     bool UseCalls) {
634   // Don't insert coverage for unreachable blocks: we will never call
635   // __sanitizer_cov() for them, so counting them in
636   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
637   // percentage. Also, unreachable instructions frequently have no debug
638   // locations.
639   if (isa<UnreachableInst>(BB.getTerminator()))
640     return;
641   BasicBlock::iterator IP = BB.getFirstInsertionPt();
642 
643   bool IsEntryBB = &BB == &F.getEntryBlock();
644   DebugLoc EntryLoc;
645   if (IsEntryBB) {
646     if (auto SP = F.getSubprogram())
647       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
648     // Keep static allocas and llvm.localescape calls in the entry block.  Even
649     // if we aren't splitting the block, it's nice for allocas to be before
650     // calls.
651     IP = PrepareToSplitEntryBlock(BB, IP);
652   } else {
653     EntryLoc = IP->getDebugLoc();
654   }
655 
656   IRBuilder<> IRB(&*IP);
657   IRB.SetCurrentDebugLocation(EntryLoc);
658   Value *GuardP = IRB.CreateAdd(
659       IRB.CreatePointerCast(GuardArray, IntptrTy),
660       ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
661   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
662   GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
663   if (Options.TracePC) {
664     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
665     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
666   } else if (Options.TracePCGuard) {
667     auto GuardVar = new GlobalVariable(
668         *F.getParent(), Int64Ty, false, GlobalVariable::LinkOnceODRLinkage,
669         Constant::getNullValue(Int64Ty), "__sancov_guard." + F.getName());
670     // TODO: add debug into to GuardVar.
671     GuardVar->setSection(SanCovTracePCGuardSection);
672     auto GuardPtr = IRB.CreatePointerCast(GuardVar, Int64PtrTy);
673     if (!UseCalls) {
674       auto GuardLoad = IRB.CreateLoad(GuardPtr);
675       GuardLoad->setAtomic(AtomicOrdering::Monotonic);
676       GuardLoad->setAlignment(8);
677       SetNoSanitizeMetadata(GuardLoad);  // Don't instrument with e.g. asan.
678       auto Cmp = IRB.CreateICmpSGE(
679           GuardLoad, Constant::getNullValue(GuardLoad->getType()));
680       auto Ins = SplitBlockAndInsertIfThen(
681           Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
682       IRB.SetCurrentDebugLocation(EntryLoc);
683       IRB.SetInsertPoint(Ins);
684     }
685     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
686     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
687   } else if (Options.TraceBB) {
688     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
689   } else if (UseCalls) {
690     IRB.CreateCall(SanCovWithCheckFunction, GuardP);
691   } else {
692     LoadInst *Load = IRB.CreateLoad(GuardP);
693     Load->setAtomic(AtomicOrdering::Monotonic);
694     Load->setAlignment(4);
695     SetNoSanitizeMetadata(Load);
696     Value *Cmp =
697         IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
698     Instruction *Ins = SplitBlockAndInsertIfThen(
699         Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
700     IRB.SetInsertPoint(Ins);
701     IRB.SetCurrentDebugLocation(EntryLoc);
702     // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
703     IRB.CreateCall(SanCovFunction, GuardP);
704     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
705   }
706 
707   if (Options.Use8bitCounters) {
708     IRB.SetInsertPoint(&*IP);
709     Value *P = IRB.CreateAdd(
710         IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
711         ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
712     P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
713     LoadInst *LI = IRB.CreateLoad(P);
714     Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
715     StoreInst *SI = IRB.CreateStore(Inc, P);
716     SetNoSanitizeMetadata(LI);
717     SetNoSanitizeMetadata(SI);
718   }
719 }
720 
721 char SanitizerCoverageModule::ID = 0;
722 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
723                       "SanitizerCoverage: TODO."
724                       "ModulePass",
725                       false, false)
726 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
727 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
728 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
729                     "SanitizerCoverage: TODO."
730                     "ModulePass",
731                     false, false)
732 ModulePass *llvm::createSanitizerCoverageModulePass(
733     const SanitizerCoverageOptions &Options) {
734   return new SanitizerCoverageModule(Options);
735 }
736