blob: a2755adc7fac201c6c8d6071d6faa2f04b5bdc2c [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//
10// Coverage instrumentation that works with AddressSanitizer
11// and potentially with other Sanitizers.
12//
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000013// We create a Guard variable with the same linkage
Alexey Samsonov3514f272015-05-07 01:00:31 +000014// as the function and inject this code into the entry block (SCK_Function)
15// or all blocks (SCK_BB):
Kostya Serebryany9fdeb372014-12-23 22:32:17 +000016// if (Guard < 0) {
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +000017// __sanitizer_cov(&Guard);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000018// }
19// The accesses to Guard are atomic. The rest of the logic is
20// in __sanitizer_cov (it's fine to call it more than once).
21//
Alexey Samsonov3514f272015-05-07 01:00:31 +000022// With SCK_Edge we also split critical edges this effectively
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000023// instrumenting all edges.
24//
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000025// This coverage implementation provides very limited data:
26// it only tells if a given function (block) was ever executed. No counters.
27// But for many use cases this is what we need and the added slowdown small.
28//
29//===----------------------------------------------------------------------===//
30
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000031#include "llvm/ADT/ArrayRef.h"
32#include "llvm/ADT/SmallVector.h"
David Majnemer70497c62015-12-02 23:06:39 +000033#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth30061152016-03-18 22:43:42 +000034#include "llvm/Analysis/PostDominators.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000035#include "llvm/IR/CFG.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000036#include "llvm/IR/CallSite.h"
37#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000038#include "llvm/IR/DebugInfo.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000039#include "llvm/IR/Dominators.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000040#include "llvm/IR/Function.h"
41#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000042#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000043#include "llvm/IR/LLVMContext.h"
44#include "llvm/IR/MDBuilder.h"
45#include "llvm/IR/Module.h"
46#include "llvm/IR/Type.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/raw_ostream.h"
Mike Aizatsky5971f182016-02-26 01:17:22 +000050#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000051#include "llvm/Transforms/Scalar.h"
52#include "llvm/Transforms/Utils/BasicBlockUtils.h"
53#include "llvm/Transforms/Utils/ModuleUtils.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "sancov"
58
Mike Aizatsky759aca02016-03-18 23:29:29 +000059static const char *const SanCovModuleInitName = "__sanitizer_cov_module_init";
60static const char *const SanCovName = "__sanitizer_cov";
61static const char *const SanCovWithCheckName = "__sanitizer_cov_with_check";
62static const char *const SanCovIndirCallName = "__sanitizer_cov_indir_call16";
63static const char *const SanCovTracePCIndirName =
64 "__sanitizer_cov_trace_pc_indir";
65static const char *const SanCovTraceEnterName =
66 "__sanitizer_cov_trace_func_enter";
67static const char *const SanCovTraceBBName =
68 "__sanitizer_cov_trace_basic_block";
69static const char *const SanCovTracePCName = "__sanitizer_cov_trace_pc";
Kostya Serebryany524c3f32016-08-18 01:25:28 +000070static const char *const SanCovTraceCmp1 = "__sanitizer_cov_trace_cmp1";
71static const char *const SanCovTraceCmp2 = "__sanitizer_cov_trace_cmp2";
72static const char *const SanCovTraceCmp4 = "__sanitizer_cov_trace_cmp4";
73static const char *const SanCovTraceCmp8 = "__sanitizer_cov_trace_cmp8";
Kostya Serebryany5ac427b2016-08-30 01:12:10 +000074static const char *const SanCovTraceDiv4 = "__sanitizer_cov_trace_div4";
75static const char *const SanCovTraceDiv8 = "__sanitizer_cov_trace_div8";
76static const char *const SanCovTraceGep = "__sanitizer_cov_trace_gep";
Mike Aizatsky759aca02016-03-18 23:29:29 +000077static const char *const SanCovTraceSwitchName = "__sanitizer_cov_trace_switch";
78static const char *const SanCovModuleCtorName = "sancov.module_ctor";
79static const uint64_t SanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000080
Kostya Serebryanyda718e52016-09-14 01:39:35 +000081static const char *const SanCovTracePCGuardSection = "__sancov_guards";
82static const char *const SanCovTracePCGuardName =
83 "__sanitizer_cov_trace_pc_guard";
84static const char *const SanCovTracePCGuardInitName =
85 "__sanitizer_cov_trace_pc_guard_init";
86
Mike Aizatsky759aca02016-03-18 23:29:29 +000087static cl::opt<int> ClCoverageLevel(
88 "sanitizer-coverage-level",
89 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
90 "3: all blocks and critical edges, "
91 "4: above plus indirect calls"),
92 cl::Hidden, cl::init(0));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000093
Kostya Serebryany77cc7292015-02-04 01:21:45 +000094static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000095 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000096 cl::desc("Use a callback with a guard check inside it if there are"
97 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000098 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000099
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000100static cl::opt<bool>
101 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
102 cl::desc("Experimental basic-block tracing: insert "
103 "callbacks at every basic block"),
104 cl::Hidden, cl::init(false));
105
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000106static cl::opt<bool> ClExperimentalTracePC("sanitizer-coverage-trace-pc",
107 cl::desc("Experimental pc tracing"),
108 cl::Hidden, cl::init(false));
109
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000110static cl::opt<bool> ClTracePCGuard("sanitizer-coverage-trace-pc-guard",
111 cl::desc("pc tracing with a guard"),
112 cl::Hidden, cl::init(false));
113
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000114static cl::opt<bool>
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000115 ClCMPTracing("sanitizer-coverage-trace-compares",
116 cl::desc("Tracing of CMP and similar instructions"),
117 cl::Hidden, cl::init(false));
118
119static cl::opt<bool> ClDIVTracing("sanitizer-coverage-trace-divs",
120 cl::desc("Tracing of DIV instructions"),
121 cl::Hidden, cl::init(false));
122
123static cl::opt<bool> ClGEPTracing("sanitizer-coverage-trace-geps",
124 cl::desc("Tracing of GEP instructions"),
125 cl::Hidden, cl::init(false));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000126
Mike Aizatsky70ea4532016-04-06 23:24:37 +0000127static cl::opt<bool>
128 ClPruneBlocks("sanitizer-coverage-prune-blocks",
129 cl::desc("Reduce the number of instrumented blocks"),
130 cl::Hidden, cl::init(true));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000131
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000132// Experimental 8-bit counters used as an additional search heuristic during
133// coverage-guided fuzzing.
134// The counters are not thread-friendly:
135// - contention on these counters may cause significant slowdown;
136// - the counter updates are racy and the results may be inaccurate.
137// They are also inaccurate due to 8-bit integer overflow.
138static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
139 cl::desc("Experimental 8-bit counters"),
140 cl::Hidden, cl::init(false));
141
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000142namespace {
143
Alexey Samsonov3514f272015-05-07 01:00:31 +0000144SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
145 SanitizerCoverageOptions Res;
146 switch (LegacyCoverageLevel) {
147 case 0:
148 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
149 break;
150 case 1:
151 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
152 break;
153 case 2:
154 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
155 break;
156 case 3:
157 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
158 break;
159 case 4:
160 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
161 Res.IndirectCalls = true;
162 break;
163 }
164 return Res;
165}
166
167SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
168 // Sets CoverageType and IndirectCalls.
169 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
170 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
171 Options.IndirectCalls |= CLOpts.IndirectCalls;
172 Options.TraceBB |= ClExperimentalTracing;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000173 Options.TraceCmp |= ClCMPTracing;
174 Options.TraceDiv |= ClDIVTracing;
175 Options.TraceGep |= ClGEPTracing;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000176 Options.Use8bitCounters |= ClUse8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000177 Options.TracePC |= ClExperimentalTracePC;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000178 Options.TracePCGuard |= ClTracePCGuard;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000179 return Options;
180}
181
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000182class SanitizerCoverageModule : public ModulePass {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000183public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000184 SanitizerCoverageModule(
185 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
Chandler Carruthe2b70212016-03-18 22:35:58 +0000186 : ModulePass(ID), Options(OverrideFromCL(Options)) {
187 initializeSanitizerCoverageModulePass(*PassRegistry::getPassRegistry());
188 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000189 bool runOnModule(Module &M) override;
190 bool runOnFunction(Function &F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000191 static char ID; // Pass identification, replacement for typeid
192 const char *getPassName() const override { return "SanitizerCoverageModule"; }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000193
Chandler Carruth30061152016-03-18 22:43:42 +0000194 void getAnalysisUsage(AnalysisUsage &AU) const override {
195 AU.addRequired<DominatorTreeWrapperPass>();
196 AU.addRequired<PostDominatorTreeWrapperPass>();
197 }
198
199private:
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000200 void InjectCoverageForIndirectCalls(Function &F,
201 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000202 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000203 void InjectTraceForDiv(Function &F,
204 ArrayRef<BinaryOperator *> DivTraceTargets);
205 void InjectTraceForGep(Function &F,
206 ArrayRef<GetElementPtrInst *> GepTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000207 void InjectTraceForSwitch(Function &F,
208 ArrayRef<Instruction *> SwitchTraceTargets);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000209 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000210 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000211 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000212 unsigned NumberOfInstrumentedBlocks() {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000213 return SanCovFunction->getNumUses() +
214 SanCovWithCheckFunction->getNumUses() + SanCovTraceBB->getNumUses() +
215 SanCovTraceEnter->getNumUses();
Kostya Serebryany48a40232015-03-10 01:58:27 +0000216 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000217 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000218 Function *SanCovWithCheckFunction;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000219 Function *SanCovIndirCallFunction, *SanCovTracePCIndir;
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000220 Function *SanCovTraceEnter, *SanCovTraceBB, *SanCovTracePC, *SanCovTracePCGuard;
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000221 Function *SanCovTraceCmpFunction[4];
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000222 Function *SanCovTraceDivFunction[2];
223 Function *SanCovTraceGepFunction;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000224 Function *SanCovTraceSwitchFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000225 InlineAsm *EmptyAsm;
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000226 Type *IntptrTy, *IntptrPtrTy, *Int64Ty, *Int64PtrTy;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000227 Module *CurModule;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000228 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000229 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000230
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000231 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000232 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000233
Alexey Samsonov3514f272015-05-07 01:00:31 +0000234 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000235};
236
Mike Aizatsky759aca02016-03-18 23:29:29 +0000237} // namespace
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000238
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000239bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000240 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
241 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000242 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000243 DL = &M.getDataLayout();
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000244 CurModule = &M;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000245 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000246 IntptrPtrTy = PointerType::getUnqual(IntptrTy);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000247 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000248 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000249 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000250 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000251 Int64PtrTy = PointerType::getUnqual(IRB.getInt64Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000252 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000253
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000254 SanCovFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000255 M.getOrInsertFunction(SanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000256 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000257 M.getOrInsertFunction(SanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
258 SanCovTracePCIndir = checkSanitizerInterfaceFunction(
259 M.getOrInsertFunction(SanCovTracePCIndirName, VoidTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000260 SanCovIndirCallFunction =
261 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000262 SanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000263 SanCovTraceCmpFunction[0] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000264 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000265 SanCovTraceCmp1, VoidTy, IRB.getInt8Ty(), IRB.getInt8Ty(), nullptr));
266 SanCovTraceCmpFunction[1] = checkSanitizerInterfaceFunction(
267 M.getOrInsertFunction(SanCovTraceCmp2, VoidTy, IRB.getInt16Ty(),
268 IRB.getInt16Ty(), nullptr));
269 SanCovTraceCmpFunction[2] = checkSanitizerInterfaceFunction(
270 M.getOrInsertFunction(SanCovTraceCmp4, VoidTy, IRB.getInt32Ty(),
271 IRB.getInt32Ty(), nullptr));
272 SanCovTraceCmpFunction[3] =
273 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
274 SanCovTraceCmp8, VoidTy, Int64Ty, Int64Ty, nullptr));
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000275
276 SanCovTraceDivFunction[0] =
277 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
278 SanCovTraceDiv4, VoidTy, IRB.getInt32Ty(), nullptr));
279 SanCovTraceDivFunction[1] =
280 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
281 SanCovTraceDiv8, VoidTy, Int64Ty, nullptr));
282 SanCovTraceGepFunction =
283 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
284 SanCovTraceGep, VoidTy, IntptrTy, nullptr));
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000285 SanCovTraceSwitchFunction =
286 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000287 SanCovTraceSwitchName, VoidTy, Int64Ty, Int64PtrTy, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000288
Kostya Serebryany73762942014-12-16 21:24:15 +0000289 // We insert an empty inline asm after cov callbacks to avoid callback merge.
290 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
291 StringRef(""), StringRef(""),
292 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000293
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000294 SanCovTracePC = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000295 M.getOrInsertFunction(SanCovTracePCName, VoidTy, nullptr));
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000296 SanCovTracePCGuard = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000297 SanCovTracePCGuardName, VoidTy, IntptrPtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000298 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000299 M.getOrInsertFunction(SanCovTraceEnterName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000300 SanCovTraceBB = checkSanitizerInterfaceFunction(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000301 M.getOrInsertFunction(SanCovTraceBBName, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000302
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000303 // At this point we create a dummy array of guards because we don't
304 // know how many elements we will need.
305 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000306 Type *Int8Ty = IRB.getInt8Ty();
307
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000308 GuardArray =
309 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
310 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000311 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000312 EightBitCounterArray =
313 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
314 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000315
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000316 for (auto &F : M)
317 runOnFunction(F);
318
Kostya Serebryany48a40232015-03-10 01:58:27 +0000319 auto N = NumberOfInstrumentedBlocks();
320
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000321 // Now we know how many elements we need. Create an array of guards
322 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000323 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000324 GlobalVariable *RealGuardArray = new GlobalVariable(
325 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
326 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
327
328 // Replace the dummy array with the real one.
329 GuardArray->replaceAllUsesWith(
330 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
331 GuardArray->eraseFromParent();
332
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000333 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000334 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000335 // Make sure the array is 16-aligned.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000336 static const int CounterAlignment = 16;
337 Type *Int8ArrayNTy = ArrayType::get(Int8Ty, alignTo(N, CounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000338 RealEightBitCounterArray = new GlobalVariable(
339 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
340 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000341 RealEightBitCounterArray->setAlignment(CounterAlignment);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000342 EightBitCounterArray->replaceAllUsesWith(
343 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
344 EightBitCounterArray->eraseFromParent();
345 }
346
Kostya Serebryany88599462015-02-20 00:30:44 +0000347 // Create variable for module (compilation unit) name
348 Constant *ModNameStrConst =
349 ConstantDataArray::getString(M.getContext(), M.getName(), true);
350 GlobalVariable *ModuleName =
351 new GlobalVariable(M, ModNameStrConst->getType(), true,
352 GlobalValue::PrivateLinkage, ModNameStrConst);
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000353 if (Options.TracePCGuard) {
354 Function *CtorFunc;
355 std::string SectionName(SanCovTracePCGuardSection);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000356 GlobalVariable *Bounds[2];
357 const char *Prefix[2] = {"__start_", "__stop_"};
358 for (int i = 0; i < 2; i++) {
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000359 Bounds[i] = new GlobalVariable(M, IntptrPtrTy, false,
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000360 GlobalVariable::ExternalLinkage, nullptr,
361 Prefix[i] + SectionName);
362 Bounds[i]->setVisibility(GlobalValue::HiddenVisibility);
363 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000364 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
365 M, SanCovModuleCtorName, SanCovTracePCGuardInitName,
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000366 {IntptrPtrTy, IntptrPtrTy},
367 {IRB.CreatePointerCast(Bounds[0], IntptrPtrTy),
368 IRB.CreatePointerCast(Bounds[1], IntptrPtrTy)});
Kostya Serebryany88599462015-02-20 00:30:44 +0000369
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000370 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
371
372 } else if (!Options.TracePC) {
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000373 Function *CtorFunc;
374 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000375 M, SanCovModuleCtorName, SanCovModuleInitName,
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000376 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
377 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000378 ConstantInt::get(IntptrTy, N),
379 Options.Use8bitCounters
380 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
381 : Constant::getNullValue(Int8PtrTy),
382 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000383
Mike Aizatsky759aca02016-03-18 23:29:29 +0000384 appendToGlobalCtors(M, CtorFunc, SanCtorAndDtorPriority);
Kostya Serebryany3c767db2016-02-27 05:45:12 +0000385 }
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000386
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000387 return true;
388}
389
Mike Aizatsky9987f432016-03-23 23:15:03 +0000390// True if block has successors and it dominates all of them.
391static bool isFullDominator(const BasicBlock *BB, const DominatorTree *DT) {
392 if (succ_begin(BB) == succ_end(BB))
393 return false;
394
395 for (const BasicBlock *SUCC : make_range(succ_begin(BB), succ_end(BB))) {
396 if (!DT->dominates(BB, SUCC))
397 return false;
398 }
399
400 return true;
401}
402
403// True if block has predecessors and it postdominates all of them.
404static bool isFullPostDominator(const BasicBlock *BB,
405 const PostDominatorTree *PDT) {
406 if (pred_begin(BB) == pred_end(BB))
407 return false;
408
409 for (const BasicBlock *PRED : make_range(pred_begin(BB), pred_end(BB))) {
410 if (!PDT->dominates(BB, PRED))
411 return false;
412 }
413
414 return true;
415}
416
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000417static bool shouldInstrumentBlock(const Function& F, const BasicBlock *BB, const DominatorTree *DT,
Mike Aizatsky602f7922016-03-21 23:08:16 +0000418 const PostDominatorTree *PDT) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000419 if (!ClPruneBlocks || &F.getEntryBlock() == BB)
Mike Aizatsky5971f182016-02-26 01:17:22 +0000420 return true;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000421
Mike Aizatsky9987f432016-03-23 23:15:03 +0000422 return !(isFullDominator(BB, DT) || isFullPostDominator(BB, PDT));
Mike Aizatsky5971f182016-02-26 01:17:22 +0000423}
424
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000425bool SanitizerCoverageModule::runOnFunction(Function &F) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000426 if (F.empty())
427 return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000428 if (F.getName().find(".module_ctor") != std::string::npos)
Mike Aizatsky759aca02016-03-18 23:29:29 +0000429 return false; // Should not instrument sanitizer init functions.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000430 if (F.getName().startswith("__sanitizer_"))
431 return false; // Don't instrument __sanitizer_* callbacks.
Reid Klecknerdf523372015-09-03 20:18:29 +0000432 // Don't instrument functions using SEH for now. Splitting basic blocks like
433 // we do for coverage breaks WinEHPrepare.
434 // FIXME: Remove this when SEH no longer uses landingpad pattern matching.
435 if (F.hasPersonalityFn() &&
436 isAsynchronousEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
437 return false;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000438 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000439 SplitAllCriticalEdges(F);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000440 SmallVector<Instruction *, 8> IndirCalls;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000441 SmallVector<BasicBlock *, 16> BlocksToInstrument;
Mike Aizatsky759aca02016-03-18 23:29:29 +0000442 SmallVector<Instruction *, 8> CmpTraceTargets;
443 SmallVector<Instruction *, 8> SwitchTraceTargets;
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000444 SmallVector<BinaryOperator *, 8> DivTraceTargets;
445 SmallVector<GetElementPtrInst *, 8> GepTraceTargets;
Mike Aizatsky5971f182016-02-26 01:17:22 +0000446
Mike Aizatsky602f7922016-03-21 23:08:16 +0000447 const DominatorTree *DT =
448 &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
449 const PostDominatorTree *PDT =
450 &getAnalysis<PostDominatorTreeWrapperPass>(F).getPostDomTree();
451
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000452 for (auto &BB : F) {
Mike Aizatsky01c0f8d2016-04-01 18:13:19 +0000453 if (shouldInstrumentBlock(F, &BB, DT, PDT))
Mike Aizatsky5971f182016-02-26 01:17:22 +0000454 BlocksToInstrument.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000455 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000456 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000457 CallSite CS(&Inst);
458 if (CS && !CS.getCalledFunction())
459 IndirCalls.push_back(&Inst);
460 }
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000461 if (Options.TraceCmp) {
462 if (isa<ICmpInst>(&Inst))
463 CmpTraceTargets.push_back(&Inst);
464 if (isa<SwitchInst>(&Inst))
465 SwitchTraceTargets.push_back(&Inst);
466 }
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000467 if (Options.TraceDiv)
468 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&Inst))
469 if (BO->getOpcode() == Instruction::SDiv ||
470 BO->getOpcode() == Instruction::UDiv)
471 DivTraceTargets.push_back(BO);
472 if (Options.TraceGep)
473 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Inst))
474 GepTraceTargets.push_back(GEP);
475 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000476 }
Mike Aizatsky5971f182016-02-26 01:17:22 +0000477
478 InjectCoverage(F, BlocksToInstrument);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000479 InjectCoverageForIndirectCalls(F, IndirCalls);
480 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000481 InjectTraceForSwitch(F, SwitchTraceTargets);
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000482 InjectTraceForDiv(F, DivTraceTargets);
483 InjectTraceForGep(F, GepTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000484 return true;
485}
486
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000487bool SanitizerCoverageModule::InjectCoverage(Function &F,
488 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000489 switch (Options.CoverageType) {
490 case SanitizerCoverageOptions::SCK_None:
491 return false;
492 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000493 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000494 return true;
495 default: {
496 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000497 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000498 InjectCoverageAtBlock(F, *BB, UseCalls);
499 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000500 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000501 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000502}
503
504// On every indirect call we call a run-time function
505// __sanitizer_cov_indir_call* with two parameters:
506// - callee address,
Mike Aizatsky759aca02016-03-18 23:29:29 +0000507// - global cache array that contains CacheSize pointers (zero-initialized).
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000508// The cache is used to speed up recording the caller-callee pairs.
509// The address of the caller is passed implicitly via caller PC.
Mike Aizatsky759aca02016-03-18 23:29:29 +0000510// CacheSize is encoded in the name of the run-time function.
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000511void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
512 Function &F, ArrayRef<Instruction *> IndirCalls) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000513 if (IndirCalls.empty())
514 return;
515 const int CacheSize = 16;
516 const int CacheAlignment = 64; // Align for better performance.
517 Type *Ty = ArrayType::get(IntptrTy, CacheSize);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000518 for (auto I : IndirCalls) {
519 IRBuilder<> IRB(I);
520 CallSite CS(I);
521 Value *Callee = CS.getCalledValue();
Mike Aizatsky759aca02016-03-18 23:29:29 +0000522 if (isa<InlineAsm>(Callee))
523 continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000524 GlobalVariable *CalleeCache = new GlobalVariable(
525 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
526 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
Mike Aizatsky759aca02016-03-18 23:29:29 +0000527 CalleeCache->setAlignment(CacheAlignment);
Kostya Serebryany66a9c172016-09-15 22:11:08 +0000528 if (Options.TracePC || Options.TracePCGuard)
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000529 IRB.CreateCall(SanCovTracePCIndir,
530 IRB.CreatePointerCast(Callee, IntptrTy));
531 else
532 IRB.CreateCall(SanCovIndirCallFunction,
533 {IRB.CreatePointerCast(Callee, IntptrTy),
Mike Aizatsky759aca02016-03-18 23:29:29 +0000534 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000535 }
536}
537
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000538// For every switch statement we insert a call:
539// __sanitizer_cov_trace_switch(CondValue,
540// {NumCases, ValueSizeInBits, Case0Value, Case1Value, Case2Value, ... })
541
542void SanitizerCoverageModule::InjectTraceForSwitch(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000543 Function &, ArrayRef<Instruction *> SwitchTraceTargets) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000544 for (auto I : SwitchTraceTargets) {
545 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
546 IRBuilder<> IRB(I);
547 SmallVector<Constant *, 16> Initializers;
548 Value *Cond = SI->getCondition();
Kostya Serebryany25691182015-08-11 00:24:39 +0000549 if (Cond->getType()->getScalarSizeInBits() >
550 Int64Ty->getScalarSizeInBits())
551 continue;
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000552 Initializers.push_back(ConstantInt::get(Int64Ty, SI->getNumCases()));
553 Initializers.push_back(
554 ConstantInt::get(Int64Ty, Cond->getType()->getScalarSizeInBits()));
555 if (Cond->getType()->getScalarSizeInBits() <
556 Int64Ty->getScalarSizeInBits())
557 Cond = IRB.CreateIntCast(Cond, Int64Ty, false);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000558 for (auto It : SI->cases()) {
Kostya Serebryanyfb7d8d92015-07-31 01:33:06 +0000559 Constant *C = It.getCaseValue();
560 if (C->getType()->getScalarSizeInBits() <
561 Int64Ty->getScalarSizeInBits())
562 C = ConstantExpr::getCast(CastInst::ZExt, It.getCaseValue(), Int64Ty);
563 Initializers.push_back(C);
564 }
565 ArrayType *ArrayOfInt64Ty = ArrayType::get(Int64Ty, Initializers.size());
566 GlobalVariable *GV = new GlobalVariable(
567 *CurModule, ArrayOfInt64Ty, false, GlobalVariable::InternalLinkage,
568 ConstantArray::get(ArrayOfInt64Ty, Initializers),
569 "__sancov_gen_cov_switch_values");
570 IRB.CreateCall(SanCovTraceSwitchFunction,
571 {Cond, IRB.CreatePointerCast(GV, Int64PtrTy)});
572 }
573 }
574}
575
Kostya Serebryany5ac427b2016-08-30 01:12:10 +0000576void SanitizerCoverageModule::InjectTraceForDiv(
577 Function &, ArrayRef<BinaryOperator *> DivTraceTargets) {
578 for (auto BO : DivTraceTargets) {
579 IRBuilder<> IRB(BO);
580 Value *A1 = BO->getOperand(1);
581 if (isa<ConstantInt>(A1)) continue;
582 if (!A1->getType()->isIntegerTy())
583 continue;
584 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A1->getType());
585 int CallbackIdx = TypeSize == 32 ? 0 :
586 TypeSize == 64 ? 1 : -1;
587 if (CallbackIdx < 0) continue;
588 auto Ty = Type::getIntNTy(*C, TypeSize);
589 IRB.CreateCall(SanCovTraceDivFunction[CallbackIdx],
590 {IRB.CreateIntCast(A1, Ty, true)});
591 }
592}
593
594void SanitizerCoverageModule::InjectTraceForGep(
595 Function &, ArrayRef<GetElementPtrInst *> GepTraceTargets) {
596 for (auto GEP : GepTraceTargets) {
597 IRBuilder<> IRB(GEP);
598 for (auto I = GEP->idx_begin(); I != GEP->idx_end(); ++I)
599 if (!isa<ConstantInt>(*I))
600 IRB.CreateCall(SanCovTraceGepFunction,
601 {IRB.CreateIntCast(*I, IntptrTy, true)});
602 }
603}
604
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000605void SanitizerCoverageModule::InjectTraceForCmp(
Mike Aizatsky759aca02016-03-18 23:29:29 +0000606 Function &, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000607 for (auto I : CmpTraceTargets) {
608 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
609 IRBuilder<> IRB(ICMP);
610 Value *A0 = ICMP->getOperand(0);
611 Value *A1 = ICMP->getOperand(1);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000612 if (!A0->getType()->isIntegerTy())
613 continue;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000614 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000615 int CallbackIdx = TypeSize == 8 ? 0 :
616 TypeSize == 16 ? 1 :
617 TypeSize == 32 ? 2 :
618 TypeSize == 64 ? 3 : -1;
619 if (CallbackIdx < 0) continue;
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000620 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000621 auto Ty = Type::getIntNTy(*C, TypeSize);
David Blaikieff6409d2015-05-18 22:13:54 +0000622 IRB.CreateCall(
Kostya Serebryany524c3f32016-08-18 01:25:28 +0000623 SanCovTraceCmpFunction[CallbackIdx],
624 {IRB.CreateIntCast(A0, Ty, true), IRB.CreateIntCast(A1, Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000625 }
626 }
627}
628
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000629void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Mike Aizatsky759aca02016-03-18 23:29:29 +0000630 I->setMetadata(I->getModule()->getMDKindID("nosanitize"),
631 MDNode::get(*C, None));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000632}
633
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000634void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
635 bool UseCalls) {
Alexey Samsonov342b1e82015-06-30 23:11:45 +0000636 // Don't insert coverage for unreachable blocks: we will never call
637 // __sanitizer_cov() for them, so counting them in
638 // NumberOfInstrumentedBlocks() might complicate calculation of code coverage
639 // percentage. Also, unreachable instructions frequently have no debug
640 // locations.
641 if (isa<UnreachableInst>(BB.getTerminator()))
642 return;
Justin Bogner7ae63aa2015-08-14 17:03:45 +0000643 BasicBlock::iterator IP = BB.getFirstInsertionPt();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000644
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000645 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000646 DebugLoc EntryLoc;
647 if (IsEntryBB) {
Pete Cooperadebb932016-03-11 02:14:16 +0000648 if (auto SP = F.getSubprogram())
Alexey Samsonov201733b2015-06-12 01:48:47 +0000649 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
Reid Klecknera57d0152015-08-14 16:45:42 +0000650 // Keep static allocas and llvm.localescape calls in the entry block. Even
651 // if we aren't splitting the block, it's nice for allocas to be before
652 // calls.
653 IP = PrepareToSplitEntryBlock(BB, IP);
Alexey Samsonov201733b2015-06-12 01:48:47 +0000654 } else {
655 EntryLoc = IP->getDebugLoc();
656 }
657
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000658 IRBuilder<> IRB(&*IP);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000659 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000660 Value *GuardP = IRB.CreateAdd(
661 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000662 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000663 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
664 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000665 if (Options.TracePC) {
Kostya Serebryanydd5c7f92016-07-14 17:59:01 +0000666 IRB.CreateCall(SanCovTracePC); // gets the PC using GET_CALLER_PC.
667 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000668 } else if (Options.TracePCGuard) {
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000669 auto GuardVar = new GlobalVariable(
670 *F.getParent(), Int64Ty, false, GlobalVariable::LinkOnceODRLinkage,
671 Constant::getNullValue(Int64Ty), "__sancov_guard." + F.getName());
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000672 // TODO: add debug into to GuardVar.
673 GuardVar->setSection(SanCovTracePCGuardSection);
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000674 auto GuardPtr = IRB.CreatePointerCast(GuardVar, IntptrPtrTy);
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000675 if (!UseCalls) {
676 auto GuardLoad = IRB.CreateLoad(GuardPtr);
677 GuardLoad->setAtomic(AtomicOrdering::Monotonic);
678 GuardLoad->setAlignment(8);
679 SetNoSanitizeMetadata(GuardLoad); // Don't instrument with e.g. asan.
Kostya Serebryany8e781a82016-09-18 04:52:23 +0000680 auto Cmp = IRB.CreateICmpNE(
Kostya Serebryany8ad41552016-09-17 05:03:05 +0000681 GuardLoad, Constant::getNullValue(GuardLoad->getType()));
682 auto Ins = SplitBlockAndInsertIfThen(
683 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
684 IRB.SetCurrentDebugLocation(EntryLoc);
685 IRB.SetInsertPoint(Ins);
686 }
Kostya Serebryanyda718e52016-09-14 01:39:35 +0000687 IRB.CreateCall(SanCovTracePCGuard, GuardPtr);
688 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000689 } else if (Options.TraceBB) {
Kostya Serebryanya3c53472015-12-02 02:37:13 +0000690 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
691 } else if (UseCalls) {
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000692 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
693 } else {
694 LoadInst *Load = IRB.CreateLoad(GuardP);
JF Bastien800f87a2016-04-06 21:19:33 +0000695 Load->setAtomic(AtomicOrdering::Monotonic);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000696 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000697 SetNoSanitizeMetadata(Load);
Mike Aizatsky759aca02016-03-18 23:29:29 +0000698 Value *Cmp =
699 IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000700 Instruction *Ins = SplitBlockAndInsertIfThen(
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000701 Cmp, &*IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000702 IRB.SetInsertPoint(Ins);
703 IRB.SetCurrentDebugLocation(EntryLoc);
704 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
705 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000706 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000707 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000708
Alexey Samsonov3514f272015-05-07 01:00:31 +0000709 if (Options.Use8bitCounters) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +0000710 IRB.SetInsertPoint(&*IP);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000711 Value *P = IRB.CreateAdd(
712 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000713 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000714 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000715 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000716 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000717 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000718 SetNoSanitizeMetadata(LI);
719 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000720 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000721}
722
723char SanitizerCoverageModule::ID = 0;
Mike Aizatsky90562842016-02-27 05:50:40 +0000724INITIALIZE_PASS_BEGIN(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000725 "SanitizerCoverage: TODO."
726 "ModulePass",
727 false, false)
Mike Aizatsky90562842016-02-27 05:50:40 +0000728INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
729INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
730INITIALIZE_PASS_END(SanitizerCoverageModule, "sancov",
Mike Aizatsky759aca02016-03-18 23:29:29 +0000731 "SanitizerCoverage: TODO."
732 "ModulePass",
733 false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000734ModulePass *llvm::createSanitizerCoverageModulePass(
735 const SanitizerCoverageOptions &Options) {
736 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000737}