xref: /llvm-project/llvm/lib/Transforms/Instrumentation/SanitizerCoverage.cpp (revision 0f2f1c2be164810da96f2bc7229ef56f54c7d137)
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/Transforms/Instrumentation/SanitizerCoverage.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/EHPersonalities.h"
18 #include "llvm/Analysis/GlobalsModRef.h"
19 #include "llvm/Analysis/PostDominators.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/DataLayout.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/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/SpecialCaseList.h"
34 #include "llvm/Support/VirtualFileSystem.h"
35 #include "llvm/Transforms/Instrumentation.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/ModuleUtils.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "sancov"
42 
43 const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
44 const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
45 const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
46 const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
47 const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
48 const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
49 const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
50 const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
51 const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
52 const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
53 const char SanCovLoad1[] = "__sanitizer_cov_load1";
54 const char SanCovLoad2[] = "__sanitizer_cov_load2";
55 const char SanCovLoad4[] = "__sanitizer_cov_load4";
56 const char SanCovLoad8[] = "__sanitizer_cov_load8";
57 const char SanCovLoad16[] = "__sanitizer_cov_load16";
58 const char SanCovStore1[] = "__sanitizer_cov_store1";
59 const char SanCovStore2[] = "__sanitizer_cov_store2";
60 const char SanCovStore4[] = "__sanitizer_cov_store4";
61 const char SanCovStore8[] = "__sanitizer_cov_store8";
62 const char SanCovStore16[] = "__sanitizer_cov_store16";
63 const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
64 const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
65 const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
66 const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
67 const char SanCovModuleCtorTracePcGuardName[] =
68     "sancov.module_ctor_trace_pc_guard";
69 const char SanCovModuleCtor8bitCountersName[] =
70     "sancov.module_ctor_8bit_counters";
71 const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
72 static const uint64_t SanCtorAndDtorPriority = 2;
73 
74 const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
75 const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
76 const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
77 const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
78 const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
79 
80 const char SanCovGuardsSectionName[] = "sancov_guards";
81 const char SanCovCountersSectionName[] = "sancov_cntrs";
82 const char SanCovBoolFlagSectionName[] = "sancov_bools";
83 const char SanCovPCsSectionName[] = "sancov_pcs";
84 
85 const char SanCovLowestStackName[] = "__sancov_lowest_stack";
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     cl::Hidden, cl::init(0));
92 
93 static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
94                                cl::desc("Experimental pc tracing"), cl::Hidden,
95                                cl::init(false));
96 
97 static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
98                                     cl::desc("pc tracing with a guard"),
99                                     cl::Hidden, cl::init(false));
100 
101 // If true, we create a global variable that contains PCs of all instrumented
102 // BBs, put this global into a named section, and pass this section's bounds
103 // to __sanitizer_cov_pcs_init.
104 // This way the coverage instrumentation does not need to acquire the PCs
105 // at run-time. Works with trace-pc-guard, inline-8bit-counters, and
106 // inline-bool-flag.
107 static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
108                                      cl::desc("create a static PC table"),
109                                      cl::Hidden, cl::init(false));
110 
111 static cl::opt<bool>
112     ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
113                          cl::desc("increments 8-bit counter for every edge"),
114                          cl::Hidden, cl::init(false));
115 
116 static cl::opt<bool>
117     ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
118                      cl::desc("sets a boolean flag for every edge"), cl::Hidden,
119                      cl::init(false));
120 
121 static cl::opt<bool>
122     ClCMPTracing("sanitizer-coverage-trace-compares",
123                  cl::desc("Tracing of CMP and similar instructions"),
124                  cl::Hidden, cl::init(false));
125 
126 static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
127                                   cl::desc("Tracing of DIV instructions"),
128                                   cl::Hidden, cl::init(false));
129 
130 static cl::opt<bool> ClLoadTracing("sanitizer-coverage-trace-loads",
131                                    cl::desc("Tracing of load instructions"),
132                                    cl::Hidden, cl::init(false));
133 
134 static cl::opt<bool> ClStoreTracing("sanitizer-coverage-trace-stores",
135                                     cl::desc("Tracing of store instructions"),
136                                     cl::Hidden, cl::init(false));
137 
138 static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
139                                   cl::desc("Tracing of GEP instructions"),
140                                   cl::Hidden, cl::init(false));
141 
142 static cl::opt<bool>
143     ClPruneBlocks("sanitizer-coverage-prune-blocks",
144                   cl::desc("Reduce the number of instrumented blocks"),
145                   cl::Hidden, cl::init(true));
146 
147 static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
148                                   cl::desc("max stack depth tracing"),
149                                   cl::Hidden, cl::init(false));
150 
151 namespace {
152 
153 SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
154   SanitizerCoverageOptions Res;
155   switch (LegacyCoverageLevel) {
156   case 0:
157     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
158     break;
159   case 1:
160     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
161     break;
162   case 2:
163     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
164     break;
165   case 3:
166     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
167     break;
168   case 4:
169     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
170     Res.IndirectCalls = true;
171     break;
172   }
173   return Res;
174 }
175 
176 SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
177   // Sets CoverageType and IndirectCalls.
178   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
179   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
180   Options.IndirectCalls |= CLOpts.IndirectCalls;
181   Options.TraceCmp |= ClCMPTracing;
182   Options.TraceDiv |= ClDIVTracing;
183   Options.TraceGep |= ClGEPTracing;
184   Options.TracePC |= ClTracePC;
185   Options.TracePCGuard |= ClTracePCGuard;
186   Options.Inline8bitCounters |= ClInline8bitCounters;
187   Options.InlineBoolFlag |= ClInlineBoolFlag;
188   Options.PCTable |= ClCreatePCTable;
189   Options.NoPrune |= !ClPruneBlocks;
190   Options.StackDepth |= ClStackDepth;
191   Options.TraceLoads |= ClLoadTracing;
192   Options.TraceStores |= ClStoreTracing;
193   if (!Options.TracePCGuard && !Options.TracePC &&
194       !Options.Inline8bitCounters && !Options.StackDepth &&
195       !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
196     Options.TracePCGuard = true; // TracePCGuard is default.
197   return Options;
198 }
199 
200 using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
201 using PostDomTreeCallback =
202     function_ref<const PostDominatorTree *(Function &F)>;
203 
204 class ModuleSanitizerCoverage {
205 public:
206   ModuleSanitizerCoverage(
207       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
208       const SpecialCaseList *Allowlist = nullptr,
209       const SpecialCaseList *Blocklist = nullptr)
210       : Options(OverrideFromCL(Options)), Allowlist(Allowlist),
211         Blocklist(Blocklist) {}
212   bool instrumentModule(Module &M, DomTreeCallback DTCallback,
213                         PostDomTreeCallback PDTCallback);
214 
215 private:
216   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
217                           PostDomTreeCallback PDTCallback);
218   void InjectCoverageForIndirectCalls(Function &F,
219                                       ArrayRef<Instruction *> IndirCalls);
220   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
221   void InjectTraceForDiv(Function &F,
222                          ArrayRef<BinaryOperator *> DivTraceTargets);
223   void InjectTraceForGep(Function &F,
224                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
225   void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
226                                     ArrayRef<StoreInst *> Stores);
227   void InjectTraceForSwitch(Function &F,
228                             ArrayRef<Instruction *> SwitchTraceTargets);
229   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
230                       bool IsLeafFunc = true);
231   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
232                                                     Function &F, Type *Ty,
233                                                     const char *Section);
234   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
235   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
236   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
237                              bool IsLeafFunc = true);
238   Function *CreateInitCallsForSections(Module &M, const char *CtorName,
239                                        const char *InitFunctionName, Type *Ty,
240                                        const char *Section);
241   std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
242                                                 Type *Ty);
243 
244   void SetNoSanitizeMetadata(Instruction *I) {
245     I->setMetadata(LLVMContext::MD_nosanitize, MDNode::get(*C, None));
246   }
247 
248   std::string getSectionName(const std::string &Section) const;
249   std::string getSectionStart(const std::string &Section) const;
250   std::string getSectionEnd(const std::string &Section) const;
251   FunctionCallee SanCovTracePCIndir;
252   FunctionCallee SanCovTracePC, SanCovTracePCGuard;
253   std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
254   std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
255   std::array<FunctionCallee, 5> SanCovLoadFunction;
256   std::array<FunctionCallee, 5> SanCovStoreFunction;
257   std::array<FunctionCallee, 2> SanCovTraceDivFunction;
258   FunctionCallee SanCovTraceGepFunction;
259   FunctionCallee SanCovTraceSwitchFunction;
260   GlobalVariable *SanCovLowestStack;
261   Type *Int128PtrTy, *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty,
262       *Int32PtrTy, *Int16PtrTy, *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty,
263       *Int1PtrTy;
264   Module *CurModule;
265   std::string CurModuleUniqueId;
266   Triple TargetTriple;
267   LLVMContext *C;
268   const DataLayout *DL;
269 
270   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
271   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
272   GlobalVariable *FunctionBoolArray;         // for inline-bool-flag.
273   GlobalVariable *FunctionPCsArray;  // for pc-table.
274   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
275   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
276 
277   SanitizerCoverageOptions Options;
278 
279   const SpecialCaseList *Allowlist;
280   const SpecialCaseList *Blocklist;
281 };
282 } // namespace
283 
284 PreservedAnalyses SanitizerCoveragePass::run(Module &M,
285                                              ModuleAnalysisManager &MAM) {
286   ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
287                                        Blocklist.get());
288   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
289   auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
290     return &FAM.getResult<DominatorTreeAnalysis>(F);
291   };
292   auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
293     return &FAM.getResult<PostDominatorTreeAnalysis>(F);
294   };
295   if (!ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
296     return PreservedAnalyses::all();
297 
298   PreservedAnalyses PA = PreservedAnalyses::none();
299   // GlobalsAA is considered stateless and does not get invalidated unless
300   // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
301   // make changes that require GlobalsAA to be invalidated.
302   PA.abandon<GlobalsAA>();
303   return PA;
304 }
305 
306 std::pair<Value *, Value *>
307 ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
308                                            Type *Ty) {
309   // Use ExternalWeak so that if all sections are discarded due to section
310   // garbage collection, the linker will not report undefined symbol errors.
311   // Windows defines the start/stop symbols in compiler-rt so no need for
312   // ExternalWeak.
313   GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
314                                           ? GlobalVariable::ExternalLinkage
315                                           : GlobalVariable::ExternalWeakLinkage;
316   GlobalVariable *SecStart =
317       new GlobalVariable(M, Ty, false, Linkage, nullptr,
318                          getSectionStart(Section));
319   SecStart->setVisibility(GlobalValue::HiddenVisibility);
320   GlobalVariable *SecEnd =
321       new GlobalVariable(M, Ty, false, Linkage, nullptr,
322                          getSectionEnd(Section));
323   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
324   IRBuilder<> IRB(M.getContext());
325   if (!TargetTriple.isOSBinFormatCOFF())
326     return std::make_pair(SecStart, SecEnd);
327 
328   // Account for the fact that on windows-msvc __start_* symbols actually
329   // point to a uint64_t before the start of the array.
330   auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
331   auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
332                            ConstantInt::get(IntptrTy, sizeof(uint64_t)));
333   return std::make_pair(IRB.CreatePointerCast(GEP, PointerType::getUnqual(Ty)),
334                         SecEnd);
335 }
336 
337 Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
338     Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
339     const char *Section) {
340   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
341   auto SecStart = SecStartEnd.first;
342   auto SecEnd = SecStartEnd.second;
343   Function *CtorFunc;
344   Type *PtrTy = PointerType::getUnqual(Ty);
345   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
346       M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
347   assert(CtorFunc->getName() == CtorName);
348 
349   if (TargetTriple.supportsCOMDAT()) {
350     // Use comdat to dedup CtorFunc.
351     CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
352     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
353   } else {
354     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
355   }
356 
357   if (TargetTriple.isOSBinFormatCOFF()) {
358     // In COFF files, if the contructors are set as COMDAT (they are because
359     // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
360     // functions and data) is used, the constructors get stripped. To prevent
361     // this, give the constructors weak ODR linkage and ensure the linker knows
362     // to include the sancov constructor. This way the linker can deduplicate
363     // the constructors but always leave one copy.
364     CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
365   }
366   return CtorFunc;
367 }
368 
369 bool ModuleSanitizerCoverage::instrumentModule(
370     Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
371   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
372     return false;
373   if (Allowlist &&
374       !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
375     return false;
376   if (Blocklist &&
377       Blocklist->inSection("coverage", "src", M.getSourceFileName()))
378     return false;
379   C = &(M.getContext());
380   DL = &M.getDataLayout();
381   CurModule = &M;
382   CurModuleUniqueId = getUniqueModuleId(CurModule);
383   TargetTriple = Triple(M.getTargetTriple());
384   FunctionGuardArray = nullptr;
385   Function8bitCounterArray = nullptr;
386   FunctionBoolArray = nullptr;
387   FunctionPCsArray = nullptr;
388   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
389   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
390   Type *VoidTy = Type::getVoidTy(*C);
391   IRBuilder<> IRB(*C);
392   Int128PtrTy = PointerType::getUnqual(IRB.getInt128Ty());
393   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
394   Int16PtrTy = PointerType::getUnqual(IRB.getInt16Ty());
395   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
396   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
397   Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
398   Int64Ty = IRB.getInt64Ty();
399   Int32Ty = IRB.getInt32Ty();
400   Int16Ty = IRB.getInt16Ty();
401   Int8Ty = IRB.getInt8Ty();
402   Int1Ty = IRB.getInt1Ty();
403 
404   SanCovTracePCIndir =
405       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
406   // Make sure smaller parameters are zero-extended to i64 if required by the
407   // target ABI.
408   AttributeList SanCovTraceCmpZeroExtAL;
409   SanCovTraceCmpZeroExtAL =
410       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
411   SanCovTraceCmpZeroExtAL =
412       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
413 
414   SanCovTraceCmpFunction[0] =
415       M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
416                             IRB.getInt8Ty(), IRB.getInt8Ty());
417   SanCovTraceCmpFunction[1] =
418       M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
419                             IRB.getInt16Ty(), IRB.getInt16Ty());
420   SanCovTraceCmpFunction[2] =
421       M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
422                             IRB.getInt32Ty(), IRB.getInt32Ty());
423   SanCovTraceCmpFunction[3] =
424       M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
425 
426   SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
427       SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
428   SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
429       SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
430   SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
431       SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
432   SanCovTraceConstCmpFunction[3] =
433       M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
434 
435   // Loads.
436   SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, Int8PtrTy);
437   SanCovLoadFunction[1] =
438       M.getOrInsertFunction(SanCovLoad2, VoidTy, Int16PtrTy);
439   SanCovLoadFunction[2] =
440       M.getOrInsertFunction(SanCovLoad4, VoidTy, Int32PtrTy);
441   SanCovLoadFunction[3] =
442       M.getOrInsertFunction(SanCovLoad8, VoidTy, Int64PtrTy);
443   SanCovLoadFunction[4] =
444       M.getOrInsertFunction(SanCovLoad16, VoidTy, Int128PtrTy);
445   // Stores.
446   SanCovStoreFunction[0] =
447       M.getOrInsertFunction(SanCovStore1, VoidTy, Int8PtrTy);
448   SanCovStoreFunction[1] =
449       M.getOrInsertFunction(SanCovStore2, VoidTy, Int16PtrTy);
450   SanCovStoreFunction[2] =
451       M.getOrInsertFunction(SanCovStore4, VoidTy, Int32PtrTy);
452   SanCovStoreFunction[3] =
453       M.getOrInsertFunction(SanCovStore8, VoidTy, Int64PtrTy);
454   SanCovStoreFunction[4] =
455       M.getOrInsertFunction(SanCovStore16, VoidTy, Int128PtrTy);
456 
457   {
458     AttributeList AL;
459     AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
460     SanCovTraceDivFunction[0] =
461         M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
462   }
463   SanCovTraceDivFunction[1] =
464       M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
465   SanCovTraceGepFunction =
466       M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
467   SanCovTraceSwitchFunction =
468       M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
469 
470   Constant *SanCovLowestStackConstant =
471       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
472   SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
473   if (!SanCovLowestStack || SanCovLowestStack->getValueType() != IntptrTy) {
474     C->emitError(StringRef("'") + SanCovLowestStackName +
475                  "' should not be declared by the user");
476     return true;
477   }
478   SanCovLowestStack->setThreadLocalMode(
479       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
480   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
481     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
482 
483   SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
484   SanCovTracePCGuard =
485       M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
486 
487   for (auto &F : M)
488     instrumentFunction(F, DTCallback, PDTCallback);
489 
490   Function *Ctor = nullptr;
491 
492   if (FunctionGuardArray)
493     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
494                                       SanCovTracePCGuardInitName, Int32Ty,
495                                       SanCovGuardsSectionName);
496   if (Function8bitCounterArray)
497     Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
498                                       SanCov8bitCountersInitName, Int8Ty,
499                                       SanCovCountersSectionName);
500   if (FunctionBoolArray) {
501     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
502                                       SanCovBoolFlagInitName, Int1Ty,
503                                       SanCovBoolFlagSectionName);
504   }
505   if (Ctor && Options.PCTable) {
506     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
507     FunctionCallee InitFunction = declareSanitizerInitFunction(
508         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
509     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
510     IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
511   }
512   appendToUsed(M, GlobalsToAppendToUsed);
513   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
514   return true;
515 }
516 
517 // True if block has successors and it dominates all of them.
518 static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
519   if (succ_empty(BB))
520     return false;
521 
522   return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
523     return DT->dominates(BB, SUCC);
524   });
525 }
526 
527 // True if block has predecessors and it postdominates all of them.
528 static bool isFullPostDominator(const BasicBlock *BB,
529                                 const PostDominatorTree *PDT) {
530   if (pred_empty(BB))
531     return false;
532 
533   return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
534     return PDT->dominates(BB, PRED);
535   });
536 }
537 
538 static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
539                                   const DominatorTree *DT,
540                                   const PostDominatorTree *PDT,
541                                   const SanitizerCoverageOptions &Options) {
542   // Don't insert coverage for blocks containing nothing but unreachable: we
543   // will never call __sanitizer_cov() for them, so counting them in
544   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
545   // percentage. Also, unreachable instructions frequently have no debug
546   // locations.
547   if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
548     return false;
549 
550   // Don't insert coverage into blocks without a valid insertion point
551   // (catchswitch blocks).
552   if (BB->getFirstInsertionPt() == BB->end())
553     return false;
554 
555   if (Options.NoPrune || &F.getEntryBlock() == BB)
556     return true;
557 
558   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
559       &F.getEntryBlock() != BB)
560     return false;
561 
562   // Do not instrument full dominators, or full post-dominators with multiple
563   // predecessors.
564   return !isFullDominator(BB, DT)
565     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
566 }
567 
568 
569 // Returns true iff From->To is a backedge.
570 // A twist here is that we treat From->To as a backedge if
571 //   * To dominates From or
572 //   * To->UniqueSuccessor dominates From
573 static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
574                        const DominatorTree *DT) {
575   if (DT->dominates(To, From))
576     return true;
577   if (auto Next = To->getUniqueSuccessor())
578     if (DT->dominates(Next, From))
579       return true;
580   return false;
581 }
582 
583 // Prunes uninteresting Cmp instrumentation:
584 //   * CMP instructions that feed into loop backedge branch.
585 //
586 // Note that Cmp pruning is controlled by the same flag as the
587 // BB pruning.
588 static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
589                              const SanitizerCoverageOptions &Options) {
590   if (!Options.NoPrune)
591     if (CMP->hasOneUse())
592       if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
593         for (BasicBlock *B : BR->successors())
594           if (IsBackEdge(BR->getParent(), B, DT))
595             return false;
596   return true;
597 }
598 
599 void ModuleSanitizerCoverage::instrumentFunction(
600     Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
601   if (F.empty())
602     return;
603   if (F.getName().find(".module_ctor") != std::string::npos)
604     return; // Should not instrument sanitizer init functions.
605   if (F.getName().startswith("__sanitizer_"))
606     return; // Don't instrument __sanitizer_* callbacks.
607   // Don't touch available_externally functions, their actual body is elewhere.
608   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
609     return;
610   // Don't instrument MSVC CRT configuration helpers. They may run before normal
611   // initialization.
612   if (F.getName() == "__local_stdio_printf_options" ||
613       F.getName() == "__local_stdio_scanf_options")
614     return;
615   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
616     return;
617   // Don't instrument functions using SEH for now. Splitting basic blocks like
618   // we do for coverage breaks WinEHPrepare.
619   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
620   if (F.hasPersonalityFn() &&
621       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
622     return;
623   if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
624     return;
625   if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
626     return;
627   if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
628     return;
629   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
630     SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
631   SmallVector<Instruction *, 8> IndirCalls;
632   SmallVector<BasicBlock *, 16> BlocksToInstrument;
633   SmallVector<Instruction *, 8> CmpTraceTargets;
634   SmallVector<Instruction *, 8> SwitchTraceTargets;
635   SmallVector<BinaryOperator *, 8> DivTraceTargets;
636   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
637   SmallVector<LoadInst *, 8> Loads;
638   SmallVector<StoreInst *, 8> Stores;
639 
640   const DominatorTree *DT = DTCallback(F);
641   const PostDominatorTree *PDT = PDTCallback(F);
642   bool IsLeafFunc = true;
643 
644   for (auto &BB : F) {
645     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
646       BlocksToInstrument.push_back(&BB);
647     for (auto &Inst : BB) {
648       if (Options.IndirectCalls) {
649         CallBase *CB = dyn_cast<CallBase>(&Inst);
650         if (CB && CB->isIndirectCall())
651           IndirCalls.push_back(&Inst);
652       }
653       if (Options.TraceCmp) {
654         if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
655           if (IsInterestingCmp(CMP, DT, Options))
656             CmpTraceTargets.push_back(&Inst);
657         if (isa<SwitchInst>(&Inst))
658           SwitchTraceTargets.push_back(&Inst);
659       }
660       if (Options.TraceDiv)
661         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
662           if (BO->getOpcode() == Instruction::SDiv ||
663               BO->getOpcode() == Instruction::UDiv)
664             DivTraceTargets.push_back(BO);
665       if (Options.TraceGep)
666         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
667           GepTraceTargets.push_back(GEP);
668       if (Options.TraceLoads)
669         if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
670           Loads.push_back(LI);
671       if (Options.TraceStores)
672         if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
673           Stores.push_back(SI);
674       if (Options.StackDepth)
675         if (isa<InvokeInst>(Inst) ||
676             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
677           IsLeafFunc = false;
678     }
679   }
680 
681   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
682   InjectCoverageForIndirectCalls(F, IndirCalls);
683   InjectTraceForCmp(F, CmpTraceTargets);
684   InjectTraceForSwitch(F, SwitchTraceTargets);
685   InjectTraceForDiv(F, DivTraceTargets);
686   InjectTraceForGep(F, GepTraceTargets);
687   InjectTraceForLoadsAndStores(F, Loads, Stores);
688 }
689 
690 GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
691     size_t NumElements, Function &F, Type *Ty, const char *Section) {
692   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
693   auto Array = new GlobalVariable(
694       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
695       Constant::getNullValue(ArrayTy), "__sancov_gen_");
696 
697   if (TargetTriple.supportsCOMDAT() &&
698       (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
699     if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
700       Array->setComdat(Comdat);
701   Array->setSection(getSectionName(Section));
702   Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
703 
704   // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
705   // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
706   // section(s) as a unit, so we conservatively retain all unconditionally in
707   // the compiler.
708   //
709   // With comdat (COFF/ELF), the linker can guarantee the associated sections
710   // will be retained or discarded as a unit, so llvm.compiler.used is
711   // sufficient. Otherwise, conservatively make all of them retained by the
712   // linker.
713   if (Array->hasComdat())
714     GlobalsToAppendToCompilerUsed.push_back(Array);
715   else
716     GlobalsToAppendToUsed.push_back(Array);
717 
718   return Array;
719 }
720 
721 GlobalVariable *
722 ModuleSanitizerCoverage::CreatePCArray(Function &F,
723                                        ArrayRef<BasicBlock *> AllBlocks) {
724   size_t N = AllBlocks.size();
725   assert(N);
726   SmallVector<Constant *, 32> PCs;
727   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
728   for (size_t i = 0; i < N; i++) {
729     if (&F.getEntryBlock() == AllBlocks[i]) {
730       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
731       PCs.push_back((Constant *)IRB.CreateIntToPtr(
732           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
733     } else {
734       PCs.push_back((Constant *)IRB.CreatePointerCast(
735           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
736       PCs.push_back(Constant::getNullValue(IntptrPtrTy));
737     }
738   }
739   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
740                                                     SanCovPCsSectionName);
741   PCArray->setInitializer(
742       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
743   PCArray->setConstant(true);
744 
745   return PCArray;
746 }
747 
748 void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
749     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
750   if (Options.TracePCGuard)
751     FunctionGuardArray = CreateFunctionLocalArrayInSection(
752         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
753 
754   if (Options.Inline8bitCounters)
755     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
756         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
757   if (Options.InlineBoolFlag)
758     FunctionBoolArray = CreateFunctionLocalArrayInSection(
759         AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
760 
761   if (Options.PCTable)
762     FunctionPCsArray = CreatePCArray(F, AllBlocks);
763 }
764 
765 bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
766                                              ArrayRef<BasicBlock *> AllBlocks,
767                                              bool IsLeafFunc) {
768   if (AllBlocks.empty()) return false;
769   CreateFunctionLocalArrays(F, AllBlocks);
770   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
771     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
772   return true;
773 }
774 
775 // On every indirect call we call a run-time function
776 // __sanitizer_cov_indir_call* with two parameters:
777 //   - callee address,
778 //   - global cache array that contains CacheSize pointers (zero-initialized).
779 //     The cache is used to speed up recording the caller-callee pairs.
780 // The address of the caller is passed implicitly via caller PC.
781 // CacheSize is encoded in the name of the run-time function.
782 void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
783     Function &F, ArrayRef<Instruction *> IndirCalls) {
784   if (IndirCalls.empty())
785     return;
786   assert(Options.TracePC || Options.TracePCGuard ||
787          Options.Inline8bitCounters || Options.InlineBoolFlag);
788   for (auto *I : IndirCalls) {
789     IRBuilder<> IRB(I);
790     CallBase &CB = cast<CallBase>(*I);
791     Value *Callee = CB.getCalledOperand();
792     if (isa<InlineAsm>(Callee))
793       continue;
794     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
795   }
796 }
797 
798 // For every switch statement we insert a call:
799 // __sanitizer_cov_trace_switch(CondValue,
800 //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
801 
802 void ModuleSanitizerCoverage::InjectTraceForSwitch(
803     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
804   for (auto *I : SwitchTraceTargets) {
805     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
806       IRBuilder<> IRB(I);
807       SmallVector<Constant *, 16> Initializers;
808       Value *Cond = SI->getCondition();
809       if (Cond->getType()->getScalarSizeInBits() >
810           Int64Ty->getScalarSizeInBits())
811         continue;
812       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
813       Initializers.push_back(
814           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
815       if (Cond->getType()->getScalarSizeInBits() <
816           Int64Ty->getScalarSizeInBits())
817         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
818       for (auto It : SI->cases()) {
819         Constant *C = It.getCaseValue();
820         if (C->getType()->getScalarSizeInBits() <
821             Int64Ty->getScalarSizeInBits())
822           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
823         Initializers.push_back(C);
824       }
825       llvm::sort(drop_begin(Initializers, 2),
826                  [](const Constant *A, const Constant *B) {
827                    return cast<ConstantInt>(A)->getLimitedValue() <
828                           cast<ConstantInt>(B)->getLimitedValue();
829                  });
830       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
831       GlobalVariable *GV = new GlobalVariable(
832           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
833           ConstantArray::get(ArrayOfInt64Ty, Initializers),
834           "__sancov_gen_cov_switch_values");
835       IRB.CreateCall(SanCovTraceSwitchFunction,
836                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
837     }
838   }
839 }
840 
841 void ModuleSanitizerCoverage::InjectTraceForDiv(
842     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
843   for (auto *BO : DivTraceTargets) {
844     IRBuilder<> IRB(BO);
845     Value *A1 = BO->getOperand(1);
846     if (isa<ConstantInt>(A1)) continue;
847     if (!A1->getType()->isIntegerTy())
848       continue;
849     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
850     int CallbackIdx = TypeSize == 32 ? 0 :
851         TypeSize == 64 ? 1 : -1;
852     if (CallbackIdx < 0) continue;
853     auto Ty = Type::getIntNTy(*C, TypeSize);
854     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
855                    {IRB.CreateIntCast(A1, Ty, true)});
856   }
857 }
858 
859 void ModuleSanitizerCoverage::InjectTraceForGep(
860     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
861   for (auto *GEP : GepTraceTargets) {
862     IRBuilder<> IRB(GEP);
863     for (Use &Idx : GEP->indices())
864       if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
865         IRB.CreateCall(SanCovTraceGepFunction,
866                        {IRB.CreateIntCast(Idx, IntptrTy, true)});
867   }
868 }
869 
870 void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
871     Function &, ArrayRef<LoadInst *> Loads, ArrayRef<StoreInst *> Stores) {
872   auto CallbackIdx = [&](Type *ElementTy) -> int {
873     uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
874     return TypeSize == 8     ? 0
875            : TypeSize == 16  ? 1
876            : TypeSize == 32  ? 2
877            : TypeSize == 64  ? 3
878            : TypeSize == 128 ? 4
879                              : -1;
880   };
881   Type *PointerType[5] = {Int8PtrTy, Int16PtrTy, Int32PtrTy, Int64PtrTy,
882                           Int128PtrTy};
883   for (auto *LI : Loads) {
884     IRBuilder<> IRB(LI);
885     auto Ptr = LI->getPointerOperand();
886     int Idx = CallbackIdx(LI->getType());
887     if (Idx < 0)
888       continue;
889     IRB.CreateCall(SanCovLoadFunction[Idx],
890                    IRB.CreatePointerCast(Ptr, PointerType[Idx]));
891   }
892   for (auto *SI : Stores) {
893     IRBuilder<> IRB(SI);
894     auto Ptr = SI->getPointerOperand();
895     int Idx = CallbackIdx(SI->getValueOperand()->getType());
896     if (Idx < 0)
897       continue;
898     IRB.CreateCall(SanCovStoreFunction[Idx],
899                    IRB.CreatePointerCast(Ptr, PointerType[Idx]));
900   }
901 }
902 
903 void ModuleSanitizerCoverage::InjectTraceForCmp(
904     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
905   for (auto *I : CmpTraceTargets) {
906     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
907       IRBuilder<> IRB(ICMP);
908       Value *A0 = ICMP->getOperand(0);
909       Value *A1 = ICMP->getOperand(1);
910       if (!A0->getType()->isIntegerTy())
911         continue;
912       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
913       int CallbackIdx = TypeSize == 8 ? 0 :
914                         TypeSize == 16 ? 1 :
915                         TypeSize == 32 ? 2 :
916                         TypeSize == 64 ? 3 : -1;
917       if (CallbackIdx < 0) continue;
918       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
919       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
920       bool FirstIsConst = isa<ConstantInt>(A0);
921       bool SecondIsConst = isa<ConstantInt>(A1);
922       // If both are const, then we don't need such a comparison.
923       if (FirstIsConst && SecondIsConst) continue;
924       // If only one is const, then make it the first callback argument.
925       if (FirstIsConst || SecondIsConst) {
926         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
927         if (SecondIsConst)
928           std::swap(A0, A1);
929       }
930 
931       auto Ty = Type::getIntNTy(*C, TypeSize);
932       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
933               IRB.CreateIntCast(A1, Ty, true)});
934     }
935   }
936 }
937 
938 void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
939                                                     size_t Idx,
940                                                     bool IsLeafFunc) {
941   BasicBlock::iterator IP = BB.getFirstInsertionPt();
942   bool IsEntryBB = &BB == &F.getEntryBlock();
943   DebugLoc EntryLoc;
944   if (IsEntryBB) {
945     if (auto SP = F.getSubprogram())
946       EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
947     // Keep static allocas and llvm.localescape calls in the entry block.  Even
948     // if we aren't splitting the block, it's nice for allocas to be before
949     // calls.
950     IP = PrepareToSplitEntryBlock(BB, IP);
951   }
952 
953   InstrumentationIRBuilder IRB(&*IP);
954   if (EntryLoc)
955     IRB.SetCurrentDebugLocation(EntryLoc);
956   if (Options.TracePC) {
957     IRB.CreateCall(SanCovTracePC)
958         ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
959   }
960   if (Options.TracePCGuard) {
961     auto GuardPtr = IRB.CreateIntToPtr(
962         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
963                       ConstantInt::get(IntptrTy, Idx * 4)),
964         Int32PtrTy);
965     IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
966   }
967   if (Options.Inline8bitCounters) {
968     auto CounterPtr = IRB.CreateGEP(
969         Function8bitCounterArray->getValueType(), Function8bitCounterArray,
970         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
971     auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
972     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
973     auto Store = IRB.CreateStore(Inc, CounterPtr);
974     SetNoSanitizeMetadata(Load);
975     SetNoSanitizeMetadata(Store);
976   }
977   if (Options.InlineBoolFlag) {
978     auto FlagPtr = IRB.CreateGEP(
979         FunctionBoolArray->getValueType(), FunctionBoolArray,
980         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
981     auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
982     auto ThenTerm =
983         SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
984     IRBuilder<> ThenIRB(ThenTerm);
985     auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
986     SetNoSanitizeMetadata(Load);
987     SetNoSanitizeMetadata(Store);
988   }
989   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
990     // Check stack depth.  If it's the deepest so far, record it.
991     Module *M = F.getParent();
992     Function *GetFrameAddr = Intrinsic::getDeclaration(
993         M, Intrinsic::frameaddress,
994         IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
995     auto FrameAddrPtr =
996         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
997     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
998     auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
999     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
1000     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
1001     IRBuilder<> ThenIRB(ThenTerm);
1002     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
1003     SetNoSanitizeMetadata(LowestStack);
1004     SetNoSanitizeMetadata(Store);
1005   }
1006 }
1007 
1008 std::string
1009 ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1010   if (TargetTriple.isOSBinFormatCOFF()) {
1011     if (Section == SanCovCountersSectionName)
1012       return ".SCOV$CM";
1013     if (Section == SanCovBoolFlagSectionName)
1014       return ".SCOV$BM";
1015     if (Section == SanCovPCsSectionName)
1016       return ".SCOVP$M";
1017     return ".SCOV$GM"; // For SanCovGuardsSectionName.
1018   }
1019   if (TargetTriple.isOSBinFormatMachO())
1020     return "__DATA,__" + Section;
1021   return "__" + Section;
1022 }
1023 
1024 std::string
1025 ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1026   if (TargetTriple.isOSBinFormatMachO())
1027     return "\1section$start$__DATA$__" + Section;
1028   return "__start___" + Section;
1029 }
1030 
1031 std::string
1032 ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1033   if (TargetTriple.isOSBinFormatMachO())
1034     return "\1section$end$__DATA$__" + Section;
1035   return "__stop___" + Section;
1036 }
1037