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