blob: dff39efa5b969c5c5ecee4fb2ae17542889f5e72 [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
31#include "llvm/Transforms/Instrumentation.h"
32#include "llvm/ADT/ArrayRef.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/DataLayout.h"
Alexey Samsonov201733b2015-06-12 01:48:47 +000036#include "llvm/IR/DebugInfo.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000037#include "llvm/IR/Function.h"
38#include "llvm/IR/IRBuilder.h"
Kostya Serebryany73762942014-12-16 21:24:15 +000039#include "llvm/IR/InlineAsm.h"
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000040#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/MDBuilder.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
44#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/Transforms/Scalar.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/ModuleUtils.h"
50
51using namespace llvm;
52
53#define DEBUG_TYPE "sancov"
54
55static const char *const kSanCovModuleInitName = "__sanitizer_cov_module_init";
56static const char *const kSanCovName = "__sanitizer_cov";
Kostya Serebryany77cc7292015-02-04 01:21:45 +000057static const char *const kSanCovWithCheckName = "__sanitizer_cov_with_check";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000058static const char *const kSanCovIndirCallName = "__sanitizer_cov_indir_call16";
Kostya Serebryanycb45b122014-11-19 00:22:58 +000059static const char *const kSanCovTraceEnter = "__sanitizer_cov_trace_func_enter";
60static const char *const kSanCovTraceBB = "__sanitizer_cov_trace_basic_block";
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000061static const char *const kSanCovTraceCmp = "__sanitizer_cov_trace_cmp";
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000062static const char *const kSanCovModuleCtorName = "sancov.module_ctor";
Evgeniy Stepanov3fdfc7b2015-01-27 15:01:22 +000063static const uint64_t kSanCtorAndDtorPriority = 2;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000064
65static cl::opt<int> ClCoverageLevel("sanitizer-coverage-level",
66 cl::desc("Sanitizer Coverage. 0: none, 1: entry block, 2: all blocks, "
67 "3: all blocks and critical edges, "
68 "4: above plus indirect calls"),
69 cl::Hidden, cl::init(0));
70
Kostya Serebryany77cc7292015-02-04 01:21:45 +000071static cl::opt<unsigned> ClCoverageBlockThreshold(
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000072 "sanitizer-coverage-block-threshold",
Kostya Serebryany77cc7292015-02-04 01:21:45 +000073 cl::desc("Use a callback with a guard check inside it if there are"
74 " more than this number of blocks."),
Kostya Serebryany8fb05ac2015-03-10 01:11:53 +000075 cl::Hidden, cl::init(500));
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000076
Kostya Serebryanycb45b122014-11-19 00:22:58 +000077static cl::opt<bool>
78 ClExperimentalTracing("sanitizer-coverage-experimental-tracing",
79 cl::desc("Experimental basic-block tracing: insert "
80 "callbacks at every basic block"),
81 cl::Hidden, cl::init(false));
82
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +000083static cl::opt<bool>
84 ClExperimentalCMPTracing("sanitizer-coverage-experimental-trace-compares",
85 cl::desc("Experimental tracing of CMP and similar "
86 "instructions"),
87 cl::Hidden, cl::init(false));
88
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +000089// Experimental 8-bit counters used as an additional search heuristic during
90// coverage-guided fuzzing.
91// The counters are not thread-friendly:
92// - contention on these counters may cause significant slowdown;
93// - the counter updates are racy and the results may be inaccurate.
94// They are also inaccurate due to 8-bit integer overflow.
95static cl::opt<bool> ClUse8bitCounters("sanitizer-coverage-8bit-counters",
96 cl::desc("Experimental 8-bit counters"),
97 cl::Hidden, cl::init(false));
98
Kostya Serebryany29a18dc2014-11-11 22:14:37 +000099namespace {
100
Alexey Samsonov3514f272015-05-07 01:00:31 +0000101SanitizerCoverageOptions getOptions(int LegacyCoverageLevel) {
102 SanitizerCoverageOptions Res;
103 switch (LegacyCoverageLevel) {
104 case 0:
105 Res.CoverageType = SanitizerCoverageOptions::SCK_None;
106 break;
107 case 1:
108 Res.CoverageType = SanitizerCoverageOptions::SCK_Function;
109 break;
110 case 2:
111 Res.CoverageType = SanitizerCoverageOptions::SCK_BB;
112 break;
113 case 3:
114 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
115 break;
116 case 4:
117 Res.CoverageType = SanitizerCoverageOptions::SCK_Edge;
118 Res.IndirectCalls = true;
119 break;
120 }
121 return Res;
122}
123
124SanitizerCoverageOptions OverrideFromCL(SanitizerCoverageOptions Options) {
125 // Sets CoverageType and IndirectCalls.
126 SanitizerCoverageOptions CLOpts = getOptions(ClCoverageLevel);
127 Options.CoverageType = std::max(Options.CoverageType, CLOpts.CoverageType);
128 Options.IndirectCalls |= CLOpts.IndirectCalls;
129 Options.TraceBB |= ClExperimentalTracing;
130 Options.TraceCmp |= ClExperimentalCMPTracing;
131 Options.Use8bitCounters |= ClUse8bitCounters;
132 return Options;
133}
134
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000135class SanitizerCoverageModule : public ModulePass {
136 public:
Alexey Samsonov3514f272015-05-07 01:00:31 +0000137 SanitizerCoverageModule(
138 const SanitizerCoverageOptions &Options = SanitizerCoverageOptions())
139 : ModulePass(ID), Options(OverrideFromCL(Options)) {}
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000140 bool runOnModule(Module &M) override;
141 bool runOnFunction(Function &F);
142 static char ID; // Pass identification, replacement for typeid
143 const char *getPassName() const override {
144 return "SanitizerCoverageModule";
145 }
146
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000147 private:
148 void InjectCoverageForIndirectCalls(Function &F,
149 ArrayRef<Instruction *> IndirCalls);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000150 void InjectTraceForCmp(Function &F, ArrayRef<Instruction *> CmpTraceTargets);
151 bool InjectCoverage(Function &F, ArrayRef<BasicBlock *> AllBlocks);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000152 void SetNoSanitizeMetadata(Instruction *I);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000153 void InjectCoverageAtBlock(Function &F, BasicBlock &BB, bool UseCalls);
Kostya Serebryany48a40232015-03-10 01:58:27 +0000154 unsigned NumberOfInstrumentedBlocks() {
155 return SanCovFunction->getNumUses() + SanCovWithCheckFunction->getNumUses();
156 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000157 Function *SanCovFunction;
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000158 Function *SanCovWithCheckFunction;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000159 Function *SanCovIndirCallFunction;
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000160 Function *SanCovTraceEnter, *SanCovTraceBB;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000161 Function *SanCovTraceCmpFunction;
Kostya Serebryany73762942014-12-16 21:24:15 +0000162 InlineAsm *EmptyAsm;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000163 Type *IntptrTy, *Int64Ty;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000164 LLVMContext *C;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000165 const DataLayout *DL;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000166
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000167 GlobalVariable *GuardArray;
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000168 GlobalVariable *EightBitCounterArray;
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000169
Alexey Samsonov3514f272015-05-07 01:00:31 +0000170 SanitizerCoverageOptions Options;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000171};
172
173} // namespace
174
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000175bool SanitizerCoverageModule::runOnModule(Module &M) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000176 if (Options.CoverageType == SanitizerCoverageOptions::SCK_None)
177 return false;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000178 C = &(M.getContext());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000179 DL = &M.getDataLayout();
180 IntptrTy = Type::getIntNTy(*C, DL->getPointerSizeInBits());
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000181 Type *VoidTy = Type::getVoidTy(*C);
Kostya Serebryany4cadd4a2014-11-24 18:49:53 +0000182 IRBuilder<> IRB(*C);
Kostya Serebryany88599462015-02-20 00:30:44 +0000183 Type *Int8PtrTy = PointerType::getUnqual(IRB.getInt8Ty());
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000184 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000185 Int64Ty = IRB.getInt64Ty();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000186
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000187 SanCovFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany9fdeb372014-12-23 22:32:17 +0000188 M.getOrInsertFunction(kSanCovName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000189 SanCovWithCheckFunction = checkSanitizerInterfaceFunction(
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000190 M.getOrInsertFunction(kSanCovWithCheckName, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000191 SanCovIndirCallFunction =
192 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
193 kSanCovIndirCallName, VoidTy, IntptrTy, IntptrTy, nullptr));
194 SanCovTraceCmpFunction =
195 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
196 kSanCovTraceCmp, VoidTy, Int64Ty, Int64Ty, Int64Ty, nullptr));
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000197
Kostya Serebryany73762942014-12-16 21:24:15 +0000198 // We insert an empty inline asm after cov callbacks to avoid callback merge.
199 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
200 StringRef(""), StringRef(""),
201 /*hasSideEffects=*/true);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000202
Alexey Samsonov3514f272015-05-07 01:00:31 +0000203 if (Options.TraceBB) {
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000204 SanCovTraceEnter = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000205 M.getOrInsertFunction(kSanCovTraceEnter, VoidTy, Int32PtrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +0000206 SanCovTraceBB = checkSanitizerInterfaceFunction(
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000207 M.getOrInsertFunction(kSanCovTraceBB, VoidTy, Int32PtrTy, nullptr));
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000208 }
209
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000210 // At this point we create a dummy array of guards because we don't
211 // know how many elements we will need.
212 Type *Int32Ty = IRB.getInt32Ty();
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000213 Type *Int8Ty = IRB.getInt8Ty();
214
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000215 GuardArray =
216 new GlobalVariable(M, Int32Ty, false, GlobalValue::ExternalLinkage,
217 nullptr, "__sancov_gen_cov_tmp");
Alexey Samsonov3514f272015-05-07 01:00:31 +0000218 if (Options.Use8bitCounters)
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000219 EightBitCounterArray =
220 new GlobalVariable(M, Int8Ty, false, GlobalVariable::ExternalLinkage,
221 nullptr, "__sancov_gen_cov_tmp");
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000222
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000223 for (auto &F : M)
224 runOnFunction(F);
225
Kostya Serebryany48a40232015-03-10 01:58:27 +0000226 auto N = NumberOfInstrumentedBlocks();
227
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000228 // Now we know how many elements we need. Create an array of guards
229 // with one extra element at the beginning for the size.
Kostya Serebryany48a40232015-03-10 01:58:27 +0000230 Type *Int32ArrayNTy = ArrayType::get(Int32Ty, N + 1);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000231 GlobalVariable *RealGuardArray = new GlobalVariable(
232 M, Int32ArrayNTy, false, GlobalValue::PrivateLinkage,
233 Constant::getNullValue(Int32ArrayNTy), "__sancov_gen_cov");
234
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000235
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000236 // Replace the dummy array with the real one.
237 GuardArray->replaceAllUsesWith(
238 IRB.CreatePointerCast(RealGuardArray, Int32PtrTy));
239 GuardArray->eraseFromParent();
240
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000241 GlobalVariable *RealEightBitCounterArray;
Alexey Samsonov3514f272015-05-07 01:00:31 +0000242 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000243 // Make sure the array is 16-aligned.
244 static const int kCounterAlignment = 16;
245 Type *Int8ArrayNTy =
Kostya Serebryany48a40232015-03-10 01:58:27 +0000246 ArrayType::get(Int8Ty, RoundUpToAlignment(N, kCounterAlignment));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000247 RealEightBitCounterArray = new GlobalVariable(
248 M, Int8ArrayNTy, false, GlobalValue::PrivateLinkage,
249 Constant::getNullValue(Int8ArrayNTy), "__sancov_gen_cov_counter");
250 RealEightBitCounterArray->setAlignment(kCounterAlignment);
251 EightBitCounterArray->replaceAllUsesWith(
252 IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy));
253 EightBitCounterArray->eraseFromParent();
254 }
255
Kostya Serebryany88599462015-02-20 00:30:44 +0000256 // Create variable for module (compilation unit) name
257 Constant *ModNameStrConst =
258 ConstantDataArray::getString(M.getContext(), M.getName(), true);
259 GlobalVariable *ModuleName =
260 new GlobalVariable(M, ModNameStrConst->getType(), true,
261 GlobalValue::PrivateLinkage, ModNameStrConst);
262
Ismail Pazarbasid02ce132015-05-10 13:45:05 +0000263 Function *CtorFunc;
264 std::tie(CtorFunc, std::ignore) = createSanitizerCtorAndInitFunctions(
265 M, kSanCovModuleCtorName, kSanCovModuleInitName,
266 {Int32PtrTy, IntptrTy, Int8PtrTy, Int8PtrTy},
267 {IRB.CreatePointerCast(RealGuardArray, Int32PtrTy),
268 ConstantInt::get(IntptrTy, N),
269 Options.Use8bitCounters
270 ? IRB.CreatePointerCast(RealEightBitCounterArray, Int8PtrTy)
271 : Constant::getNullValue(Int8PtrTy),
272 IRB.CreatePointerCast(ModuleName, Int8PtrTy)});
273
274 appendToGlobalCtors(M, CtorFunc, kSanCtorAndDtorPriority);
275
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000276 return true;
277}
278
279bool SanitizerCoverageModule::runOnFunction(Function &F) {
280 if (F.empty()) return false;
Kostya Serebryanyfea4fb42014-12-17 21:50:04 +0000281 if (F.getName().find(".module_ctor") != std::string::npos)
282 return false; // Should not instrument sanitizer init functions.
Alexey Samsonov3514f272015-05-07 01:00:31 +0000283 if (Options.CoverageType >= SanitizerCoverageOptions::SCK_Edge)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000284 SplitAllCriticalEdges(F);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000285 SmallVector<Instruction*, 8> IndirCalls;
286 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000287 SmallVector<Instruction*, 8> CmpTraceTargets;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000288 for (auto &BB : F) {
289 AllBlocks.push_back(&BB);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000290 for (auto &Inst : BB) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000291 if (Options.IndirectCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000292 CallSite CS(&Inst);
293 if (CS && !CS.getCalledFunction())
294 IndirCalls.push_back(&Inst);
295 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000296 if (Options.TraceCmp && isa<ICmpInst>(&Inst))
297 CmpTraceTargets.push_back(&Inst);
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000298 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000299 }
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000300 InjectCoverage(F, AllBlocks);
301 InjectCoverageForIndirectCalls(F, IndirCalls);
302 InjectTraceForCmp(F, CmpTraceTargets);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000303 return true;
304}
305
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000306bool SanitizerCoverageModule::InjectCoverage(Function &F,
307 ArrayRef<BasicBlock *> AllBlocks) {
Alexey Samsonov3514f272015-05-07 01:00:31 +0000308 switch (Options.CoverageType) {
309 case SanitizerCoverageOptions::SCK_None:
310 return false;
311 case SanitizerCoverageOptions::SCK_Function:
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000312 InjectCoverageAtBlock(F, F.getEntryBlock(), false);
Alexey Samsonov3514f272015-05-07 01:00:31 +0000313 return true;
314 default: {
315 bool UseCalls = ClCoverageBlockThreshold < AllBlocks.size();
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000316 for (auto BB : AllBlocks)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000317 InjectCoverageAtBlock(F, *BB, UseCalls);
318 return true;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000319 }
Alexey Samsonov3514f272015-05-07 01:00:31 +0000320 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000321}
322
323// On every indirect call we call a run-time function
324// __sanitizer_cov_indir_call* with two parameters:
325// - callee address,
326// - global cache array that contains kCacheSize pointers (zero-initialized).
327// The cache is used to speed up recording the caller-callee pairs.
328// The address of the caller is passed implicitly via caller PC.
329// kCacheSize is encoded in the name of the run-time function.
330void SanitizerCoverageModule::InjectCoverageForIndirectCalls(
331 Function &F, ArrayRef<Instruction *> IndirCalls) {
332 if (IndirCalls.empty()) return;
333 const int kCacheSize = 16;
334 const int kCacheAlignment = 64; // Align for better performance.
335 Type *Ty = ArrayType::get(IntptrTy, kCacheSize);
336 for (auto I : IndirCalls) {
337 IRBuilder<> IRB(I);
338 CallSite CS(I);
339 Value *Callee = CS.getCalledValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +0000340 if (isa<InlineAsm>(Callee)) continue;
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000341 GlobalVariable *CalleeCache = new GlobalVariable(
342 *F.getParent(), Ty, false, GlobalValue::PrivateLinkage,
343 Constant::getNullValue(Ty), "__sancov_gen_callee_cache");
344 CalleeCache->setAlignment(kCacheAlignment);
David Blaikieff6409d2015-05-18 22:13:54 +0000345 IRB.CreateCall(SanCovIndirCallFunction,
346 {IRB.CreatePointerCast(Callee, IntptrTy),
347 IRB.CreatePointerCast(CalleeCache, IntptrTy)});
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000348 }
349}
350
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000351void SanitizerCoverageModule::InjectTraceForCmp(
352 Function &F, ArrayRef<Instruction *> CmpTraceTargets) {
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000353 for (auto I : CmpTraceTargets) {
354 if (ICmpInst *ICMP = dyn_cast<ICmpInst>(I)) {
355 IRBuilder<> IRB(ICMP);
356 Value *A0 = ICMP->getOperand(0);
357 Value *A1 = ICMP->getOperand(1);
358 if (!A0->getType()->isIntegerTy()) continue;
359 uint64_t TypeSize = DL->getTypeStoreSizeInBits(A0->getType());
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000360 // __sanitizer_cov_trace_cmp((type_size << 32) | predicate, A0, A1);
David Blaikieff6409d2015-05-18 22:13:54 +0000361 IRB.CreateCall(
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000362 SanCovTraceCmpFunction,
David Blaikieff6409d2015-05-18 22:13:54 +0000363 {ConstantInt::get(Int64Ty, (TypeSize << 32) | ICMP->getPredicate()),
364 IRB.CreateIntCast(A0, Int64Ty, true),
365 IRB.CreateIntCast(A1, Int64Ty, true)});
Kostya Serebryanyf4e35cc2015-03-21 01:29:36 +0000366 }
367 }
368}
369
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000370void SanitizerCoverageModule::SetNoSanitizeMetadata(Instruction *I) {
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000371 I->setMetadata(
372 I->getParent()->getParent()->getParent()->getMDKindID("nosanitize"),
373 MDNode::get(*C, None));
374}
375
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000376void SanitizerCoverageModule::InjectCoverageAtBlock(Function &F, BasicBlock &BB,
377 bool UseCalls) {
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000378 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
379 // Skip static allocas at the top of the entry block so they don't become
380 // dynamic when we split the block. If we used our optimized stack layout,
381 // then there will only be one alloca and it will come first.
382 for (; IP != BE; ++IP) {
383 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
384 if (!AI || !AI->isStaticAlloca())
385 break;
386 }
387
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000388 bool IsEntryBB = &BB == &F.getEntryBlock();
Alexey Samsonov201733b2015-06-12 01:48:47 +0000389 DebugLoc EntryLoc;
390 if (IsEntryBB) {
391 if (auto SP = getDISubprogram(&F))
392 EntryLoc = DebugLoc::get(SP->getScopeLine(), 0, SP);
393 } else {
394 EntryLoc = IP->getDebugLoc();
395 }
396
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000397 IRBuilder<> IRB(IP);
398 IRB.SetCurrentDebugLocation(EntryLoc);
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000399 SmallVector<Value *, 1> Indices;
400 Value *GuardP = IRB.CreateAdd(
401 IRB.CreatePointerCast(GuardArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000402 ConstantInt::get(IntptrTy, (1 + NumberOfInstrumentedBlocks()) * 4));
Kostya Serebryanyaa185bf2014-12-30 19:29:28 +0000403 Type *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
404 GuardP = IRB.CreateIntToPtr(GuardP, Int32PtrTy);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000405 if (UseCalls) {
406 IRB.CreateCall(SanCovWithCheckFunction, GuardP);
407 } else {
408 LoadInst *Load = IRB.CreateLoad(GuardP);
409 Load->setAtomic(Monotonic);
410 Load->setAlignment(4);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000411 SetNoSanitizeMetadata(Load);
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000412 Value *Cmp = IRB.CreateICmpSGE(Constant::getNullValue(Load->getType()), Load);
413 Instruction *Ins = SplitBlockAndInsertIfThen(
414 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
415 IRB.SetInsertPoint(Ins);
416 IRB.SetCurrentDebugLocation(EntryLoc);
417 // __sanitizer_cov gets the PC of the instruction using GET_CALLER_PC.
418 IRB.CreateCall(SanCovFunction, GuardP);
David Blaikieff6409d2015-05-18 22:13:54 +0000419 IRB.CreateCall(EmptyAsm, {}); // Avoids callback merge.
Kostya Serebryany77cc7292015-02-04 01:21:45 +0000420 }
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000421
Alexey Samsonov3514f272015-05-07 01:00:31 +0000422 if (Options.Use8bitCounters) {
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000423 IRB.SetInsertPoint(IP);
424 Value *P = IRB.CreateAdd(
425 IRB.CreatePointerCast(EightBitCounterArray, IntptrTy),
Kostya Serebryany48a40232015-03-10 01:58:27 +0000426 ConstantInt::get(IntptrTy, NumberOfInstrumentedBlocks() - 1));
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000427 P = IRB.CreateIntToPtr(P, IRB.getInt8PtrTy());
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000428 LoadInst *LI = IRB.CreateLoad(P);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000429 Value *Inc = IRB.CreateAdd(LI, ConstantInt::get(IRB.getInt8Ty(), 1));
Kostya Serebryany83ce8772015-03-05 01:20:05 +0000430 StoreInst *SI = IRB.CreateStore(Inc, P);
Alexey Samsonov0a648a42015-05-06 21:35:25 +0000431 SetNoSanitizeMetadata(LI);
432 SetNoSanitizeMetadata(SI);
Kostya Serebryanybe5e0ed2015-03-03 23:27:02 +0000433 }
434
Alexey Samsonov3514f272015-05-07 01:00:31 +0000435 if (Options.TraceBB) {
Kostya Serebryanyd421db02015-01-03 00:54:43 +0000436 // Experimental support for tracing.
437 // Insert a callback with the same guard variable as used for coverage.
438 IRB.SetInsertPoint(IP);
439 IRB.CreateCall(IsEntryBB ? SanCovTraceEnter : SanCovTraceBB, GuardP);
440 }
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000441}
442
443char SanitizerCoverageModule::ID = 0;
444INITIALIZE_PASS(SanitizerCoverageModule, "sancov",
445 "SanitizerCoverage: TODO."
446 "ModulePass", false, false)
Alexey Samsonov3514f272015-05-07 01:00:31 +0000447ModulePass *llvm::createSanitizerCoverageModulePass(
448 const SanitizerCoverageOptions &Options) {
449 return new SanitizerCoverageModule(Options);
Kostya Serebryany29a18dc2014-11-11 22:14:37 +0000450}