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