blob: eeb314d74aded7136aeb2e0f36748545b18aad80 [file] [log] [blame]
Derek Brueningd862c172016-04-21 21:30:22 +00001//===-- EfficiencySanitizer.cpp - performance tuner -----------------------===//
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// This file is a part of EfficiencySanitizer, a family of performance tuners
11// that detects multiple performance issues via separate sub-tools.
12//
13// The instrumentation phase is straightforward:
14// - Take action on every memory access: either inlined instrumentation,
15// or Inserted calls to our run-time library.
16// - Optimizations may apply to avoid instrumenting some of the accesses.
17// - Turn mem{set,cpy,move} instrinsics into library calls.
18// The rest is handled by the run-time library.
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Transforms/Instrumentation.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/ADT/StringExtras.h"
Marcin Koscielnicki3feda222016-06-18 10:10:37 +000026#include "llvm/Analysis/TargetLibraryInfo.h"
Derek Brueningd862c172016-04-21 21:30:22 +000027#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/IntrinsicInst.h"
30#include "llvm/IR/Module.h"
31#include "llvm/IR/Type.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Qin Zhao6d3bd682016-06-02 17:30:47 +000034#include "llvm/Support/raw_ostream.h"
Derek Brueningd862c172016-04-21 21:30:22 +000035#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Marcin Koscielnicki3feda222016-06-18 10:10:37 +000036#include "llvm/Transforms/Utils/Local.h"
Derek Brueningd862c172016-04-21 21:30:22 +000037#include "llvm/Transforms/Utils/ModuleUtils.h"
38
39using namespace llvm;
40
41#define DEBUG_TYPE "esan"
42
43// The tool type must be just one of these ClTool* options, as the tools
44// cannot be combined due to shadow memory constraints.
45static cl::opt<bool>
46 ClToolCacheFrag("esan-cache-frag", cl::init(false),
47 cl::desc("Detect data cache fragmentation"), cl::Hidden);
Derek Bruening5662b932016-05-25 00:17:24 +000048static cl::opt<bool>
49 ClToolWorkingSet("esan-working-set", cl::init(false),
50 cl::desc("Measure the working set size"), cl::Hidden);
Derek Brueningd862c172016-04-21 21:30:22 +000051// Each new tool will get its own opt flag here.
52// These are converted to EfficiencySanitizerOptions for use
53// in the code.
54
55static cl::opt<bool> ClInstrumentLoadsAndStores(
56 "esan-instrument-loads-and-stores", cl::init(true),
57 cl::desc("Instrument loads and stores"), cl::Hidden);
58static cl::opt<bool> ClInstrumentMemIntrinsics(
59 "esan-instrument-memintrinsics", cl::init(true),
60 cl::desc("Instrument memintrinsics (memset/memcpy/memmove)"), cl::Hidden);
Qin Zhaod677d882016-06-10 00:48:53 +000061static cl::opt<bool> ClInstrumentFastpath(
62 "esan-instrument-fastpath", cl::init(true),
63 cl::desc("Instrument fastpath"), cl::Hidden);
Derek Brueningd862c172016-04-21 21:30:22 +000064
Derek Bruening9ef57722016-06-03 22:29:52 +000065// Experiments show that the performance difference can be 2x or more,
66// and accuracy loss is typically negligible, so we turn this on by default.
67static cl::opt<bool> ClAssumeIntraCacheLine(
68 "esan-assume-intra-cache-line", cl::init(true),
69 cl::desc("Assume each memory access touches just one cache line, for "
70 "better performance but with a potential loss of accuracy."),
71 cl::Hidden);
72
Derek Brueningd862c172016-04-21 21:30:22 +000073STATISTIC(NumInstrumentedLoads, "Number of instrumented loads");
74STATISTIC(NumInstrumentedStores, "Number of instrumented stores");
75STATISTIC(NumFastpaths, "Number of instrumented fastpaths");
76STATISTIC(NumAccessesWithIrregularSize,
77 "Number of accesses with a size outside our targeted callout sizes");
Qin Zhao6d3bd682016-06-02 17:30:47 +000078STATISTIC(NumIgnoredStructs, "Number of ignored structs");
Qin Zhaoc14c2492016-06-03 02:33:04 +000079STATISTIC(NumIgnoredGEPs, "Number of ignored GEP instructions");
80STATISTIC(NumInstrumentedGEPs, "Number of instrumented GEP instructions");
Derek Bruening9ef57722016-06-03 22:29:52 +000081STATISTIC(NumAssumedIntraCacheLine,
82 "Number of accesses assumed to be intra-cache-line");
Derek Brueningd862c172016-04-21 21:30:22 +000083
Derek Bruening0b872d92016-05-24 22:48:24 +000084static const uint64_t EsanCtorAndDtorPriority = 0;
Derek Brueningd862c172016-04-21 21:30:22 +000085static const char *const EsanModuleCtorName = "esan.module_ctor";
Derek Bruening0b872d92016-05-24 22:48:24 +000086static const char *const EsanModuleDtorName = "esan.module_dtor";
Derek Brueningd862c172016-04-21 21:30:22 +000087static const char *const EsanInitName = "__esan_init";
Derek Bruening0b872d92016-05-24 22:48:24 +000088static const char *const EsanExitName = "__esan_exit";
Derek Brueningd862c172016-04-21 21:30:22 +000089
Derek Bruening4252a162016-06-03 19:40:37 +000090// We need to specify the tool to the runtime earlier than
91// the ctor is called in some cases, so we set a global variable.
92static const char *const EsanWhichToolName = "__esan_which_tool";
93
Derek Bruening5662b932016-05-25 00:17:24 +000094// We must keep these Shadow* constants consistent with the esan runtime.
95// FIXME: Try to place these shadow constants, the names of the __esan_*
96// interface functions, and the ToolType enum into a header shared between
97// llvm and compiler-rt.
98static const uint64_t ShadowMask = 0x00000fffffffffffull;
99static const uint64_t ShadowOffs[3] = { // Indexed by scale
100 0x0000130000000000ull,
101 0x0000220000000000ull,
102 0x0000440000000000ull,
103};
104// This array is indexed by the ToolType enum.
105static const int ShadowScale[] = {
106 0, // ESAN_None.
107 2, // ESAN_CacheFrag: 4B:1B, so 4 to 1 == >>2.
108 6, // ESAN_WorkingSet: 64B:1B, so 64 to 1 == >>6.
109};
110
Qin Zhao6d3bd682016-06-02 17:30:47 +0000111// MaxStructCounterNameSize is a soft size limit to avoid insanely long
112// names for those extremely large structs.
113static const unsigned MaxStructCounterNameSize = 512;
114
Derek Brueningd862c172016-04-21 21:30:22 +0000115namespace {
116
117static EfficiencySanitizerOptions
118OverrideOptionsFromCL(EfficiencySanitizerOptions Options) {
119 if (ClToolCacheFrag)
120 Options.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
Derek Bruening5662b932016-05-25 00:17:24 +0000121 else if (ClToolWorkingSet)
122 Options.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
Derek Brueningd862c172016-04-21 21:30:22 +0000123
124 // Direct opt invocation with no params will have the default ESAN_None.
125 // We run the default tool in that case.
126 if (Options.ToolType == EfficiencySanitizerOptions::ESAN_None)
127 Options.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
128
129 return Options;
130}
131
Qin Zhao1762eef2016-05-31 17:14:02 +0000132// Create a constant for Str so that we can pass it to the run-time lib.
133static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
134 bool AllowMerging) {
135 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
136 // We use private linkage for module-local strings. If they can be merged
137 // with another one, we set the unnamed_addr attribute.
138 GlobalVariable *GV =
139 new GlobalVariable(M, StrConst->getType(), true,
140 GlobalValue::PrivateLinkage, StrConst, "");
141 if (AllowMerging)
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000142 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Qin Zhao1762eef2016-05-31 17:14:02 +0000143 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
144 return GV;
145}
146
Derek Brueningd862c172016-04-21 21:30:22 +0000147/// EfficiencySanitizer: instrument each module to find performance issues.
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000148class EfficiencySanitizer : public ModulePass {
Derek Brueningd862c172016-04-21 21:30:22 +0000149public:
150 EfficiencySanitizer(
151 const EfficiencySanitizerOptions &Opts = EfficiencySanitizerOptions())
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000152 : ModulePass(ID), Options(OverrideOptionsFromCL(Opts)) {}
Derek Brueningd862c172016-04-21 21:30:22 +0000153 const char *getPassName() const override;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000154 void getAnalysisUsage(AnalysisUsage &AU) const override;
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000155 bool runOnModule(Module &M) override;
Derek Brueningd862c172016-04-21 21:30:22 +0000156 static char ID;
157
158private:
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000159 bool initOnModule(Module &M);
Derek Brueningd862c172016-04-21 21:30:22 +0000160 void initializeCallbacks(Module &M);
Qin Zhao6d3bd682016-06-02 17:30:47 +0000161 bool shouldIgnoreStructType(StructType *StructTy);
162 void createStructCounterName(
163 StructType *StructTy, SmallString<MaxStructCounterNameSize> &NameStr);
Qin Zhao0b96aa72016-06-10 02:10:06 +0000164 GlobalVariable *createCacheFragInfoGV(Module &M, const DataLayout &DL,
165 Constant *UnitName);
166 Constant *createEsanInitToolInfoArg(Module &M, const DataLayout &DL);
Qin Zhao1762eef2016-05-31 17:14:02 +0000167 void createDestructor(Module &M, Constant *ToolInfoArg);
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000168 bool runOnFunction(Function &F, Module &M);
Derek Brueningd862c172016-04-21 21:30:22 +0000169 bool instrumentLoadOrStore(Instruction *I, const DataLayout &DL);
170 bool instrumentMemIntrinsic(MemIntrinsic *MI);
Qin Zhaoc14c2492016-06-03 02:33:04 +0000171 bool instrumentGetElementPtr(Instruction *I, Module &M);
Derek Brueningd862c172016-04-21 21:30:22 +0000172 bool shouldIgnoreMemoryAccess(Instruction *I);
173 int getMemoryAccessFuncIndex(Value *Addr, const DataLayout &DL);
Derek Bruening5662b932016-05-25 00:17:24 +0000174 Value *appToShadow(Value *Shadow, IRBuilder<> &IRB);
Derek Brueningd862c172016-04-21 21:30:22 +0000175 bool instrumentFastpath(Instruction *I, const DataLayout &DL, bool IsStore,
176 Value *Addr, unsigned Alignment);
177 // Each tool has its own fastpath routine:
178 bool instrumentFastpathCacheFrag(Instruction *I, const DataLayout &DL,
179 Value *Addr, unsigned Alignment);
Derek Bruening5662b932016-05-25 00:17:24 +0000180 bool instrumentFastpathWorkingSet(Instruction *I, const DataLayout &DL,
181 Value *Addr, unsigned Alignment);
Derek Brueningd862c172016-04-21 21:30:22 +0000182
183 EfficiencySanitizerOptions Options;
184 LLVMContext *Ctx;
185 Type *IntptrTy;
186 // Our slowpath involves callouts to the runtime library.
187 // Access sizes are powers of two: 1, 2, 4, 8, 16.
188 static const size_t NumberOfAccessSizes = 5;
189 Function *EsanAlignedLoad[NumberOfAccessSizes];
190 Function *EsanAlignedStore[NumberOfAccessSizes];
191 Function *EsanUnalignedLoad[NumberOfAccessSizes];
192 Function *EsanUnalignedStore[NumberOfAccessSizes];
193 // For irregular sizes of any alignment:
194 Function *EsanUnalignedLoadN, *EsanUnalignedStoreN;
195 Function *MemmoveFn, *MemcpyFn, *MemsetFn;
196 Function *EsanCtorFunction;
Derek Bruening0b872d92016-05-24 22:48:24 +0000197 Function *EsanDtorFunction;
Qin Zhaoc14c2492016-06-03 02:33:04 +0000198 // Remember the counter variable for each struct type to avoid
199 // recomputing the variable name later during instrumentation.
200 std::map<Type *, GlobalVariable *> StructTyMap;
Derek Brueningd862c172016-04-21 21:30:22 +0000201};
202} // namespace
203
204char EfficiencySanitizer::ID = 0;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000205INITIALIZE_PASS_BEGIN(
206 EfficiencySanitizer, "esan",
207 "EfficiencySanitizer: finds performance issues.", false, false)
208INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
209INITIALIZE_PASS_END(
210 EfficiencySanitizer, "esan",
211 "EfficiencySanitizer: finds performance issues.", false, false)
Derek Brueningd862c172016-04-21 21:30:22 +0000212
213const char *EfficiencySanitizer::getPassName() const {
214 return "EfficiencySanitizer";
215}
216
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000217void EfficiencySanitizer::getAnalysisUsage(AnalysisUsage &AU) const {
218 AU.addRequired<TargetLibraryInfoWrapperPass>();
219}
220
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000221ModulePass *
Derek Brueningd862c172016-04-21 21:30:22 +0000222llvm::createEfficiencySanitizerPass(const EfficiencySanitizerOptions &Options) {
223 return new EfficiencySanitizer(Options);
224}
225
226void EfficiencySanitizer::initializeCallbacks(Module &M) {
227 IRBuilder<> IRB(M.getContext());
228 // Initialize the callbacks.
229 for (size_t Idx = 0; Idx < NumberOfAccessSizes; ++Idx) {
230 const unsigned ByteSize = 1U << Idx;
231 std::string ByteSizeStr = utostr(ByteSize);
232 // We'll inline the most common (i.e., aligned and frequent sizes)
233 // load + store instrumentation: these callouts are for the slowpath.
234 SmallString<32> AlignedLoadName("__esan_aligned_load" + ByteSizeStr);
235 EsanAlignedLoad[Idx] =
236 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
237 AlignedLoadName, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
238 SmallString<32> AlignedStoreName("__esan_aligned_store" + ByteSizeStr);
239 EsanAlignedStore[Idx] =
240 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
241 AlignedStoreName, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
242 SmallString<32> UnalignedLoadName("__esan_unaligned_load" + ByteSizeStr);
243 EsanUnalignedLoad[Idx] =
244 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
245 UnalignedLoadName, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
246 SmallString<32> UnalignedStoreName("__esan_unaligned_store" + ByteSizeStr);
247 EsanUnalignedStore[Idx] =
248 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
249 UnalignedStoreName, IRB.getVoidTy(), IRB.getInt8PtrTy(), nullptr));
250 }
251 EsanUnalignedLoadN = checkSanitizerInterfaceFunction(
252 M.getOrInsertFunction("__esan_unaligned_loadN", IRB.getVoidTy(),
253 IRB.getInt8PtrTy(), IntptrTy, nullptr));
254 EsanUnalignedStoreN = checkSanitizerInterfaceFunction(
255 M.getOrInsertFunction("__esan_unaligned_storeN", IRB.getVoidTy(),
256 IRB.getInt8PtrTy(), IntptrTy, nullptr));
257 MemmoveFn = checkSanitizerInterfaceFunction(
258 M.getOrInsertFunction("memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
259 IRB.getInt8PtrTy(), IntptrTy, nullptr));
260 MemcpyFn = checkSanitizerInterfaceFunction(
261 M.getOrInsertFunction("memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
262 IRB.getInt8PtrTy(), IntptrTy, nullptr));
263 MemsetFn = checkSanitizerInterfaceFunction(
264 M.getOrInsertFunction("memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
265 IRB.getInt32Ty(), IntptrTy, nullptr));
266}
267
Qin Zhao6d3bd682016-06-02 17:30:47 +0000268bool EfficiencySanitizer::shouldIgnoreStructType(StructType *StructTy) {
269 if (StructTy == nullptr || StructTy->isOpaque() /* no struct body */)
270 return true;
271 return false;
272}
273
274void EfficiencySanitizer::createStructCounterName(
275 StructType *StructTy, SmallString<MaxStructCounterNameSize> &NameStr) {
276 // Append NumFields and field type ids to avoid struct conflicts
277 // with the same name but different fields.
278 if (StructTy->hasName())
279 NameStr += StructTy->getName();
280 else
281 NameStr += "struct.anon";
282 // We allow the actual size of the StructCounterName to be larger than
283 // MaxStructCounterNameSize and append #NumFields and at least one
284 // field type id.
285 // Append #NumFields.
286 NameStr += "#";
287 Twine(StructTy->getNumElements()).toVector(NameStr);
288 // Append struct field type ids in the reverse order.
289 for (int i = StructTy->getNumElements() - 1; i >= 0; --i) {
290 NameStr += "#";
291 Twine(StructTy->getElementType(i)->getTypeID()).toVector(NameStr);
292 if (NameStr.size() >= MaxStructCounterNameSize)
293 break;
294 }
295 if (StructTy->isLiteral()) {
296 // End with # for literal struct.
297 NameStr += "#";
298 }
299}
300
Qin Zhao1762eef2016-05-31 17:14:02 +0000301// Create the global variable for the cache-fragmentation tool.
302GlobalVariable *EfficiencySanitizer::createCacheFragInfoGV(
Qin Zhao0b96aa72016-06-10 02:10:06 +0000303 Module &M, const DataLayout &DL, Constant *UnitName) {
Qin Zhao1762eef2016-05-31 17:14:02 +0000304 assert(Options.ToolType == EfficiencySanitizerOptions::ESAN_CacheFrag);
305
306 auto *Int8PtrTy = Type::getInt8PtrTy(*Ctx);
307 auto *Int8PtrPtrTy = Int8PtrTy->getPointerTo();
308 auto *Int32Ty = Type::getInt32Ty(*Ctx);
Qin Zhao0b96aa72016-06-10 02:10:06 +0000309 auto *Int32PtrTy = Type::getInt32PtrTy(*Ctx);
Qin Zhao6d3bd682016-06-02 17:30:47 +0000310 auto *Int64Ty = Type::getInt64Ty(*Ctx);
Qin Zhao1762eef2016-05-31 17:14:02 +0000311 auto *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
312 // This structure should be kept consistent with the StructInfo struct
313 // in the runtime library.
314 // struct StructInfo {
315 // const char *StructName;
Qin Zhao0b96aa72016-06-10 02:10:06 +0000316 // u32 Size;
Qin Zhao6d3bd682016-06-02 17:30:47 +0000317 // u32 NumFields;
Qin Zhao0b96aa72016-06-10 02:10:06 +0000318 // u32 *FieldOffsets;
Qin Zhaobb4496f2016-06-17 04:50:20 +0000319 // u32 *FieldSize;
Qin Zhao1762eef2016-05-31 17:14:02 +0000320 // u64 *FieldCounters;
321 // const char **FieldTypeNames;
322 // };
323 auto *StructInfoTy =
Qin Zhaobb4496f2016-06-17 04:50:20 +0000324 StructType::get(Int8PtrTy, Int32Ty, Int32Ty, Int32PtrTy, Int32PtrTy,
325 Int64PtrTy, Int8PtrPtrTy, nullptr);
Qin Zhao1762eef2016-05-31 17:14:02 +0000326 auto *StructInfoPtrTy = StructInfoTy->getPointerTo();
327 // This structure should be kept consistent with the CacheFragInfo struct
328 // in the runtime library.
329 // struct CacheFragInfo {
330 // const char *UnitName;
Qin Zhao6d3bd682016-06-02 17:30:47 +0000331 // u32 NumStructs;
Qin Zhao1762eef2016-05-31 17:14:02 +0000332 // StructInfo *Structs;
333 // };
334 auto *CacheFragInfoTy =
335 StructType::get(Int8PtrTy, Int32Ty, StructInfoPtrTy, nullptr);
336
337 std::vector<StructType *> Vec = M.getIdentifiedStructTypes();
Qin Zhao6d3bd682016-06-02 17:30:47 +0000338 unsigned NumStructs = 0;
339 SmallVector<Constant *, 16> Initializers;
340
341 for (auto &StructTy : Vec) {
342 if (shouldIgnoreStructType(StructTy)) {
343 ++NumIgnoredStructs;
344 continue;
345 }
346 ++NumStructs;
347
348 // StructName.
349 SmallString<MaxStructCounterNameSize> CounterNameStr;
350 createStructCounterName(StructTy, CounterNameStr);
351 GlobalVariable *StructCounterName = createPrivateGlobalForString(
352 M, CounterNameStr, /*AllowMerging*/true);
353
354 // FieldCounters.
355 // We create the counter array with StructCounterName and weak linkage
356 // so that the structs with the same name and layout from different
357 // compilation units will be merged into one.
358 auto *CounterArrayTy = ArrayType::get(Int64Ty, StructTy->getNumElements());
359 GlobalVariable *Counters =
360 new GlobalVariable(M, CounterArrayTy, false,
361 GlobalVariable::WeakAnyLinkage,
362 ConstantAggregateZero::get(CounterArrayTy),
363 CounterNameStr);
364
Qin Zhaoc14c2492016-06-03 02:33:04 +0000365 // Remember the counter variable for each struct type.
366 StructTyMap.insert(std::pair<Type *, GlobalVariable *>(StructTy, Counters));
367
Qin Zhao0b96aa72016-06-10 02:10:06 +0000368 // We pass the field type name array and offset array to the runtime for
369 // better reporting.
Qin Zhao6d3bd682016-06-02 17:30:47 +0000370 // FieldTypeNames.
Qin Zhao6d3bd682016-06-02 17:30:47 +0000371 auto *TypeNameArrayTy = ArrayType::get(Int8PtrTy, StructTy->getNumElements());
Qin Zhao0b96aa72016-06-10 02:10:06 +0000372 GlobalVariable *TypeNames =
Qin Zhao6d3bd682016-06-02 17:30:47 +0000373 new GlobalVariable(M, TypeNameArrayTy, true,
374 GlobalVariable::InternalLinkage, nullptr);
375 SmallVector<Constant *, 16> TypeNameVec;
Qin Zhao0b96aa72016-06-10 02:10:06 +0000376 // FieldOffsets.
377 const StructLayout *SL = DL.getStructLayout(StructTy);
378 auto *OffsetArrayTy = ArrayType::get(Int32Ty, StructTy->getNumElements());
379 GlobalVariable *Offsets =
380 new GlobalVariable(M, OffsetArrayTy, true,
381 GlobalVariable::InternalLinkage, nullptr);
382 SmallVector<Constant *, 16> OffsetVec;
Qin Zhaobb4496f2016-06-17 04:50:20 +0000383 // FieldSize
384 auto *SizeArrayTy = ArrayType::get(Int32Ty, StructTy->getNumElements());
385 GlobalVariable *Size =
386 new GlobalVariable(M, SizeArrayTy, true,
387 GlobalVariable::InternalLinkage, nullptr);
388 SmallVector<Constant *, 16> SizeVec;
Qin Zhao6d3bd682016-06-02 17:30:47 +0000389 for (unsigned i = 0; i < StructTy->getNumElements(); ++i) {
390 Type *Ty = StructTy->getElementType(i);
391 std::string Str;
392 raw_string_ostream StrOS(Str);
393 Ty->print(StrOS);
394 TypeNameVec.push_back(
395 ConstantExpr::getPointerCast(
396 createPrivateGlobalForString(M, StrOS.str(), true),
397 Int8PtrTy));
Qin Zhao0b96aa72016-06-10 02:10:06 +0000398 OffsetVec.push_back(ConstantInt::get(Int32Ty, SL->getElementOffset(i)));
Qin Zhaobb4496f2016-06-17 04:50:20 +0000399 SizeVec.push_back(ConstantInt::get(Int32Ty,
400 DL.getTypeAllocSize(Ty)));
Qin Zhao6d3bd682016-06-02 17:30:47 +0000401 }
Qin Zhao0b96aa72016-06-10 02:10:06 +0000402 TypeNames->setInitializer(ConstantArray::get(TypeNameArrayTy, TypeNameVec));
403 Offsets->setInitializer(ConstantArray::get(OffsetArrayTy, OffsetVec));
Qin Zhaobb4496f2016-06-17 04:50:20 +0000404 Size->setInitializer(ConstantArray::get(SizeArrayTy, SizeVec));
Qin Zhao6d3bd682016-06-02 17:30:47 +0000405
406 Initializers.push_back(
407 ConstantStruct::get(
408 StructInfoTy,
409 ConstantExpr::getPointerCast(StructCounterName, Int8PtrTy),
Qin Zhao0b96aa72016-06-10 02:10:06 +0000410 ConstantInt::get(Int32Ty, SL->getSizeInBytes()),
Qin Zhao6d3bd682016-06-02 17:30:47 +0000411 ConstantInt::get(Int32Ty, StructTy->getNumElements()),
Qin Zhao0b96aa72016-06-10 02:10:06 +0000412 ConstantExpr::getPointerCast(Offsets, Int32PtrTy),
Qin Zhaobb4496f2016-06-17 04:50:20 +0000413 ConstantExpr::getPointerCast(Size, Int32PtrTy),
Qin Zhao6d3bd682016-06-02 17:30:47 +0000414 ConstantExpr::getPointerCast(Counters, Int64PtrTy),
Qin Zhao0b96aa72016-06-10 02:10:06 +0000415 ConstantExpr::getPointerCast(TypeNames, Int8PtrPtrTy),
Qin Zhao6d3bd682016-06-02 17:30:47 +0000416 nullptr));
417 }
418 // Structs.
419 Constant *StructInfo;
420 if (NumStructs == 0) {
421 StructInfo = ConstantPointerNull::get(StructInfoPtrTy);
422 } else {
423 auto *StructInfoArrayTy = ArrayType::get(StructInfoTy, NumStructs);
424 StructInfo = ConstantExpr::getPointerCast(
425 new GlobalVariable(M, StructInfoArrayTy, false,
426 GlobalVariable::InternalLinkage,
427 ConstantArray::get(StructInfoArrayTy, Initializers)),
428 StructInfoPtrTy);
429 }
430
Qin Zhao1762eef2016-05-31 17:14:02 +0000431 auto *CacheFragInfoGV = new GlobalVariable(
432 M, CacheFragInfoTy, true, GlobalVariable::InternalLinkage,
433 ConstantStruct::get(CacheFragInfoTy,
434 UnitName,
Qin Zhao6d3bd682016-06-02 17:30:47 +0000435 ConstantInt::get(Int32Ty, NumStructs),
436 StructInfo,
Qin Zhao1762eef2016-05-31 17:14:02 +0000437 nullptr));
438 return CacheFragInfoGV;
Derek Bruening0b872d92016-05-24 22:48:24 +0000439}
440
Qin Zhao1762eef2016-05-31 17:14:02 +0000441// Create the tool-specific argument passed to EsanInit and EsanExit.
Qin Zhao0b96aa72016-06-10 02:10:06 +0000442Constant *EfficiencySanitizer::createEsanInitToolInfoArg(Module &M,
443 const DataLayout &DL) {
Qin Zhao1762eef2016-05-31 17:14:02 +0000444 // This structure contains tool-specific information about each compilation
445 // unit (module) and is passed to the runtime library.
446 GlobalVariable *ToolInfoGV = nullptr;
447
448 auto *Int8PtrTy = Type::getInt8PtrTy(*Ctx);
449 // Compilation unit name.
450 auto *UnitName = ConstantExpr::getPointerCast(
451 createPrivateGlobalForString(M, M.getModuleIdentifier(), true),
452 Int8PtrTy);
453
454 // Create the tool-specific variable.
455 if (Options.ToolType == EfficiencySanitizerOptions::ESAN_CacheFrag)
Qin Zhao0b96aa72016-06-10 02:10:06 +0000456 ToolInfoGV = createCacheFragInfoGV(M, DL, UnitName);
Qin Zhao1762eef2016-05-31 17:14:02 +0000457
458 if (ToolInfoGV != nullptr)
459 return ConstantExpr::getPointerCast(ToolInfoGV, Int8PtrTy);
460
461 // Create the null pointer if no tool-specific variable created.
462 return ConstantPointerNull::get(Int8PtrTy);
463}
464
465void EfficiencySanitizer::createDestructor(Module &M, Constant *ToolInfoArg) {
466 PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx);
Derek Bruening0b872d92016-05-24 22:48:24 +0000467 EsanDtorFunction = Function::Create(FunctionType::get(Type::getVoidTy(*Ctx),
468 false),
469 GlobalValue::InternalLinkage,
470 EsanModuleDtorName, &M);
471 ReturnInst::Create(*Ctx, BasicBlock::Create(*Ctx, "", EsanDtorFunction));
472 IRBuilder<> IRB_Dtor(EsanDtorFunction->getEntryBlock().getTerminator());
473 Function *EsanExit = checkSanitizerInterfaceFunction(
474 M.getOrInsertFunction(EsanExitName, IRB_Dtor.getVoidTy(),
Qin Zhao1762eef2016-05-31 17:14:02 +0000475 Int8PtrTy, nullptr));
Derek Bruening0b872d92016-05-24 22:48:24 +0000476 EsanExit->setLinkage(Function::ExternalLinkage);
Qin Zhao1762eef2016-05-31 17:14:02 +0000477 IRB_Dtor.CreateCall(EsanExit, {ToolInfoArg});
Derek Bruening0b872d92016-05-24 22:48:24 +0000478 appendToGlobalDtors(M, EsanDtorFunction, EsanCtorAndDtorPriority);
479}
480
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000481bool EfficiencySanitizer::initOnModule(Module &M) {
Derek Brueningd862c172016-04-21 21:30:22 +0000482 Ctx = &M.getContext();
483 const DataLayout &DL = M.getDataLayout();
484 IRBuilder<> IRB(M.getContext());
485 IntegerType *OrdTy = IRB.getInt32Ty();
Qin Zhao1762eef2016-05-31 17:14:02 +0000486 PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx);
Derek Brueningd862c172016-04-21 21:30:22 +0000487 IntptrTy = DL.getIntPtrType(M.getContext());
Derek Bruening0b872d92016-05-24 22:48:24 +0000488 // Create the variable passed to EsanInit and EsanExit.
Qin Zhao0b96aa72016-06-10 02:10:06 +0000489 Constant *ToolInfoArg = createEsanInitToolInfoArg(M, DL);
Derek Bruening0b872d92016-05-24 22:48:24 +0000490 // Constructor
Derek Bruening4252a162016-06-03 19:40:37 +0000491 // We specify the tool type both in the EsanWhichToolName global
492 // and as an arg to the init routine as a sanity check.
Derek Brueningd862c172016-04-21 21:30:22 +0000493 std::tie(EsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
Qin Zhao1762eef2016-05-31 17:14:02 +0000494 M, EsanModuleCtorName, EsanInitName, /*InitArgTypes=*/{OrdTy, Int8PtrTy},
Derek Brueningd862c172016-04-21 21:30:22 +0000495 /*InitArgs=*/{
Derek Bruening0b872d92016-05-24 22:48:24 +0000496 ConstantInt::get(OrdTy, static_cast<int>(Options.ToolType)),
Qin Zhao1762eef2016-05-31 17:14:02 +0000497 ToolInfoArg});
Derek Bruening0b872d92016-05-24 22:48:24 +0000498 appendToGlobalCtors(M, EsanCtorFunction, EsanCtorAndDtorPriority);
Derek Brueningd862c172016-04-21 21:30:22 +0000499
Qin Zhao1762eef2016-05-31 17:14:02 +0000500 createDestructor(M, ToolInfoArg);
Derek Bruening4252a162016-06-03 19:40:37 +0000501
502 new GlobalVariable(M, OrdTy, true,
503 GlobalValue::WeakAnyLinkage,
504 ConstantInt::get(OrdTy,
505 static_cast<int>(Options.ToolType)),
506 EsanWhichToolName);
507
Derek Brueningd862c172016-04-21 21:30:22 +0000508 return true;
509}
510
Derek Bruening5662b932016-05-25 00:17:24 +0000511Value *EfficiencySanitizer::appToShadow(Value *Shadow, IRBuilder<> &IRB) {
512 // Shadow = ((App & Mask) + Offs) >> Scale
513 Shadow = IRB.CreateAnd(Shadow, ConstantInt::get(IntptrTy, ShadowMask));
514 uint64_t Offs;
515 int Scale = ShadowScale[Options.ToolType];
516 if (Scale <= 2)
517 Offs = ShadowOffs[Scale];
518 else
519 Offs = ShadowOffs[0] << Scale;
520 Shadow = IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Offs));
521 if (Scale > 0)
522 Shadow = IRB.CreateLShr(Shadow, Scale);
523 return Shadow;
524}
525
Derek Brueningd862c172016-04-21 21:30:22 +0000526bool EfficiencySanitizer::shouldIgnoreMemoryAccess(Instruction *I) {
527 if (Options.ToolType == EfficiencySanitizerOptions::ESAN_CacheFrag) {
528 // We'd like to know about cache fragmentation in vtable accesses and
529 // constant data references, so we do not currently ignore anything.
530 return false;
Derek Bruening5662b932016-05-25 00:17:24 +0000531 } else if (Options.ToolType == EfficiencySanitizerOptions::ESAN_WorkingSet) {
532 // TODO: the instrumentation disturbs the data layout on the stack, so we
533 // may want to add an option to ignore stack references (if we can
534 // distinguish them) to reduce overhead.
Derek Brueningd862c172016-04-21 21:30:22 +0000535 }
536 // TODO(bruening): future tools will be returning true for some cases.
537 return false;
538}
539
Derek Brueningbc0a68e2016-05-20 20:00:05 +0000540bool EfficiencySanitizer::runOnModule(Module &M) {
541 bool Res = initOnModule(M);
542 initializeCallbacks(M);
543 for (auto &F : M) {
544 Res |= runOnFunction(F, M);
545 }
546 return Res;
547}
548
549bool EfficiencySanitizer::runOnFunction(Function &F, Module &M) {
Derek Brueningd862c172016-04-21 21:30:22 +0000550 // This is required to prevent instrumenting the call to __esan_init from
551 // within the module constructor.
552 if (&F == EsanCtorFunction)
553 return false;
Derek Brueningd862c172016-04-21 21:30:22 +0000554 SmallVector<Instruction *, 8> LoadsAndStores;
555 SmallVector<Instruction *, 8> MemIntrinCalls;
Qin Zhaoc14c2492016-06-03 02:33:04 +0000556 SmallVector<Instruction *, 8> GetElementPtrs;
Derek Brueningd862c172016-04-21 21:30:22 +0000557 bool Res = false;
Derek Bruening0b872d92016-05-24 22:48:24 +0000558 const DataLayout &DL = M.getDataLayout();
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000559 const TargetLibraryInfo *TLI =
560 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Derek Brueningd862c172016-04-21 21:30:22 +0000561
562 for (auto &BB : F) {
563 for (auto &Inst : BB) {
564 if ((isa<LoadInst>(Inst) || isa<StoreInst>(Inst) ||
565 isa<AtomicRMWInst>(Inst) || isa<AtomicCmpXchgInst>(Inst)) &&
566 !shouldIgnoreMemoryAccess(&Inst))
567 LoadsAndStores.push_back(&Inst);
568 else if (isa<MemIntrinsic>(Inst))
569 MemIntrinCalls.push_back(&Inst);
Qin Zhaoc14c2492016-06-03 02:33:04 +0000570 else if (isa<GetElementPtrInst>(Inst))
571 GetElementPtrs.push_back(&Inst);
Marcin Koscielnicki3feda222016-06-18 10:10:37 +0000572 else if (CallInst *CI = dyn_cast<CallInst>(&Inst))
573 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Derek Brueningd862c172016-04-21 21:30:22 +0000574 }
575 }
576
577 if (ClInstrumentLoadsAndStores) {
578 for (auto Inst : LoadsAndStores) {
579 Res |= instrumentLoadOrStore(Inst, DL);
580 }
581 }
582
583 if (ClInstrumentMemIntrinsics) {
584 for (auto Inst : MemIntrinCalls) {
585 Res |= instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
586 }
587 }
588
Qin Zhaoc14c2492016-06-03 02:33:04 +0000589 if (Options.ToolType == EfficiencySanitizerOptions::ESAN_CacheFrag) {
590 for (auto Inst : GetElementPtrs) {
591 Res |= instrumentGetElementPtr(Inst, M);
592 }
593 }
594
Derek Brueningd862c172016-04-21 21:30:22 +0000595 return Res;
596}
597
598bool EfficiencySanitizer::instrumentLoadOrStore(Instruction *I,
599 const DataLayout &DL) {
600 IRBuilder<> IRB(I);
601 bool IsStore;
602 Value *Addr;
603 unsigned Alignment;
604 if (LoadInst *Load = dyn_cast<LoadInst>(I)) {
605 IsStore = false;
606 Alignment = Load->getAlignment();
607 Addr = Load->getPointerOperand();
608 } else if (StoreInst *Store = dyn_cast<StoreInst>(I)) {
609 IsStore = true;
610 Alignment = Store->getAlignment();
611 Addr = Store->getPointerOperand();
612 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
613 IsStore = true;
614 Alignment = 0;
615 Addr = RMW->getPointerOperand();
616 } else if (AtomicCmpXchgInst *Xchg = dyn_cast<AtomicCmpXchgInst>(I)) {
617 IsStore = true;
618 Alignment = 0;
619 Addr = Xchg->getPointerOperand();
620 } else
621 llvm_unreachable("Unsupported mem access type");
622
623 Type *OrigTy = cast<PointerType>(Addr->getType())->getElementType();
624 const uint32_t TypeSizeBytes = DL.getTypeStoreSizeInBits(OrigTy) / 8;
625 Value *OnAccessFunc = nullptr;
Derek Bruening5662b932016-05-25 00:17:24 +0000626
627 // Convert 0 to the default alignment.
628 if (Alignment == 0)
629 Alignment = DL.getPrefTypeAlignment(OrigTy);
630
Derek Brueningd862c172016-04-21 21:30:22 +0000631 if (IsStore)
632 NumInstrumentedStores++;
633 else
634 NumInstrumentedLoads++;
635 int Idx = getMemoryAccessFuncIndex(Addr, DL);
636 if (Idx < 0) {
637 OnAccessFunc = IsStore ? EsanUnalignedStoreN : EsanUnalignedLoadN;
638 IRB.CreateCall(OnAccessFunc,
639 {IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
640 ConstantInt::get(IntptrTy, TypeSizeBytes)});
641 } else {
Qin Zhaod677d882016-06-10 00:48:53 +0000642 if (ClInstrumentFastpath &&
643 instrumentFastpath(I, DL, IsStore, Addr, Alignment)) {
Derek Brueningd862c172016-04-21 21:30:22 +0000644 NumFastpaths++;
645 return true;
646 }
647 if (Alignment == 0 || Alignment >= 8 || (Alignment % TypeSizeBytes) == 0)
648 OnAccessFunc = IsStore ? EsanAlignedStore[Idx] : EsanAlignedLoad[Idx];
649 else
650 OnAccessFunc = IsStore ? EsanUnalignedStore[Idx] : EsanUnalignedLoad[Idx];
651 IRB.CreateCall(OnAccessFunc,
652 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()));
653 }
654 return true;
655}
656
657// It's simplest to replace the memset/memmove/memcpy intrinsics with
658// calls that the runtime library intercepts.
659// Our pass is late enough that calls should not turn back into intrinsics.
660bool EfficiencySanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
661 IRBuilder<> IRB(MI);
662 bool Res = false;
663 if (isa<MemSetInst>(MI)) {
664 IRB.CreateCall(
665 MemsetFn,
666 {IRB.CreatePointerCast(MI->getArgOperand(0), IRB.getInt8PtrTy()),
667 IRB.CreateIntCast(MI->getArgOperand(1), IRB.getInt32Ty(), false),
668 IRB.CreateIntCast(MI->getArgOperand(2), IntptrTy, false)});
669 MI->eraseFromParent();
670 Res = true;
671 } else if (isa<MemTransferInst>(MI)) {
672 IRB.CreateCall(
673 isa<MemCpyInst>(MI) ? MemcpyFn : MemmoveFn,
674 {IRB.CreatePointerCast(MI->getArgOperand(0), IRB.getInt8PtrTy()),
675 IRB.CreatePointerCast(MI->getArgOperand(1), IRB.getInt8PtrTy()),
676 IRB.CreateIntCast(MI->getArgOperand(2), IntptrTy, false)});
677 MI->eraseFromParent();
678 Res = true;
679 } else
680 llvm_unreachable("Unsupported mem intrinsic type");
681 return Res;
682}
683
Qin Zhaoc14c2492016-06-03 02:33:04 +0000684bool EfficiencySanitizer::instrumentGetElementPtr(Instruction *I, Module &M) {
685 GetElementPtrInst *GepInst = dyn_cast<GetElementPtrInst>(I);
Qin Zhaobc8fbea2016-06-10 22:28:55 +0000686 bool Res = false;
687 if (GepInst == nullptr || GepInst->getNumIndices() == 1) {
Qin Zhaoc14c2492016-06-03 02:33:04 +0000688 ++NumIgnoredGEPs;
689 return false;
690 }
Qin Zhaobc8fbea2016-06-10 22:28:55 +0000691 Type *SourceTy = GepInst->getSourceElementType();
692 // Iterate all (except the first and the last) idx within each GEP instruction
693 // for possible nested struct field address calculation.
694 for (unsigned i = 1; i < GepInst->getNumIndices(); ++i) {
695 SmallVector<Value *, 8> IdxVec(GepInst->idx_begin(),
696 GepInst->idx_begin() + i);
697 StructType *StructTy = dyn_cast<StructType>(
698 GetElementPtrInst::getIndexedType(SourceTy, IdxVec));
699 if (StructTy == nullptr || shouldIgnoreStructType(StructTy) ||
700 StructTyMap.count(StructTy) == 0)
701 continue;
702 // Get the StructTy's subfield index.
703 ConstantInt *Idx = dyn_cast<ConstantInt>(GepInst->getOperand(i+1));
704 if (Idx == nullptr || Idx->getZExtValue() > StructTy->getNumElements())
705 continue;
706 GlobalVariable *CounterArray = StructTyMap[StructTy];
707 if (CounterArray == nullptr)
708 return false;
709 IRBuilder<> IRB(I);
710 Constant *Indices[2];
711 // Xref http://llvm.org/docs/LangRef.html#i-getelementptr and
712 // http://llvm.org/docs/GetElementPtr.html.
713 // The first index of the GEP instruction steps through the first operand,
714 // i.e., the array itself.
715 Indices[0] = ConstantInt::get(IRB.getInt32Ty(), 0);
716 // The second index is the index within the array.
717 Indices[1] = ConstantInt::get(IRB.getInt32Ty(), Idx->getZExtValue());
718 Constant *Counter =
719 ConstantExpr::getGetElementPtr(
720 ArrayType::get(IRB.getInt64Ty(), StructTy->getNumElements()),
721 CounterArray, Indices);
722 Value *Load = IRB.CreateLoad(Counter);
723 IRB.CreateStore(IRB.CreateAdd(Load, ConstantInt::get(IRB.getInt64Ty(), 1)),
724 Counter);
725 Res = true;
Qin Zhaoc14c2492016-06-03 02:33:04 +0000726 }
Qin Zhaobc8fbea2016-06-10 22:28:55 +0000727 if (Res)
728 ++NumInstrumentedGEPs;
729 else
730 ++NumIgnoredGEPs;
731 return Res;
Qin Zhaoc14c2492016-06-03 02:33:04 +0000732}
733
Derek Brueningd862c172016-04-21 21:30:22 +0000734int EfficiencySanitizer::getMemoryAccessFuncIndex(Value *Addr,
735 const DataLayout &DL) {
736 Type *OrigPtrTy = Addr->getType();
737 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
738 assert(OrigTy->isSized());
739 // The size is always a multiple of 8.
740 uint32_t TypeSizeBytes = DL.getTypeStoreSizeInBits(OrigTy) / 8;
741 if (TypeSizeBytes != 1 && TypeSizeBytes != 2 && TypeSizeBytes != 4 &&
742 TypeSizeBytes != 8 && TypeSizeBytes != 16) {
743 // Irregular sizes do not have per-size call targets.
744 NumAccessesWithIrregularSize++;
745 return -1;
746 }
747 size_t Idx = countTrailingZeros(TypeSizeBytes);
748 assert(Idx < NumberOfAccessSizes);
749 return Idx;
750}
751
752bool EfficiencySanitizer::instrumentFastpath(Instruction *I,
753 const DataLayout &DL, bool IsStore,
754 Value *Addr, unsigned Alignment) {
755 if (Options.ToolType == EfficiencySanitizerOptions::ESAN_CacheFrag) {
756 return instrumentFastpathCacheFrag(I, DL, Addr, Alignment);
Derek Bruening5662b932016-05-25 00:17:24 +0000757 } else if (Options.ToolType == EfficiencySanitizerOptions::ESAN_WorkingSet) {
758 return instrumentFastpathWorkingSet(I, DL, Addr, Alignment);
Derek Brueningd862c172016-04-21 21:30:22 +0000759 }
760 return false;
761}
762
763bool EfficiencySanitizer::instrumentFastpathCacheFrag(Instruction *I,
764 const DataLayout &DL,
765 Value *Addr,
766 unsigned Alignment) {
Qin Zhaod677d882016-06-10 00:48:53 +0000767 // Do nothing.
768 return true; // Return true to avoid slowpath instrumentation.
Derek Brueningd862c172016-04-21 21:30:22 +0000769}
Derek Bruening5662b932016-05-25 00:17:24 +0000770
771bool EfficiencySanitizer::instrumentFastpathWorkingSet(
772 Instruction *I, const DataLayout &DL, Value *Addr, unsigned Alignment) {
773 assert(ShadowScale[Options.ToolType] == 6); // The code below assumes this
774 IRBuilder<> IRB(I);
775 Type *OrigTy = cast<PointerType>(Addr->getType())->getElementType();
776 const uint32_t TypeSize = DL.getTypeStoreSizeInBits(OrigTy);
777 // Bail to the slowpath if the access might touch multiple cache lines.
778 // An access aligned to its size is guaranteed to be intra-cache-line.
779 // getMemoryAccessFuncIndex has already ruled out a size larger than 16
780 // and thus larger than a cache line for platforms this tool targets
781 // (and our shadow memory setup assumes 64-byte cache lines).
782 assert(TypeSize <= 64);
783 if (!(TypeSize == 8 ||
Derek Bruening9ef57722016-06-03 22:29:52 +0000784 (Alignment % (TypeSize / 8)) == 0)) {
785 if (ClAssumeIntraCacheLine)
786 ++NumAssumedIntraCacheLine;
787 else
788 return false;
789 }
Derek Bruening5662b932016-05-25 00:17:24 +0000790
791 // We inline instrumentation to set the corresponding shadow bits for
792 // each cache line touched by the application. Here we handle a single
793 // load or store where we've already ruled out the possibility that it
794 // might touch more than one cache line and thus we simply update the
795 // shadow memory for a single cache line.
796 // Our shadow memory model is fine with races when manipulating shadow values.
797 // We generate the following code:
798 //
799 // const char BitMask = 0x81;
800 // char *ShadowAddr = appToShadow(AppAddr);
801 // if ((*ShadowAddr & BitMask) != BitMask)
802 // *ShadowAddr |= Bitmask;
803 //
804 Value *AddrPtr = IRB.CreatePointerCast(Addr, IntptrTy);
805 Value *ShadowPtr = appToShadow(AddrPtr, IRB);
806 Type *ShadowTy = IntegerType::get(*Ctx, 8U);
807 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
808 // The bottom bit is used for the current sampling period's working set.
809 // The top bit is used for the total working set. We set both on each
810 // memory access, if they are not already set.
811 Value *ValueMask = ConstantInt::get(ShadowTy, 0x81); // 10000001B
812
813 Value *OldValue = IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
814 // The AND and CMP will be turned into a TEST instruction by the compiler.
815 Value *Cmp = IRB.CreateICmpNE(IRB.CreateAnd(OldValue, ValueMask), ValueMask);
816 TerminatorInst *CmpTerm = SplitBlockAndInsertIfThen(Cmp, I, false);
817 // FIXME: do I need to call SetCurrentDebugLocation?
818 IRB.SetInsertPoint(CmpTerm);
819 // We use OR to set the shadow bits to avoid corrupting the middle 6 bits,
820 // which are used by the runtime library.
821 Value *NewVal = IRB.CreateOr(OldValue, ValueMask);
822 IRB.CreateStore(NewVal, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
823 IRB.SetInsertPoint(I);
824
825 return true;
826}