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