blob: 01689dfd1618a18a1f4c68916602748198e95716 [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"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000020#include "llvm/IR/Constant.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000021#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000022#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000023#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000024#include "llvm/IR/Function.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000025#include "llvm/IR/GlobalVariable.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000026#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000027#include "llvm/IR/InlineAsm.h"
Matt Morehousef42bd312017-08-25 21:18:29 +000028#include "llvm/IR/IntrinsicInst.h"
Matt Morehouse5c7fc762017-08-18 18:43:30 +000029#include "llvm/IR/Intrinsics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000030#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/MDBuilder.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Type.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000037#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000038#include "llvm/Transforms/Scalar.h"
39#include "llvm/Transforms/Utils/BasicBlockUtils.h"
40#include "llvm/Transforms/Utils/ModuleUtils.h"
41
42using namespace llvm;
43
44#define DEBUG_TYPE "sancov"
45
Mike Aizatsky759aca02016-03-18 23:29:29 +000046static const char *const SanCovTracePCIndirName =
47 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000048static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000049static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
50static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
51static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
52static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Alexander Potapenko52410812017-08-10 15:00:13 +000053static const char *const SanCovTraceConstCmp1 =
54 "__sanitizer_cov_trace_const_cmp1";
55static const char *const SanCovTraceConstCmp2 =
56 "__sanitizer_cov_trace_const_cmp2";
57static const char *const SanCovTraceConstCmp4 =
58 "__sanitizer_cov_trace_const_cmp4";
59static const char *const SanCovTraceConstCmp8 =
60 "__sanitizer_cov_trace_const_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000061static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
62static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
63static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000064static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
65static const char *const SanCovModuleCtorName = "sancov.module_ctor";
66static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000067
Kostya Serebryanyda718e52016-09-14 01:39:35 +000068static const char *const SanCovTracePCGuardName =
69 "__sanitizer_cov_trace_pc_guard";
70static const char *const SanCovTracePCGuardInitName =
71 "__sanitizer_cov_trace_pc_guard_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000072static const char *const SanCov8bitCountersInitName =
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000073 "__sanitizer_cov_8bit_counters_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000074static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
Kostya Serebryanyda718e52016-09-14 01:39:35 +000075
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000076static const char *const SanCovGuardsSectionName = "sancov_guards";
George Karpenkov406c1132017-06-14 23:40:25 +000077static const char *const SanCovCountersSectionName = "sancov_cntrs";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000078static const char *const SanCovPCsSectionName = "sancov_pcs";
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000079
Matt Morehouse5c7fc762017-08-18 18:43:30 +000080static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
Matt Morehouse5c7fc762017-08-18 18:43:30 +000081
Mike Aizatsky759aca02016-03-18 23:29:29 +000082static cl::opt<int> ClCoverageLevel(
83 "sanitizer-coverage-level",
84 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000085 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000086 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000087
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000088static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
89 cl::desc("Experimental pc tracing"), cl::Hidden,
90 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000091
Kostya Serebryanyda718e52016-09-14 01:39:35 +000092static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
93 cl::desc("pc tracing with a guard"),
94 cl::Hidden, cl::init(false));
95
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000096// If true, we create a global variable that contains PCs of all instrumented
97// BBs, put this global into a named section, and pass this section's bounds
98// to __sanitizer_cov_pcs_init.
99// This way the coverage instrumentation does not need to acquire the PCs
100// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000101static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000102 cl::desc("create a static PC table"),
103 cl::Hidden, cl::init(false));
104
105static cl::opt<bool>
106 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
107 cl::desc("increments 8-bit counter for every edge"),
108 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000109
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000110static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000111 ClCMPTracing("sanitizer-coverage-trace-compares",
112 cl::desc("Tracing of CMP and similar instructions"),
113 cl::Hidden, cl::init(false));
114
115static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
116 cl::desc("Tracing of DIV instructions"),
117 cl::Hidden, cl::init(false));
118
119static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
120 cl::desc("Tracing of GEP instructions"),
121 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000122
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000123static cl::opt<bool>
124 ClPruneBlocks("sanitizer-coverage-prune-blocks",
125 cl::desc("Reduce the number of instrumented blocks"),
126 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000127
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000128static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
129 cl::desc("max stack depth tracing"),
130 cl::Hidden, cl::init(false));
131
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000132namespace {
133
Alexey Samsonov3514f272015-05-07 01:00:31 +0000134SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
135 SanitizerCoverageOptions Res;
136 switch (LegacyCoverageLevel) {
137 case 0:
138 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
139 break;
140 case 1:
141 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
142 break;
143 case 2:
144 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
145 break;
146 case 3:
147 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
148 break;
149 case 4:
150 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
151 Res.IndirectCalls = true;
152 break;
153 }
154 return Res;
155}
156
157SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
158 // Sets CoverageType and IndirectCalls.
159 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
160 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
161 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000162 Options.TraceCmp |= ClCMPTracing;
163 Options.TraceDiv |= ClDIVTracing;
164 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000165 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000166 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000167 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000168 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000169 Options.NoPrune |= !ClPruneBlocks;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000170 Options.StackDepth |= ClStackDepth;
171 if (!Options.TracePCGuard && !Options.TracePC &&
172 !Options.Inline8bitCounters && !Options.StackDepth)
173 Options.TracePCGuard = true; // TracePCGuard is default.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000174 return Options;
175}
176
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000177class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000178public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000179 SanitizerCoverageModule(
180 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000181 : ModulePass(ID), Options(OverrideFromCL(Options)) {
182 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
183 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000184 bool runOnModule(Module &M) override;
185 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000186 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000187 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000188
Chandler Carruth30061152016-03-18 22:43:42 +0000189 void getAnalysisUsage(AnalysisUsage &AU) const override {
190 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000191 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000192 }
193
194private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000195 void InjectCoverageForIndirectCalls(Function &F,
196 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000197 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000198 void InjectTraceForDiv(Function &F,
199 ArrayRef<BinaryOperator *> DivTraceTargets);
200 void InjectTraceForGep(Function &F,
201 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000202 void InjectTraceForSwitch(Function &F,
203 ArrayRef<Instruction *> SwitchTraceTargets);
Matt Morehousef42bd312017-08-25 21:18:29 +0000204 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks,
205 bool IsLeafFunc = true);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000206 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
207 Function &F, Type *Ty,
208 const char *Section);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000209 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
210 void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Matt Morehousef42bd312017-08-25 21:18:29 +0000211 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx,
212 bool IsLeafFunc = true);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000213 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
214 Type *Ty, const char *Section);
215 std::pair<GlobalVariable *, GlobalVariable *>
216 CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000217
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000218 void SetNoSanitizeMetadata(Instruction *I) {
219 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
220 MDNode::get(*C, None));
221 }
222
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000223 std::string getSectionName(const std::string &Section) const;
224 std::string getSectionStart(const std::string &Section) const;
225 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000226 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000227 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000228 Function *SanCovTraceCmpFunction[4];
Alexander Potapenko52410812017-08-10 15:00:13 +0000229 Function *SanCovTraceConstCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000230 Function *SanCovTraceDivFunction[2];
231 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000232 Function *SanCovTraceSwitchFunction;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000233 GlobalVariable *SanCovLowestStack;
Kostya Serebryany73762942014-12-16 21:24:15 +0000234 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000235 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
Alexander Potapenko52410812017-08-10 15:00:13 +0000236 *Int16Ty, *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000237 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000238 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000240 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000241
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000242 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000243 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000244 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000245
Alexey Samsonov3514f272015-05-07 01:00:31 +0000246 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000247};
248
Mike Aizatsky759aca02016-03-18 23:29:29 +0000249} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000250
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000251std::pair<GlobalVariable *, GlobalVariable *>
252SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
253 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000254 GlobalVariable *SecStart =
255 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
256 getSectionStart(Section));
257 SecStart->setVisibility(GlobalValue::HiddenVisibility);
258 GlobalVariable *SecEnd =
259 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
260 nullptr, getSectionEnd(Section));
261 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
262
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000263 return std::make_pair(SecStart, SecEnd);
264}
265
266
267Function *SanitizerCoverageModule::CreateInitCallsForSections(
268 Module &M, const char *InitFunctionName, Type *Ty,
269 const char *Section) {
270 IRBuilder<> IRB(M.getContext());
271 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
272 auto SecStart = SecStartEnd.first;
273 auto SecEnd = SecStartEnd.second;
274 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000275 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
276 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
277 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
278
279 if (TargetTriple.supportsCOMDAT()) {
280 // Use comdat to dedup CtorFunc.
281 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
282 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
283 } else {
284 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
285 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000286 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000287}
288
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000289bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000290 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
291 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000292 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000293 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000294 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000295 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000296 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000297 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000298 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000299 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000300 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000301 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000302 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000303 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000304 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000305 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000306 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000307 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000308 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000309 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000310
Mike Aizatsky759aca02016-03-18 23:29:29 +0000311 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000312 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000313 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000314 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000315 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000316 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
317 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000318 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000319 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
320 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000321 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000322 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000323 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000324 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000325
Alexander Potapenko52410812017-08-10 15:00:13 +0000326 SanCovTraceConstCmpFunction[0] =
327 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
328 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
329 SanCovTraceConstCmpFunction[1] =
330 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
331 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
332 SanCovTraceConstCmpFunction[2] =
333 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
334 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
335 SanCovTraceConstCmpFunction[3] =
336 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
337 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
338
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000339 SanCovTraceDivFunction[0] =
340 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000341 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000342 SanCovTraceDivFunction[1] =
343 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000344 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000345 SanCovTraceGepFunction =
346 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000347 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000348 SanCovTraceSwitchFunction =
349 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000350 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000351
352 Constant *SanCovLowestStackConstant =
353 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000354 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
355 SanCovLowestStack->setThreadLocalMode(
356 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
357 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
358 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000359
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000360 // Make sure smaller parameters are zero-extended to i64 as required by the
361 // x86_64 ABI.
362 if (TargetTriple.getArch() == Triple::x86_64) {
363 for (int i = 0; i < 3; i++) {
364 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
365 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000366 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
367 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000368 }
369 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
370 }
371
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000372
Kostya Serebryany73762942014-12-16 21:24:15 +0000373 // We insert an empty inline asm after cov callbacks to avoid callback merge.
374 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
375 StringRef(""), StringRef(""),
376 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000377
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000378 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000379 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000380 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000381 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000382
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000383 for (auto &F : M)
384 runOnFunction(F);
385
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000386 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000387
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000388 if (FunctionGuardArray)
389 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
390 SanCovGuardsSectionName);
391 if (Function8bitCounterArray)
392 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
393 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000394 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000395 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000396 Function *InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000397 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000398 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
399 IRBCtor.CreateCall(InitFunction,
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000400 {IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy),
401 IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000402 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000403 return true;
404}
405
Mike Aizatsky9987f432016-03-23 23:15:03 +0000406// True if block has successors and it dominates all of them.
407static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
408 if (succ_begin(BB) == succ_end(BB))
409 return false;
410
411 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
412 if (!DT->dominates(BB, SUCC))
413 return false;
414 }
415
416 return true;
417}
418
George Karpenkov018472c2017-05-24 00:29:12 +0000419// True if block has predecessors and it postdominates all of them.
420static bool isFullPostDominator(const BasicBlock *BB,
421 const PostDominatorTree *PDT) {
422 if (pred_begin(BB) == pred_end(BB))
423 return false;
424
425 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
426 if (!PDT->dominates(BB, PRED))
427 return false;
428 }
429
430 return true;
431}
432
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000433static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
434 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000435 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000436 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000437 // Don't insert coverage for unreachable blocks: we will never call
438 // __sanitizer_cov() for them, so counting them in
439 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
440 // percentage. Also, unreachable instructions frequently have no debug
441 // locations.
442 if (isa<UnreachableInst>(BB->getTerminator()))
443 return false;
444
Reid Kleckner392f0622017-03-23 23:30:41 +0000445 // Don't insert coverage into blocks without a valid insertion point
446 // (catchswitch blocks).
447 if (BB->getFirstInsertionPt() == BB->end())
448 return false;
449
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000450 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000451 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000452
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000453 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
454 &F.getEntryBlock() != BB)
455 return false;
456
George Karpenkova1c53272017-05-25 01:41:46 +0000457 // Do not instrument full dominators, or full post-dominators with multiple
458 // predecessors.
459 return !isFullDominator(BB, DT)
460 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000461}
462
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000463bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000464 if (F.empty())
465 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000466 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000467 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000468 if (F.getName().startswith("__sanitizer_"))
469 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000470 // Don't touch available_externally functions, their actual body is elewhere.
471 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
472 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000473 // Don't instrument MSVC CRT configuration helpers. They may run before normal
474 // initialization.
475 if (F.getName() == "__local_stdio_printf_options" ||
476 F.getName() == "__local_stdio_scanf_options")
477 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000478 // Don't instrument functions using SEH for now. Splitting basic blocks like
479 // we do for coverage breaks WinEHPrepare.
480 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
481 if (F.hasPersonalityFn() &&
482 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
483 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000484 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000485 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000486 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000487 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000488 SmallVector<Instruction *, 8> CmpTraceTargets;
489 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000490 SmallVector<BinaryOperator *, 8> DivTraceTargets;
491 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000492
Mike Aizatsky602f7922016-03-21 23:08:16 +0000493 const DominatorTree *DT =
494 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000495 const PostDominatorTree *PDT =
496 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Matt Morehousef42bd312017-08-25 21:18:29 +0000497 bool IsLeafFunc = true;
Mike Aizatsky602f7922016-03-21 23:08:16 +0000498
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000499 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000500 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000501 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000502 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000503 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000504 CallSite CS(&Inst);
505 if (CS && !CS.getCalledFunction())
506 IndirCalls.push_back(&Inst);
507 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000508 if (Options.TraceCmp) {
509 if (isa<ICmpInst>(&Inst))
510 CmpTraceTargets.push_back(&Inst);
511 if (isa<SwitchInst>(&Inst))
512 SwitchTraceTargets.push_back(&Inst);
513 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000514 if (Options.TraceDiv)
515 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
516 if (BO->getOpcode() == Instruction::SDiv ||
517 BO->getOpcode() == Instruction::UDiv)
518 DivTraceTargets.push_back(BO);
519 if (Options.TraceGep)
520 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
521 GepTraceTargets.push_back(GEP);
Matt Morehousef42bd312017-08-25 21:18:29 +0000522 if (Options.StackDepth)
523 if (isa<InvokeInst>(Inst) ||
524 (isa<CallInst>(Inst) && !isa<IntrinsicInst>(Inst)))
525 IsLeafFunc = false;
526 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000527 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000528
Matt Morehousef42bd312017-08-25 21:18:29 +0000529 InjectCoverage(F, BlocksToInstrument, IsLeafFunc);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000530 InjectCoverageForIndirectCalls(F, IndirCalls);
531 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000532 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000533 InjectTraceForDiv(F, DivTraceTargets);
534 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000535 return true;
536}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000537
538GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
539 size_t NumElements, Function &F, Type *Ty, const char *Section) {
540 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
541 auto Array = new GlobalVariable(
542 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
543 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000544 if (auto Comdat = F.getComdat())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000545 Array->setComdat(Comdat);
546 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000547 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
548 : Ty->getPrimitiveSizeInBits() / 8);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000549 return Array;
550}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000551
552void SanitizerCoverageModule::CreatePCArray(Function &F,
553 ArrayRef<BasicBlock *> AllBlocks) {
554 size_t N = AllBlocks.size();
555 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000556 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000557 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000558 for (size_t i = 0; i < N; i++) {
559 if (&F.getEntryBlock() == AllBlocks[i]) {
560 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
561 PCs.push_back((Constant *)IRB.CreateIntToPtr(
562 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
563 } else {
564 PCs.push_back((Constant *)IRB.CreatePointerCast(
565 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
566 PCs.push_back((Constant *)IRB.CreateIntToPtr(
567 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
568 }
569 }
570 FunctionPCsArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
571 SanCovPCsSectionName);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000572 FunctionPCsArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000573 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000574 FunctionPCsArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000575
576 // We don't reference the PCs array in any of our runtime functions, so we
577 // need to prevent it from being dead stripped.
578 appendToUsed(*F.getParent(), {FunctionPCsArray});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000579}
580
581void SanitizerCoverageModule::CreateFunctionLocalArrays(
582 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000583 if (Options.TracePCGuard)
584 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000585 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000586 if (Options.Inline8bitCounters)
587 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000588 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000589 if (Options.PCTable)
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000590 CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000591}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000592
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000593bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehousef42bd312017-08-25 21:18:29 +0000594 ArrayRef<BasicBlock *> AllBlocks,
595 bool IsLeafFunc) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000596 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000597 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000598 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehousef42bd312017-08-25 21:18:29 +0000599 InjectCoverageAtBlock(F, *AllBlocks[i], i, IsLeafFunc);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000600 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000601}
602
603// On every indirect call we call a run-time function
604// __sanitizer_cov_indir_call* with two parameters:
605// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000606// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000607// The cache is used to speed up recording the caller-callee pairs.
608// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000609// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000610void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
611 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000612 if (IndirCalls.empty())
613 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000614 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000615 for (auto I : IndirCalls) {
616 IRBuilder<> IRB(I);
617 CallSite CS(I);
618 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000619 if (isa<InlineAsm>(Callee))
620 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000621 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000622 }
623}
624
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000625// For every switch statement we insert a call:
626// __sanitizer_cov_trace_switch(CondValue,
627// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
628
629void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000630 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000631 for (auto I : SwitchTraceTargets) {
632 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
633 IRBuilder<> IRB(I);
634 SmallVector<Constant *, 16> Initializers;
635 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000636 if (Cond->getType()->getScalarSizeInBits() >
637 Int64Ty->getScalarSizeInBits())
638 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000639 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
640 Initializers.push_back(
641 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
642 if (Cond->getType()->getScalarSizeInBits() <
643 Int64Ty->getScalarSizeInBits())
644 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000645 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000646 Constant *C = It.getCaseValue();
647 if (C->getType()->getScalarSizeInBits() <
648 Int64Ty->getScalarSizeInBits())
649 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
650 Initializers.push_back(C);
651 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000652 std::sort(Initializers.begin() + 2, Initializers.end(),
653 [](const Constant *A, const Constant *B) {
654 return cast<ConstantInt>(A)->getLimitedValue() <
655 cast<ConstantInt>(B)->getLimitedValue();
656 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000657 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
658 GlobalVariable *GV = new GlobalVariable(
659 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
660 ConstantArray::get(ArrayOfInt64Ty, Initializers),
661 "__sancov_gen_cov_switch_values");
662 IRB.CreateCall(SanCovTraceSwitchFunction,
663 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
664 }
665 }
666}
667
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000668void SanitizerCoverageModule::InjectTraceForDiv(
669 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
670 for (auto BO : DivTraceTargets) {
671 IRBuilder<> IRB(BO);
672 Value *A1 = BO->getOperand(1);
673 if (isa<ConstantInt>(A1)) continue;
674 if (!A1->getType()->isIntegerTy())
675 continue;
676 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
677 int CallbackIdx = TypeSize == 32 ? 0 :
678 TypeSize == 64 ? 1 : -1;
679 if (CallbackIdx < 0) continue;
680 auto Ty = Type::getIntNTy(*C, TypeSize);
681 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
682 {IRB.CreateIntCast(A1, Ty, true)});
683 }
684}
685
686void SanitizerCoverageModule::InjectTraceForGep(
687 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
688 for (auto GEP : GepTraceTargets) {
689 IRBuilder<> IRB(GEP);
690 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000691 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000692 IRB.CreateCall(SanCovTraceGepFunction,
693 {IRB.CreateIntCast(*I, IntptrTy, true)});
694 }
695}
696
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000697void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000698 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000699 for (auto I : CmpTraceTargets) {
700 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
701 IRBuilder<> IRB(ICMP);
702 Value *A0 = ICMP->getOperand(0);
703 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000704 if (!A0->getType()->isIntegerTy())
705 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000706 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000707 int CallbackIdx = TypeSize == 8 ? 0 :
708 TypeSize == 16 ? 1 :
709 TypeSize == 32 ? 2 :
710 TypeSize == 64 ? 3 : -1;
711 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000712 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000713 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
714 bool FirstIsConst = isa<ConstantInt>(A0);
715 bool SecondIsConst = isa<ConstantInt>(A1);
716 // If both are const, then we don't need such a comparison.
717 if (FirstIsConst && SecondIsConst) continue;
718 // If only one is const, then make it the first callback argument.
719 if (FirstIsConst || SecondIsConst) {
720 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
721 if (SecondIsConst)
722 std::swap(A0, A1);
723 }
724
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000725 auto Ty = Type::getIntNTy(*C, TypeSize);
Alexander Potapenko52410812017-08-10 15:00:13 +0000726 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
727 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000728 }
729 }
730}
731
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000732void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehousef42bd312017-08-25 21:18:29 +0000733 size_t Idx,
734 bool IsLeafFunc) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000735 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000736 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000737 DebugLoc EntryLoc;
738 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000739 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000740 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000741 // Keep static allocas and llvm.localescape calls in the entry block. Even
742 // if we aren't splitting the block, it's nice for allocas to be before
743 // calls.
744 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000745 } else {
746 EntryLoc = IP->getDebugLoc();
747 }
748
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000749 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000750 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000751 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000752 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
753 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000754 }
755 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000756 auto GuardPtr = IRB.CreateIntToPtr(
757 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
758 ConstantInt::get(IntptrTy, Idx * 4)),
759 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000760 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
761 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000762 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000763 if (Options.Inline8bitCounters) {
764 auto CounterPtr = IRB.CreateGEP(
765 Function8bitCounterArray,
766 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
767 auto Load = IRB.CreateLoad(CounterPtr);
768 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
769 auto Store = IRB.CreateStore(Inc, CounterPtr);
770 SetNoSanitizeMetadata(Load);
771 SetNoSanitizeMetadata(Store);
772 }
Matt Morehousef42bd312017-08-25 21:18:29 +0000773 if (Options.StackDepth && IsEntryBB && !IsLeafFunc) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000774 // Check stack depth. If it's the deepest so far, record it.
775 Function *GetFrameAddr =
776 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
777 auto FrameAddrPtr =
778 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
779 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000780 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000781 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
782 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
783 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehousef42bd312017-08-25 21:18:29 +0000784 auto Store = ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
785 SetNoSanitizeMetadata(LowestStack);
786 SetNoSanitizeMetadata(Store);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000787 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000788}
789
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000790std::string
791SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000792 if (TargetTriple.getObjectFormat() == Triple::COFF)
793 return ".SCOV$M";
794 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000795 return "__DATA,__" + Section;
796 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000797}
798
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000799std::string
800SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000801 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000802 return "\1section$start$__DATA$__" + Section;
803 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000804}
805
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000806std::string
807SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000808 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000809 return "\1section$end$__DATA$__" + Section;
810 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000811}
812
813
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000814char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000815INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000816 "SanitizerCoverage: TODO."
817 "ModulePass",
818 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000819INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000820INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000821INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000822 "SanitizerCoverage: TODO."
823 "ModulePass",
824 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000825ModulePass *llvm::createSanitizerCoverageModulePass(
826 const SanitizerCoverageOptions &Options) {
827 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000828}