blob: bac6b116e71427a82bd4599517ed86ba773fe7f2 [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 Morehouse5c7fc762017-08-18 18:43:30 +000028#include "llvm/IR/Intrinsics.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000029#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/MDBuilder.h"
31#include "llvm/IR/Module.h"
32#include "llvm/IR/Type.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000036#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000037#include "llvm/Transforms/Scalar.h"
38#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/ModuleUtils.h"
40
41using namespace llvm;
42
43#define DEBUG_TYPE "sancov"
44
Mike Aizatsky759aca02016-03-18 23:29:29 +000045static const char *const SanCovTracePCIndirName =
46 "__sanitizer_cov_trace_pc_indir";
Mike Aizatsky759aca02016-03-18 23:29:29 +000047static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000048static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
49static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
50static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
51static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Justin Bognerbe757de2017-08-28 23:38:12 +000052static const char *const SanCovTraceConstCmp1 =
Alexander Potapenko52410812017-08-10 15:00:13 +000053 "__sanitizer_cov_trace_const_cmp1";
Justin Bognerbe757de2017-08-28 23:38:12 +000054static const char *const SanCovTraceConstCmp2 =
Alexander Potapenko52410812017-08-10 15:00:13 +000055 "__sanitizer_cov_trace_const_cmp2";
Justin Bognerbe757de2017-08-28 23:38:12 +000056static const char *const SanCovTraceConstCmp4 =
Alexander Potapenko52410812017-08-10 15:00:13 +000057 "__sanitizer_cov_trace_const_cmp4";
Justin Bognerbe757de2017-08-28 23:38:12 +000058static const char *const SanCovTraceConstCmp8 =
Alexander Potapenko52410812017-08-10 15:00:13 +000059 "__sanitizer_cov_trace_const_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000060static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
61static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
62static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000063static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
64static const char *const SanCovModuleCtorName = "sancov.module_ctor";
65static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000066
Kostya Serebryanyda718e52016-09-14 01:39:35 +000067static const char *const SanCovTracePCGuardName =
68 "__sanitizer_cov_trace_pc_guard";
69static const char *const SanCovTracePCGuardInitName =
70 "__sanitizer_cov_trace_pc_guard_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000071static const char *const SanCov8bitCountersInitName =
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000072 "__sanitizer_cov_8bit_counters_init";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000073static const char *const SanCovPCsInitName = "__sanitizer_cov_pcs_init";
Kostya Serebryanyda718e52016-09-14 01:39:35 +000074
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000075static const char *const SanCovGuardsSectionName = "sancov_guards";
George Karpenkov406c1132017-06-14 23:40:25 +000076static const char *const SanCovCountersSectionName = "sancov_cntrs";
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000077static const char *const SanCovPCsSectionName = "sancov_pcs";
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +000078
Matt Morehouse5c7fc762017-08-18 18:43:30 +000079static const char *const SanCovLowestStackName = "__sancov_lowest_stack";
Matt Morehouse5c7fc762017-08-18 18:43:30 +000080
Mike Aizatsky759aca02016-03-18 23:29:29 +000081static cl::opt<int> ClCoverageLevel(
82 "sanitizer-coverage-level",
83 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +000084 "3: all blocks and critical edges"),
Mike Aizatsky759aca02016-03-18 23:29:29 +000085 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000086
Kostya Serebryany2c2fb882017-06-08 22:58:19 +000087static cl::opt<bool> ClTracePC("sanitizer-coverage-trace-pc",
88 cl::desc("Experimental pc tracing"), cl::Hidden,
89 cl::init(false));
Kostya Serebryanyd4590c72016-02-17 21:34:43 +000090
Kostya Serebryanyda718e52016-09-14 01:39:35 +000091static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
92 cl::desc("pc tracing with a guard"),
93 cl::Hidden, cl::init(false));
94
Kostya Serebryanyb75d0022017-07-27 23:36:49 +000095// If true, we create a global variable that contains PCs of all instrumented
96// BBs, put this global into a named section, and pass this section's bounds
97// to __sanitizer_cov_pcs_init.
98// This way the coverage instrumentation does not need to acquire the PCs
99// at run-time. Works with trace-pc-guard and inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000100static cl::opt<bool> ClCreatePCTable("sanitizer-coverage-pc-table",
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000101 cl::desc("create a static PC table"),
102 cl::Hidden, cl::init(false));
103
104static cl::opt<bool>
105 ClInline8bitCounters("sanitizer-coverage-inline-8bit-counters",
106 cl::desc("increments 8-bit counter for every edge"),
107 cl::Hidden, cl::init(false));
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000108
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000109static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000110 ClCMPTracing("sanitizer-coverage-trace-compares",
111 cl::desc("Tracing of CMP and similar instructions"),
112 cl::Hidden, cl::init(false));
113
114static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
115 cl::desc("Tracing of DIV instructions"),
116 cl::Hidden, cl::init(false));
117
118static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
119 cl::desc("Tracing of GEP instructions"),
120 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000121
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000122static cl::opt<bool>
123 ClPruneBlocks("sanitizer-coverage-prune-blocks",
124 cl::desc("Reduce the number of instrumented blocks"),
125 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000126
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000127static cl::opt<bool> ClStackDepth("sanitizer-coverage-stack-depth",
128 cl::desc("max stack depth tracing"),
129 cl::Hidden, cl::init(false));
130
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000131namespace {
132
Alexey Samsonov3514f272015-05-07 01:00:31 +0000133SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
134 SanitizerCoverageOptions Res;
135 switch (LegacyCoverageLevel) {
136 case 0:
137 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
138 break;
139 case 1:
140 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
141 break;
142 case 2:
143 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
144 break;
145 case 3:
146 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
147 break;
148 case 4:
149 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
150 Res.IndirectCalls = true;
151 break;
152 }
153 return Res;
154}
155
156SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
157 // Sets CoverageType and IndirectCalls.
158 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
159 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
160 Options.IndirectCalls |= CLOpts.IndirectCalls;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000161 Options.TraceCmp |= ClCMPTracing;
162 Options.TraceDiv |= ClDIVTracing;
163 Options.TraceGep |= ClGEPTracing;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000164 Options.TracePC |= ClTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000165 Options.TracePCGuard |= ClTracePCGuard;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000166 Options.Inline8bitCounters |= ClInline8bitCounters;
Kostya Serebryany063b6522017-07-28 00:09:29 +0000167 Options.PCTable |= ClCreatePCTable;
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000168 Options.NoPrune |= !ClPruneBlocks;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000169 Options.StackDepth |= ClStackDepth;
170 if (!Options.TracePCGuard && !Options.TracePC &&
171 !Options.Inline8bitCounters && !Options.StackDepth)
172 Options.TracePCGuard = true; // TracePCGuard is default.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000173 return Options;
174}
175
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000176class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000177public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000178 SanitizerCoverageModule(
179 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000180 : ModulePass(ID), Options(OverrideFromCL(Options)) {
181 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
182 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000183 bool runOnModule(Module &M) override;
184 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000185 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000186 StringRef getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000187
Chandler Carruth30061152016-03-18 22:43:42 +0000188 void getAnalysisUsage(AnalysisUsage &AU) const override {
189 AU.addRequired<DominatorTreeWrapperPass>();
George Karpenkov018472c2017-05-24 00:29:12 +0000190 AU.addRequired<PostDominatorTreeWrapperPass>();
Chandler Carruth30061152016-03-18 22:43:42 +0000191 }
192
193private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000194 void InjectCoverageForIndirectCalls(Function &F,
195 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000196 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000197 void InjectTraceForDiv(Function &F,
198 ArrayRef<BinaryOperator *> DivTraceTargets);
199 void InjectTraceForGep(Function &F,
200 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000201 void InjectTraceForSwitch(Function &F,
202 ArrayRef<Instruction *> SwitchTraceTargets);
Matt Morehouse6ec75952017-08-25 22:01:21 +0000203 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000204 GlobalVariable *CreateFunctionLocalArrayInSection(size_t NumElements,
205 Function &F, Type *Ty,
206 const char *Section);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000207 void CreateFunctionLocalArrays(Function &F, ArrayRef<BasicBlock *> AllBlocks);
208 void CreatePCArray(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Matt Morehouse6ec75952017-08-25 22:01:21 +0000209 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, size_t Idx);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000210 Function *CreateInitCallsForSections(Module &M, const char *InitFunctionName,
211 Type *Ty, const char *Section);
212 std::pair<GlobalVariable *, GlobalVariable *>
213 CreateSecStartEnd(Module &M, const char *Section, Type *Ty);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000214
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000215 void SetNoSanitizeMetadata(Instruction *I) {
216 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
217 MDNode::get(*C, None));
218 }
219
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000220 std::string getSectionName(const std::string &Section) const;
221 std::string getSectionStart(const std::string &Section) const;
222 std::string getSectionEnd(const std::string &Section) const;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000223 Function *SanCovTracePCIndir;
Kostya Serebryanybe87d482017-04-19 21:48:09 +0000224 Function *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000225 Function *SanCovTraceCmpFunction[4];
Alexander Potapenko52410812017-08-10 15:00:13 +0000226 Function *SanCovTraceConstCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000227 Function *SanCovTraceDivFunction[2];
228 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000229 Function *SanCovTraceSwitchFunction;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000230 GlobalVariable *SanCovLowestStack;
Kostya Serebryany73762942014-12-16 21:24:15 +0000231 InlineAsm *EmptyAsm;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000232 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy, *Int32Ty, *Int32PtrTy,
Alexander Potapenko52410812017-08-10 15:00:13 +0000233 *Int16Ty, *Int8Ty, *Int8PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000234 Module *CurModule;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000235 Triple TargetTriple;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000236 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000237 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000238
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000239 GlobalVariable *FunctionGuardArray; // for trace-pc-guard.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000240 GlobalVariable *Function8bitCounterArray; // for inline-8bit-counters.
Kostya Serebryany063b6522017-07-28 00:09:29 +0000241 GlobalVariable *FunctionPCsArray; // for pc-table.
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000242
Alexey Samsonov3514f272015-05-07 01:00:31 +0000243 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000244};
245
Mike Aizatsky759aca02016-03-18 23:29:29 +0000246} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000247
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000248std::pair<GlobalVariable *, GlobalVariable *>
249SanitizerCoverageModule::CreateSecStartEnd(Module &M, const char *Section,
250 Type *Ty) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000251 GlobalVariable *SecStart =
252 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, nullptr,
253 getSectionStart(Section));
254 SecStart->setVisibility(GlobalValue::HiddenVisibility);
255 GlobalVariable *SecEnd =
256 new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
257 nullptr, getSectionEnd(Section));
258 SecEnd->setVisibility(GlobalValue::HiddenVisibility);
259
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000260 return std::make_pair(SecStart, SecEnd);
261}
262
263
264Function *SanitizerCoverageModule::CreateInitCallsForSections(
265 Module &M, const char *InitFunctionName, Type *Ty,
266 const char *Section) {
267 IRBuilder<> IRB(M.getContext());
268 auto SecStartEnd = CreateSecStartEnd(M, Section, Ty);
269 auto SecStart = SecStartEnd.first;
270 auto SecEnd = SecStartEnd.second;
271 Function *CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000272 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
273 M, SanCovModuleCtorName, InitFunctionName, {Ty, Ty},
274 {IRB.CreatePointerCast(SecStart, Ty), IRB.CreatePointerCast(SecEnd, Ty)});
275
276 if (TargetTriple.supportsCOMDAT()) {
277 // Use comdat to dedup CtorFunc.
278 CtorFunc->setComdat(M.getOrInsertComdat(SanCovModuleCtorName));
279 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority, CtorFunc);
280 } else {
281 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
282 }
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000283 return CtorFunc;
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000284}
285
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000286bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000287 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
288 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000289 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000290 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000291 CurModule = &M;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000292 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000293 FunctionGuardArray = nullptr;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000294 Function8bitCounterArray = nullptr;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000295 FunctionPCsArray = nullptr;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000296 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000297 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000298 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000299 IRBuilder<> IRB(*C);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000300 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000301 Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000302 Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000303 Int64Ty = IRB.getInt64Ty();
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000304 Int32Ty = IRB.getInt32Ty();
Alexander Potapenko52410812017-08-10 15:00:13 +0000305 Int16Ty = IRB.getInt16Ty();
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000306 Int8Ty = IRB.getInt8Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000307
Mike Aizatsky759aca02016-03-18 23:29:29 +0000308 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000309 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000310 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000311 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000312 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000313 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
314 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000315 IRB.getInt16Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000316 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
317 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000318 IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000319 SanCovTraceCmpFunction[3] =
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000320 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000321 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000322
Alexander Potapenko52410812017-08-10 15:00:13 +0000323 SanCovTraceConstCmpFunction[0] =
324 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
325 SanCovTraceConstCmp1, VoidTy, Int8Ty, Int8Ty));
326 SanCovTraceConstCmpFunction[1] =
327 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
328 SanCovTraceConstCmp2, VoidTy, Int16Ty, Int16Ty));
329 SanCovTraceConstCmpFunction[2] =
330 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
331 SanCovTraceConstCmp4, VoidTy, Int32Ty, Int32Ty));
332 SanCovTraceConstCmpFunction[3] =
333 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
334 SanCovTraceConstCmp8, VoidTy, Int64Ty, Int64Ty));
335
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000336 SanCovTraceDivFunction[0] =
337 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000338 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty()));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000339 SanCovTraceDivFunction[1] =
340 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000341 SanCovTraceDiv8, VoidTy, Int64Ty));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000342 SanCovTraceGepFunction =
343 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000344 SanCovTraceGep, VoidTy, IntptrTy));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000345 SanCovTraceSwitchFunction =
346 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000347 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000348
349 Constant *SanCovLowestStackConstant =
350 M.getOrInsertGlobal(SanCovLowestStackName, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000351 SanCovLowestStack = cast<GlobalVariable>(SanCovLowestStackConstant);
352 SanCovLowestStack->setThreadLocalMode(
353 GlobalValue::ThreadLocalMode::InitialExecTLSModel);
354 if (Options.StackDepth && !SanCovLowestStack->isDeclaration())
355 SanCovLowestStack->setInitializer(Constant::getAllOnesValue(IntptrTy));
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000356
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000357 // Make sure smaller parameters are zero-extended to i64 as required by the
358 // x86_64 ABI.
359 if (TargetTriple.getArch() == Triple::x86_64) {
360 for (int i = 0; i < 3; i++) {
361 SanCovTraceCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
362 SanCovTraceCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko52410812017-08-10 15:00:13 +0000363 SanCovTraceConstCmpFunction[i]->addParamAttr(0, Attribute::ZExt);
364 SanCovTraceConstCmpFunction[i]->addParamAttr(1, Attribute::ZExt);
Alexander Potapenko9385aaa2017-07-18 11:47:56 +0000365 }
366 SanCovTraceDivFunction[0]->addParamAttr(0, Attribute::ZExt);
367 }
368
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000369
Kostya Serebryany73762942014-12-16 21:24:15 +0000370 // We insert an empty inline asm after cov callbacks to avoid callback merge.
371 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
372 StringRef(""), StringRef(""),
373 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000374
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000375 SanCovTracePC = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000376 M.getOrInsertFunction(SanCovTracePCName, VoidTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000377 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000378 SanCovTracePCGuardName, VoidTy, Int32PtrTy));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000379
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000380 for (auto &F : M)
381 runOnFunction(F);
382
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000383 Function *Ctor = nullptr;
Justin Bogner41e632b2017-02-01 02:38:39 +0000384
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000385 if (FunctionGuardArray)
386 Ctor = CreateInitCallsForSections(M, SanCovTracePCGuardInitName, Int32PtrTy,
387 SanCovGuardsSectionName);
388 if (Function8bitCounterArray)
389 Ctor = CreateInitCallsForSections(M, SanCov8bitCountersInitName, Int8PtrTy,
390 SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000391 if (Ctor && Options.PCTable) {
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000392 auto SecStartEnd = CreateSecStartEnd(M, SanCovPCsSectionName, IntptrPtrTy);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000393 Function *InitFunction = declareSanitizerInitFunction(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000394 M, SanCovPCsInitName, {IntptrPtrTy, IntptrPtrTy});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000395 IRBuilder<> IRBCtor(Ctor->getEntryBlock().getTerminator());
396 IRBCtor.CreateCall(InitFunction,
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000397 {IRB.CreatePointerCast(SecStartEnd.first, IntptrPtrTy),
398 IRB.CreatePointerCast(SecStartEnd.second, IntptrPtrTy)});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000399 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000400 return true;
401}
402
Mike Aizatsky9987f432016-03-23 23:15:03 +0000403// True if block has successors and it dominates all of them.
404static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
405 if (succ_begin(BB) == succ_end(BB))
406 return false;
407
408 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
409 if (!DT->dominates(BB, SUCC))
410 return false;
411 }
412
413 return true;
414}
415
George Karpenkov018472c2017-05-24 00:29:12 +0000416// True if block has predecessors and it postdominates all of them.
417static bool isFullPostDominator(const BasicBlock *BB,
418 const PostDominatorTree *PDT) {
419 if (pred_begin(BB) == pred_end(BB))
420 return false;
421
422 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
423 if (!PDT->dominates(BB, PRED))
424 return false;
425 }
426
427 return true;
428}
429
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000430static bool shouldInstrumentBlock(const Function &F, const BasicBlock *BB,
431 const DominatorTree *DT,
George Karpenkov018472c2017-05-24 00:29:12 +0000432 const PostDominatorTree *PDT,
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000433 const SanitizerCoverageOptions &Options) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000434 // Don't insert coverage for unreachable blocks: we will never call
435 // __sanitizer_cov() for them, so counting them in
436 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
437 // percentage. Also, unreachable instructions frequently have no debug
438 // locations.
439 if (isa<UnreachableInst>(BB->getTerminator()))
440 return false;
441
Reid Kleckner392f0622017-03-23 23:30:41 +0000442 // Don't insert coverage into blocks without a valid insertion point
443 // (catchswitch blocks).
444 if (BB->getFirstInsertionPt() == BB->end())
445 return false;
446
Kostya Serebryany424bfed2017-05-05 23:14:40 +0000447 if (Options.NoPrune || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000448 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000449
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000450 if (Options.CoverageType == SanitizerCoverageOptions::SCK_Function &&
451 &F.getEntryBlock() != BB)
452 return false;
453
George Karpenkova1c53272017-05-25 01:41:46 +0000454 // Do not instrument full dominators, or full post-dominators with multiple
455 // predecessors.
456 return !isFullDominator(BB, DT)
457 && !(isFullPostDominator(BB, PDT) && !BB->getSinglePredecessor());
Mike Aizatsky5971f182016-02-26 01:17:22 +0000458}
459
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000460bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000461 if (F.empty())
462 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000463 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000464 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000465 if (F.getName().startswith("__sanitizer_"))
466 return false; // Don't instrument __sanitizer_* callbacks.
Kostya Serebryanybfc83fa2017-07-31 20:00:22 +0000467 // Don't touch available_externally functions, their actual body is elewhere.
468 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage)
469 return false;
Reid Klecknerec803542016-11-11 19:18:45 +0000470 // Don't instrument MSVC CRT configuration helpers. They may run before normal
471 // initialization.
472 if (F.getName() == "__local_stdio_printf_options" ||
473 F.getName() == "__local_stdio_scanf_options")
474 return false;
Reid Klecknerdf523372015-09-03 20:18:29 +0000475 // Don't instrument functions using SEH for now. Splitting basic blocks like
476 // we do for coverage breaks WinEHPrepare.
477 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
478 if (F.hasPersonalityFn() &&
479 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
480 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000481 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000482 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000483 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000484 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000485 SmallVector<Instruction *, 8> CmpTraceTargets;
486 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000487 SmallVector<BinaryOperator *, 8> DivTraceTargets;
488 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000489
Mike Aizatsky602f7922016-03-21 23:08:16 +0000490 const DominatorTree *DT =
491 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
George Karpenkov018472c2017-05-24 00:29:12 +0000492 const PostDominatorTree *PDT =
493 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
Mike Aizatsky602f7922016-03-21 23:08:16 +0000494
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000495 for (auto &BB : F) {
George Karpenkov018472c2017-05-24 00:29:12 +0000496 if (shouldInstrumentBlock(F, &BB, DT, PDT, Options))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000497 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000498 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000499 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000500 CallSite CS(&Inst);
501 if (CS && !CS.getCalledFunction())
502 IndirCalls.push_back(&Inst);
503 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000504 if (Options.TraceCmp) {
505 if (isa<ICmpInst>(&Inst))
506 CmpTraceTargets.push_back(&Inst);
507 if (isa<SwitchInst>(&Inst))
508 SwitchTraceTargets.push_back(&Inst);
509 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000510 if (Options.TraceDiv)
511 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
512 if (BO->getOpcode() == Instruction::SDiv ||
513 BO->getOpcode() == Instruction::UDiv)
514 DivTraceTargets.push_back(BO);
515 if (Options.TraceGep)
516 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
517 GepTraceTargets.push_back(GEP);
Matt Morehouse6ec75952017-08-25 22:01:21 +0000518 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000519 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000520
Matt Morehouse6ec75952017-08-25 22:01:21 +0000521 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000522 InjectCoverageForIndirectCalls(F, IndirCalls);
523 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000524 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000525 InjectTraceForDiv(F, DivTraceTargets);
526 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000527 return true;
528}
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000529
530GlobalVariable *SanitizerCoverageModule::CreateFunctionLocalArrayInSection(
531 size_t NumElements, Function &F, Type *Ty, const char *Section) {
532 ArrayType *ArrayTy = ArrayType::get(Ty, NumElements);
533 auto Array = new GlobalVariable(
534 *CurModule, ArrayTy, false, GlobalVariable::PrivateLinkage,
535 Constant::getNullValue(ArrayTy), "__sancov_gen_");
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000536 if (auto Comdat = F.getComdat())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000537 Array->setComdat(Comdat);
538 Array->setSection(getSectionName(Section));
Kostya Serebryanybb6f0792017-07-31 19:49:45 +0000539 Array->setAlignment(Ty->isPointerTy() ? DL->getPointerSize()
540 : Ty->getPrimitiveSizeInBits() / 8);
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000541 return Array;
542}
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000543
544void SanitizerCoverageModule::CreatePCArray(Function &F,
545 ArrayRef<BasicBlock *> AllBlocks) {
546 size_t N = AllBlocks.size();
547 assert(N);
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000548 SmallVector<Constant *, 32> PCs;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000549 IRBuilder<> IRB(&*F.getEntryBlock().getFirstInsertionPt());
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000550 for (size_t i = 0; i < N; i++) {
551 if (&F.getEntryBlock() == AllBlocks[i]) {
552 PCs.push_back((Constant *)IRB.CreatePointerCast(&F, IntptrPtrTy));
553 PCs.push_back((Constant *)IRB.CreateIntToPtr(
554 ConstantInt::get(IntptrTy, 1), IntptrPtrTy));
555 } else {
556 PCs.push_back((Constant *)IRB.CreatePointerCast(
557 BlockAddress::get(AllBlocks[i]), IntptrPtrTy));
558 PCs.push_back((Constant *)IRB.CreateIntToPtr(
559 ConstantInt::get(IntptrTy, 0), IntptrPtrTy));
560 }
561 }
562 FunctionPCsArray = CreateFunctionLocalArrayInSection(N * 2, F, IntptrPtrTy,
563 SanCovPCsSectionName);
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000564 FunctionPCsArray->setInitializer(
Kostya Serebryanyd3e4b7e2017-08-25 19:29:47 +0000565 ConstantArray::get(ArrayType::get(IntptrPtrTy, N * 2), PCs));
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000566 FunctionPCsArray->setConstant(true);
Justin Bognerad96ff12017-08-25 01:24:54 +0000567
568 // We don't reference the PCs array in any of our runtime functions, so we
569 // need to prevent it from being dead stripped.
570 appendToUsed(*F.getParent(), {FunctionPCsArray});
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000571}
572
573void SanitizerCoverageModule::CreateFunctionLocalArrays(
574 Function &F, ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000575 if (Options.TracePCGuard)
576 FunctionGuardArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000577 AllBlocks.size(), F, Int32Ty, SanCovGuardsSectionName);
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000578 if (Options.Inline8bitCounters)
579 Function8bitCounterArray = CreateFunctionLocalArrayInSection(
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000580 AllBlocks.size(), F, Int8Ty, SanCovCountersSectionName);
Kostya Serebryany063b6522017-07-28 00:09:29 +0000581 if (Options.PCTable)
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000582 CreatePCArray(F, AllBlocks);
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000583}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000584
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000585bool SanitizerCoverageModule::InjectCoverage(Function &F,
Matt Morehouse6ec75952017-08-25 22:01:21 +0000586 ArrayRef<BasicBlock *> AllBlocks) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000587 if (AllBlocks.empty()) return false;
Kostya Serebryanyb75d0022017-07-27 23:36:49 +0000588 CreateFunctionLocalArrays(F, AllBlocks);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000589 for (size_t i = 0, N = AllBlocks.size(); i < N; i++)
Matt Morehouse6ec75952017-08-25 22:01:21 +0000590 InjectCoverageAtBlock(F, *AllBlocks[i], i);
Kostya Serebryanyc485ca02017-07-25 02:07:38 +0000591 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000592}
593
594// On every indirect call we call a run-time function
595// __sanitizer_cov_indir_call* with two parameters:
596// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000597// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000598// The cache is used to speed up recording the caller-callee pairs.
599// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000600// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000601void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
602 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000603 if (IndirCalls.empty())
604 return;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000605 assert(Options.TracePC || Options.TracePCGuard || Options.Inline8bitCounters);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000606 for (auto I : IndirCalls) {
607 IRBuilder<> IRB(I);
608 CallSite CS(I);
609 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000610 if (isa<InlineAsm>(Callee))
611 continue;
Kostya Serebryanyc5d3d492017-04-19 22:42:11 +0000612 IRB.CreateCall(SanCovTracePCIndir, IRB.CreatePointerCast(Callee, IntptrTy));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000613 }
614}
615
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000616// For every switch statement we insert a call:
617// __sanitizer_cov_trace_switch(CondValue,
618// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
619
620void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000621 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000622 for (auto I : SwitchTraceTargets) {
623 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
624 IRBuilder<> IRB(I);
625 SmallVector<Constant *, 16> Initializers;
626 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000627 if (Cond->getType()->getScalarSizeInBits() >
628 Int64Ty->getScalarSizeInBits())
629 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000630 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
631 Initializers.push_back(
632 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
633 if (Cond->getType()->getScalarSizeInBits() <
634 Int64Ty->getScalarSizeInBits())
635 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000636 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000637 Constant *C = It.getCaseValue();
638 if (C->getType()->getScalarSizeInBits() <
639 Int64Ty->getScalarSizeInBits())
640 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
641 Initializers.push_back(C);
642 }
Kostya Serebryanyf24e52c2016-12-27 21:20:06 +0000643 std::sort(Initializers.begin() + 2, Initializers.end(),
644 [](const Constant *A, const Constant *B) {
645 return cast<ConstantInt>(A)->getLimitedValue() <
646 cast<ConstantInt>(B)->getLimitedValue();
647 });
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000648 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
649 GlobalVariable *GV = new GlobalVariable(
650 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
651 ConstantArray::get(ArrayOfInt64Ty, Initializers),
652 "__sancov_gen_cov_switch_values");
653 IRB.CreateCall(SanCovTraceSwitchFunction,
654 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
655 }
656 }
657}
658
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000659void SanitizerCoverageModule::InjectTraceForDiv(
660 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
661 for (auto BO : DivTraceTargets) {
662 IRBuilder<> IRB(BO);
663 Value *A1 = BO->getOperand(1);
664 if (isa<ConstantInt>(A1)) continue;
665 if (!A1->getType()->isIntegerTy())
666 continue;
667 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
668 int CallbackIdx = TypeSize == 32 ? 0 :
669 TypeSize == 64 ? 1 : -1;
670 if (CallbackIdx < 0) continue;
671 auto Ty = Type::getIntNTy(*C, TypeSize);
672 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
673 {IRB.CreateIntCast(A1, Ty, true)});
674 }
675}
676
677void SanitizerCoverageModule::InjectTraceForGep(
678 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
679 for (auto GEP : GepTraceTargets) {
680 IRBuilder<> IRB(GEP);
681 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
Kostya Serebryany45c14472016-09-27 01:55:08 +0000682 if (!isa<ConstantInt>(*I) && (*I)->getType()->isIntegerTy())
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000683 IRB.CreateCall(SanCovTraceGepFunction,
684 {IRB.CreateIntCast(*I, IntptrTy, true)});
685 }
686}
687
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000688void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000689 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000690 for (auto I : CmpTraceTargets) {
691 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
692 IRBuilder<> IRB(ICMP);
693 Value *A0 = ICMP->getOperand(0);
694 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000695 if (!A0->getType()->isIntegerTy())
696 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000697 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000698 int CallbackIdx = TypeSize == 8 ? 0 :
699 TypeSize == 16 ? 1 :
700 TypeSize == 32 ? 2 :
701 TypeSize == 64 ? 3 : -1;
702 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000703 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Alexander Potapenko52410812017-08-10 15:00:13 +0000704 auto CallbackFunc = SanCovTraceCmpFunction[CallbackIdx];
705 bool FirstIsConst = isa<ConstantInt>(A0);
706 bool SecondIsConst = isa<ConstantInt>(A1);
707 // If both are const, then we don't need such a comparison.
708 if (FirstIsConst && SecondIsConst) continue;
709 // If only one is const, then make it the first callback argument.
710 if (FirstIsConst || SecondIsConst) {
711 CallbackFunc = SanCovTraceConstCmpFunction[CallbackIdx];
Justin Bognerbe757de2017-08-28 23:38:12 +0000712 if (SecondIsConst)
Alexander Potapenko52410812017-08-10 15:00:13 +0000713 std::swap(A0, A1);
714 }
715
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000716 auto Ty = Type::getIntNTy(*C, TypeSize);
Justin Bognerbe757de2017-08-28 23:38:12 +0000717 IRB.CreateCall(CallbackFunc, {IRB.CreateIntCast(A0, Ty, true),
Alexander Potapenko52410812017-08-10 15:00:13 +0000718 IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000719 }
720 }
721}
722
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000723void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
Matt Morehouse6ec75952017-08-25 22:01:21 +0000724 size_t Idx) {
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000725 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000726 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000727 DebugLoc EntryLoc;
728 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000729 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000730 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000731 // Keep static allocas and llvm.localescape calls in the entry block. Even
732 // if we aren't splitting the block, it's nice for allocas to be before
733 // calls.
734 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000735 } else {
736 EntryLoc = IP->getDebugLoc();
737 }
738
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000739 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000740 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000741 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000742 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
743 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000744 }
745 if (Options.TracePCGuard) {
Kostya Serebryanya9b0dd02016-09-29 17:43:24 +0000746 auto GuardPtr = IRB.CreateIntToPtr(
747 IRB.CreateAdd(IRB.CreatePointerCast(FunctionGuardArray, IntptrTy),
748 ConstantInt::get(IntptrTy, Idx * 4)),
749 Int32PtrTy);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000750 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
751 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000752 }
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000753 if (Options.Inline8bitCounters) {
754 auto CounterPtr = IRB.CreateGEP(
755 Function8bitCounterArray,
756 {ConstantInt::get(IntptrTy, 0), ConstantInt::get(IntptrTy, Idx)});
757 auto Load = IRB.CreateLoad(CounterPtr);
758 auto Inc = IRB.CreateAdd(Load, ConstantInt::get(Int8Ty, 1));
759 auto Store = IRB.CreateStore(Inc, CounterPtr);
760 SetNoSanitizeMetadata(Load);
761 SetNoSanitizeMetadata(Store);
762 }
Matt Morehouse6ec75952017-08-25 22:01:21 +0000763 if (Options.StackDepth && IsEntryBB) {
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000764 // Check stack depth. If it's the deepest so far, record it.
765 Function *GetFrameAddr =
766 Intrinsic::getDeclaration(F.getParent(), Intrinsic::frameaddress);
767 auto FrameAddrPtr =
768 IRB.CreateCall(GetFrameAddr, {Constant::getNullValue(Int32Ty)});
769 auto FrameAddrInt = IRB.CreatePtrToInt(FrameAddrPtr, IntptrTy);
Matt Morehouseb1fa8252017-08-22 21:28:29 +0000770 auto LowestStack = IRB.CreateLoad(SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000771 auto IsStackLower = IRB.CreateICmpULT(FrameAddrInt, LowestStack);
772 auto ThenTerm = SplitBlockAndInsertIfThen(IsStackLower, &*IP, false);
773 IRBuilder<> ThenIRB(ThenTerm);
Matt Morehouse6ec75952017-08-25 22:01:21 +0000774 ThenIRB.CreateStore(FrameAddrInt, SanCovLowestStack);
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000775 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000776}
777
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000778std::string
779SanitizerCoverageModule::getSectionName(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000780 if (TargetTriple.getObjectFormat() == Triple::COFF)
781 return ".SCOV$M";
782 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000783 return "__DATA,__" + Section;
784 return "__" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000785}
786
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000787std::string
788SanitizerCoverageModule::getSectionStart(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000789 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000790 return "\1section$start$__DATA$__" + Section;
791 return "__start___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000792}
793
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000794std::string
795SanitizerCoverageModule::getSectionEnd(const std::string &Section) const {
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000796 if (TargetTriple.isOSBinFormatMachO())
Kostya Serebryanyaed6ba72017-06-02 23:13:44 +0000797 return "\1section$end$__DATA$__" + Section;
798 return "__stop___" + Section;
Marcos Pividoridb5a5652017-02-03 01:08:06 +0000799}
800
801
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000802char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000803INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000804 "SanitizerCoverage: TODO."
805 "ModulePass",
806 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000807INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
George Karpenkov018472c2017-05-24 00:29:12 +0000808INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
Mike Aizatsky90562842016-02-27 05:50:40 +0000809INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000810 "SanitizerCoverage: TODO."
811 "ModulePass",
812 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000813ModulePass *llvm::createSanitizerCoverageModulePass(
814 const SanitizerCoverageOptions &Options) {
815 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000816}