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