xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 14359ef1b6a0610ac91df5f5a91c88a0b51c187c)
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"
15 #include "llvm/Analysis/EHPersonalities.h"
16 #include "llvm/Analysis/PostDominators.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"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Transforms/Instrumentation.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/ModuleUtils.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 
81 static cl::opt<int> ClCoverageLevel(
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) {
134   SanitizerCoverageOptions Res;
135   switch (LegacyCoverageLevel) {
136   case 0:
137     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
138     break;
139   case 1:
140     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
141     break;
142   case 2:
143     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
144     break;
145   case 3:
146     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
147     break;
148   case 4:
149     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
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;
166   Options.Inline8bitCounters |= ClInline8bitCounters;
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(
179       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
180       : ModulePass(ID), Options(OverrideFromCL(Options)) {
181     initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
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 {
189     AU.addRequired<DominatorTreeWrapperPass>();
190     AU.addRequired<PostDominatorTreeWrapperPass>();
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   FunctionCallee SanCovTracePCIndir;
226   FunctionCallee SanCovTracePC, SanCovTracePCGuard;
227   FunctionCallee SanCovTraceCmpFunction[4];
228   FunctionCallee SanCovTraceConstCmpFunction[4];
229   FunctionCallee SanCovTraceDivFunction[2];
230   FunctionCallee SanCovTraceGepFunction;
231   FunctionCallee 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));
259   SecStart->setVisibility(GlobalValue::HiddenVisibility);
260   GlobalVariable *SecEnd =
261       new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
262                          nullptr, getSectionEnd(Section));
263   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
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 {
292     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
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.
302     CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
303     appendToUsed(M, CtorFunc);
304   }
305   return CtorFunc;
306 }
307 
308 bool SanitizerCoverageModule::runOnModule(Module &M) {
309   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
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 =
332       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
333   // Make sure smaller parameters are zero-extended to i64 as required by the
334   // x86_64 ABI.
335   AttributeList SanCovTraceCmpZeroExtAL;
336   if (TargetTriple.getArch() == Triple::x86_64) {
337     SanCovTraceCmpZeroExtAL =
338         SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
339     SanCovTraceCmpZeroExtAL =
340         SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
341   }
342 
343   SanCovTraceCmpFunction[0] =
344       M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
345                             IRB.getInt8Ty(), IRB.getInt8Ty());
346   SanCovTraceCmpFunction[1] =
347       M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
348                             IRB.getInt16Ty(), IRB.getInt16Ty());
349   SanCovTraceCmpFunction[2] =
350       M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
351                             IRB.getInt32Ty(), IRB.getInt32Ty());
352   SanCovTraceCmpFunction[3] =
353       M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
354 
355   SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
356       SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
357   SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
358       SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
359   SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
360       SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
361   SanCovTraceConstCmpFunction[3] =
362       M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
363 
364   {
365     AttributeList AL;
366     if (TargetTriple.getArch() == Triple::x86_64)
367       AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
368     SanCovTraceDivFunction[0] =
369         M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
370   }
371   SanCovTraceDivFunction[1] =
372       M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
373   SanCovTraceGepFunction =
374       M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
375   SanCovTraceSwitchFunction =
376       M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
377 
378   Constant *SanCovLowestStackConstant =
379       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
380   SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
381   SanCovLowestStack->setThreadLocalMode(
382       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
383   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
384     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
385 
386   // We insert an empty inline asm after cov callbacks to avoid callback merge.
387   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
388                             StringRef(""), StringRef(""),
389                             /*hasSideEffects=*/true);
390 
391   SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
392   SanCovTracePCGuard =
393       M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
394 
395   for (auto &F : M)
396     runOnFunction(F);
397 
398   Function *Ctor = nullptr;
399 
400   if (FunctionGuardArray)
401     Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
402                                       SanCovGuardsSectionName);
403   if (Function8bitCounterArray)
404     Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
405                                       SanCovCountersSectionName);
406   if (Ctor && Options.PCTable) {
407     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
408     FunctionCallee InitFunction = declareSanitizerInitFunction(
409         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
410     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
411     IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
412   }
413   // We don't reference these arrays directly in any of our runtime functions,
414   // so we need to prevent them from being dead stripped.
415   if (TargetTriple.isOSBinFormatMachO())
416     appendToUsed(M, GlobalsToAppendToUsed);
417   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
418   return true;
419 }
420 
421 // True if block has successors and it dominates all of them.
422 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
423   if (succ_begin(BB) == succ_end(BB))
424     return false;
425 
426   for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
427     if (!DT->dominates(BB, SUCC))
428       return false;
429   }
430 
431   return true;
432 }
433 
434 // True if block has predecessors and it postdominates all of them.
435 static bool isFullPostDominator(const BasicBlock *BB,
436                                 const PostDominatorTree *PDT) {
437   if (pred_begin(BB) == pred_end(BB))
438     return false;
439 
440   for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
441     if (!PDT->dominates(BB, PRED))
442       return false;
443   }
444 
445   return true;
446 }
447 
448 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
449                                   const DominatorTree *DT,
450                                   const PostDominatorTree *PDT,
451                                   const SanitizerCoverageOptions &Options) {
452   // Don't insert coverage for unreachable blocks: we will never call
453   // __sanitizer_cov() for them, so counting them in
454   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
455   // percentage. Also, unreachable instructions frequently have no debug
456   // locations.
457   if (isa<UnreachableInst>(BB->getTerminator()))
458     return false;
459 
460   // Don't insert coverage into blocks without a valid insertion point
461   // (catchswitch blocks).
462   if (BB->getFirstInsertionPt() == BB->end())
463     return false;
464 
465   if (Options.NoPrune || &F.getEntryBlock() == BB)
466     return true;
467 
468   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
469       &F.getEntryBlock() != BB)
470     return false;
471 
472   // Do not instrument full dominators, or full post-dominators with multiple
473   // predecessors.
474   return !isFullDominator(BB, DT)
475     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
476 }
477 
478 
479 // Returns true iff From->To is a backedge.
480 // A twist here is that we treat From->To as a backedge if
481 //   * To dominates From or
482 //   * To->UniqueSuccessor dominates From
483 static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
484                        const DominatorTree *DT) {
485   if (DT->dominates(To, From))
486     return true;
487   if (auto Next = To->getUniqueSuccessor())
488     if (DT->dominates(Next, From))
489       return true;
490   return false;
491 }
492 
493 // Prunes uninteresting Cmp instrumentation:
494 //   * CMP instructions that feed into loop backedge branch.
495 //
496 // Note that Cmp pruning is controlled by the same flag as the
497 // BB pruning.
498 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
499                              const SanitizerCoverageOptions &Options) {
500   if (!Options.NoPrune)
501     if (CMP->hasOneUse())
502       if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
503         for (BasicBlock *B : BR->successors())
504           if (IsBackEdge(BR->getParent(), B, DT))
505             return false;
506   return true;
507 }
508 
509 bool SanitizerCoverageModule::runOnFunction(Function &F) {
510   if (F.empty())
511     return false;
512   if (F.getName().find(".module_ctor") != std::string::npos)
513     return false; // Should not instrument sanitizer init functions.
514   if (F.getName().startswith("__sanitizer_"))
515     return false;  // Don't instrument __sanitizer_* callbacks.
516   // Don't touch available_externally functions, their actual body is elewhere.
517   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
518     return false;
519   // Don't instrument MSVC CRT configuration helpers. They may run before normal
520   // initialization.
521   if (F.getName() == "__local_stdio_printf_options" ||
522       F.getName() == "__local_stdio_scanf_options")
523     return false;
524   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
525     return false;
526   // Don't instrument functions using SEH for now. Splitting basic blocks like
527   // we do for coverage breaks WinEHPrepare.
528   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
529   if (F.hasPersonalityFn() &&
530       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
531     return false;
532   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
533     SplitAllCriticalEdges(F);
534   SmallVector<Instruction *, 8> IndirCalls;
535   SmallVector<BasicBlock *, 16> BlocksToInstrument;
536   SmallVector<Instruction *, 8> CmpTraceTargets;
537   SmallVector<Instruction *, 8> SwitchTraceTargets;
538   SmallVector<BinaryOperator *, 8> DivTraceTargets;
539   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
540 
541   const DominatorTree *DT =
542       &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
543   const PostDominatorTree *PDT =
544       &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
545   bool IsLeafFunc = true;
546 
547   for (auto &BB : F) {
548     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
549       BlocksToInstrument.push_back(&BB);
550     for (auto &Inst : BB) {
551       if (Options.IndirectCalls) {
552         CallSite CS(&Inst);
553         if (CS && !CS.getCalledFunction())
554           IndirCalls.push_back(&Inst);
555       }
556       if (Options.TraceCmp) {
557         if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
558           if (IsInterestingCmp(CMP, DT, Options))
559             CmpTraceTargets.push_back(&Inst);
560         if (isa<SwitchInst>(&Inst))
561           SwitchTraceTargets.push_back(&Inst);
562       }
563       if (Options.TraceDiv)
564         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
565           if (BO->getOpcode() == Instruction::SDiv ||
566               BO->getOpcode() == Instruction::UDiv)
567             DivTraceTargets.push_back(BO);
568       if (Options.TraceGep)
569         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
570           GepTraceTargets.push_back(GEP);
571       if (Options.StackDepth)
572         if (isa<InvokeInst>(Inst) ||
573             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
574           IsLeafFunc = false;
575     }
576   }
577 
578   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
579   InjectCoverageForIndirectCalls(F, IndirCalls);
580   InjectTraceForCmp(F, CmpTraceTargets);
581   InjectTraceForSwitch(F, SwitchTraceTargets);
582   InjectTraceForDiv(F, DivTraceTargets);
583   InjectTraceForGep(F, GepTraceTargets);
584   return true;
585 }
586 
587 GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
588     size_t NumElements, Function &F, Type *Ty, const char *Section) {
589   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
590   auto Array = new GlobalVariable(
591       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
592       Constant::getNullValue(ArrayTy), "__sancov_gen_");
593 
594   if (TargetTriple.supportsCOMDAT() && !F.isInterposable())
595     if (auto Comdat =
596             GetOrCreateFunctionComdat(F, TargetTriple, CurModuleUniqueId))
597       Array->setComdat(Comdat);
598   Array->setSection(getSectionName(Section));
599   Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
600                                         : Ty->getPrimitiveSizeInBits() / 8);
601   GlobalsToAppendToUsed.push_back(Array);
602   GlobalsToAppendToCompilerUsed.push_back(Array);
603   MDNode *MD = MDNode::get(F.getContext(), ValueAsMetadata::get(&F));
604   Array->addMetadata(LLVMContext::MD_associated, *MD);
605 
606   return Array;
607 }
608 
609 GlobalVariable *
610 SanitizerCoverageModule::CreatePCArray(Function &F,
611                                        ArrayRef<BasicBlock *> AllBlocks) {
612   size_t N = AllBlocks.size();
613   assert(N);
614   SmallVector<Constant *, 32> PCs;
615   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
616   for (size_t i = 0; i < N; i++) {
617     if (&F.getEntryBlock() == AllBlocks[i]) {
618       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
619       PCs.push_back((Constant *)IRB.CreateIntToPtr(
620           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
621     } else {
622       PCs.push_back((Constant *)IRB.CreatePointerCast(
623           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
624       PCs.push_back((Constant *)IRB.CreateIntToPtr(
625           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
626     }
627   }
628   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
629                                                     SanCovPCsSectionName);
630   PCArray->setInitializer(
631       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
632   PCArray->setConstant(true);
633 
634   return PCArray;
635 }
636 
637 void SanitizerCoverageModule::CreateFunctionLocalArrays(
638     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
639   if (Options.TracePCGuard)
640     FunctionGuardArray = CreateFunctionLocalArrayInSection(
641         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
642 
643   if (Options.Inline8bitCounters)
644     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
645         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
646 
647   if (Options.PCTable)
648     FunctionPCsArray = CreatePCArray(F, AllBlocks);
649 }
650 
651 bool SanitizerCoverageModule::InjectCoverage(Function &F,
652                                              ArrayRef<BasicBlock *> AllBlocks,
653                                              bool IsLeafFunc) {
654   if (AllBlocks.empty()) return false;
655   CreateFunctionLocalArrays(F, AllBlocks);
656   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
657     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
658   return true;
659 }
660 
661 // On every indirect call we call a run-time function
662 // __sanitizer_cov_indir_call* with two parameters:
663 //   - callee address,
664 //   - global cache array that contains CacheSize pointers (zero-initialized).
665 //     The cache is used to speed up recording the caller-callee pairs.
666 // The address of the caller is passed implicitly via caller PC.
667 // CacheSize is encoded in the name of the run-time function.
668 void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
669     Function &F, ArrayRef<Instruction *> IndirCalls) {
670   if (IndirCalls.empty())
671     return;
672   assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
673   for (auto I : IndirCalls) {
674     IRBuilder<> IRB(I);
675     CallSite CS(I);
676     Value *Callee = CS.getCalledValue();
677     if (isa<InlineAsm>(Callee))
678       continue;
679     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
680   }
681 }
682 
683 // For every switch statement we insert a call:
684 // __sanitizer_cov_trace_switch(CondValue,
685 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
686 
687 void SanitizerCoverageModule::InjectTraceForSwitch(
688     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
689   for (auto I : SwitchTraceTargets) {
690     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
691       IRBuilder<> IRB(I);
692       SmallVector<Constant *, 16> Initializers;
693       Value *Cond = SI->getCondition();
694       if (Cond->getType()->getScalarSizeInBits() >
695           Int64Ty->getScalarSizeInBits())
696         continue;
697       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
698       Initializers.push_back(
699           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
700       if (Cond->getType()->getScalarSizeInBits() <
701           Int64Ty->getScalarSizeInBits())
702         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
703       for (auto It : SI->cases()) {
704         Constant *C = It.getCaseValue();
705         if (C->getType()->getScalarSizeInBits() <
706             Int64Ty->getScalarSizeInBits())
707           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
708         Initializers.push_back(C);
709       }
710       llvm::sort(Initializers.begin() + 2, Initializers.end(),
711                  [](const Constant *A, const Constant *B) {
712                    return cast<ConstantInt>(A)->getLimitedValue() <
713                           cast<ConstantInt>(B)->getLimitedValue();
714                  });
715       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
716       GlobalVariable *GV = new GlobalVariable(
717           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
718           ConstantArray::get(ArrayOfInt64Ty, Initializers),
719           "__sancov_gen_cov_switch_values");
720       IRB.CreateCall(SanCovTraceSwitchFunction,
721                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
722     }
723   }
724 }
725 
726 void SanitizerCoverageModule::InjectTraceForDiv(
727     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
728   for (auto BO : DivTraceTargets) {
729     IRBuilder<> IRB(BO);
730     Value *A1 = BO->getOperand(1);
731     if (isa<ConstantInt>(A1)) continue;
732     if (!A1->getType()->isIntegerTy())
733       continue;
734     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
735     int CallbackIdx = TypeSize == 32 ? 0 :
736         TypeSize == 64 ? 1 : -1;
737     if (CallbackIdx < 0) continue;
738     auto Ty = Type::getIntNTy(*C, TypeSize);
739     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
740                    {IRB.CreateIntCast(A1, Ty, true)});
741   }
742 }
743 
744 void SanitizerCoverageModule::InjectTraceForGep(
745     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
746   for (auto GEP : GepTraceTargets) {
747     IRBuilder<> IRB(GEP);
748     for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
749       if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
750         IRB.CreateCall(SanCovTraceGepFunction,
751                        {IRB.CreateIntCast(*I, IntptrTy, true)});
752   }
753 }
754 
755 void SanitizerCoverageModule::InjectTraceForCmp(
756     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
757   for (auto I : CmpTraceTargets) {
758     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
759       IRBuilder<> IRB(ICMP);
760       Value *A0 = ICMP->getOperand(0);
761       Value *A1 = ICMP->getOperand(1);
762       if (!A0->getType()->isIntegerTy())
763         continue;
764       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
765       int CallbackIdx = TypeSize == 8 ? 0 :
766                         TypeSize == 16 ? 1 :
767                         TypeSize == 32 ? 2 :
768                         TypeSize == 64 ? 3 : -1;
769       if (CallbackIdx < 0) continue;
770       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
771       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
772       bool FirstIsConst = isa<ConstantInt>(A0);
773       bool SecondIsConst = isa<ConstantInt>(A1);
774       // If both are const, then we don't need such a comparison.
775       if (FirstIsConst && SecondIsConst) continue;
776       // If only one is const, then make it the first callback argument.
777       if (FirstIsConst || SecondIsConst) {
778         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
779         if (SecondIsConst)
780           std::swap(A0, A1);
781       }
782 
783       auto Ty = Type::getIntNTy(*C, TypeSize);
784       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
785               IRB.CreateIntCast(A1, Ty, true)});
786     }
787   }
788 }
789 
790 void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
791                                                     size_t Idx,
792                                                     bool IsLeafFunc) {
793   BasicBlock::iterator IP = BB.getFirstInsertionPt();
794   bool IsEntryBB = &BB == &F.getEntryBlock();
795   DebugLoc EntryLoc;
796   if (IsEntryBB) {
797     if (auto SP = F.getSubprogram())
798       EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
799     // Keep static allocas and llvm.localescape calls in the entry block.  Even
800     // if we aren't splitting the block, it's nice for allocas to be before
801     // calls.
802     IP = PrepareToSplitEntryBlock(BB, IP);
803   } else {
804     EntryLoc = IP->getDebugLoc();
805   }
806 
807   IRBuilder<> IRB(&*IP);
808   IRB.SetCurrentDebugLocation(EntryLoc);
809   if (Options.TracePC) {
810     IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
811     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
812   }
813   if (Options.TracePCGuard) {
814     auto GuardPtr = IRB.CreateIntToPtr(
815         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
816                       ConstantInt::get(IntptrTy, Idx * 4)),
817         Int32PtrTy);
818     IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
819     IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
820   }
821   if (Options.Inline8bitCounters) {
822     auto CounterPtr = IRB.CreateGEP(
823         Function8bitCounterArray,
824         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
825     auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
826     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
827     auto Store = IRB.CreateStore(Inc, CounterPtr);
828     SetNoSanitizeMetadata(Load);
829     SetNoSanitizeMetadata(Store);
830   }
831   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
832     // Check stack depth.  If it's the deepest so far, record it.
833     Function *GetFrameAddr =
834         Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
835     auto FrameAddrPtr =
836         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
837     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
838     auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
839     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
840     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
841     IRBuilder<> ThenIRB(ThenTerm);
842     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
843     SetNoSanitizeMetadata(LowestStack);
844     SetNoSanitizeMetadata(Store);
845   }
846 }
847 
848 std::string
849 SanitizerCoverageModule::getSectionName(const std::string &Section) const {
850   if (TargetTriple.isOSBinFormatCOFF()) {
851     if (Section == SanCovCountersSectionName)
852       return ".SCOV$CM";
853     if (Section == SanCovPCsSectionName)
854       return ".SCOVP$M";
855     return ".SCOV$GM"; // For SanCovGuardsSectionName.
856   }
857   if (TargetTriple.isOSBinFormatMachO())
858     return "__DATA,__" + Section;
859   return "__" + Section;
860 }
861 
862 std::string
863 SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
864   if (TargetTriple.isOSBinFormatMachO())
865     return "\1section$start$__DATA$__" + Section;
866   return "__start___" + Section;
867 }
868 
869 std::string
870 SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
871   if (TargetTriple.isOSBinFormatMachO())
872     return "\1section$end$__DATA$__" + Section;
873   return "__stop___" + Section;
874 }
875 
876 
877 char SanitizerCoverageModule::ID = 0;
878 INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
879                       "SanitizerCoverage: TODO."
880                       "ModulePass",
881                       false, false)
882 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
883 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
884 INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
885                     "SanitizerCoverage: TODO."
886                     "ModulePass",
887                     false, false)
888 ModulePass *llvm::createSanitizerCoverageModulePass(
889     const SanitizerCoverageOptions &Options) {
890   return new SanitizerCoverageModule(Options);
891 }
892