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