129a18dcbSKostya Serebryany //===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
229a18dcbSKostya Serebryany //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
629a18dcbSKostya Serebryany //
729a18dcbSKostya Serebryany //===----------------------------------------------------------------------===//
829a18dcbSKostya Serebryany //
953b34c84SKostya Serebryany // Coverage instrumentation done on LLVM IR level, works with Sanitizers.
1029a18dcbSKostya Serebryany //
1129a18dcbSKostya Serebryany //===----------------------------------------------------------------------===//
1229a18dcbSKostya Serebryany 
13007f674cSLeonard Chan #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
1429a18dcbSKostya Serebryany #include "llvm/ADT/ArrayRef.h"
1529a18dcbSKostya Serebryany #include "llvm/ADT/SmallVector.h"
16ffe8720aSserge-sans-paille #include "llvm/ADT/Triple.h"
1770497c69SDavid Majnemer #include "llvm/Analysis/EHPersonalities.h"
18018472c3SGeorge Karpenkov #include "llvm/Analysis/PostDominators.h"
195c7fc769SMatt Morehouse #include "llvm/IR/Constant.h"
2029a18dcbSKostya Serebryany #include "llvm/IR/DataLayout.h"
215971f181SMike Aizatsky #include "llvm/IR/Dominators.h"
2229a18dcbSKostya Serebryany #include "llvm/IR/Function.h"
235c7fc769SMatt Morehouse #include "llvm/IR/GlobalVariable.h"
2429a18dcbSKostya Serebryany #include "llvm/IR/IRBuilder.h"
25034126e5SMatt Morehouse #include "llvm/IR/IntrinsicInst.h"
265c7fc769SMatt Morehouse #include "llvm/IR/Intrinsics.h"
2729a18dcbSKostya Serebryany #include "llvm/IR/LLVMContext.h"
2829a18dcbSKostya Serebryany #include "llvm/IR/Module.h"
2929a18dcbSKostya Serebryany #include "llvm/IR/Type.h"
3005da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
3129a18dcbSKostya Serebryany #include "llvm/Support/CommandLine.h"
32bef187c7SMatt Morehouse #include "llvm/Support/SpecialCaseList.h"
33bef187c7SMatt Morehouse #include "llvm/Support/VirtualFileSystem.h"
345971f181SMike Aizatsky #include "llvm/Transforms/Instrumentation.h"
3529a18dcbSKostya Serebryany #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3629a18dcbSKostya Serebryany #include "llvm/Transforms/Utils/ModuleUtils.h"
3729a18dcbSKostya Serebryany 
3829a18dcbSKostya Serebryany using namespace llvm;
3929a18dcbSKostya Serebryany 
4029a18dcbSKostya Serebryany #define DEBUG_TYPE "sancov"
4129a18dcbSKostya Serebryany 
42a5309438SFangrui Song const char SanCovTracePCIndirName[] = "__sanitizer_cov_trace_pc_indir";
43a5309438SFangrui Song const char SanCovTracePCName[] = "__sanitizer_cov_trace_pc";
44a5309438SFangrui Song const char SanCovTraceCmp1[] = "__sanitizer_cov_trace_cmp1";
45a5309438SFangrui Song const char SanCovTraceCmp2[] = "__sanitizer_cov_trace_cmp2";
46a5309438SFangrui Song const char SanCovTraceCmp4[] = "__sanitizer_cov_trace_cmp4";
47a5309438SFangrui Song const char SanCovTraceCmp8[] = "__sanitizer_cov_trace_cmp8";
48a5309438SFangrui Song const char SanCovTraceConstCmp1[] = "__sanitizer_cov_trace_const_cmp1";
49a5309438SFangrui Song const char SanCovTraceConstCmp2[] = "__sanitizer_cov_trace_const_cmp2";
50a5309438SFangrui Song const char SanCovTraceConstCmp4[] = "__sanitizer_cov_trace_const_cmp4";
51a5309438SFangrui Song const char SanCovTraceConstCmp8[] = "__sanitizer_cov_trace_const_cmp8";
52b7f3a4f4SKostya Serebryany const char SanCovLoad1[] = "__sanitizer_cov_load1";
53b7f3a4f4SKostya Serebryany const char SanCovLoad2[] = "__sanitizer_cov_load2";
54b7f3a4f4SKostya Serebryany const char SanCovLoad4[] = "__sanitizer_cov_load4";
55b7f3a4f4SKostya Serebryany const char SanCovLoad8[] = "__sanitizer_cov_load8";
56b7f3a4f4SKostya Serebryany const char SanCovLoad16[] = "__sanitizer_cov_load16";
57b7f3a4f4SKostya Serebryany const char SanCovStore1[] = "__sanitizer_cov_store1";
58b7f3a4f4SKostya Serebryany const char SanCovStore2[] = "__sanitizer_cov_store2";
59b7f3a4f4SKostya Serebryany const char SanCovStore4[] = "__sanitizer_cov_store4";
60b7f3a4f4SKostya Serebryany const char SanCovStore8[] = "__sanitizer_cov_store8";
61b7f3a4f4SKostya Serebryany const char SanCovStore16[] = "__sanitizer_cov_store16";
62a5309438SFangrui Song const char SanCovTraceDiv4[] = "__sanitizer_cov_trace_div4";
63a5309438SFangrui Song const char SanCovTraceDiv8[] = "__sanitizer_cov_trace_div8";
64a5309438SFangrui Song const char SanCovTraceGep[] = "__sanitizer_cov_trace_gep";
65a5309438SFangrui Song const char SanCovTraceSwitchName[] = "__sanitizer_cov_trace_switch";
66a5309438SFangrui Song const char SanCovModuleCtorTracePcGuardName[] =
67a400ca3fSFangrui Song     "sancov.module_ctor_trace_pc_guard";
68a5309438SFangrui Song const char SanCovModuleCtor8bitCountersName[] =
69a400ca3fSFangrui Song     "sancov.module_ctor_8bit_counters";
70a5309438SFangrui Song const char SanCovModuleCtorBoolFlagName[] = "sancov.module_ctor_bool_flag";
71759aca01SMike Aizatsky static const uint64_t SanCtorAndDtorPriority = 2;
7229a18dcbSKostya Serebryany 
73a5309438SFangrui Song const char SanCovTracePCGuardName[] = "__sanitizer_cov_trace_pc_guard";
74a5309438SFangrui Song const char SanCovTracePCGuardInitName[] = "__sanitizer_cov_trace_pc_guard_init";
75a5309438SFangrui Song const char SanCov8bitCountersInitName[] = "__sanitizer_cov_8bit_counters_init";
76a5309438SFangrui Song const char SanCovBoolFlagInitName[] = "__sanitizer_cov_bool_flag_init";
77a5309438SFangrui Song const char SanCovPCsInitName[] = "__sanitizer_cov_pcs_init";
78da718e55SKostya Serebryany 
79a5309438SFangrui Song const char SanCovGuardsSectionName[] = "sancov_guards";
80a5309438SFangrui Song const char SanCovCountersSectionName[] = "sancov_cntrs";
81a5309438SFangrui Song const char SanCovBoolFlagSectionName[] = "sancov_bools";
82a5309438SFangrui Song const char SanCovPCsSectionName[] = "sancov_pcs";
83aed6ba77SKostya Serebryany 
84a5309438SFangrui Song const char SanCovLowestStackName[] = "__sancov_lowest_stack";
855c7fc769SMatt Morehouse 
86759aca01SMike Aizatsky static cl::opt<int> ClCoverageLevel(
87759aca01SMike Aizatsky     "sanitizer-coverage-level",
8829a18dcbSKostya Serebryany     cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
89c5d3d490SKostya Serebryany              "3: all blocks and critical edges"),
9029a18dcbSKostya Serebryany     cl::Hidden, cl::init(0));
9129a18dcbSKostya Serebryany 
922c2fb889SKostya Serebryany static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
932c2fb889SKostya Serebryany                                cl::desc("Experimental pc tracing"), cl::Hidden,
942c2fb889SKostya Serebryany                                cl::init(false));
95d4590c73SKostya Serebryany 
96da718e55SKostya Serebryany static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
97da718e55SKostya Serebryany                                     cl::desc("pc tracing with a guard"),
98da718e55SKostya Serebryany                                     cl::Hidden, cl::init(false));
99da718e55SKostya Serebryany 
100b75d002fSKostya Serebryany // If true, we create a global variable that contains PCs of all instrumented
101b75d002fSKostya Serebryany // BBs, put this global into a named section, and pass this section's bounds
102b75d002fSKostya Serebryany // to __sanitizer_cov_pcs_init.
103b75d002fSKostya Serebryany // This way the coverage instrumentation does not need to acquire the PCs
104e8d1c652SPratyai Mazumder // at run-time. Works with trace-pc-guard, inline-8bit-counters, and
105e8d1c652SPratyai Mazumder // inline-bool-flag.
106063b6520SKostya Serebryany static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
107b75d002fSKostya Serebryany                                      cl::desc("create a static PC table"),
108b75d002fSKostya Serebryany                                      cl::Hidden, cl::init(false));
109b75d002fSKostya Serebryany 
110b75d002fSKostya Serebryany static cl::opt<bool>
111b75d002fSKostya Serebryany     ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
1122c2fb889SKostya Serebryany                          cl::desc("increments 8-bit counter for every edge"),
1132c2fb889SKostya Serebryany                          cl::Hidden, cl::init(false));
1142c2fb889SKostya Serebryany 
115f4e35cc4SKostya Serebryany static cl::opt<bool>
116e8d1c652SPratyai Mazumder     ClInlineBoolFlag("sanitizer-coverage-inline-bool-flag",
117e8d1c652SPratyai Mazumder                      cl::desc("sets a boolean flag for every edge"), cl::Hidden,
118e8d1c652SPratyai Mazumder                      cl::init(false));
119e8d1c652SPratyai Mazumder 
120e8d1c652SPratyai Mazumder static cl::opt<bool>
1215ac427b8SKostya Serebryany     ClCMPTracing("sanitizer-coverage-trace-compares",
1225ac427b8SKostya Serebryany                  cl::desc("Tracing of CMP and similar instructions"),
1235ac427b8SKostya Serebryany                  cl::Hidden, cl::init(false));
1245ac427b8SKostya Serebryany 
1255ac427b8SKostya Serebryany static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
1265ac427b8SKostya Serebryany                                   cl::desc("Tracing of DIV instructions"),
1275ac427b8SKostya Serebryany                                   cl::Hidden, cl::init(false));
1285ac427b8SKostya Serebryany 
129b7f3a4f4SKostya Serebryany static cl::opt<bool> ClLoadTracing("sanitizer-coverage-trace-loads",
130b7f3a4f4SKostya Serebryany                                    cl::desc("Tracing of load instructions"),
131b7f3a4f4SKostya Serebryany                                    cl::Hidden, cl::init(false));
132b7f3a4f4SKostya Serebryany 
133b7f3a4f4SKostya Serebryany static cl::opt<bool> ClStoreTracing("sanitizer-coverage-trace-stores",
134b7f3a4f4SKostya Serebryany                                     cl::desc("Tracing of store instructions"),
135b7f3a4f4SKostya Serebryany                                     cl::Hidden, cl::init(false));
136b7f3a4f4SKostya Serebryany 
1375ac427b8SKostya Serebryany static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
1385ac427b8SKostya Serebryany                                   cl::desc("Tracing of GEP instructions"),
139f4e35cc4SKostya Serebryany                                   cl::Hidden, cl::init(false));
140f4e35cc4SKostya Serebryany 
14170ea4530SMike Aizatsky static cl::opt<bool>
14270ea4530SMike Aizatsky     ClPruneBlocks("sanitizer-coverage-prune-blocks",
14370ea4530SMike Aizatsky                   cl::desc("Reduce the number of instrumented blocks"),
14470ea4530SMike Aizatsky                   cl::Hidden, cl::init(true));
1455971f181SMike Aizatsky 
1465c7fc769SMatt Morehouse static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
1475c7fc769SMatt Morehouse                                   cl::desc("max stack depth tracing"),
1485c7fc769SMatt Morehouse                                   cl::Hidden, cl::init(false));
1495c7fc769SMatt Morehouse 
15029a18dcbSKostya Serebryany namespace {
15129a18dcbSKostya Serebryany 
getOptions(int LegacyCoverageLevel)1523514f274SAlexey Samsonov SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
1533514f274SAlexey Samsonov   SanitizerCoverageOptions Res;
1543514f274SAlexey Samsonov   switch (LegacyCoverageLevel) {
1553514f274SAlexey Samsonov   case 0:
1563514f274SAlexey Samsonov     Res.CoverageType = SanitizerCoverageOptions::SCK_None;
1573514f274SAlexey Samsonov     break;
1583514f274SAlexey Samsonov   case 1:
1593514f274SAlexey Samsonov     Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
1603514f274SAlexey Samsonov     break;
1613514f274SAlexey Samsonov   case 2:
1623514f274SAlexey Samsonov     Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
1633514f274SAlexey Samsonov     break;
1643514f274SAlexey Samsonov   case 3:
1653514f274SAlexey Samsonov     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
1663514f274SAlexey Samsonov     break;
1673514f274SAlexey Samsonov   case 4:
1683514f274SAlexey Samsonov     Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
1693514f274SAlexey Samsonov     Res.IndirectCalls = true;
1703514f274SAlexey Samsonov     break;
1713514f274SAlexey Samsonov   }
1723514f274SAlexey Samsonov   return Res;
1733514f274SAlexey Samsonov }
1743514f274SAlexey Samsonov 
OverrideFromCL(SanitizerCoverageOptions Options)1753514f274SAlexey Samsonov SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
1763514f274SAlexey Samsonov   // Sets CoverageType and IndirectCalls.
1773514f274SAlexey Samsonov   SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
1783514f274SAlexey Samsonov   Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
1793514f274SAlexey Samsonov   Options.IndirectCalls |= CLOpts.IndirectCalls;
1805ac427b8SKostya Serebryany   Options.TraceCmp |= ClCMPTracing;
1815ac427b8SKostya Serebryany   Options.TraceDiv |= ClDIVTracing;
1825ac427b8SKostya Serebryany   Options.TraceGep |= ClGEPTracing;
1832c2fb889SKostya Serebryany   Options.TracePC |= ClTracePC;
184da718e55SKostya Serebryany   Options.TracePCGuard |= ClTracePCGuard;
1852c2fb889SKostya Serebryany   Options.Inline8bitCounters |= ClInline8bitCounters;
186e8d1c652SPratyai Mazumder   Options.InlineBoolFlag |= ClInlineBoolFlag;
187063b6520SKostya Serebryany   Options.PCTable |= ClCreatePCTable;
188424bfed6SKostya Serebryany   Options.NoPrune |= !ClPruneBlocks;
1895c7fc769SMatt Morehouse   Options.StackDepth |= ClStackDepth;
190b7f3a4f4SKostya Serebryany   Options.TraceLoads |= ClLoadTracing;
191b7f3a4f4SKostya Serebryany   Options.TraceStores |= ClStoreTracing;
1925c7fc769SMatt Morehouse   if (!Options.TracePCGuard && !Options.TracePC &&
193e8d1c652SPratyai Mazumder       !Options.Inline8bitCounters && !Options.StackDepth &&
194b7f3a4f4SKostya Serebryany       !Options.InlineBoolFlag && !Options.TraceLoads && !Options.TraceStores)
1955c7fc769SMatt Morehouse     Options.TracePCGuard = true; // TracePCGuard is default.
1963514f274SAlexey Samsonov   return Options;
1973514f274SAlexey Samsonov }
1983514f274SAlexey Samsonov 
199eca01b03SLeonard Chan using DomTreeCallback = function_ref<const DominatorTree *(Function &F)>;
200eca01b03SLeonard Chan using PostDomTreeCallback =
201eca01b03SLeonard Chan     function_ref<const PostDominatorTree *(Function &F)>;
2025652f358SLeonard Chan 
203007f674cSLeonard Chan class ModuleSanitizerCoverage {
204007f674cSLeonard Chan public:
ModuleSanitizerCoverage(const SanitizerCoverageOptions & Options=SanitizerCoverageOptions (),const SpecialCaseList * Allowlist=nullptr,const SpecialCaseList * Blocklist=nullptr)205eca01b03SLeonard Chan   ModuleSanitizerCoverage(
206bef187c7SMatt Morehouse       const SanitizerCoverageOptions &Options = SanitizerCoverageOptions(),
2072a4317bfSFangrui Song       const SpecialCaseList *Allowlist = nullptr,
2082a4317bfSFangrui Song       const SpecialCaseList *Blocklist = nullptr)
2092a4317bfSFangrui Song       : Options(OverrideFromCL(Options)), Allowlist(Allowlist),
2102a4317bfSFangrui Song         Blocklist(Blocklist) {}
211eca01b03SLeonard Chan   bool instrumentModule(Module &M, DomTreeCallback DTCallback,
212eca01b03SLeonard Chan                         PostDomTreeCallback PDTCallback);
2133006115cSChandler Carruth 
21429a18dcbSKostya Serebryany private:
215eca01b03SLeonard Chan   void instrumentFunction(Function &F, DomTreeCallback DTCallback,
216eca01b03SLeonard Chan                           PostDomTreeCallback PDTCallback);
21729a18dcbSKostya Serebryany   void InjectCoverageForIndirectCalls(Function &F,
21829a18dcbSKostya Serebryany                                       ArrayRef<Instruction *> IndirCalls);
219f4e35cc4SKostya Serebryany   void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
2205ac427b8SKostya Serebryany   void InjectTraceForDiv(Function &F,
2215ac427b8SKostya Serebryany                          ArrayRef<BinaryOperator *> DivTraceTargets);
2225ac427b8SKostya Serebryany   void InjectTraceForGep(Function &F,
2235ac427b8SKostya Serebryany                          ArrayRef<GetElementPtrInst *> GepTraceTargets);
224b7f3a4f4SKostya Serebryany   void InjectTraceForLoadsAndStores(Function &F, ArrayRef<LoadInst *> Loads,
225b7f3a4f4SKostya Serebryany                                     ArrayRef<StoreInst *> Stores);
226fb7d8d9dSKostya Serebryany   void InjectTraceForSwitch(Function &F,
227fb7d8d9dSKostya Serebryany                             ArrayRef<Instruction *> SwitchTraceTargets);
228034126e5SMatt Morehouse   bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
229034126e5SMatt Morehouse                       bool IsLeafFunc = true);
230aed6ba77SKostya Serebryany   GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
231aed6ba77SKostya Serebryany                                                     Function &F, Type *Ty,
232aed6ba77SKostya Serebryany                                                     const char *Section);
233873a0746SJustin Bogner   GlobalVariable *CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
234b75d002fSKostya Serebryany   void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
235034126e5SMatt Morehouse   void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
236034126e5SMatt Morehouse                              bool IsLeafFunc = true);
237eca01b03SLeonard Chan   Function *CreateInitCallsForSections(Module &M, const char *CtorName,
238eca01b03SLeonard Chan                                        const char *InitFunctionName, Type *Ty,
239eca01b03SLeonard Chan                                        const char *Section);
240eca01b03SLeonard Chan   std::pair<Value *, Value *> CreateSecStartEnd(Module &M, const char *Section,
241eca01b03SLeonard Chan                                                 Type *Ty);
242aed6ba77SKostya Serebryany 
SetNoSanitizeMetadata(Instruction * I)2432c2fb889SKostya Serebryany   void SetNoSanitizeMetadata(Instruction *I) {
244*52992f13SEnna1     I->setMetadata(LLVMContext::MD_nosanitize, MDNode::get(*C, None));
2452c2fb889SKostya Serebryany   }
2462c2fb889SKostya Serebryany 
247aed6ba77SKostya Serebryany   std::string getSectionName(const std::string &Section) const;
248bb147aabSLeonard Chan   std::string getSectionStart(const std::string &Section) const;
249bb147aabSLeonard Chan   std::string getSectionEnd(const std::string &Section) const;
25013680223SJames Y Knight   FunctionCallee SanCovTracePCIndir;
25113680223SJames Y Knight   FunctionCallee SanCovTracePC, SanCovTracePCGuard;
252b7f3a4f4SKostya Serebryany   std::array<FunctionCallee, 4> SanCovTraceCmpFunction;
253b7f3a4f4SKostya Serebryany   std::array<FunctionCallee, 4> SanCovTraceConstCmpFunction;
254b7f3a4f4SKostya Serebryany   std::array<FunctionCallee, 5> SanCovLoadFunction;
255b7f3a4f4SKostya Serebryany   std::array<FunctionCallee, 5> SanCovStoreFunction;
256b7f3a4f4SKostya Serebryany   std::array<FunctionCallee, 2> SanCovTraceDivFunction;
25713680223SJames Y Knight   FunctionCallee SanCovTraceGepFunction;
25813680223SJames Y Knight   FunctionCallee SanCovTraceSwitchFunction;
2595c7fc769SMatt Morehouse   GlobalVariable *SanCovLowestStack;
260b7f3a4f4SKostya Serebryany   Type *Int128PtrTy, *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty,
261b7f3a4f4SKostya Serebryany       *Int32PtrTy, *Int16PtrTy, *Int16Ty, *Int8Ty, *Int8PtrTy, *Int1Ty,
262b7f3a4f4SKostya Serebryany       *Int1PtrTy;
263fb7d8d9dSKostya Serebryany   Module *CurModule;
2643bea25e5SMatt Morehouse   std::string CurModuleUniqueId;
265db5a5655SMarcos Pividori   Triple TargetTriple;
26629a18dcbSKostya Serebryany   LLVMContext *C;
267f4e35cc4SKostya Serebryany   const DataLayout *DL;
26829a18dcbSKostya Serebryany 
269a9b0dd0eSKostya Serebryany   GlobalVariable *FunctionGuardArray;  // for trace-pc-guard.
2702c2fb889SKostya Serebryany   GlobalVariable *Function8bitCounterArray;  // for inline-8bit-counters.
271e8d1c652SPratyai Mazumder   GlobalVariable *FunctionBoolArray;         // for inline-bool-flag.
272063b6520SKostya Serebryany   GlobalVariable *FunctionPCsArray;  // for pc-table.
2734192b963SKostya Serebryany   SmallVector<GlobalValue *, 20> GlobalsToAppendToUsed;
2740ea9a90bSMatt Morehouse   SmallVector<GlobalValue *, 20> GlobalsToAppendToCompilerUsed;
2759fdeb37bSKostya Serebryany 
2763514f274SAlexey Samsonov   SanitizerCoverageOptions Options;
277bef187c7SMatt Morehouse 
2782a4317bfSFangrui Song   const SpecialCaseList *Allowlist;
2792a4317bfSFangrui Song   const SpecialCaseList *Blocklist;
28029a18dcbSKostya Serebryany };
28129a18dcbSKostya Serebryany } // namespace
28229a18dcbSKostya Serebryany 
run(Module & M,ModuleAnalysisManager & MAM)283007f674cSLeonard Chan PreservedAnalyses ModuleSanitizerCoveragePass::run(Module &M,
284eca01b03SLeonard Chan                                                    ModuleAnalysisManager &MAM) {
2852a4317bfSFangrui Song   ModuleSanitizerCoverage ModuleSancov(Options, Allowlist.get(),
2862a4317bfSFangrui Song                                        Blocklist.get());
287eca01b03SLeonard Chan   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
288eca01b03SLeonard Chan   auto DTCallback = [&FAM](Function &F) -> const DominatorTree * {
289eca01b03SLeonard Chan     return &FAM.getResult<DominatorTreeAnalysis>(F);
290eca01b03SLeonard Chan   };
291eca01b03SLeonard Chan   auto PDTCallback = [&FAM](Function &F) -> const PostDominatorTree * {
292eca01b03SLeonard Chan     return &FAM.getResult<PostDominatorTreeAnalysis>(F);
293eca01b03SLeonard Chan   };
294eca01b03SLeonard Chan   if (ModuleSancov.instrumentModule(M, DTCallback, PDTCallback))
295007f674cSLeonard Chan     return PreservedAnalyses::none();
296007f674cSLeonard Chan   return PreservedAnalyses::all();
297007f674cSLeonard Chan }
298007f674cSLeonard Chan 
2995eb8cba2SJonathan Metzman std::pair<Value *, Value *>
CreateSecStartEnd(Module & M,const char * Section,Type * Ty)300007f674cSLeonard Chan ModuleSanitizerCoverage::CreateSecStartEnd(Module &M, const char *Section,
301b75d002fSKostya Serebryany                                            Type *Ty) {
3029558456bSFangrui Song   // Use ExternalWeak so that if all sections are discarded due to section
3039558456bSFangrui Song   // garbage collection, the linker will not report undefined symbol errors.
3043c81822eSFangrui Song   // Windows defines the start/stop symbols in compiler-rt so no need for
3053c81822eSFangrui Song   // ExternalWeak.
3063c81822eSFangrui Song   GlobalValue::LinkageTypes Linkage = TargetTriple.isOSBinFormatCOFF()
3073c81822eSFangrui Song                                           ? GlobalVariable::ExternalLinkage
3083c81822eSFangrui Song                                           : GlobalVariable::ExternalWeakLinkage;
3093c81822eSFangrui Song   GlobalVariable *SecStart =
3107ac0442fSNikita Popov       new GlobalVariable(M, Ty, false, Linkage, nullptr,
3117ac0442fSNikita Popov                          getSectionStart(Section));
312aed6ba77SKostya Serebryany   SecStart->setVisibility(GlobalValue::HiddenVisibility);
3133c81822eSFangrui Song   GlobalVariable *SecEnd =
3147ac0442fSNikita Popov       new GlobalVariable(M, Ty, false, Linkage, nullptr,
3157ac0442fSNikita Popov                          getSectionEnd(Section));
316aed6ba77SKostya Serebryany   SecEnd->setVisibility(GlobalValue::HiddenVisibility);
3175eb8cba2SJonathan Metzman   IRBuilder<> IRB(M.getContext());
318e159a0ddSJonathan Metzman   if (!TargetTriple.isOSBinFormatCOFF())
319153df137SIlya Leoshkevich     return std::make_pair(SecStart, SecEnd);
320aed6ba77SKostya Serebryany 
3215eb8cba2SJonathan Metzman   // Account for the fact that on windows-msvc __start_* symbols actually
3225eb8cba2SJonathan Metzman   // point to a uint64_t before the start of the array.
3235eb8cba2SJonathan Metzman   auto SecStartI8Ptr = IRB.CreatePointerCast(SecStart, Int8PtrTy);
3247716075aSJames Y Knight   auto GEP = IRB.CreateGEP(Int8Ty, SecStartI8Ptr,
3255eb8cba2SJonathan Metzman                            ConstantInt::get(IntptrTy, sizeof(uint64_t)));
3267ac0442fSNikita Popov   return std::make_pair(IRB.CreatePointerCast(GEP, PointerType::getUnqual(Ty)),
3277ac0442fSNikita Popov                         SecEnd);
328b75d002fSKostya Serebryany }
329b75d002fSKostya Serebryany 
CreateInitCallsForSections(Module & M,const char * CtorName,const char * InitFunctionName,Type * Ty,const char * Section)330007f674cSLeonard Chan Function *ModuleSanitizerCoverage::CreateInitCallsForSections(
331a400ca3fSFangrui Song     Module &M, const char *CtorName, const char *InitFunctionName, Type *Ty,
332b75d002fSKostya Serebryany     const char *Section) {
333b75d002fSKostya Serebryany   auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
334b75d002fSKostya Serebryany   auto SecStart = SecStartEnd.first;
335b75d002fSKostya Serebryany   auto SecEnd = SecStartEnd.second;
336b75d002fSKostya Serebryany   Function *CtorFunc;
3377ac0442fSNikita Popov   Type *PtrTy = PointerType::getUnqual(Ty);
338aed6ba77SKostya Serebryany   std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
3397ac0442fSNikita Popov       M, CtorName, InitFunctionName, {PtrTy, PtrTy}, {SecStart, SecEnd});
340a400ca3fSFangrui Song   assert(CtorFunc->getName() == CtorName);
341aed6ba77SKostya Serebryany 
342aed6ba77SKostya Serebryany   if (TargetTriple.supportsCOMDAT()) {
343aed6ba77SKostya Serebryany     // Use comdat to dedup CtorFunc.
344a400ca3fSFangrui Song     CtorFunc->setComdat(M.getOrInsertComdat(CtorName));
345aed6ba77SKostya Serebryany     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
346aed6ba77SKostya Serebryany   } else {
347aed6ba77SKostya Serebryany     appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
348aed6ba77SKostya Serebryany   }
3490b94e880SJonathan Metzman 
350e159a0ddSJonathan Metzman   if (TargetTriple.isOSBinFormatCOFF()) {
3510b94e880SJonathan Metzman     // In COFF files, if the contructors are set as COMDAT (they are because
3520b94e880SJonathan Metzman     // COFF supports COMDAT) and the linker flag /OPT:REF (strip unreferenced
3530b94e880SJonathan Metzman     // functions and data) is used, the constructors get stripped. To prevent
354e159a0ddSJonathan Metzman     // this, give the constructors weak ODR linkage and ensure the linker knows
355e159a0ddSJonathan Metzman     // to include the sancov constructor. This way the linker can deduplicate
356e159a0ddSJonathan Metzman     // the constructors but always leave one copy.
3570b94e880SJonathan Metzman     CtorFunc->setLinkage(GlobalValue::WeakODRLinkage);
3580b94e880SJonathan Metzman   }
359b75d002fSKostya Serebryany   return CtorFunc;
360aed6ba77SKostya Serebryany }
361aed6ba77SKostya Serebryany 
instrumentModule(Module & M,DomTreeCallback DTCallback,PostDomTreeCallback PDTCallback)362eca01b03SLeonard Chan bool ModuleSanitizerCoverage::instrumentModule(
363eca01b03SLeonard Chan     Module &M, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
3643514f274SAlexey Samsonov   if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
365eca01b03SLeonard Chan     return false;
3662a4317bfSFangrui Song   if (Allowlist &&
3672a4317bfSFangrui Song       !Allowlist->inSection("coverage", "src", M.getSourceFileName()))
368bef187c7SMatt Morehouse     return false;
3692a4317bfSFangrui Song   if (Blocklist &&
3702a4317bfSFangrui Song       Blocklist->inSection("coverage", "src", M.getSourceFileName()))
371bef187c7SMatt Morehouse     return false;
37229a18dcbSKostya Serebryany   C = &(M.getContext());
373f4e35cc4SKostya Serebryany   DL = &M.getDataLayout();
374eca01b03SLeonard Chan   CurModule = &M;
3753bea25e5SMatt Morehouse   CurModuleUniqueId = getUniqueModuleId(CurModule);
376db5a5655SMarcos Pividori   TargetTriple = Triple(M.getTargetTriple());
377aed6ba77SKostya Serebryany   FunctionGuardArray = nullptr;
3782c2fb889SKostya Serebryany   Function8bitCounterArray = nullptr;
379e8d1c652SPratyai Mazumder   FunctionBoolArray = nullptr;
380b75d002fSKostya Serebryany   FunctionPCsArray = nullptr;
381f4e35cc4SKostya Serebryany   IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
3828e781a88SKostya Serebryany   IntptrPtrTy = PointerType::getUnqual(IntptrTy);
38329a18dcbSKostya Serebryany   Type *VoidTy = Type::getVoidTy(*C);
3844cadd4afSKostya Serebryany   IRBuilder<> IRB(*C);
385b7f3a4f4SKostya Serebryany   Int128PtrTy = PointerType::getUnqual(IRB.getInt128Ty());
386fb7d8d9dSKostya Serebryany   Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
387b7f3a4f4SKostya Serebryany   Int16PtrTy = PointerType::getUnqual(IRB.getInt16Ty());
388a9b0dd0eSKostya Serebryany   Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
3892c2fb889SKostya Serebryany   Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
390e8d1c652SPratyai Mazumder   Int1PtrTy = PointerType::getUnqual(IRB.getInt1Ty());
391f4e35cc4SKostya Serebryany   Int64Ty = IRB.getInt64Ty();
392a9b0dd0eSKostya Serebryany   Int32Ty = IRB.getInt32Ty();
39352410815SAlexander Potapenko   Int16Ty = IRB.getInt16Ty();
3942c2fb889SKostya Serebryany   Int8Ty = IRB.getInt8Ty();
395e8d1c652SPratyai Mazumder   Int1Ty = IRB.getInt1Ty();
39629a18dcbSKostya Serebryany 
39713680223SJames Y Knight   SanCovTracePCIndir =
39813680223SJames Y Knight       M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy);
399f5a252edSIlya Leoshkevich   // Make sure smaller parameters are zero-extended to i64 if required by the
400f5a252edSIlya Leoshkevich   // target ABI.
40113680223SJames Y Knight   AttributeList SanCovTraceCmpZeroExtAL;
40213680223SJames Y Knight   SanCovTraceCmpZeroExtAL =
40313680223SJames Y Knight       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 0, Attribute::ZExt);
40413680223SJames Y Knight   SanCovTraceCmpZeroExtAL =
40513680223SJames Y Knight       SanCovTraceCmpZeroExtAL.addParamAttribute(*C, 1, Attribute::ZExt);
40613680223SJames Y Knight 
407524c3f32SKostya Serebryany   SanCovTraceCmpFunction[0] =
40813680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceCmp1, SanCovTraceCmpZeroExtAL, VoidTy,
40913680223SJames Y Knight                             IRB.getInt8Ty(), IRB.getInt8Ty());
41013680223SJames Y Knight   SanCovTraceCmpFunction[1] =
41113680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceCmp2, SanCovTraceCmpZeroExtAL, VoidTy,
41213680223SJames Y Knight                             IRB.getInt16Ty(), IRB.getInt16Ty());
41313680223SJames Y Knight   SanCovTraceCmpFunction[2] =
41413680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceCmp4, SanCovTraceCmpZeroExtAL, VoidTy,
41513680223SJames Y Knight                             IRB.getInt32Ty(), IRB.getInt32Ty());
416db11fdfdSMehdi Amini   SanCovTraceCmpFunction[3] =
41713680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty);
4185ac427b8SKostya Serebryany 
41913680223SJames Y Knight   SanCovTraceConstCmpFunction[0] = M.getOrInsertFunction(
42013680223SJames Y Knight       SanCovTraceConstCmp1, SanCovTraceCmpZeroExtAL, VoidTy, Int8Ty, Int8Ty);
42113680223SJames Y Knight   SanCovTraceConstCmpFunction[1] = M.getOrInsertFunction(
42213680223SJames Y Knight       SanCovTraceConstCmp2, SanCovTraceCmpZeroExtAL, VoidTy, Int16Ty, Int16Ty);
42313680223SJames Y Knight   SanCovTraceConstCmpFunction[2] = M.getOrInsertFunction(
42413680223SJames Y Knight       SanCovTraceConstCmp4, SanCovTraceCmpZeroExtAL, VoidTy, Int32Ty, Int32Ty);
42552410815SAlexander Potapenko   SanCovTraceConstCmpFunction[3] =
42613680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty);
42752410815SAlexander Potapenko 
428b7f3a4f4SKostya Serebryany   // Loads.
429b7f3a4f4SKostya Serebryany   SanCovLoadFunction[0] = M.getOrInsertFunction(SanCovLoad1, VoidTy, Int8PtrTy);
430b7f3a4f4SKostya Serebryany   SanCovLoadFunction[1] =
431b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovLoad2, VoidTy, Int16PtrTy);
432b7f3a4f4SKostya Serebryany   SanCovLoadFunction[2] =
433b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovLoad4, VoidTy, Int32PtrTy);
434b7f3a4f4SKostya Serebryany   SanCovLoadFunction[3] =
435b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovLoad8, VoidTy, Int64PtrTy);
436b7f3a4f4SKostya Serebryany   SanCovLoadFunction[4] =
437b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovLoad16, VoidTy, Int128PtrTy);
438b7f3a4f4SKostya Serebryany   // Stores.
439b7f3a4f4SKostya Serebryany   SanCovStoreFunction[0] =
440b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovStore1, VoidTy, Int8PtrTy);
441b7f3a4f4SKostya Serebryany   SanCovStoreFunction[1] =
442b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovStore2, VoidTy, Int16PtrTy);
443b7f3a4f4SKostya Serebryany   SanCovStoreFunction[2] =
444b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovStore4, VoidTy, Int32PtrTy);
445b7f3a4f4SKostya Serebryany   SanCovStoreFunction[3] =
446b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovStore8, VoidTy, Int64PtrTy);
447b7f3a4f4SKostya Serebryany   SanCovStoreFunction[4] =
448b7f3a4f4SKostya Serebryany       M.getOrInsertFunction(SanCovStore16, VoidTy, Int128PtrTy);
449b7f3a4f4SKostya Serebryany 
45013680223SJames Y Knight   {
45113680223SJames Y Knight     AttributeList AL;
45213680223SJames Y Knight     AL = AL.addParamAttribute(*C, 0, Attribute::ZExt);
453db11fdfdSMehdi Amini     SanCovTraceDivFunction[0] =
45413680223SJames Y Knight         M.getOrInsertFunction(SanCovTraceDiv4, AL, VoidTy, IRB.getInt32Ty());
45513680223SJames Y Knight   }
456db11fdfdSMehdi Amini   SanCovTraceDivFunction[1] =
45713680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceDiv8, VoidTy, Int64Ty);
458db11fdfdSMehdi Amini   SanCovTraceGepFunction =
45913680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceGep, VoidTy, IntptrTy);
460fb7d8d9dSKostya Serebryany   SanCovTraceSwitchFunction =
46113680223SJames Y Knight       M.getOrInsertFunction(SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy);
4625c7fc769SMatt Morehouse 
4635c7fc769SMatt Morehouse   Constant *SanCovLowestStackConstant =
4645c7fc769SMatt Morehouse       M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
46529ac3a5bSJulian Lettner   SanCovLowestStack = dyn_cast<GlobalVariable>(SanCovLowestStackConstant);
466c4de78e9SNikita Popov   if (!SanCovLowestStack || SanCovLowestStack->getValueType() != IntptrTy) {
467eca01b03SLeonard Chan     C->emitError(StringRef("'") + SanCovLowestStackName +
468eca01b03SLeonard Chan                  "' should not be declared by the user");
469eca01b03SLeonard Chan     return true;
470eca01b03SLeonard Chan   }
471b1fa8255SMatt Morehouse   SanCovLowestStack->setThreadLocalMode(
472b1fa8255SMatt Morehouse       GlobalValue::ThreadLocalMode::InitialExecTLSModel);
473b1fa8255SMatt Morehouse   if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
4745c7fc769SMatt Morehouse     SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
4755c7fc769SMatt Morehouse 
47613680223SJames Y Knight   SanCovTracePC = M.getOrInsertFunction(SanCovTracePCName, VoidTy);
47713680223SJames Y Knight   SanCovTracePCGuard =
47813680223SJames Y Knight       M.getOrInsertFunction(SanCovTracePCGuardName, VoidTy, Int32PtrTy);
479007f674cSLeonard Chan 
480eca01b03SLeonard Chan   for (auto &F : M)
481eca01b03SLeonard Chan     instrumentFunction(F, DTCallback, PDTCallback);
482eca01b03SLeonard Chan 
483eca01b03SLeonard Chan   Function *Ctor = nullptr;
484eca01b03SLeonard Chan 
485eca01b03SLeonard Chan   if (FunctionGuardArray)
486eca01b03SLeonard Chan     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorTracePcGuardName,
4877ac0442fSNikita Popov                                       SanCovTracePCGuardInitName, Int32Ty,
488eca01b03SLeonard Chan                                       SanCovGuardsSectionName);
489eca01b03SLeonard Chan   if (Function8bitCounterArray)
490eca01b03SLeonard Chan     Ctor = CreateInitCallsForSections(M, SanCovModuleCtor8bitCountersName,
4917ac0442fSNikita Popov                                       SanCov8bitCountersInitName, Int8Ty,
492eca01b03SLeonard Chan                                       SanCovCountersSectionName);
493e8d1c652SPratyai Mazumder   if (FunctionBoolArray) {
494e8d1c652SPratyai Mazumder     Ctor = CreateInitCallsForSections(M, SanCovModuleCtorBoolFlagName,
4957ac0442fSNikita Popov                                       SanCovBoolFlagInitName, Int1Ty,
496e8d1c652SPratyai Mazumder                                       SanCovBoolFlagSectionName);
497e8d1c652SPratyai Mazumder   }
498eca01b03SLeonard Chan   if (Ctor && Options.PCTable) {
4997ac0442fSNikita Popov     auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrTy);
500eca01b03SLeonard Chan     FunctionCallee InitFunction = declareSanitizerInitFunction(
501eca01b03SLeonard Chan         M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
502eca01b03SLeonard Chan     IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
503eca01b03SLeonard Chan     IRBCtor.CreateCall(InitFunction, {SecStartEnd.first, SecStartEnd.second});
504eca01b03SLeonard Chan   }
5054192b963SKostya Serebryany   appendToUsed(M, GlobalsToAppendToUsed);
5060ea9a90bSMatt Morehouse   appendToCompilerUsed(M, GlobalsToAppendToCompilerUsed);
507eca01b03SLeonard Chan   return true;
50829a18dcbSKostya Serebryany }
50929a18dcbSKostya Serebryany 
5109987f43fSMike Aizatsky // True if block has successors and it dominates all of them.
isFullDominator(const BasicBlock * BB,const DominatorTree * DT)5119987f43fSMike Aizatsky static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
512918e3439SKazu Hirata   if (succ_empty(BB))
5139987f43fSMike Aizatsky     return false;
5149987f43fSMike Aizatsky 
5155935952cSKazu Hirata   return llvm::all_of(successors(BB), [&](const BasicBlock *SUCC) {
516918e3439SKazu Hirata     return DT->dominates(BB, SUCC);
517918e3439SKazu Hirata   });
5189987f43fSMike Aizatsky }
5199987f43fSMike Aizatsky 
520018472c3SGeorge Karpenkov // True if block has predecessors and it postdominates all of them.
isFullPostDominator(const BasicBlock * BB,const PostDominatorTree * PDT)521018472c3SGeorge Karpenkov static bool isFullPostDominator(const BasicBlock *BB,
522018472c3SGeorge Karpenkov                                 const PostDominatorTree *PDT) {
523918e3439SKazu Hirata   if (pred_empty(BB))
524018472c3SGeorge Karpenkov     return false;
525018472c3SGeorge Karpenkov 
5265935952cSKazu Hirata   return llvm::all_of(predecessors(BB), [&](const BasicBlock *PRED) {
527918e3439SKazu Hirata     return PDT->dominates(BB, PRED);
528918e3439SKazu Hirata   });
529018472c3SGeorge Karpenkov }
530018472c3SGeorge Karpenkov 
shouldInstrumentBlock(const Function & F,const BasicBlock * BB,const DominatorTree * DT,const PostDominatorTree * PDT,const SanitizerCoverageOptions & Options)531424bfed6SKostya Serebryany static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
532424bfed6SKostya Serebryany                                   const DominatorTree *DT,
533018472c3SGeorge Karpenkov                                   const PostDominatorTree *PDT,
534424bfed6SKostya Serebryany                                   const SanitizerCoverageOptions &Options) {
535701593f1SReid Kleckner   // Don't insert coverage for blocks containing nothing but unreachable: we
536701593f1SReid Kleckner   // will never call __sanitizer_cov() for them, so counting them in
537a9b0dd0eSKostya Serebryany   // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
538a9b0dd0eSKostya Serebryany   // percentage. Also, unreachable instructions frequently have no debug
539a9b0dd0eSKostya Serebryany   // locations.
540701593f1SReid Kleckner   if (isa<UnreachableInst>(BB->getFirstNonPHIOrDbgOrLifetime()))
541a9b0dd0eSKostya Serebryany     return false;
542a9b0dd0eSKostya Serebryany 
543392f0626SReid Kleckner   // Don't insert coverage into blocks without a valid insertion point
544392f0626SReid Kleckner   // (catchswitch blocks).
545392f0626SReid Kleckner   if (BB->getFirstInsertionPt() == BB->end())
546392f0626SReid Kleckner     return false;
547392f0626SReid Kleckner 
548424bfed6SKostya Serebryany   if (Options.NoPrune || &F.getEntryBlock() == BB)
5495971f181SMike Aizatsky     return true;
5505971f181SMike Aizatsky 
551c485ca05SKostya Serebryany   if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
552c485ca05SKostya Serebryany       &F.getEntryBlock() != BB)
553c485ca05SKostya Serebryany     return false;
554c485ca05SKostya Serebryany 
555a1c53278SGeorge Karpenkov   // Do not instrument full dominators, or full post-dominators with multiple
556a1c53278SGeorge Karpenkov   // predecessors.
557a1c53278SGeorge Karpenkov   return !isFullDominator(BB, DT)
558a1c53278SGeorge Karpenkov     && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
5595971f181SMike Aizatsky }
5605971f181SMike Aizatsky 
561a78a44d4SKostya Serebryany 
562a78a44d4SKostya Serebryany // Returns true iff From->To is a backedge.
563a78a44d4SKostya Serebryany // A twist here is that we treat From->To as a backedge if
564a78a44d4SKostya Serebryany //   * To dominates From or
565a78a44d4SKostya Serebryany //   * To->UniqueSuccessor dominates From
IsBackEdge(BasicBlock * From,BasicBlock * To,const DominatorTree * DT)566a78a44d4SKostya Serebryany static bool IsBackEdge(BasicBlock *From, BasicBlock *To,
567a78a44d4SKostya Serebryany                        const DominatorTree *DT) {
568a78a44d4SKostya Serebryany   if (DT->dominates(To, From))
569a78a44d4SKostya Serebryany     return true;
570a78a44d4SKostya Serebryany   if (auto Next = To->getUniqueSuccessor())
571a78a44d4SKostya Serebryany     if (DT->dominates(Next, From))
572a78a44d4SKostya Serebryany       return true;
573a78a44d4SKostya Serebryany   return false;
574a78a44d4SKostya Serebryany }
575a78a44d4SKostya Serebryany 
576a78a44d4SKostya Serebryany // Prunes uninteresting Cmp instrumentation:
577a78a44d4SKostya Serebryany //   * CMP instructions that feed into loop backedge branch.
578a78a44d4SKostya Serebryany //
579a78a44d4SKostya Serebryany // Note that Cmp pruning is controlled by the same flag as the
580a78a44d4SKostya Serebryany // BB pruning.
IsInterestingCmp(ICmpInst * CMP,const DominatorTree * DT,const SanitizerCoverageOptions & Options)581a78a44d4SKostya Serebryany static bool IsInterestingCmp(ICmpInst *CMP, const DominatorTree *DT,
582a78a44d4SKostya Serebryany                              const SanitizerCoverageOptions &Options) {
583a78a44d4SKostya Serebryany   if (!Options.NoPrune)
584a78a44d4SKostya Serebryany     if (CMP->hasOneUse())
585a78a44d4SKostya Serebryany       if (auto BR = dyn_cast<BranchInst>(CMP->user_back()))
586a78a44d4SKostya Serebryany         for (BasicBlock *B : BR->successors())
587a78a44d4SKostya Serebryany           if (IsBackEdge(BR->getParent(), B, DT))
588a78a44d4SKostya Serebryany             return false;
589a78a44d4SKostya Serebryany   return true;
590a78a44d4SKostya Serebryany }
591a78a44d4SKostya Serebryany 
instrumentFunction(Function & F,DomTreeCallback DTCallback,PostDomTreeCallback PDTCallback)592eca01b03SLeonard Chan void ModuleSanitizerCoverage::instrumentFunction(
593eca01b03SLeonard Chan     Function &F, DomTreeCallback DTCallback, PostDomTreeCallback PDTCallback) {
594eca01b03SLeonard Chan   if (F.empty())
595eca01b03SLeonard Chan     return;
596eca01b03SLeonard Chan   if (F.getName().find(".module_ctor") != std::string::npos)
597eca01b03SLeonard Chan     return; // Should not instrument sanitizer init functions.
598eca01b03SLeonard Chan   if (F.getName().startswith("__sanitizer_"))
599eca01b03SLeonard Chan     return; // Don't instrument __sanitizer_* callbacks.
600eca01b03SLeonard Chan   // Don't touch available_externally functions, their actual body is elewhere.
601eca01b03SLeonard Chan   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
602eca01b03SLeonard Chan     return;
603eca01b03SLeonard Chan   // Don't instrument MSVC CRT configuration helpers. They may run before normal
604eca01b03SLeonard Chan   // initialization.
605eca01b03SLeonard Chan   if (F.getName() == "__local_stdio_printf_options" ||
606eca01b03SLeonard Chan       F.getName() == "__local_stdio_scanf_options")
607eca01b03SLeonard Chan     return;
608eca01b03SLeonard Chan   if (isa<UnreachableInst>(F.getEntryBlock().getTerminator()))
609eca01b03SLeonard Chan     return;
610eca01b03SLeonard Chan   // Don't instrument functions using SEH for now. Splitting basic blocks like
611eca01b03SLeonard Chan   // we do for coverage breaks WinEHPrepare.
612eca01b03SLeonard Chan   // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
613eca01b03SLeonard Chan   if (F.hasPersonalityFn() &&
614eca01b03SLeonard Chan       isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
615eca01b03SLeonard Chan     return;
6162a4317bfSFangrui Song   if (Allowlist && !Allowlist->inSection("coverage", "fun", F.getName()))
617bef187c7SMatt Morehouse     return;
6182a4317bfSFangrui Song   if (Blocklist && Blocklist->inSection("coverage", "fun", F.getName()))
619bef187c7SMatt Morehouse     return;
62028033302SMarco Elver   if (F.hasFnAttribute(Attribute::NoSanitizeCoverage))
62128033302SMarco Elver     return;
6223514f274SAlexey Samsonov   if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
62303e93f51SCraig Topper     SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions().setIgnoreUnreachableDests());
62429a18dcbSKostya Serebryany   SmallVector<Instruction *, 8> IndirCalls;
6255971f181SMike Aizatsky   SmallVector<BasicBlock *, 16> BlocksToInstrument;
626f4e35cc4SKostya Serebryany   SmallVector<Instruction *, 8> CmpTraceTargets;
627fb7d8d9dSKostya Serebryany   SmallVector<Instruction *, 8> SwitchTraceTargets;
6285ac427b8SKostya Serebryany   SmallVector<BinaryOperator *, 8> DivTraceTargets;
6295ac427b8SKostya Serebryany   SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
630b7f3a4f4SKostya Serebryany   SmallVector<LoadInst *, 8> Loads;
631b7f3a4f4SKostya Serebryany   SmallVector<StoreInst *, 8> Stores;
6325971f181SMike Aizatsky 
633eca01b03SLeonard Chan   const DominatorTree *DT = DTCallback(F);
634eca01b03SLeonard Chan   const PostDominatorTree *PDT = PDTCallback(F);
635034126e5SMatt Morehouse   bool IsLeafFunc = true;
636602f7927SMike Aizatsky 
63729a18dcbSKostya Serebryany   for (auto &BB : F) {
638018472c3SGeorge Karpenkov     if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
6395971f181SMike Aizatsky       BlocksToInstrument.push_back(&BB);
64029a18dcbSKostya Serebryany     for (auto &Inst : BB) {
6413514f274SAlexey Samsonov       if (Options.IndirectCalls) {
6421b6b05a2SMircea Trofin         CallBase *CB = dyn_cast<CallBase>(&Inst);
6431067f217SAhmed Bougacha         if (CB && CB->isIndirectCall())
64429a18dcbSKostya Serebryany           IndirCalls.push_back(&Inst);
64529a18dcbSKostya Serebryany       }
646fb7d8d9dSKostya Serebryany       if (Options.TraceCmp) {
647a78a44d4SKostya Serebryany         if (ICmpInst *CMP = dyn_cast<ICmpInst>(&Inst))
648a78a44d4SKostya Serebryany           if (IsInterestingCmp(CMP, DT, Options))
649f4e35cc4SKostya Serebryany             CmpTraceTargets.push_back(&Inst);
650fb7d8d9dSKostya Serebryany         if (isa<SwitchInst>(&Inst))
651fb7d8d9dSKostya Serebryany           SwitchTraceTargets.push_back(&Inst);
652fb7d8d9dSKostya Serebryany       }
6535ac427b8SKostya Serebryany       if (Options.TraceDiv)
6545ac427b8SKostya Serebryany         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
6555ac427b8SKostya Serebryany           if (BO->getOpcode() == Instruction::SDiv ||
6565ac427b8SKostya Serebryany               BO->getOpcode() == Instruction::UDiv)
6575ac427b8SKostya Serebryany             DivTraceTargets.push_back(BO);
6585ac427b8SKostya Serebryany       if (Options.TraceGep)
6595ac427b8SKostya Serebryany         if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
6605ac427b8SKostya Serebryany           GepTraceTargets.push_back(GEP);
661b7f3a4f4SKostya Serebryany       if (Options.TraceLoads)
662b7f3a4f4SKostya Serebryany         if (LoadInst *LI = dyn_cast<LoadInst>(&Inst))
663b7f3a4f4SKostya Serebryany           Loads.push_back(LI);
664b7f3a4f4SKostya Serebryany       if (Options.TraceStores)
665b7f3a4f4SKostya Serebryany         if (StoreInst *SI = dyn_cast<StoreInst>(&Inst))
666b7f3a4f4SKostya Serebryany           Stores.push_back(SI);
667034126e5SMatt Morehouse       if (Options.StackDepth)
668034126e5SMatt Morehouse         if (isa<InvokeInst>(Inst) ||
669034126e5SMatt Morehouse             (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
670034126e5SMatt Morehouse           IsLeafFunc = false;
67129a18dcbSKostya Serebryany     }
672f4e35cc4SKostya Serebryany   }
6735971f181SMike Aizatsky 
674034126e5SMatt Morehouse   InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
675f4e35cc4SKostya Serebryany   InjectCoverageForIndirectCalls(F, IndirCalls);
676f4e35cc4SKostya Serebryany   InjectTraceForCmp(F, CmpTraceTargets);
677fb7d8d9dSKostya Serebryany   InjectTraceForSwitch(F, SwitchTraceTargets);
6785ac427b8SKostya Serebryany   InjectTraceForDiv(F, DivTraceTargets);
6795ac427b8SKostya Serebryany   InjectTraceForGep(F, GepTraceTargets);
680b7f3a4f4SKostya Serebryany   InjectTraceForLoadsAndStores(F, Loads, Stores);
68129a18dcbSKostya Serebryany }
682aed6ba77SKostya Serebryany 
CreateFunctionLocalArrayInSection(size_t NumElements,Function & F,Type * Ty,const char * Section)683eca01b03SLeonard Chan GlobalVariable *ModuleSanitizerCoverage::CreateFunctionLocalArrayInSection(
684aed6ba77SKostya Serebryany     size_t NumElements, Function &F, Type *Ty, const char *Section) {
685aed6ba77SKostya Serebryany   ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
686aed6ba77SKostya Serebryany   auto Array = new GlobalVariable(
687aed6ba77SKostya Serebryany       *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
688aed6ba77SKostya Serebryany       Constant::getNullValue(ArrayTy), "__sancov_gen_");
689bc504559SKostya Serebryany 
6904d63892aSFangrui Song   if (TargetTriple.supportsCOMDAT() &&
6914d63892aSFangrui Song       (TargetTriple.isOSBinFormatELF() || !F.isInterposable()))
6924d63892aSFangrui Song     if (auto Comdat = getOrCreateFunctionComdat(F, TargetTriple))
693aed6ba77SKostya Serebryany       Array->setComdat(Comdat);
694aed6ba77SKostya Serebryany   Array->setSection(getSectionName(Section));
6958b1a6c0aSVitaly Buka   Array->setAlignment(Align(DL->getTypeStoreSize(Ty).getFixedSize()));
696b55f29c1SFangrui Song 
697b55f29c1SFangrui Song   // sancov_pcs parallels the other metadata section(s). Optimizers (e.g.
698b55f29c1SFangrui Song   // GlobalOpt/ConstantMerge) may not discard sancov_pcs and the other
699b55f29c1SFangrui Song   // section(s) as a unit, so we conservatively retain all unconditionally in
700b55f29c1SFangrui Song   // the compiler.
701b55f29c1SFangrui Song   //
702b55f29c1SFangrui Song   // With comdat (COFF/ELF), the linker can guarantee the associated sections
703b55f29c1SFangrui Song   // will be retained or discarded as a unit, so llvm.compiler.used is
704b55f29c1SFangrui Song   // sufficient. Otherwise, conservatively make all of them retained by the
705b55f29c1SFangrui Song   // linker.
706b55f29c1SFangrui Song   if (Array->hasComdat())
7073bea25e5SMatt Morehouse     GlobalsToAppendToCompilerUsed.push_back(Array);
708b55f29c1SFangrui Song   else
709b55f29c1SFangrui Song     GlobalsToAppendToUsed.push_back(Array);
7103bea25e5SMatt Morehouse 
711aed6ba77SKostya Serebryany   return Array;
712aed6ba77SKostya Serebryany }
713b75d002fSKostya Serebryany 
714873a0746SJustin Bogner GlobalVariable *
CreatePCArray(Function & F,ArrayRef<BasicBlock * > AllBlocks)715eca01b03SLeonard Chan ModuleSanitizerCoverage::CreatePCArray(Function &F,
716b75d002fSKostya Serebryany                                        ArrayRef<BasicBlock *> AllBlocks) {
717b75d002fSKostya Serebryany   size_t N = AllBlocks.size();
718b75d002fSKostya Serebryany   assert(N);
719d3e4b7e2SKostya Serebryany   SmallVector<Constant *, 32> PCs;
720b75d002fSKostya Serebryany   IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
721d3e4b7e2SKostya Serebryany   for (size_t i = 0; i < N; i++) {
722d3e4b7e2SKostya Serebryany     if (&F.getEntryBlock() == AllBlocks[i]) {
723d3e4b7e2SKostya Serebryany       PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
724d3e4b7e2SKostya Serebryany       PCs.push_back((Constant *)IRB.CreateIntToPtr(
725d3e4b7e2SKostya Serebryany           ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
726d3e4b7e2SKostya Serebryany     } else {
727d3e4b7e2SKostya Serebryany       PCs.push_back((Constant *)IRB.CreatePointerCast(
728d3e4b7e2SKostya Serebryany           BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
729d3e4b7e2SKostya Serebryany       PCs.push_back((Constant *)IRB.CreateIntToPtr(
730d3e4b7e2SKostya Serebryany           ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
731d3e4b7e2SKostya Serebryany     }
732d3e4b7e2SKostya Serebryany   }
733873a0746SJustin Bogner   auto *PCArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
734d3e4b7e2SKostya Serebryany                                                     SanCovPCsSectionName);
735873a0746SJustin Bogner   PCArray->setInitializer(
736d3e4b7e2SKostya Serebryany       ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
737873a0746SJustin Bogner   PCArray->setConstant(true);
738ad96ff12SJustin Bogner 
739873a0746SJustin Bogner   return PCArray;
740b75d002fSKostya Serebryany }
741b75d002fSKostya Serebryany 
CreateFunctionLocalArrays(Function & F,ArrayRef<BasicBlock * > AllBlocks)742eca01b03SLeonard Chan void ModuleSanitizerCoverage::CreateFunctionLocalArrays(
743b75d002fSKostya Serebryany     Function &F, ArrayRef<BasicBlock *> AllBlocks) {
7444d010ca3SMax Moroz   if (Options.TracePCGuard)
745aed6ba77SKostya Serebryany     FunctionGuardArray = CreateFunctionLocalArrayInSection(
746b75d002fSKostya Serebryany         AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
7474d010ca3SMax Moroz 
7483bea25e5SMatt Morehouse   if (Options.Inline8bitCounters)
7492c2fb889SKostya Serebryany     Function8bitCounterArray = CreateFunctionLocalArrayInSection(
750b75d002fSKostya Serebryany         AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
751e8d1c652SPratyai Mazumder   if (Options.InlineBoolFlag)
752e8d1c652SPratyai Mazumder     FunctionBoolArray = CreateFunctionLocalArrayInSection(
753e8d1c652SPratyai Mazumder         AllBlocks.size(), F, Int1Ty, SanCovBoolFlagSectionName);
7544d010ca3SMax Moroz 
7553bea25e5SMatt Morehouse   if (Options.PCTable)
756873a0746SJustin Bogner     FunctionPCsArray = CreatePCArray(F, AllBlocks);
757a9b0dd0eSKostya Serebryany }
75829a18dcbSKostya Serebryany 
InjectCoverage(Function & F,ArrayRef<BasicBlock * > AllBlocks,bool IsLeafFunc)759eca01b03SLeonard Chan bool ModuleSanitizerCoverage::InjectCoverage(Function &F,
760034126e5SMatt Morehouse                                              ArrayRef<BasicBlock *> AllBlocks,
761034126e5SMatt Morehouse                                              bool IsLeafFunc) {
762a9b0dd0eSKostya Serebryany   if (AllBlocks.empty()) return false;
763b75d002fSKostya Serebryany   CreateFunctionLocalArrays(F, AllBlocks);
764a9b0dd0eSKostya Serebryany   for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
765034126e5SMatt Morehouse     InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
7663514f274SAlexey Samsonov   return true;
7673514f274SAlexey Samsonov }
76829a18dcbSKostya Serebryany 
76929a18dcbSKostya Serebryany // On every indirect call we call a run-time function
77029a18dcbSKostya Serebryany // __sanitizer_cov_indir_call* with two parameters:
77129a18dcbSKostya Serebryany //   - callee address,
772759aca01SMike Aizatsky //   - global cache array that contains CacheSize pointers (zero-initialized).
77329a18dcbSKostya Serebryany //     The cache is used to speed up recording the caller-callee pairs.
77429a18dcbSKostya Serebryany // The address of the caller is passed implicitly via caller PC.
775759aca01SMike Aizatsky // CacheSize is encoded in the name of the run-time function.
InjectCoverageForIndirectCalls(Function & F,ArrayRef<Instruction * > IndirCalls)776eca01b03SLeonard Chan void ModuleSanitizerCoverage::InjectCoverageForIndirectCalls(
77729a18dcbSKostya Serebryany     Function &F, ArrayRef<Instruction *> IndirCalls) {
778759aca01SMike Aizatsky   if (IndirCalls.empty())
779759aca01SMike Aizatsky     return;
780e8d1c652SPratyai Mazumder   assert(Options.TracePC || Options.TracePCGuard ||
781e8d1c652SPratyai Mazumder          Options.Inline8bitCounters || Options.InlineBoolFlag);
78229a18dcbSKostya Serebryany   for (auto I : IndirCalls) {
78329a18dcbSKostya Serebryany     IRBuilder<> IRB(I);
7841b6b05a2SMircea Trofin     CallBase &CB = cast<CallBase>(*I);
785a58b62b4SCraig Topper     Value *Callee = CB.getCalledOperand();
786759aca01SMike Aizatsky     if (isa<InlineAsm>(Callee))
787759aca01SMike Aizatsky       continue;
788c5d3d490SKostya Serebryany     IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
78929a18dcbSKostya Serebryany   }
79029a18dcbSKostya Serebryany }
79129a18dcbSKostya Serebryany 
792fb7d8d9dSKostya Serebryany // For every switch statement we insert a call:
793fb7d8d9dSKostya Serebryany // __sanitizer_cov_trace_switch(CondValue,
794fb7d8d9dSKostya Serebryany //      {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
795fb7d8d9dSKostya Serebryany 
InjectTraceForSwitch(Function &,ArrayRef<Instruction * > SwitchTraceTargets)796eca01b03SLeonard Chan void ModuleSanitizerCoverage::InjectTraceForSwitch(
797759aca01SMike Aizatsky     Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
798fb7d8d9dSKostya Serebryany   for (auto I : SwitchTraceTargets) {
799fb7d8d9dSKostya Serebryany     if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
800fb7d8d9dSKostya Serebryany       IRBuilder<> IRB(I);
801fb7d8d9dSKostya Serebryany       SmallVector<Constant *, 16> Initializers;
802fb7d8d9dSKostya Serebryany       Value *Cond = SI->getCondition();
80325691186SKostya Serebryany       if (Cond->getType()->getScalarSizeInBits() >
80425691186SKostya Serebryany           Int64Ty->getScalarSizeInBits())
80525691186SKostya Serebryany         continue;
806fb7d8d9dSKostya Serebryany       Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
807fb7d8d9dSKostya Serebryany       Initializers.push_back(
808fb7d8d9dSKostya Serebryany           ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
809fb7d8d9dSKostya Serebryany       if (Cond->getType()->getScalarSizeInBits() <
810fb7d8d9dSKostya Serebryany           Int64Ty->getScalarSizeInBits())
811fb7d8d9dSKostya Serebryany         Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
812fb7d8d9dSKostya Serebryany       for (auto It : SI->cases()) {
813fb7d8d9dSKostya Serebryany         Constant *C = It.getCaseValue();
814fb7d8d9dSKostya Serebryany         if (C->getType()->getScalarSizeInBits() <
815fb7d8d9dSKostya Serebryany             Int64Ty->getScalarSizeInBits())
816fb7d8d9dSKostya Serebryany           C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
817fb7d8d9dSKostya Serebryany         Initializers.push_back(C);
818fb7d8d9dSKostya Serebryany       }
8199bcc0d10SKazu Hirata       llvm::sort(drop_begin(Initializers, 2),
820f24e52c0SKostya Serebryany                  [](const Constant *A, const Constant *B) {
821f24e52c0SKostya Serebryany                    return cast<ConstantInt>(A)->getLimitedValue() <
822f24e52c0SKostya Serebryany                           cast<ConstantInt>(B)->getLimitedValue();
823f24e52c0SKostya Serebryany                  });
824fb7d8d9dSKostya Serebryany       ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
825fb7d8d9dSKostya Serebryany       GlobalVariable *GV = new GlobalVariable(
826fb7d8d9dSKostya Serebryany           *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
827fb7d8d9dSKostya Serebryany           ConstantArray::get(ArrayOfInt64Ty, Initializers),
828fb7d8d9dSKostya Serebryany           "__sancov_gen_cov_switch_values");
829fb7d8d9dSKostya Serebryany       IRB.CreateCall(SanCovTraceSwitchFunction,
830fb7d8d9dSKostya Serebryany                      {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
831fb7d8d9dSKostya Serebryany     }
832fb7d8d9dSKostya Serebryany   }
833fb7d8d9dSKostya Serebryany }
834fb7d8d9dSKostya Serebryany 
InjectTraceForDiv(Function &,ArrayRef<BinaryOperator * > DivTraceTargets)835eca01b03SLeonard Chan void ModuleSanitizerCoverage::InjectTraceForDiv(
8365ac427b8SKostya Serebryany     Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
8375ac427b8SKostya Serebryany   for (auto BO : DivTraceTargets) {
8385ac427b8SKostya Serebryany     IRBuilder<> IRB(BO);
8395ac427b8SKostya Serebryany     Value *A1 = BO->getOperand(1);
8405ac427b8SKostya Serebryany     if (isa<ConstantInt>(A1)) continue;
8415ac427b8SKostya Serebryany     if (!A1->getType()->isIntegerTy())
8425ac427b8SKostya Serebryany       continue;
8435ac427b8SKostya Serebryany     uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
8445ac427b8SKostya Serebryany     int CallbackIdx = TypeSize == 32 ? 0 :
8455ac427b8SKostya Serebryany         TypeSize == 64 ? 1 : -1;
8465ac427b8SKostya Serebryany     if (CallbackIdx < 0) continue;
8475ac427b8SKostya Serebryany     auto Ty = Type::getIntNTy(*C, TypeSize);
84847211fa8SArthur Eubanks     IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
8495ac427b8SKostya Serebryany                    {IRB.CreateIntCast(A1, Ty, true)});
8505ac427b8SKostya Serebryany   }
8515ac427b8SKostya Serebryany }
8525ac427b8SKostya Serebryany 
InjectTraceForGep(Function &,ArrayRef<GetElementPtrInst * > GepTraceTargets)853eca01b03SLeonard Chan void ModuleSanitizerCoverage::InjectTraceForGep(
8545ac427b8SKostya Serebryany     Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
8555ac427b8SKostya Serebryany   for (auto GEP : GepTraceTargets) {
8565ac427b8SKostya Serebryany     IRBuilder<> IRB(GEP);
857ea3175c1SKazu Hirata     for (Use &Idx : GEP->indices())
858ea3175c1SKazu Hirata       if (!isa<ConstantInt>(Idx) && Idx->getType()->isIntegerTy())
8595ac427b8SKostya Serebryany         IRB.CreateCall(SanCovTraceGepFunction,
860ea3175c1SKazu Hirata                        {IRB.CreateIntCast(Idx, IntptrTy, true)});
8615ac427b8SKostya Serebryany   }
8625ac427b8SKostya Serebryany }
8635ac427b8SKostya Serebryany 
InjectTraceForLoadsAndStores(Function &,ArrayRef<LoadInst * > Loads,ArrayRef<StoreInst * > Stores)864b7f3a4f4SKostya Serebryany void ModuleSanitizerCoverage::InjectTraceForLoadsAndStores(
865b7f3a4f4SKostya Serebryany     Function &, ArrayRef<LoadInst *> Loads, ArrayRef<StoreInst *> Stores) {
8662f02c7e1SNikita Popov   auto CallbackIdx = [&](Type *ElementTy) -> int {
867b7f3a4f4SKostya Serebryany     uint64_t TypeSize = DL->getTypeStoreSizeInBits(ElementTy);
868b7f3a4f4SKostya Serebryany     return TypeSize == 8     ? 0
869b7f3a4f4SKostya Serebryany            : TypeSize == 16  ? 1
870b7f3a4f4SKostya Serebryany            : TypeSize == 32  ? 2
871b7f3a4f4SKostya Serebryany            : TypeSize == 64  ? 3
872b7f3a4f4SKostya Serebryany            : TypeSize == 128 ? 4
873b7f3a4f4SKostya Serebryany                              : -1;
874b7f3a4f4SKostya Serebryany   };
875b7f3a4f4SKostya Serebryany   Type *PointerType[5] = {Int8PtrTy, Int16PtrTy, Int32PtrTy, Int64PtrTy,
876b7f3a4f4SKostya Serebryany                           Int128PtrTy};
877b7f3a4f4SKostya Serebryany   for (auto LI : Loads) {
878b7f3a4f4SKostya Serebryany     IRBuilder<> IRB(LI);
879b7f3a4f4SKostya Serebryany     auto Ptr = LI->getPointerOperand();
8802f02c7e1SNikita Popov     int Idx = CallbackIdx(LI->getType());
881b7f3a4f4SKostya Serebryany     if (Idx < 0)
882b7f3a4f4SKostya Serebryany       continue;
883b7f3a4f4SKostya Serebryany     IRB.CreateCall(SanCovLoadFunction[Idx],
884b7f3a4f4SKostya Serebryany                    IRB.CreatePointerCast(Ptr, PointerType[Idx]));
885b7f3a4f4SKostya Serebryany   }
886b7f3a4f4SKostya Serebryany   for (auto SI : Stores) {
887b7f3a4f4SKostya Serebryany     IRBuilder<> IRB(SI);
888b7f3a4f4SKostya Serebryany     auto Ptr = SI->getPointerOperand();
8892f02c7e1SNikita Popov     int Idx = CallbackIdx(SI->getValueOperand()->getType());
890b7f3a4f4SKostya Serebryany     if (Idx < 0)
891b7f3a4f4SKostya Serebryany       continue;
892b7f3a4f4SKostya Serebryany     IRB.CreateCall(SanCovStoreFunction[Idx],
893b7f3a4f4SKostya Serebryany                    IRB.CreatePointerCast(Ptr, PointerType[Idx]));
894b7f3a4f4SKostya Serebryany   }
895b7f3a4f4SKostya Serebryany }
896b7f3a4f4SKostya Serebryany 
InjectTraceForCmp(Function &,ArrayRef<Instruction * > CmpTraceTargets)897eca01b03SLeonard Chan void ModuleSanitizerCoverage::InjectTraceForCmp(
898759aca01SMike Aizatsky     Function &, ArrayRef<Instruction *> CmpTraceTargets) {
899f4e35cc4SKostya Serebryany   for (auto I : CmpTraceTargets) {
900f4e35cc4SKostya Serebryany     if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
901f4e35cc4SKostya Serebryany       IRBuilder<> IRB(ICMP);
902f4e35cc4SKostya Serebryany       Value *A0 = ICMP->getOperand(0);
903f4e35cc4SKostya Serebryany       Value *A1 = ICMP->getOperand(1);
904759aca01SMike Aizatsky       if (!A0->getType()->isIntegerTy())
905759aca01SMike Aizatsky         continue;
906f4e35cc4SKostya Serebryany       uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
907524c3f32SKostya Serebryany       int CallbackIdx = TypeSize == 8 ? 0 :
908524c3f32SKostya Serebryany                         TypeSize == 16 ? 1 :
909524c3f32SKostya Serebryany                         TypeSize == 32 ? 2 :
910524c3f32SKostya Serebryany                         TypeSize == 64 ? 3 : -1;
911524c3f32SKostya Serebryany       if (CallbackIdx < 0) continue;
9120a648a4bSAlexey Samsonov       // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
91352410815SAlexander Potapenko       auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
91452410815SAlexander Potapenko       bool FirstIsConst = isa<ConstantInt>(A0);
91552410815SAlexander Potapenko       bool SecondIsConst = isa<ConstantInt>(A1);
91652410815SAlexander Potapenko       // If both are const, then we don't need such a comparison.
91752410815SAlexander Potapenko       if (FirstIsConst && SecondIsConst) continue;
91852410815SAlexander Potapenko       // If only one is const, then make it the first callback argument.
91952410815SAlexander Potapenko       if (FirstIsConst || SecondIsConst) {
92052410815SAlexander Potapenko         CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
92152410815SAlexander Potapenko         if (SecondIsConst)
92252410815SAlexander Potapenko           std::swap(A0, A1);
92352410815SAlexander Potapenko       }
92452410815SAlexander Potapenko 
925524c3f32SKostya Serebryany       auto Ty = Type::getIntNTy(*C, TypeSize);
92652410815SAlexander Potapenko       IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
92752410815SAlexander Potapenko               IRB.CreateIntCast(A1, Ty, true)});
928f4e35cc4SKostya Serebryany     }
929f4e35cc4SKostya Serebryany   }
930f4e35cc4SKostya Serebryany }
931f4e35cc4SKostya Serebryany 
InjectCoverageAtBlock(Function & F,BasicBlock & BB,size_t Idx,bool IsLeafFunc)932eca01b03SLeonard Chan void ModuleSanitizerCoverage::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
933eca01b03SLeonard Chan                                                     size_t Idx,
934eca01b03SLeonard Chan                                                     bool IsLeafFunc) {
9357ae63aa8SJustin Bogner   BasicBlock::iterator IP = BB.getFirstInsertionPt();
936d421db05SKostya Serebryany   bool IsEntryBB = &BB == &F.getEntryBlock();
937201733b7SAlexey Samsonov   DebugLoc EntryLoc;
938201733b7SAlexey Samsonov   if (IsEntryBB) {
939adebb937SPete Cooper     if (auto SP = F.getSubprogram())
940b5ad32efSFangrui Song       EntryLoc = DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
941a57d0151SReid Kleckner     // Keep static allocas and llvm.localescape calls in the entry block.  Even
942a57d0151SReid Kleckner     // if we aren't splitting the block, it's nice for allocas to be before
943a57d0151SReid Kleckner     // calls.
944a57d0151SReid Kleckner     IP = PrepareToSplitEntryBlock(BB, IP);
945201733b7SAlexey Samsonov   }
946201733b7SAlexey Samsonov 
9479ae87b59SMarco Elver   InstrumentationIRBuilder IRB(&*IP);
9489ae87b59SMarco Elver   if (EntryLoc)
94929a18dcbSKostya Serebryany     IRB.SetCurrentDebugLocation(EntryLoc);
950d4590c73SKostya Serebryany   if (Options.TracePC) {
9516a822e20SZequan Wu     IRB.CreateCall(SanCovTracePC)
9526a822e20SZequan Wu         ->setCannotMerge(); // gets the PC using GET_CALLER_PC.
9532c2fb889SKostya Serebryany   }
9542c2fb889SKostya Serebryany   if (Options.TracePCGuard) {
955a9b0dd0eSKostya Serebryany     auto GuardPtr = IRB.CreateIntToPtr(
956a9b0dd0eSKostya Serebryany         IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
957a9b0dd0eSKostya Serebryany                       ConstantInt::get(IntptrTy, Idx * 4)),
958a9b0dd0eSKostya Serebryany         Int32PtrTy);
9596a822e20SZequan Wu     IRB.CreateCall(SanCovTracePCGuard, GuardPtr)->setCannotMerge();
960a9b0dd0eSKostya Serebryany   }
9612c2fb889SKostya Serebryany   if (Options.Inline8bitCounters) {
9622c2fb889SKostya Serebryany     auto CounterPtr = IRB.CreateGEP(
9637716075aSJames Y Knight         Function8bitCounterArray->getValueType(), Function8bitCounterArray,
9642c2fb889SKostya Serebryany         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
96514359ef1SJames Y Knight     auto Load = IRB.CreateLoad(Int8Ty, CounterPtr);
9662c2fb889SKostya Serebryany     auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
9672c2fb889SKostya Serebryany     auto Store = IRB.CreateStore(Inc, CounterPtr);
9682c2fb889SKostya Serebryany     SetNoSanitizeMetadata(Load);
9692c2fb889SKostya Serebryany     SetNoSanitizeMetadata(Store);
9702c2fb889SKostya Serebryany   }
971e8d1c652SPratyai Mazumder   if (Options.InlineBoolFlag) {
972e8d1c652SPratyai Mazumder     auto FlagPtr = IRB.CreateGEP(
973e8d1c652SPratyai Mazumder         FunctionBoolArray->getValueType(), FunctionBoolArray,
974e8d1c652SPratyai Mazumder         {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
97508032e71SPratyai Mazumder     auto Load = IRB.CreateLoad(Int1Ty, FlagPtr);
97608032e71SPratyai Mazumder     auto ThenTerm =
97708032e71SPratyai Mazumder         SplitBlockAndInsertIfThen(IRB.CreateIsNull(Load), &*IP, false);
97808032e71SPratyai Mazumder     IRBuilder<> ThenIRB(ThenTerm);
97908032e71SPratyai Mazumder     auto Store = ThenIRB.CreateStore(ConstantInt::getTrue(Int1Ty), FlagPtr);
98008032e71SPratyai Mazumder     SetNoSanitizeMetadata(Load);
981e8d1c652SPratyai Mazumder     SetNoSanitizeMetadata(Store);
982e8d1c652SPratyai Mazumder   }
983034126e5SMatt Morehouse   if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
9845c7fc769SMatt Morehouse     // Check stack depth.  If it's the deepest so far, record it.
985006cf8c0SChristudasan Devadasan     Module *M = F.getParent();
986006cf8c0SChristudasan Devadasan     Function *GetFrameAddr = Intrinsic::getDeclaration(
987006cf8c0SChristudasan Devadasan         M, Intrinsic::frameaddress,
988006cf8c0SChristudasan Devadasan         IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
9895c7fc769SMatt Morehouse     auto FrameAddrPtr =
9905c7fc769SMatt Morehouse         IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
9915c7fc769SMatt Morehouse     auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
99214359ef1SJames Y Knight     auto LowestStack = IRB.CreateLoad(IntptrTy, SanCovLowestStack);
9935c7fc769SMatt Morehouse     auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
9945c7fc769SMatt Morehouse     auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
9955c7fc769SMatt Morehouse     IRBuilder<> ThenIRB(ThenTerm);
996034126e5SMatt Morehouse     auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
997034126e5SMatt Morehouse     SetNoSanitizeMetadata(LowestStack);
998034126e5SMatt Morehouse     SetNoSanitizeMetadata(Store);
9995c7fc769SMatt Morehouse   }
100029a18dcbSKostya Serebryany }
100129a18dcbSKostya Serebryany 
1002aed6ba77SKostya Serebryany std::string
getSectionName(const std::string & Section) const1003eca01b03SLeonard Chan ModuleSanitizerCoverage::getSectionName(const std::string &Section) const {
1004e159a0ddSJonathan Metzman   if (TargetTriple.isOSBinFormatCOFF()) {
10057e042bb1SMatt Morehouse     if (Section == SanCovCountersSectionName)
10067e042bb1SMatt Morehouse       return ".SCOV$CM";
1007e8d1c652SPratyai Mazumder     if (Section == SanCovBoolFlagSectionName)
1008e8d1c652SPratyai Mazumder       return ".SCOV$BM";
10097e042bb1SMatt Morehouse     if (Section == SanCovPCsSectionName)
10107e042bb1SMatt Morehouse       return ".SCOVP$M";
10117e042bb1SMatt Morehouse     return ".SCOV$GM"; // For SanCovGuardsSectionName.
10127e042bb1SMatt Morehouse   }
1013db5a5655SMarcos Pividori   if (TargetTriple.isOSBinFormatMachO())
1014aed6ba77SKostya Serebryany     return "__DATA,__" + Section;
1015aed6ba77SKostya Serebryany   return "__" + Section;
1016db5a5655SMarcos Pividori }
1017db5a5655SMarcos Pividori 
1018eca01b03SLeonard Chan std::string
getSectionStart(const std::string & Section) const1019eca01b03SLeonard Chan ModuleSanitizerCoverage::getSectionStart(const std::string &Section) const {
1020eca01b03SLeonard Chan   if (TargetTriple.isOSBinFormatMachO())
1021eca01b03SLeonard Chan     return "\1section$start$__DATA$__" + Section;
1022eca01b03SLeonard Chan   return "__start___" + Section;
1023eca01b03SLeonard Chan }
1024007f674cSLeonard Chan 
1025eca01b03SLeonard Chan std::string
getSectionEnd(const std::string & Section) const1026eca01b03SLeonard Chan ModuleSanitizerCoverage::getSectionEnd(const std::string &Section) const {
1027eca01b03SLeonard Chan   if (TargetTriple.isOSBinFormatMachO())
1028eca01b03SLeonard Chan     return "\1section$end$__DATA$__" + Section;
1029eca01b03SLeonard Chan   return "__stop___" + Section;
1030eca01b03SLeonard Chan }
1031