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