blob: 1b6d6d6f3c64e7eb636f593d0494c7775a6c06a7 [file] [log] [blame]
Kostya Serebryany29a18dc2014-11-11 22:14:37 +00001//===-- SanitizerCoverage.cpp - coverage instrumentation for sanitizers ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Kostya Serebryany53b34c82017-05-31 18:27:33 +000010// Coverage instrumentation done on LLVM IR level, works with Sanitizers.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000011//
12//===----------------------------------------------------------------------===//
13
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000014#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000016#include "llvm/Analysis/EHPersonalities.h"
George Karpenkov018472c2017-05-24 00:29:12 +000017#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000018#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000019#include "llvm/IR/CallSite.h"
20#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000021#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000022#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023#include "llvm/IR/Function.h"
24#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000025#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000026#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/MDBuilder.h"
28#include "llvm/IR/Module.h"
29#include "llvm/IR/Type.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000033#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000034#include "llvm/Transforms/Scalar.h"
35#include "llvm/Transforms/Utils/BasicBlockUtils.h"
36#include "llvm/Transforms/Utils/ModuleUtils.h"
37
38using namespace llvm;
39
40#define DEBUG_TYPE "sancov"
41
Mike Aizatsky759aca02016-03-18 23:29:29 +000042static const char *const SanCovTracePCIndirName =
43 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000044static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000045static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
46static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
47static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
48static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000049static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
50static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
51static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000052static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
53static const char *const SanCovModuleCtorName = "sancov.module_ctor";
54static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000055
Kostya Serebryanyda718e52016-09-14 01:39:35 +000056static const char *const SanCovTracePCGuardName =
57 "__sanitizer_cov_trace_pc_guard";
58static const char *const SanCovTracePCGuardInitName =
59 "__sanitizer_cov_trace_pc_guard_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000060static const char *const SanCov8bitCountersInitName =
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000061 "__sanitizer_cov_8bit_counters_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000062static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
Kostya Serebryanyda718e52016-09-14 01:39:35 +000063
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000064static const char *const SanCovGuardsSectionName = "sancov_guards";
George Karpenkov406c1132017-06-14 23:40:25 +000065static const char *const SanCovCountersSectionName = "sancov_cntrs";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000066static const char *const SanCovPCsSectionName = "sancov_pcs";
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000067
Mike Aizatsky759aca02016-03-18 23:29:29 +000068static cl::opt<int> ClCoverageLevel(
69 "sanitizer-coverage-level",
70 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000071 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000072 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000073
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000074static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
75 cl::desc("Experimental pc tracing"), cl::Hidden,
76 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000077
Kostya Serebryanyda718e52016-09-14 01:39:35 +000078static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
79 cl::desc("pc tracing with a guard"),
80 cl::Hidden, cl::init(false));
81
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000082// If true, we create a global variable that contains PCs of all instrumented
83// BBs, put this global into a named section, and pass this section's bounds
84// to __sanitizer_cov_pcs_init.
85// This way the coverage instrumentation does not need to acquire the PCs
86// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +000087static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000088 cl::desc("create a static PC table"),
89 cl::Hidden, cl::init(false));
90
91static cl::opt<bool>
92 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
93 cl::desc("increments 8-bit counter for every edge"),
94 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000095
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000096static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000097 ClCMPTracing("sanitizer-coverage-trace-compares",
98 cl::desc("Tracing of CMP and similar instructions"),
99 cl::Hidden, cl::init(false));
100
101static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
102 cl::desc("Tracing of DIV instructions"),
103 cl::Hidden, cl::init(false));
104
105static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
106 cl::desc("Tracing of GEP instructions"),
107 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000108
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000109static cl::opt<bool>
110 ClPruneBlocks("sanitizer-coverage-prune-blocks",
111 cl::desc("Reduce the number of instrumented blocks"),
112 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000113
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000114namespace {
115
Alexey Samsonov3514f272015-05-07 01:00:31 +0000116SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
117 SanitizerCoverageOptions Res;
118 switch (LegacyCoverageLevel) {
119 case 0:
120 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
121 break;
122 case 1:
123 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
124 break;
125 case 2:
126 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
127 break;
128 case 3:
129 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
130 break;
131 case 4:
132 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
133 Res.IndirectCalls = true;
134 break;
135 }
136 return Res;
137}
138
139SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
140 // Sets CoverageType and IndirectCalls.
141 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
142 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
143 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000144 Options.TraceCmp |= ClCMPTracing;
145 Options.TraceDiv |= ClDIVTracing;
146 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000147 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000148 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000149 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000150 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000151 if (!Options.TracePCGuard && !Options.TracePC && !Options.Inline8bitCounters)
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000152 Options.TracePCGuard = true; // TracePCGuard is default.
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000153 Options.NoPrune |= !ClPruneBlocks;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000154 return Options;
155}
156
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000157class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000158public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000159 SanitizerCoverageModule(
160 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000161 : ModulePass(ID), Options(OverrideFromCL(Options)) {
162 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
163 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000164 bool runOnModule(Module &M) override;
165 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000166 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000167 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000168
Chandler Carruth30061152016-03-18 22:43:42 +0000169 void getAnalysisUsage(AnalysisUsage &AU) const override {
170 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000171 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000172 }
173
174private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000175 void InjectCoverageForIndirectCalls(Function &F,
176 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000177 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000178 void InjectTraceForDiv(Function &F,
179 ArrayRef<BinaryOperator *> DivTraceTargets);
180 void InjectTraceForGep(Function &F,
181 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000182 void InjectTraceForSwitch(Function &F,
183 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000184 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000185 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
186 Function &F, Type *Ty,
187 const char *Section);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000188 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
189 void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000190 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000191 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
192 Type *Ty, const char *Section);
193 std::pair<GlobalVariable *, GlobalVariable *>
194 CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000195
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000196 void SetNoSanitizeMetadata(Instruction *I) {
197 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
198 MDNode::get(*C, None));
199 }
200
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000201 std::string getSectionName(const std::string &Section) const;
202 std::string getSectionStart(const std::string &Section) const;
203 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000204 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000205 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000206 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000207 Function *SanCovTraceDivFunction[2];
208 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000209 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000210 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000211 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
212 *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000213 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000214 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000215 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000216 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000217
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000218 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000219 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000220 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000221
Alexey Samsonov3514f272015-05-07 01:00:31 +0000222 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000223};
224
Mike Aizatsky759aca02016-03-18 23:29:29 +0000225} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000226
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000227std::pair<GlobalVariable *, GlobalVariable *>
228SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
229 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000230 GlobalVariable *SecStart =
231 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
232 getSectionStart(Section));
233 SecStart->setVisibility(GlobalValue::HiddenVisibility);
234 GlobalVariable *SecEnd =
235 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
236 nullptr, getSectionEnd(Section));
237 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
238
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000239 return std::make_pair(SecStart, SecEnd);
240}
241
242
243Function *SanitizerCoverageModule::CreateInitCallsForSections(
244 Module &M, const char *InitFunctionName, Type *Ty,
245 const char *Section) {
246 IRBuilder<> IRB(M.getContext());
247 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
248 auto SecStart = SecStartEnd.first;
249 auto SecEnd = SecStartEnd.second;
250 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000251 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
252 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
253 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
254
255 if (TargetTriple.supportsCOMDAT()) {
256 // Use comdat to dedup CtorFunc.
257 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
258 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
259 } else {
260 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
261 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000262 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000263}
264
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000265bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000266 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
267 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000268 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000269 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000270 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000271 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000272 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000273 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000274 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000275 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000276 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000277 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000278 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000279 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000280 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000281 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000282 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000283 Int32Ty = IRB.getInt32Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000284 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000285
Mike Aizatsky759aca02016-03-18 23:29:29 +0000286 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000287 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000288 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000289 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000290 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000291 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
292 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000293 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000294 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
295 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000296 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000297 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000298 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000299 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000300
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000301 SanCovTraceDivFunction[0] =
302 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000303 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000304 SanCovTraceDivFunction[1] =
305 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000306 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000307 SanCovTraceGepFunction =
308 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000309 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000310 SanCovTraceSwitchFunction =
311 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000312 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000313 // Make sure smaller parameters are zero-extended to i64 as required by the
314 // x86_64 ABI.
315 if (TargetTriple.getArch() == Triple::x86_64) {
316 for (int i = 0; i < 3; i++) {
317 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
318 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
319 }
320 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
321 }
322
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000323
Kostya Serebryany73762942014-12-16 21:24:15 +0000324 // We insert an empty inline asm after cov callbacks to avoid callback merge.
325 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
326 StringRef(""), StringRef(""),
327 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000328
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000329 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000330 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000331 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000332 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000333
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000334 for (auto &F : M)
335 runOnFunction(F);
336
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000337 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000338
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000339 if (FunctionGuardArray)
340 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
341 SanCovGuardsSectionName);
342 if (Function8bitCounterArray)
343 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
344 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000345 if (Ctor && Options.PCTable) {
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000346 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, Int8PtrTy);
347 Function *InitFunction = declareSanitizerInitFunction(
348 M, SanCovPCsInitName, {Int8PtrTy, Int8PtrTy});
349 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
350 IRBCtor.CreateCall(InitFunction,
351 {IRB.CreatePointerCast(SecStartEnd.first, Int8PtrTy),
352 IRB.CreatePointerCast(SecStartEnd.second, Int8PtrTy)});
353 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000354 return true;
355}
356
Mike Aizatsky9987f432016-03-23 23:15:03 +0000357// True if block has successors and it dominates all of them.
358static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
359 if (succ_begin(BB) == succ_end(BB))
360 return false;
361
362 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
363 if (!DT->dominates(BB, SUCC))
364 return false;
365 }
366
367 return true;
368}
369
George Karpenkov018472c2017-05-24 00:29:12 +0000370// True if block has predecessors and it postdominates all of them.
371static bool isFullPostDominator(const BasicBlock *BB,
372 const PostDominatorTree *PDT) {
373 if (pred_begin(BB) == pred_end(BB))
374 return false;
375
376 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
377 if (!PDT->dominates(BB, PRED))
378 return false;
379 }
380
381 return true;
382}
383
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000384static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
385 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000386 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000387 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000388 // Don't insert coverage for unreachable blocks: we will never call
389 // __sanitizer_cov() for them, so counting them in
390 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
391 // percentage. Also, unreachable instructions frequently have no debug
392 // locations.
393 if (isa<UnreachableInst>(BB->getTerminator()))
394 return false;
395
Reid Kleckner392f0622017-03-23 23:30:41 +0000396 // Don't insert coverage into blocks without a valid insertion point
397 // (catchswitch blocks).
398 if (BB->getFirstInsertionPt() == BB->end())
399 return false;
400
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000401 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000402 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000403
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000404 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
405 &F.getEntryBlock() != BB)
406 return false;
407
George Karpenkova1c53272017-05-25 01:41:46 +0000408 // Do not instrument full dominators, or full post-dominators with multiple
409 // predecessors.
410 return !isFullDominator(BB, DT)
411 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000412}
413
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000414bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000415 if (F.empty())
416 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000417 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000418 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000419 if (F.getName().startswith("__sanitizer_"))
420 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000421 // Don't touch available_externally functions, their actual body is elewhere.
422 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
423 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000424 // Don't instrument MSVC CRT configuration helpers. They may run before normal
425 // initialization.
426 if (F.getName() == "__local_stdio_printf_options" ||
427 F.getName() == "__local_stdio_scanf_options")
428 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000429 // Don't instrument functions using SEH for now. Splitting basic blocks like
430 // we do for coverage breaks WinEHPrepare.
431 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
432 if (F.hasPersonalityFn() &&
433 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
434 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000435 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000436 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000437 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000438 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000439 SmallVector<Instruction *, 8> CmpTraceTargets;
440 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000441 SmallVector<BinaryOperator *, 8> DivTraceTargets;
442 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000443
Mike Aizatsky602f7922016-03-21 23:08:16 +0000444 const DominatorTree *DT =
445 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000446 const PostDominatorTree *PDT =
447 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Mike Aizatsky602f7922016-03-21 23:08:16 +0000448
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000449 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000450 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000451 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000452 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000453 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000454 CallSite CS(&Inst);
455 if (CS && !CS.getCalledFunction())
456 IndirCalls.push_back(&Inst);
457 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000458 if (Options.TraceCmp) {
459 if (isa<ICmpInst>(&Inst))
460 CmpTraceTargets.push_back(&Inst);
461 if (isa<SwitchInst>(&Inst))
462 SwitchTraceTargets.push_back(&Inst);
463 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000464 if (Options.TraceDiv)
465 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
466 if (BO->getOpcode() == Instruction::SDiv ||
467 BO->getOpcode() == Instruction::UDiv)
468 DivTraceTargets.push_back(BO);
469 if (Options.TraceGep)
470 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
471 GepTraceTargets.push_back(GEP);
472 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000473 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000474
475 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000476 InjectCoverageForIndirectCalls(F, IndirCalls);
477 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000478 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000479 InjectTraceForDiv(F, DivTraceTargets);
480 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000481 return true;
482}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000483
484GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
485 size_t NumElements, Function &F, Type *Ty, const char *Section) {
486 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
487 auto Array = new GlobalVariable(
488 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
489 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000490 if (auto Comdat = F.getComdat())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000491 Array->setComdat(Comdat);
492 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000493 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
494 : Ty->getPrimitiveSizeInBits() / 8);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000495 return Array;
496}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000497
498void SanitizerCoverageModule::CreatePCArray(Function &F,
499 ArrayRef<BasicBlock *> AllBlocks) {
500 size_t N = AllBlocks.size();
501 assert(N);
502 assert(&F.getEntryBlock() == AllBlocks[0]);
503 SmallVector<Constant *, 16> PCs;
504 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
505 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, Int8PtrTy));
506 for (size_t i = 1; i < N; i++)
507 PCs.push_back(BlockAddress::get(AllBlocks[i]));
508 FunctionPCsArray =
509 CreateFunctionLocalArrayInSection(N, F, Int8PtrTy, SanCovPCsSectionName);
510 FunctionPCsArray->setInitializer(
511 ConstantArray::get(ArrayType::get(Int8PtrTy, N), PCs));
512 FunctionPCsArray->setConstant(true);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000513}
514
515void SanitizerCoverageModule::CreateFunctionLocalArrays(
516 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000517 if (Options.TracePCGuard)
518 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000519 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000520 if (Options.Inline8bitCounters)
521 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000522 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000523 if (Options.PCTable)
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000524 CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000525}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000526
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000527bool SanitizerCoverageModule::InjectCoverage(Function &F,
528 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000529 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000530 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000531 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
532 InjectCoverageAtBlock(F, *AllBlocks[i], i);
533 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000534}
535
536// On every indirect call we call a run-time function
537// __sanitizer_cov_indir_call* with two parameters:
538// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000539// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000540// The cache is used to speed up recording the caller-callee pairs.
541// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000542// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000543void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
544 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000545 if (IndirCalls.empty())
546 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000547 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000548 for (auto I : IndirCalls) {
549 IRBuilder<> IRB(I);
550 CallSite CS(I);
551 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000552 if (isa<InlineAsm>(Callee))
553 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000554 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000555 }
556}
557
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000558// For every switch statement we insert a call:
559// __sanitizer_cov_trace_switch(CondValue,
560// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
561
562void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000563 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000564 for (auto I : SwitchTraceTargets) {
565 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
566 IRBuilder<> IRB(I);
567 SmallVector<Constant *, 16> Initializers;
568 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000569 if (Cond->getType()->getScalarSizeInBits() >
570 Int64Ty->getScalarSizeInBits())
571 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000572 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
573 Initializers.push_back(
574 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
575 if (Cond->getType()->getScalarSizeInBits() <
576 Int64Ty->getScalarSizeInBits())
577 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000578 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000579 Constant *C = It.getCaseValue();
580 if (C->getType()->getScalarSizeInBits() <
581 Int64Ty->getScalarSizeInBits())
582 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
583 Initializers.push_back(C);
584 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000585 std::sort(Initializers.begin() + 2, Initializers.end(),
586 [](const Constant *A, const Constant *B) {
587 return cast<ConstantInt>(A)->getLimitedValue() <
588 cast<ConstantInt>(B)->getLimitedValue();
589 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000590 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
591 GlobalVariable *GV = new GlobalVariable(
592 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
593 ConstantArray::get(ArrayOfInt64Ty, Initializers),
594 "__sancov_gen_cov_switch_values");
595 IRB.CreateCall(SanCovTraceSwitchFunction,
596 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
597 }
598 }
599}
600
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000601void SanitizerCoverageModule::InjectTraceForDiv(
602 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
603 for (auto BO : DivTraceTargets) {
604 IRBuilder<> IRB(BO);
605 Value *A1 = BO->getOperand(1);
606 if (isa<ConstantInt>(A1)) continue;
607 if (!A1->getType()->isIntegerTy())
608 continue;
609 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
610 int CallbackIdx = TypeSize == 32 ? 0 :
611 TypeSize == 64 ? 1 : -1;
612 if (CallbackIdx < 0) continue;
613 auto Ty = Type::getIntNTy(*C, TypeSize);
614 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
615 {IRB.CreateIntCast(A1, Ty, true)});
616 }
617}
618
619void SanitizerCoverageModule::InjectTraceForGep(
620 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
621 for (auto GEP : GepTraceTargets) {
622 IRBuilder<> IRB(GEP);
623 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000624 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000625 IRB.CreateCall(SanCovTraceGepFunction,
626 {IRB.CreateIntCast(*I, IntptrTy, true)});
627 }
628}
629
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000630void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000631 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000632 for (auto I : CmpTraceTargets) {
633 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
634 IRBuilder<> IRB(ICMP);
635 Value *A0 = ICMP->getOperand(0);
636 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000637 if (!A0->getType()->isIntegerTy())
638 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000639 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000640 int CallbackIdx = TypeSize == 8 ? 0 :
641 TypeSize == 16 ? 1 :
642 TypeSize == 32 ? 2 :
643 TypeSize == 64 ? 3 : -1;
644 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000645 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000646 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000647 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000648 SanCovTraceCmpFunction[CallbackIdx],
649 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000650 }
651 }
652}
653
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000654void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Kostya Serebryany53b34c82017-05-31 18:27:33 +0000655 size_t Idx) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000656 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000657 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000658 DebugLoc EntryLoc;
659 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000660 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000661 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000662 // Keep static allocas and llvm.localescape calls in the entry block. Even
663 // if we aren't splitting the block, it's nice for allocas to be before
664 // calls.
665 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000666 } else {
667 EntryLoc = IP->getDebugLoc();
668 }
669
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000670 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000671 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000672 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000673 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
674 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000675 }
676 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000677 auto GuardPtr = IRB.CreateIntToPtr(
678 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
679 ConstantInt::get(IntptrTy, Idx * 4)),
680 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000681 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
682 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000683 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000684 if (Options.Inline8bitCounters) {
685 auto CounterPtr = IRB.CreateGEP(
686 Function8bitCounterArray,
687 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
688 auto Load = IRB.CreateLoad(CounterPtr);
689 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
690 auto Store = IRB.CreateStore(Inc, CounterPtr);
691 SetNoSanitizeMetadata(Load);
692 SetNoSanitizeMetadata(Store);
693 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000694}
695
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000696std::string
697SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000698 if (TargetTriple.getObjectFormat() == Triple::COFF)
699 return ".SCOV$M";
700 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000701 return "__DATA,__" + Section;
702 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000703}
704
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000705std::string
706SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000707 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000708 return "\1section$start$__DATA$__" + Section;
709 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000710}
711
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000712std::string
713SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000714 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000715 return "\1section$end$__DATA$__" + Section;
716 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000717}
718
719
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000720char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000721INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000722 "SanitizerCoverage: TODO."
723 "ModulePass",
724 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000725INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000726INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000727INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000728 "SanitizerCoverage: TODO."
729 "ModulePass",
730 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000731ModulePass *llvm::createSanitizerCoverageModulePass(
732 const SanitizerCoverageOptions &Options) {
733 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000734}