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