xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 45c144754bd7eea6aaa5084a3ad698062b05e551)
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, *IntptrPtrTy, *Int64Ty, *Int64PtrTy;
227   Module *CurModule;
228   LLVMContext *C;
229   const DataLayout *DL;
230 
231   GlobalVariable *GuardArray;
232   GlobalVariable *EightBitCounterArray;
233   bool HasSancovGuardsSection;
234 
235   SanitizerCoverageOptions Options;
236 };
237 
238 } // namespace
239 
240 bool SanitizerCoverageModule::runOnModule(Module &M) {
241   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
242     return false;
243   C = &(M.getContext());
244   DL = &M.getDataLayout();
245   CurModule = &M;
246   HasSancovGuardsSection = false;
247   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
248   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
249   Type *VoidTy = Type::getVoidTy(*C);
250   IRBuilder<> IRB(*C);
251   Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
252   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
253   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
254   Int64Ty = IRB.getInt64Ty();
255 
256   SanCovFunction = checkSanitizerInterfaceFunction(
257       M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
258   SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
259       M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
260   SanCovTracePCIndir = checkSanitizerInterfaceFunction(
261       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
262   SanCovIndirCallFunction =
263       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
264           SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
265   SanCovTraceCmpFunction[0] =
266       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
267           SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty(), nullptr));
268   SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
269       M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
270                             IRB.getInt16Ty(), nullptr));
271   SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
272       M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
273                             IRB.getInt32Ty(), nullptr));
274   SanCovTraceCmpFunction[3] =
275       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
276           SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty, nullptr));
277 
278   SanCovTraceDivFunction[0] =
279       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
280           SanCovTraceDiv4, VoidTy, IRB.getInt32Ty(), nullptr));
281   SanCovTraceDivFunction[1] =
282       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
283           SanCovTraceDiv8, VoidTy, Int64Ty, nullptr));
284   SanCovTraceGepFunction =
285       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
286           SanCovTraceGep, VoidTy, IntptrTy, nullptr));
287   SanCovTraceSwitchFunction =
288       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
289           SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
290 
291   // We insert an empty inline asm after cov callbacks to avoid callback merge.
292   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
293                             StringRef(""), StringRef(""),
294                             /*hasSideEffects=*/true);
295 
296   SanCovTracePC = checkSanitizerInterfaceFunction(
297       M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
298   SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
299       SanCovTracePCGuardName, VoidTy, IntptrPtrTy, nullptr));
300   SanCovTraceEnter = checkSanitizerInterfaceFunction(
301       M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
302   SanCovTraceBB = checkSanitizerInterfaceFunction(
303       M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
304 
305   // At this point we create a dummy array of guards because we don't
306   // know how many elements we will need.
307   Type *Int32Ty = IRB.getInt32Ty();
308   Type *Int8Ty = IRB.getInt8Ty();
309 
310   GuardArray =
311       new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
312                          nullptr, "__sancov_gen_cov_tmp");
313   if (Options.Use8bitCounters)
314     EightBitCounterArray =
315         new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
316                            nullptr, "__sancov_gen_cov_tmp");
317 
318   for (auto &F : M)
319     runOnFunction(F);
320 
321   auto N = NumberOfInstrumentedBlocks();
322 
323   // Now we know how many elements we need. Create an array of guards
324   // with one extra element at the beginning for the size.
325   Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
326   GlobalVariable *RealGuardArray = new GlobalVariable(
327       M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
328       Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
329 
330   // Replace the dummy array with the real one.
331   GuardArray->replaceAllUsesWith(
332       IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
333   GuardArray->eraseFromParent();
334 
335   GlobalVariable *RealEightBitCounterArray;
336   if (Options.Use8bitCounters) {
337     // Make sure the array is 16-aligned.
338     static const int CounterAlignment = 16;
339     Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
340     RealEightBitCounterArray = new GlobalVariable(
341         M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
342         Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
343     RealEightBitCounterArray->setAlignment(CounterAlignment);
344     EightBitCounterArray->replaceAllUsesWith(
345         IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
346     EightBitCounterArray->eraseFromParent();
347   }
348 
349   // Create variable for module (compilation unit) name
350   Constant *ModNameStrConst =
351       ConstantDataArray::getString(M.getContext(), M.getName(), true);
352   GlobalVariable *ModuleName =
353       new GlobalVariable(M, ModNameStrConst->getType(), true,
354                          GlobalValue::PrivateLinkage, ModNameStrConst);
355   if (Options.TracePCGuard) {
356     if (HasSancovGuardsSection) {
357       Function *CtorFunc;
358       std::string SectionName(SanCovTracePCGuardSection);
359       GlobalVariable *Bounds[2];
360       const char *Prefix[2] = {"__start_", "__stop_"};
361       for (int i = 0; i < 2; i++) {
362         Bounds[i] = new GlobalVariable(M, IntptrPtrTy, false,
363                                        GlobalVariable::ExternalLinkage, nullptr,
364                                        Prefix[i] + SectionName);
365         Bounds[i]->setVisibility(GlobalValue::HiddenVisibility);
366       }
367       std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
368           M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
369           {IntptrPtrTy, IntptrPtrTy},
370           {IRB.CreatePointerCast(Bounds[0], IntptrPtrTy),
371             IRB.CreatePointerCast(Bounds[1], IntptrPtrTy)});
372 
373       appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
374     }
375   } else if (!Options.TracePC) {
376     Function *CtorFunc;
377     std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
378         M, SanCovModuleCtorName, SanCovModuleInitName,
379         {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
380         {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
381          ConstantInt::get(IntptrTy, N),
382          Options.Use8bitCounters
383              ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
384              : Constant::getNullValue(Int8PtrTy),
385          IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
386 
387     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
388   }
389 
390   return true;
391 }
392 
393 // True if block has successors and it dominates all of them.
394 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
395   if (succ_begin(BB) == succ_end(BB))
396     return false;
397 
398   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
399     if (!DT->dominates(BB, SUCC))
400       return false;
401   }
402 
403   return true;
404 }
405 
406 // True if block has predecessors and it postdominates all of them.
407 static bool isFullPostDominator(const BasicBlock *BB,
408                                 const PostDominatorTree *PDT) {
409   if (pred_begin(BB) == pred_end(BB))
410     return false;
411 
412   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
413     if (!PDT->dominates(BB, PRED))
414       return false;
415   }
416 
417   return true;
418 }
419 
420 static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
421                                   const PostDominatorTree *PDT) {
422   if (!ClPruneBlocks || &F.getEntryBlock() == BB)
423     return true;
424 
425   return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
426 }
427 
428 bool SanitizerCoverageModule::runOnFunction(Function &F) {
429   if (F.empty())
430     return false;
431   if (F.getName().find(".module_ctor") != std::string::npos)
432     return false; // Should not instrument sanitizer init functions.
433   if (F.getName().startswith("__sanitizer_"))
434     return false;  // Don't instrument __sanitizer_* callbacks.
435   // Don't instrument functions using SEH for now. Splitting basic blocks like
436   // we do for coverage breaks WinEHPrepare.
437   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
438   if (F.hasPersonalityFn() &&
439       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
440     return false;
441   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
442     SplitAllCriticalEdges(F);
443   SmallVector<Instruction *, 8> IndirCalls;
444   SmallVector<BasicBlock *, 16> BlocksToInstrument;
445   SmallVector<Instruction *, 8> CmpTraceTargets;
446   SmallVector<Instruction *, 8> SwitchTraceTargets;
447   SmallVector<BinaryOperator *, 8> DivTraceTargets;
448   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
449 
450   const DominatorTree *DT =
451       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
452   const PostDominatorTree *PDT =
453       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
454 
455   for (auto &BB : F) {
456     if (shouldInstrumentBlock(F, &BB, DT, PDT))
457       BlocksToInstrument.push_back(&BB);
458     for (auto &Inst : BB) {
459       if (Options.IndirectCalls) {
460         CallSite CS(&Inst);
461         if (CS && !CS.getCalledFunction())
462           IndirCalls.push_back(&Inst);
463       }
464       if (Options.TraceCmp) {
465         if (isa<ICmpInst>(&Inst))
466           CmpTraceTargets.push_back(&Inst);
467         if (isa<SwitchInst>(&Inst))
468           SwitchTraceTargets.push_back(&Inst);
469       }
470       if (Options.TraceDiv)
471         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
472           if (BO->getOpcode() == Instruction::SDiv ||
473               BO->getOpcode() == Instruction::UDiv)
474             DivTraceTargets.push_back(BO);
475       if (Options.TraceGep)
476         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
477           GepTraceTargets.push_back(GEP);
478    }
479   }
480 
481   InjectCoverage(F, BlocksToInstrument);
482   InjectCoverageForIndirectCalls(F, IndirCalls);
483   InjectTraceForCmp(F, CmpTraceTargets);
484   InjectTraceForSwitch(F, SwitchTraceTargets);
485   InjectTraceForDiv(F, DivTraceTargets);
486   InjectTraceForGep(F, GepTraceTargets);
487   return true;
488 }
489 
490 bool SanitizerCoverageModule::InjectCoverage(Function &F,
491                                              ArrayRef<BasicBlock *> AllBlocks) {
492   switch (Options.CoverageType) {
493   case SanitizerCoverageOptions::SCK_None:
494     return false;
495   case SanitizerCoverageOptions::SCK_Function:
496     InjectCoverageAtBlock(F, F.getEntryBlock(), false);
497     return true;
498   default: {
499     bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
500     for (auto BB : AllBlocks)
501       InjectCoverageAtBlock(F, *BB, UseCalls);
502     return true;
503   }
504   }
505 }
506 
507 // On every indirect call we call a run-time function
508 // __sanitizer_cov_indir_call* with two parameters:
509 //   - callee address,
510 //   - global cache array that contains CacheSize pointers (zero-initialized).
511 //     The cache is used to speed up recording the caller-callee pairs.
512 // The address of the caller is passed implicitly via caller PC.
513 // CacheSize is encoded in the name of the run-time function.
514 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
515     Function &F, ArrayRef<Instruction *> IndirCalls) {
516   if (IndirCalls.empty())
517     return;
518   const int CacheSize = 16;
519   const int CacheAlignment = 64; // Align for better performance.
520   Type *Ty = ArrayType::get(IntptrTy, CacheSize);
521   for (auto I : IndirCalls) {
522     IRBuilder<> IRB(I);
523     CallSite CS(I);
524     Value *Callee = CS.getCalledValue();
525     if (isa<InlineAsm>(Callee))
526       continue;
527     GlobalVariable *CalleeCache = new GlobalVariable(
528         *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
529         Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
530     CalleeCache->setAlignment(CacheAlignment);
531     if (Options.TracePC || Options.TracePCGuard)
532       IRB.CreateCall(SanCovTracePCIndir,
533                      IRB.CreatePointerCast(Callee, IntptrTy));
534     else
535       IRB.CreateCall(SanCovIndirCallFunction,
536                      {IRB.CreatePointerCast(Callee, IntptrTy),
537                       IRB.CreatePointerCast(CalleeCache, IntptrTy)});
538   }
539 }
540 
541 // For every switch statement we insert a call:
542 // __sanitizer_cov_trace_switch(CondValue,
543 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
544 
545 void SanitizerCoverageModule::InjectTraceForSwitch(
546     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
547   for (auto I : SwitchTraceTargets) {
548     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
549       IRBuilder<> IRB(I);
550       SmallVector<Constant *, 16> Initializers;
551       Value *Cond = SI->getCondition();
552       if (Cond->getType()->getScalarSizeInBits() >
553           Int64Ty->getScalarSizeInBits())
554         continue;
555       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
556       Initializers.push_back(
557           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
558       if (Cond->getType()->getScalarSizeInBits() <
559           Int64Ty->getScalarSizeInBits())
560         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
561       for (auto It : SI->cases()) {
562         Constant *C = It.getCaseValue();
563         if (C->getType()->getScalarSizeInBits() <
564             Int64Ty->getScalarSizeInBits())
565           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
566         Initializers.push_back(C);
567       }
568       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
569       GlobalVariable *GV = new GlobalVariable(
570           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
571           ConstantArray::get(ArrayOfInt64Ty, Initializers),
572           "__sancov_gen_cov_switch_values");
573       IRB.CreateCall(SanCovTraceSwitchFunction,
574                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
575     }
576   }
577 }
578 
579 void SanitizerCoverageModule::InjectTraceForDiv(
580     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
581   for (auto BO : DivTraceTargets) {
582     IRBuilder<> IRB(BO);
583     Value *A1 = BO->getOperand(1);
584     if (isa<ConstantInt>(A1)) continue;
585     if (!A1->getType()->isIntegerTy())
586       continue;
587     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
588     int CallbackIdx = TypeSize == 32 ? 0 :
589         TypeSize == 64 ? 1 : -1;
590     if (CallbackIdx < 0) continue;
591     auto Ty = Type::getIntNTy(*C, TypeSize);
592     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
593                    {IRB.CreateIntCast(A1, Ty, true)});
594   }
595 }
596 
597 void SanitizerCoverageModule::InjectTraceForGep(
598     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
599   for (auto GEP : GepTraceTargets) {
600     IRBuilder<> IRB(GEP);
601     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
602       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
603         IRB.CreateCall(SanCovTraceGepFunction,
604                        {IRB.CreateIntCast(*I, IntptrTy, true)});
605   }
606 }
607 
608 void SanitizerCoverageModule::InjectTraceForCmp(
609     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
610   for (auto I : CmpTraceTargets) {
611     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
612       IRBuilder<> IRB(ICMP);
613       Value *A0 = ICMP->getOperand(0);
614       Value *A1 = ICMP->getOperand(1);
615       if (!A0->getType()->isIntegerTy())
616         continue;
617       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
618       int CallbackIdx = TypeSize == 8 ? 0 :
619                         TypeSize == 16 ? 1 :
620                         TypeSize == 32 ? 2 :
621                         TypeSize == 64 ? 3 : -1;
622       if (CallbackIdx < 0) continue;
623       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
624       auto Ty = Type::getIntNTy(*C, TypeSize);
625       IRB.CreateCall(
626           SanCovTraceCmpFunction[CallbackIdx],
627           {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
628     }
629   }
630 }
631 
632 void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
633   I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
634                  MDNode::get(*C, None));
635 }
636 
637 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
638                                                     bool UseCalls) {
639   // Don't insert coverage for unreachable blocks: we will never call
640   // __sanitizer_cov() for them, so counting them in
641   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
642   // percentage. Also, unreachable instructions frequently have no debug
643   // locations.
644   if (isa<UnreachableInst>(BB.getTerminator()))
645     return;
646   BasicBlock::iterator IP = BB.getFirstInsertionPt();
647 
648   bool IsEntryBB = &BB == &F.getEntryBlock();
649   DebugLoc EntryLoc;
650   if (IsEntryBB) {
651     if (auto SP = F.getSubprogram())
652       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
653     // Keep static allocas and llvm.localescape calls in the entry block.  Even
654     // if we aren't splitting the block, it's nice for allocas to be before
655     // calls.
656     IP = PrepareToSplitEntryBlock(BB, IP);
657   } else {
658     EntryLoc = IP->getDebugLoc();
659   }
660 
661   IRBuilder<> IRB(&*IP);
662   IRB.SetCurrentDebugLocation(EntryLoc);
663   Value *GuardP = IRB.CreateAdd(
664       IRB.CreatePointerCast(GuardArray, IntptrTy),
665       ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
666   Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
667   GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
668   if (Options.TracePC) {
669     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
670     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
671   } else if (Options.TracePCGuard) {
672     auto GuardVar = new GlobalVariable(
673         *F.getParent(), Int64Ty, false, GlobalVariable::LinkOnceODRLinkage,
674         Constant::getNullValue(Int64Ty), "__sancov_guard." + F.getName());
675     if (auto Comdat = F.getComdat())
676       GuardVar->setComdat(Comdat);
677     // TODO: add debug into to GuardVar.
678     GuardVar->setSection(SanCovTracePCGuardSection);
679     HasSancovGuardsSection = true;
680     auto GuardPtr = IRB.CreatePointerCast(GuardVar, IntptrPtrTy);
681     if (!UseCalls) {
682       auto GuardLoad = IRB.CreateLoad(GuardPtr);
683       GuardLoad->setAtomic(AtomicOrdering::Monotonic);
684       GuardLoad->setAlignment(8);
685       SetNoSanitizeMetadata(GuardLoad);  // Don't instrument with e.g. asan.
686       auto Cmp = IRB.CreateICmpNE(
687           GuardLoad, Constant::getNullValue(GuardLoad->getType()));
688       auto Ins = SplitBlockAndInsertIfThen(
689           Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
690       IRB.SetCurrentDebugLocation(EntryLoc);
691       IRB.SetInsertPoint(Ins);
692     }
693     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
694     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
695   } else if (Options.TraceBB) {
696     IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
697   } else if (UseCalls) {
698     IRB.CreateCall(SanCovWithCheckFunction, GuardP);
699   } else {
700     LoadInst *Load = IRB.CreateLoad(GuardP);
701     Load->setAtomic(AtomicOrdering::Monotonic);
702     Load->setAlignment(4);
703     SetNoSanitizeMetadata(Load);
704     Value *Cmp =
705         IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
706     Instruction *Ins = SplitBlockAndInsertIfThen(
707         Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
708     IRB.SetInsertPoint(Ins);
709     IRB.SetCurrentDebugLocation(EntryLoc);
710     // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
711     IRB.CreateCall(SanCovFunction, GuardP);
712     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
713   }
714 
715   if (Options.Use8bitCounters) {
716     IRB.SetInsertPoint(&*IP);
717     Value *P = IRB.CreateAdd(
718         IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
719         ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
720     P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
721     LoadInst *LI = IRB.CreateLoad(P);
722     Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
723     StoreInst *SI = IRB.CreateStore(Inc, P);
724     SetNoSanitizeMetadata(LI);
725     SetNoSanitizeMetadata(SI);
726   }
727 }
728 
729 char SanitizerCoverageModule::ID = 0;
730 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
731                       "SanitizerCoverage: TODO."
732                       "ModulePass",
733                       false, false)
734 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
735 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
736 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
737                     "SanitizerCoverage: TODO."
738                     "ModulePass",
739                     false, false)
740 ModulePass *llvm::createSanitizerCoverageModulePass(
741     const SanitizerCoverageOptions &Options) {
742   return new SanitizerCoverageModule(Options);
743 }
744