blob: d399e6c12f0389fde8d03ab394f31e56d3614903 [file] [log] [blame]
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001//===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
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/// \file
10/// This file is a part of MemorySanitizer, a detector of uninitialized
11/// reads.
12///
13/// Status: early prototype.
14///
15/// The algorithm of the tool is similar to Memcheck
16/// (http://goo.gl/QKbem). We associate a few shadow bits with every
17/// byte of the application memory, poison the shadow of the malloc-ed
18/// or alloca-ed memory, load the shadow bits on every memory read,
19/// propagate the shadow bits through some of the arithmetic
20/// instruction (including MOV), store the shadow bits on every memory
21/// write, report a bug on some other instructions (e.g. JMP) if the
22/// associated shadow is poisoned.
23///
24/// But there are differences too. The first and the major one:
25/// compiler instrumentation instead of binary instrumentation. This
26/// gives us much better register allocation, possible compiler
27/// optimizations and a fast start-up. But this brings the major issue
28/// as well: msan needs to see all program events, including system
29/// calls and reads/writes in system libraries, so we either need to
30/// compile *everything* with msan or use a binary translation
31/// component (e.g. DynamoRIO) to instrument pre-built libraries.
32/// Another difference from Memcheck is that we use 8 shadow bits per
33/// byte of application memory and use a direct shadow mapping. This
34/// greatly simplifies the instrumentation code and avoids races on
35/// shadow updates (Memcheck is single-threaded so races are not a
36/// concern there. Memcheck uses 2 shadow bits per byte with a slow
37/// path storage that uses 8 bits per byte).
38///
39/// The default value of shadow is 0, which means "clean" (not poisoned).
40///
41/// Every module initializer should call __msan_init to ensure that the
42/// shadow memory is ready. On error, __msan_warning is called. Since
43/// parameters and return values may be passed via registers, we have a
44/// specialized thread-local shadow for return values
45/// (__msan_retval_tls) and parameters (__msan_param_tls).
46//===----------------------------------------------------------------------===//
47
48#define DEBUG_TYPE "msan"
49
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include "llvm/Transforms/Instrumentation.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000051#include "BlackList.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000052#include "llvm/ADT/DepthFirstIterator.h"
53#include "llvm/ADT/SmallString.h"
54#include "llvm/ADT/SmallVector.h"
55#include "llvm/ADT/ValueMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/DataLayout.h"
57#include "llvm/Function.h"
58#include "llvm/IRBuilder.h"
59#include "llvm/InlineAsm.h"
60#include "llvm/InstVisitor.h"
61#include "llvm/IntrinsicInst.h"
62#include "llvm/LLVMContext.h"
63#include "llvm/MDBuilder.h"
64#include "llvm/Module.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000065#include "llvm/Support/CommandLine.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000068#include "llvm/Support/raw_ostream.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000069#include "llvm/Transforms/Utils/BasicBlockUtils.h"
70#include "llvm/Transforms/Utils/ModuleUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000071#include "llvm/Type.h"
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000072
73using namespace llvm;
74
75static const uint64_t kShadowMask32 = 1ULL << 31;
76static const uint64_t kShadowMask64 = 1ULL << 46;
77static const uint64_t kOriginOffset32 = 1ULL << 30;
78static const uint64_t kOriginOffset64 = 1ULL << 45;
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +000079static const uint64_t kShadowTLSAlignment = 8;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +000080
81// This is an important flag that makes the reports much more
82// informative at the cost of greater slowdown. Not fully implemented
83// yet.
84// FIXME: this should be a top-level clang flag, e.g.
85// -fmemory-sanitizer-full.
86static cl::opt<bool> ClTrackOrigins("msan-track-origins",
87 cl::desc("Track origins (allocation sites) of poisoned memory"),
88 cl::Hidden, cl::init(false));
89static cl::opt<bool> ClKeepGoing("msan-keep-going",
90 cl::desc("keep going after reporting a UMR"),
91 cl::Hidden, cl::init(false));
92static cl::opt<bool> ClPoisonStack("msan-poison-stack",
93 cl::desc("poison uninitialized stack variables"),
94 cl::Hidden, cl::init(true));
95static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
96 cl::desc("poison uninitialized stack variables with a call"),
97 cl::Hidden, cl::init(false));
98static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
99 cl::desc("poison uninitialized stack variables with the given patter"),
100 cl::Hidden, cl::init(0xff));
101
102static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
103 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
104 cl::Hidden, cl::init(true));
105
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000106static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
107 cl::desc("store origin for clean (fully initialized) values"),
108 cl::Hidden, cl::init(false));
109
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000110// This flag controls whether we check the shadow of the address
111// operand of load or store. Such bugs are very rare, since load from
112// a garbage address typically results in SEGV, but still happen
113// (e.g. only lower bits of address are garbage, or the access happens
114// early at program startup where malloc-ed memory is more likely to
115// be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
116static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
117 cl::desc("report accesses through a pointer which has poisoned shadow"),
118 cl::Hidden, cl::init(true));
119
120static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
121 cl::desc("print out instructions with default strict semantics"),
122 cl::Hidden, cl::init(false));
123
124static cl::opt<std::string> ClBlackListFile("msan-blacklist",
125 cl::desc("File containing the list of functions where MemorySanitizer "
126 "should not report bugs"), cl::Hidden);
127
128namespace {
129
130/// \brief An instrumentation pass implementing detection of uninitialized
131/// reads.
132///
133/// MemorySanitizer: instrument the code in module to find
134/// uninitialized reads.
135class MemorySanitizer : public FunctionPass {
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000136 public:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000137 MemorySanitizer() : FunctionPass(ID), TD(0), WarningFn(0) { }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000138 const char *getPassName() const { return "MemorySanitizer"; }
139 bool runOnFunction(Function &F);
140 bool doInitialization(Module &M);
141 static char ID; // Pass identification, replacement for typeid.
142
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000143 private:
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000144 void initializeCallbacks(Module &M);
145
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000146 DataLayout *TD;
147 LLVMContext *C;
148 Type *IntptrTy;
149 Type *OriginTy;
150 /// \brief Thread-local shadow storage for function parameters.
151 GlobalVariable *ParamTLS;
152 /// \brief Thread-local origin storage for function parameters.
153 GlobalVariable *ParamOriginTLS;
154 /// \brief Thread-local shadow storage for function return value.
155 GlobalVariable *RetvalTLS;
156 /// \brief Thread-local origin storage for function return value.
157 GlobalVariable *RetvalOriginTLS;
158 /// \brief Thread-local shadow storage for in-register va_arg function
159 /// parameters (x86_64-specific).
160 GlobalVariable *VAArgTLS;
161 /// \brief Thread-local shadow storage for va_arg overflow area
162 /// (x86_64-specific).
163 GlobalVariable *VAArgOverflowSizeTLS;
164 /// \brief Thread-local space used to pass origin value to the UMR reporting
165 /// function.
166 GlobalVariable *OriginTLS;
167
168 /// \brief The run-time callback to print a warning.
169 Value *WarningFn;
170 /// \brief Run-time helper that copies origin info for a memory range.
171 Value *MsanCopyOriginFn;
172 /// \brief Run-time helper that generates a new origin value for a stack
173 /// allocation.
174 Value *MsanSetAllocaOriginFn;
175 /// \brief Run-time helper that poisons stack on function entry.
176 Value *MsanPoisonStackFn;
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000177 /// \brief MSan runtime replacements for memmove, memcpy and memset.
178 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000179
180 /// \brief Address mask used in application-to-shadow address calculation.
181 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
182 uint64_t ShadowMask;
183 /// \brief Offset of the origin shadow from the "normal" shadow.
184 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
185 uint64_t OriginOffset;
186 /// \brief Branch weights for error reporting.
187 MDNode *ColdCallWeights;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000188 /// \brief Branch weights for origin store.
189 MDNode *OriginStoreWeights;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000190 /// \brief The blacklist.
191 OwningPtr<BlackList> BL;
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000192 /// \brief An empty volatile inline asm that prevents callback merge.
193 InlineAsm *EmptyAsm;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000194
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000195 friend struct MemorySanitizerVisitor;
196 friend struct VarArgAMD64Helper;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000197};
198} // namespace
199
200char MemorySanitizer::ID = 0;
201INITIALIZE_PASS(MemorySanitizer, "msan",
202 "MemorySanitizer: detects uninitialized reads.",
203 false, false)
204
205FunctionPass *llvm::createMemorySanitizerPass() {
206 return new MemorySanitizer();
207}
208
209/// \brief Create a non-const global initialized with the given string.
210///
211/// Creates a writable global for Str so that we can pass it to the
212/// run-time lib. Runtime uses first 4 bytes of the string to store the
213/// frame ID, so the string needs to be mutable.
214static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
215 StringRef Str) {
216 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
217 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
218 GlobalValue::PrivateLinkage, StrConst, "");
219}
220
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000221
222/// \brief Insert extern declaration of runtime-provided functions and globals.
223void MemorySanitizer::initializeCallbacks(Module &M) {
224 // Only do this once.
225 if (WarningFn)
226 return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000227
228 IRBuilder<> IRB(*C);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000229 // Create the callback.
230 // FIXME: this function should have "Cold" calling conv,
231 // which is not yet implemented.
232 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
233 : "__msan_warning_noreturn";
234 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
235
236 MsanCopyOriginFn = M.getOrInsertFunction(
237 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
238 IRB.getInt8PtrTy(), IntptrTy, NULL);
239 MsanSetAllocaOriginFn = M.getOrInsertFunction(
240 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
241 IRB.getInt8PtrTy(), NULL);
242 MsanPoisonStackFn = M.getOrInsertFunction(
243 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
244 MemmoveFn = M.getOrInsertFunction(
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000245 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
246 IRB.getInt8PtrTy(), IntptrTy, NULL);
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +0000247 MemcpyFn = M.getOrInsertFunction(
248 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
249 IntptrTy, NULL);
250 MemsetFn = M.getOrInsertFunction(
251 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000252 IntptrTy, NULL);
253
254 // Create globals.
255 RetvalTLS = new GlobalVariable(
256 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
257 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
258 GlobalVariable::GeneralDynamicTLSModel);
259 RetvalOriginTLS = new GlobalVariable(
260 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
261 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
262
263 ParamTLS = new GlobalVariable(
264 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
265 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
266 GlobalVariable::GeneralDynamicTLSModel);
267 ParamOriginTLS = new GlobalVariable(
268 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
269 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
270
271 VAArgTLS = new GlobalVariable(
272 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
273 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
274 GlobalVariable::GeneralDynamicTLSModel);
275 VAArgOverflowSizeTLS = new GlobalVariable(
276 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
277 "__msan_va_arg_overflow_size_tls", 0,
278 GlobalVariable::GeneralDynamicTLSModel);
279 OriginTLS = new GlobalVariable(
280 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
281 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000282
283 // We insert an empty inline asm after __msan_report* to avoid callback merge.
284 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
285 StringRef(""), StringRef(""),
286 /*hasSideEffects=*/true);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000287}
288
289/// \brief Module-level initialization.
290///
291/// inserts a call to __msan_init to the module's constructor list.
292bool MemorySanitizer::doInitialization(Module &M) {
293 TD = getAnalysisIfAvailable<DataLayout>();
294 if (!TD)
295 return false;
296 BL.reset(new BlackList(ClBlackListFile));
297 C = &(M.getContext());
298 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
299 switch (PtrSize) {
300 case 64:
301 ShadowMask = kShadowMask64;
302 OriginOffset = kOriginOffset64;
303 break;
304 case 32:
305 ShadowMask = kShadowMask32;
306 OriginOffset = kOriginOffset32;
307 break;
308 default:
309 report_fatal_error("unsupported pointer size");
310 break;
311 }
312
313 IRBuilder<> IRB(*C);
314 IntptrTy = IRB.getIntPtrTy(TD);
315 OriginTy = IRB.getInt32Ty();
316
317 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000318 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000319
320 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
321 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
322 "__msan_init", IRB.getVoidTy(), NULL)), 0);
323
324 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
325 IRB.getInt32(ClTrackOrigins), "__msan_track_origins");
326
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000327 return true;
328}
329
330namespace {
331
332/// \brief A helper class that handles instrumentation of VarArg
333/// functions on a particular platform.
334///
335/// Implementations are expected to insert the instrumentation
336/// necessary to propagate argument shadow through VarArg function
337/// calls. Visit* methods are called during an InstVisitor pass over
338/// the function, and should avoid creating new basic blocks. A new
339/// instance of this class is created for each instrumented function.
340struct VarArgHelper {
341 /// \brief Visit a CallSite.
342 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
343
344 /// \brief Visit a va_start call.
345 virtual void visitVAStartInst(VAStartInst &I) = 0;
346
347 /// \brief Visit a va_copy call.
348 virtual void visitVACopyInst(VACopyInst &I) = 0;
349
350 /// \brief Finalize function instrumentation.
351 ///
352 /// This method is called after visiting all interesting (see above)
353 /// instructions in a function.
354 virtual void finalizeInstrumentation() = 0;
Evgeniy Stepanovda0072b2012-11-29 13:12:03 +0000355
356 virtual ~VarArgHelper() {}
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000357};
358
359struct MemorySanitizerVisitor;
360
361VarArgHelper*
362CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
363 MemorySanitizerVisitor &Visitor);
364
365/// This class does all the work for a given function. Store and Load
366/// instructions store and load corresponding shadow and origin
367/// values. Most instructions propagate shadow from arguments to their
368/// return values. Certain instructions (most importantly, BranchInst)
369/// test their argument shadow and print reports (with a runtime call) if it's
370/// non-zero.
371struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
372 Function &F;
373 MemorySanitizer &MS;
374 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
375 ValueMap<Value*, Value*> ShadowMap, OriginMap;
376 bool InsertChecks;
377 OwningPtr<VarArgHelper> VAHelper;
378
379 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
380 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000381 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000382 static const unsigned AMD64FpEndOffset = 176;
383
384 struct ShadowOriginAndInsertPoint {
385 Instruction *Shadow;
386 Instruction *Origin;
387 Instruction *OrigIns;
388 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
389 : Shadow(S), Origin(O), OrigIns(I) { }
390 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
391 };
392 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000393 SmallVector<Instruction*, 16> StoreList;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000394
395 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
396 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
397 InsertChecks = !MS.BL->isIn(F);
398 DEBUG(if (!InsertChecks)
399 dbgs() << "MemorySanitizer is not inserting checks into '"
400 << F.getName() << "'\n");
401 }
402
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000403 void materializeStores() {
404 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
405 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
406
407 IRBuilder<> IRB(&I);
408 Value *Val = I.getValueOperand();
409 Value *Addr = I.getPointerOperand();
410 Value *Shadow = getShadow(Val);
411 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
412
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000413 StoreInst *NewSI =
414 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000415 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
NAKAMURA Takumie0b1b462012-12-06 13:38:00 +0000416 (void)NewSI;
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000417 // If the store is volatile, add a check.
418 if (I.isVolatile())
419 insertCheck(Val, &I);
420 if (ClCheckAccessAddress)
421 insertCheck(Addr, &I);
422
423 if (ClTrackOrigins) {
424 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000425 IRB.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRB));
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000426 } else {
427 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
428
429 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
430 // TODO(eugenis): handle non-zero constant shadow by inserting an
431 // unconditional check (can not simply fail compilation as this could
432 // be in the dead code).
433 if (Cst)
434 continue;
435
436 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
437 getCleanShadow(ConvertedShadow), "_mscmp");
438 Instruction *CheckTerm =
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000439 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
440 MS.OriginStoreWeights);
441 IRBuilder<> IRBNew(CheckTerm);
442 IRBNew.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRBNew));
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000443 }
444 }
445 }
446 }
447
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000448 void materializeChecks() {
449 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
450 Instruction *Shadow = InstrumentationList[i].Shadow;
451 Instruction *OrigIns = InstrumentationList[i].OrigIns;
452 IRBuilder<> IRB(OrigIns);
453 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
454 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
455 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
456 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
457 getCleanShadow(ConvertedShadow), "_mscmp");
458 Instruction *CheckTerm =
459 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
460 /* Unreachable */ !ClKeepGoing,
461 MS.ColdCallWeights);
462
463 IRB.SetInsertPoint(CheckTerm);
464 if (ClTrackOrigins) {
465 Instruction *Origin = InstrumentationList[i].Origin;
466 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
467 MS.OriginTLS);
468 }
469 CallInst *Call = IRB.CreateCall(MS.WarningFn);
470 Call->setDebugLoc(OrigIns->getDebugLoc());
Evgeniy Stepanov1d2da652012-11-29 12:30:18 +0000471 IRB.CreateCall(MS.EmptyAsm);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000472 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
473 }
474 DEBUG(dbgs() << "DONE:\n" << F);
475 }
476
477 /// \brief Add MemorySanitizer instrumentation to a function.
478 bool runOnFunction() {
Evgeniy Stepanov94b257d2012-12-05 13:14:33 +0000479 MS.initializeCallbacks(*F.getParent());
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000480 if (!MS.TD) return false;
481 // Iterate all BBs in depth-first order and create shadow instructions
482 // for all instructions (where applicable).
483 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
484 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
485 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
486 BasicBlock *BB = *DI;
487 visit(*BB);
488 }
489
490 // Finalize PHI nodes.
491 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
492 PHINode *PN = ShadowPHINodes[i];
493 PHINode *PNS = cast<PHINode>(getShadow(PN));
494 PHINode *PNO = ClTrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
495 size_t NumValues = PN->getNumIncomingValues();
496 for (size_t v = 0; v < NumValues; v++) {
497 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
498 if (PNO)
499 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
500 }
501 }
502
503 VAHelper->finalizeInstrumentation();
504
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000505 // Delayed instrumentation of StoreInst.
Evgeniy Stepanov47ac9ba2012-12-06 11:58:59 +0000506 // This may add new checks to be inserted later.
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000507 materializeStores();
508
509 // Insert shadow value checks.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000510 materializeChecks();
511
512 return true;
513 }
514
515 /// \brief Compute the shadow type that corresponds to a given Value.
516 Type *getShadowTy(Value *V) {
517 return getShadowTy(V->getType());
518 }
519
520 /// \brief Compute the shadow type that corresponds to a given Type.
521 Type *getShadowTy(Type *OrigTy) {
522 if (!OrigTy->isSized()) {
523 return 0;
524 }
525 // For integer type, shadow is the same as the original type.
526 // This may return weird-sized types like i1.
527 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
528 return IT;
529 if (VectorType *VT = dyn_cast<VectorType>(OrigTy))
530 return VectorType::getInteger(VT);
531 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
532 SmallVector<Type*, 4> Elements;
533 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
534 Elements.push_back(getShadowTy(ST->getElementType(i)));
535 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
536 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
537 return Res;
538 }
539 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
540 return IntegerType::get(*MS.C, TypeSize);
541 }
542
543 /// \brief Flatten a vector type.
544 Type *getShadowTyNoVec(Type *ty) {
545 if (VectorType *vt = dyn_cast<VectorType>(ty))
546 return IntegerType::get(*MS.C, vt->getBitWidth());
547 return ty;
548 }
549
550 /// \brief Convert a shadow value to it's flattened variant.
551 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
552 Type *Ty = V->getType();
553 Type *NoVecTy = getShadowTyNoVec(Ty);
554 if (Ty == NoVecTy) return V;
555 return IRB.CreateBitCast(V, NoVecTy);
556 }
557
558 /// \brief Compute the shadow address that corresponds to a given application
559 /// address.
560 ///
561 /// Shadow = Addr & ~ShadowMask.
562 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
563 IRBuilder<> &IRB) {
564 Value *ShadowLong =
565 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
566 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
567 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
568 }
569
570 /// \brief Compute the origin address that corresponds to a given application
571 /// address.
572 ///
573 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000574 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
575 Value *ShadowLong =
576 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000577 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000578 Value *Add =
579 IRB.CreateAdd(ShadowLong,
580 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
Evgeniy Stepanov62ba6112012-11-29 13:43:05 +0000581 Value *SecondAnd =
582 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
583 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000584 }
585
586 /// \brief Compute the shadow address for a given function argument.
587 ///
588 /// Shadow = ParamTLS+ArgOffset.
589 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
590 int ArgOffset) {
591 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
592 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
593 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
594 "_msarg");
595 }
596
597 /// \brief Compute the origin address for a given function argument.
598 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
599 int ArgOffset) {
600 if (!ClTrackOrigins) return 0;
601 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
602 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
603 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
604 "_msarg_o");
605 }
606
607 /// \brief Compute the shadow address for a retval.
608 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
609 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
610 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
611 "_msret");
612 }
613
614 /// \brief Compute the origin address for a retval.
615 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
616 // We keep a single origin for the entire retval. Might be too optimistic.
617 return MS.RetvalOriginTLS;
618 }
619
620 /// \brief Set SV to be the shadow value for V.
621 void setShadow(Value *V, Value *SV) {
622 assert(!ShadowMap.count(V) && "Values may only have one shadow");
623 ShadowMap[V] = SV;
624 }
625
626 /// \brief Set Origin to be the origin value for V.
627 void setOrigin(Value *V, Value *Origin) {
628 if (!ClTrackOrigins) return;
629 assert(!OriginMap.count(V) && "Values may only have one origin");
630 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
631 OriginMap[V] = Origin;
632 }
633
634 /// \brief Create a clean shadow value for a given value.
635 ///
636 /// Clean shadow (all zeroes) means all bits of the value are defined
637 /// (initialized).
638 Value *getCleanShadow(Value *V) {
639 Type *ShadowTy = getShadowTy(V);
640 if (!ShadowTy)
641 return 0;
642 return Constant::getNullValue(ShadowTy);
643 }
644
645 /// \brief Create a dirty shadow of a given shadow type.
646 Constant *getPoisonedShadow(Type *ShadowTy) {
647 assert(ShadowTy);
648 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
649 return Constant::getAllOnesValue(ShadowTy);
650 StructType *ST = cast<StructType>(ShadowTy);
651 SmallVector<Constant *, 4> Vals;
652 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
653 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
654 return ConstantStruct::get(ST, Vals);
655 }
656
657 /// \brief Create a clean (zero) origin.
658 Value *getCleanOrigin() {
659 return Constant::getNullValue(MS.OriginTy);
660 }
661
662 /// \brief Get the shadow value for a given Value.
663 ///
664 /// This function either returns the value set earlier with setShadow,
665 /// or extracts if from ParamTLS (for function arguments).
666 Value *getShadow(Value *V) {
667 if (Instruction *I = dyn_cast<Instruction>(V)) {
668 // For instructions the shadow is already stored in the map.
669 Value *Shadow = ShadowMap[V];
670 if (!Shadow) {
671 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000672 (void)I;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000673 assert(Shadow && "No shadow for a value");
674 }
675 return Shadow;
676 }
677 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
678 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
679 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000680 (void)U;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000681 return AllOnes;
682 }
683 if (Argument *A = dyn_cast<Argument>(V)) {
684 // For arguments we compute the shadow on demand and store it in the map.
685 Value **ShadowPtr = &ShadowMap[V];
686 if (*ShadowPtr)
687 return *ShadowPtr;
688 Function *F = A->getParent();
689 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
690 unsigned ArgOffset = 0;
691 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
692 AI != AE; ++AI) {
693 if (!AI->getType()->isSized()) {
694 DEBUG(dbgs() << "Arg is not sized\n");
695 continue;
696 }
697 unsigned Size = AI->hasByValAttr()
698 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
699 : MS.TD->getTypeAllocSize(AI->getType());
700 if (A == AI) {
701 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
702 if (AI->hasByValAttr()) {
703 // ByVal pointer itself has clean shadow. We copy the actual
704 // argument shadow to the underlying memory.
705 Value *Cpy = EntryIRB.CreateMemCpy(
706 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
707 Base, Size, AI->getParamAlignment());
708 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000709 (void)Cpy;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000710 *ShadowPtr = getCleanShadow(V);
711 } else {
712 *ShadowPtr = EntryIRB.CreateLoad(Base);
713 }
714 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
715 **ShadowPtr << "\n");
716 if (ClTrackOrigins) {
717 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
718 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
719 }
720 }
721 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
722 }
723 assert(*ShadowPtr && "Could not find shadow for an argument");
724 return *ShadowPtr;
725 }
726 // For everything else the shadow is zero.
727 return getCleanShadow(V);
728 }
729
730 /// \brief Get the shadow for i-th argument of the instruction I.
731 Value *getShadow(Instruction *I, int i) {
732 return getShadow(I->getOperand(i));
733 }
734
735 /// \brief Get the origin for a value.
736 Value *getOrigin(Value *V) {
737 if (!ClTrackOrigins) return 0;
738 if (isa<Instruction>(V) || isa<Argument>(V)) {
739 Value *Origin = OriginMap[V];
740 if (!Origin) {
741 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
742 Origin = getCleanOrigin();
743 }
744 return Origin;
745 }
746 return getCleanOrigin();
747 }
748
749 /// \brief Get the origin for i-th argument of the instruction I.
750 Value *getOrigin(Instruction *I, int i) {
751 return getOrigin(I->getOperand(i));
752 }
753
754 /// \brief Remember the place where a shadow check should be inserted.
755 ///
756 /// This location will be later instrumented with a check that will print a
757 /// UMR warning in runtime if the value is not fully defined.
758 void insertCheck(Value *Val, Instruction *OrigIns) {
759 assert(Val);
760 if (!InsertChecks) return;
761 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
762 if (!Shadow) return;
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000763#ifndef NDEBUG
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000764 Type *ShadowTy = Shadow->getType();
765 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
766 "Can only insert checks for integer and vector shadow types");
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000767#endif
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000768 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
769 InstrumentationList.push_back(
770 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
771 }
772
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000773 // ------------------- Visitors.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000774
775 /// \brief Instrument LoadInst
776 ///
777 /// Loads the corresponding shadow and (optionally) origin.
778 /// Optionally, checks that the load address is fully defined.
779 void visitLoadInst(LoadInst &I) {
Matt Beaumont-Gayc76536f2012-11-29 18:15:49 +0000780 assert(I.getType()->isSized() && "Load type must have size");
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000781 IRBuilder<> IRB(&I);
782 Type *ShadowTy = getShadowTy(&I);
783 Value *Addr = I.getPointerOperand();
784 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
Evgeniy Stepanoveeb8b7c2012-11-29 14:05:53 +0000785 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000786
787 if (ClCheckAccessAddress)
788 insertCheck(I.getPointerOperand(), &I);
789
790 if (ClTrackOrigins)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +0000791 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000792 }
793
794 /// \brief Instrument StoreInst
795 ///
796 /// Stores the corresponding shadow and (optionally) origin.
797 /// Optionally, checks that the store address is fully defined.
798 /// Volatile stores check that the value being stored is fully defined.
799 void visitStoreInst(StoreInst &I) {
Evgeniy Stepanov4f220d92012-12-06 11:41:03 +0000800 StoreList.push_back(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000801 }
802
Evgeniy Stepanov30484fc2012-11-29 15:22:06 +0000803 // Vector manipulation.
804 void visitExtractElementInst(ExtractElementInst &I) {
805 insertCheck(I.getOperand(1), &I);
806 IRBuilder<> IRB(&I);
807 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
808 "_msprop"));
809 setOrigin(&I, getOrigin(&I, 0));
810 }
811
812 void visitInsertElementInst(InsertElementInst &I) {
813 insertCheck(I.getOperand(2), &I);
814 IRBuilder<> IRB(&I);
815 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
816 I.getOperand(2), "_msprop"));
817 setOriginForNaryOp(I);
818 }
819
820 void visitShuffleVectorInst(ShuffleVectorInst &I) {
821 insertCheck(I.getOperand(2), &I);
822 IRBuilder<> IRB(&I);
823 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
824 I.getOperand(2), "_msprop"));
825 setOriginForNaryOp(I);
826 }
827
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000828 // Casts.
829 void visitSExtInst(SExtInst &I) {
830 IRBuilder<> IRB(&I);
831 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
832 setOrigin(&I, getOrigin(&I, 0));
833 }
834
835 void visitZExtInst(ZExtInst &I) {
836 IRBuilder<> IRB(&I);
837 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
838 setOrigin(&I, getOrigin(&I, 0));
839 }
840
841 void visitTruncInst(TruncInst &I) {
842 IRBuilder<> IRB(&I);
843 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
844 setOrigin(&I, getOrigin(&I, 0));
845 }
846
847 void visitBitCastInst(BitCastInst &I) {
848 IRBuilder<> IRB(&I);
849 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
850 setOrigin(&I, getOrigin(&I, 0));
851 }
852
853 void visitPtrToIntInst(PtrToIntInst &I) {
854 IRBuilder<> IRB(&I);
855 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
856 "_msprop_ptrtoint"));
857 setOrigin(&I, getOrigin(&I, 0));
858 }
859
860 void visitIntToPtrInst(IntToPtrInst &I) {
861 IRBuilder<> IRB(&I);
862 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
863 "_msprop_inttoptr"));
864 setOrigin(&I, getOrigin(&I, 0));
865 }
866
867 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
868 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
869 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
870 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
871 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
872 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
873
874 /// \brief Propagate shadow for bitwise AND.
875 ///
876 /// This code is exact, i.e. if, for example, a bit in the left argument
877 /// is defined and 0, then neither the value not definedness of the
878 /// corresponding bit in B don't affect the resulting shadow.
879 void visitAnd(BinaryOperator &I) {
880 IRBuilder<> IRB(&I);
881 // "And" of 0 and a poisoned value results in unpoisoned value.
882 // 1&1 => 1; 0&1 => 0; p&1 => p;
883 // 1&0 => 0; 0&0 => 0; p&0 => 0;
884 // 1&p => p; 0&p => 0; p&p => p;
885 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
886 Value *S1 = getShadow(&I, 0);
887 Value *S2 = getShadow(&I, 1);
888 Value *V1 = I.getOperand(0);
889 Value *V2 = I.getOperand(1);
890 if (V1->getType() != S1->getType()) {
891 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
892 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
893 }
894 Value *S1S2 = IRB.CreateAnd(S1, S2);
895 Value *V1S2 = IRB.CreateAnd(V1, S2);
896 Value *S1V2 = IRB.CreateAnd(S1, V2);
897 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
898 setOriginForNaryOp(I);
899 }
900
901 void visitOr(BinaryOperator &I) {
902 IRBuilder<> IRB(&I);
903 // "Or" of 1 and a poisoned value results in unpoisoned value.
904 // 1|1 => 1; 0|1 => 1; p|1 => 1;
905 // 1|0 => 1; 0|0 => 0; p|0 => p;
906 // 1|p => 1; 0|p => p; p|p => p;
907 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
908 Value *S1 = getShadow(&I, 0);
909 Value *S2 = getShadow(&I, 1);
910 Value *V1 = IRB.CreateNot(I.getOperand(0));
911 Value *V2 = IRB.CreateNot(I.getOperand(1));
912 if (V1->getType() != S1->getType()) {
913 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
914 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
915 }
916 Value *S1S2 = IRB.CreateAnd(S1, S2);
917 Value *V1S2 = IRB.CreateAnd(V1, S2);
918 Value *S1V2 = IRB.CreateAnd(S1, V2);
919 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
920 setOriginForNaryOp(I);
921 }
922
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000923 /// \brief Default propagation of shadow and/or origin.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000924 ///
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000925 /// This class implements the general case of shadow propagation, used in all
926 /// cases where we don't know and/or don't care about what the operation
927 /// actually does. It converts all input shadow values to a common type
928 /// (extending or truncating as necessary), and bitwise OR's them.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +0000929 ///
930 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
931 /// fully initialized), and less prone to false positives.
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000932 ///
933 /// This class also implements the general case of origin propagation. For a
934 /// Nary operation, result origin is set to the origin of an argument that is
935 /// not entirely initialized. If there is more than one such arguments, the
936 /// rightmost of them is picked. It does not matter which one is picked if all
937 /// arguments are initialized.
938 template <bool CombineShadow>
939 class Combiner {
940 Value *Shadow;
941 Value *Origin;
942 IRBuilder<> &IRB;
943 MemorySanitizerVisitor *MSV;
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +0000944
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +0000945 public:
946 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
947 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
948
949 /// \brief Add a pair of shadow and origin values to the mix.
950 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
951 if (CombineShadow) {
952 assert(OpShadow);
953 if (!Shadow)
954 Shadow = OpShadow;
955 else {
956 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
957 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
958 }
959 }
960
961 if (ClTrackOrigins) {
962 assert(OpOrigin);
963 if (!Origin) {
964 Origin = OpOrigin;
965 } else {
966 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
967 Value *Cond = IRB.CreateICmpNE(FlatShadow,
968 MSV->getCleanShadow(FlatShadow));
969 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
970 }
971 }
972 return *this;
973 }
974
975 /// \brief Add an application value to the mix.
976 Combiner &Add(Value *V) {
977 Value *OpShadow = MSV->getShadow(V);
978 Value *OpOrigin = ClTrackOrigins ? MSV->getOrigin(V) : 0;
979 return Add(OpShadow, OpOrigin);
980 }
981
982 /// \brief Set the current combined values as the given instruction's shadow
983 /// and origin.
984 void Done(Instruction *I) {
985 if (CombineShadow) {
986 assert(Shadow);
987 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
988 MSV->setShadow(I, Shadow);
989 }
990 if (ClTrackOrigins) {
991 assert(Origin);
992 MSV->setOrigin(I, Origin);
993 }
994 }
995 };
996
997 typedef Combiner<true> ShadowAndOriginCombiner;
998 typedef Combiner<false> OriginCombiner;
999
1000 /// \brief Propagate origin for arbitrary operation.
1001 void setOriginForNaryOp(Instruction &I) {
1002 if (!ClTrackOrigins) return;
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001003 IRBuilder<> IRB(&I);
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001004 OriginCombiner OC(this, IRB);
1005 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1006 OC.Add(OI->get());
1007 OC.Done(&I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001008 }
1009
Evgeniy Stepanovf18e3af2012-12-14 12:54:18 +00001010 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1011 return Ty->isVectorTy() ?
1012 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1013 Ty->getPrimitiveSizeInBits();
1014 }
1015
1016 /// \brief Cast between two shadow types, extending or truncating as
1017 /// necessary.
1018 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1019 Type *srcTy = V->getType();
1020 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1021 return IRB.CreateIntCast(V, dstTy, false);
1022 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1023 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1024 return IRB.CreateIntCast(V, dstTy, false);
1025 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1026 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1027 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1028 Value *V2 =
1029 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1030 return IRB.CreateBitCast(V2, dstTy);
1031 // TODO: handle struct types.
1032 }
1033
1034 /// \brief Propagate shadow for arbitrary operation.
1035 void handleShadowOr(Instruction &I) {
1036 IRBuilder<> IRB(&I);
1037 ShadowAndOriginCombiner SC(this, IRB);
1038 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1039 SC.Add(OI->get());
1040 SC.Done(&I);
1041 }
1042
1043 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1044 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1045 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1046 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1047 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1048 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1049 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001050
1051 void handleDiv(Instruction &I) {
1052 IRBuilder<> IRB(&I);
1053 // Strict on the second argument.
1054 insertCheck(I.getOperand(1), &I);
1055 setShadow(&I, getShadow(&I, 0));
1056 setOrigin(&I, getOrigin(&I, 0));
1057 }
1058
1059 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1060 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1061 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1062 void visitURem(BinaryOperator &I) { handleDiv(I); }
1063 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1064 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1065
1066 /// \brief Instrument == and != comparisons.
1067 ///
1068 /// Sometimes the comparison result is known even if some of the bits of the
1069 /// arguments are not.
1070 void handleEqualityComparison(ICmpInst &I) {
1071 IRBuilder<> IRB(&I);
1072 Value *A = I.getOperand(0);
1073 Value *B = I.getOperand(1);
1074 Value *Sa = getShadow(A);
1075 Value *Sb = getShadow(B);
1076 if (A->getType()->isPointerTy())
1077 A = IRB.CreatePointerCast(A, MS.IntptrTy);
1078 if (B->getType()->isPointerTy())
1079 B = IRB.CreatePointerCast(B, MS.IntptrTy);
1080 // A == B <==> (C = A^B) == 0
1081 // A != B <==> (C = A^B) != 0
1082 // Sc = Sa | Sb
1083 Value *C = IRB.CreateXor(A, B);
1084 Value *Sc = IRB.CreateOr(Sa, Sb);
1085 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1086 // Result is defined if one of the following is true
1087 // * there is a defined 1 bit in C
1088 // * C is fully defined
1089 // Si = !(C & ~Sc) && Sc
1090 Value *Zero = Constant::getNullValue(Sc->getType());
1091 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1092 Value *Si =
1093 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1094 IRB.CreateICmpEQ(
1095 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1096 Si->setName("_msprop_icmp");
1097 setShadow(&I, Si);
1098 setOriginForNaryOp(I);
1099 }
1100
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001101 /// \brief Instrument signed relational comparisons.
1102 ///
1103 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1104 /// propagating the highest bit of the shadow. Everything else is delegated
1105 /// to handleShadowOr().
1106 void handleSignedRelationalComparison(ICmpInst &I) {
1107 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1108 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1109 Value* op = NULL;
1110 CmpInst::Predicate pre = I.getPredicate();
1111 if (constOp0 && constOp0->isNullValue() &&
1112 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1113 op = I.getOperand(1);
1114 } else if (constOp1 && constOp1->isNullValue() &&
1115 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1116 op = I.getOperand(0);
1117 }
1118 if (op) {
1119 IRBuilder<> IRB(&I);
1120 Value* Shadow =
1121 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1122 setShadow(&I, Shadow);
1123 setOrigin(&I, getOrigin(op));
1124 } else {
1125 handleShadowOr(I);
1126 }
1127 }
1128
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001129 void visitICmpInst(ICmpInst &I) {
1130 if (ClHandleICmp && I.isEquality())
1131 handleEqualityComparison(I);
Evgeniy Stepanov857d9d22012-11-29 14:25:47 +00001132 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1133 handleSignedRelationalComparison(I);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001134 else
1135 handleShadowOr(I);
1136 }
1137
1138 void visitFCmpInst(FCmpInst &I) {
1139 handleShadowOr(I);
1140 }
1141
1142 void handleShift(BinaryOperator &I) {
1143 IRBuilder<> IRB(&I);
1144 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1145 // Otherwise perform the same shift on S1.
1146 Value *S1 = getShadow(&I, 0);
1147 Value *S2 = getShadow(&I, 1);
1148 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1149 S2->getType());
1150 Value *V2 = I.getOperand(1);
1151 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1152 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1153 setOriginForNaryOp(I);
1154 }
1155
1156 void visitShl(BinaryOperator &I) { handleShift(I); }
1157 void visitAShr(BinaryOperator &I) { handleShift(I); }
1158 void visitLShr(BinaryOperator &I) { handleShift(I); }
1159
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001160 /// \brief Instrument llvm.memmove
1161 ///
1162 /// At this point we don't know if llvm.memmove will be inlined or not.
1163 /// If we don't instrument it and it gets inlined,
1164 /// our interceptor will not kick in and we will lose the memmove.
1165 /// If we instrument the call here, but it does not get inlined,
1166 /// we will memove the shadow twice: which is bad in case
1167 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1168 ///
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001169 /// Similar situation exists for memcpy and memset.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001170 void visitMemMoveInst(MemMoveInst &I) {
1171 IRBuilder<> IRB(&I);
1172 IRB.CreateCall3(
1173 MS.MemmoveFn,
1174 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1175 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1176 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1177 I.eraseFromParent();
1178 }
1179
Evgeniy Stepanov62b5db92012-11-29 12:49:04 +00001180 // Similar to memmove: avoid copying shadow twice.
1181 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1182 // FIXME: consider doing manual inline for small constant sizes and proper
1183 // alignment.
1184 void visitMemCpyInst(MemCpyInst &I) {
1185 IRBuilder<> IRB(&I);
1186 IRB.CreateCall3(
1187 MS.MemcpyFn,
1188 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1189 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1190 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1191 I.eraseFromParent();
1192 }
1193
1194 // Same as memcpy.
1195 void visitMemSetInst(MemSetInst &I) {
1196 IRBuilder<> IRB(&I);
1197 IRB.CreateCall3(
1198 MS.MemsetFn,
1199 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1200 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1201 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1202 I.eraseFromParent();
1203 }
1204
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001205 void visitVAStartInst(VAStartInst &I) {
1206 VAHelper->visitVAStartInst(I);
1207 }
1208
1209 void visitVACopyInst(VACopyInst &I) {
1210 VAHelper->visitVACopyInst(I);
1211 }
1212
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001213 enum IntrinsicKind {
1214 IK_DoesNotAccessMemory,
1215 IK_OnlyReadsMemory,
1216 IK_WritesMemory
1217 };
1218
1219 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1220 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1221 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1222 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1223 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1224 const int UnknownModRefBehavior = IK_WritesMemory;
1225#define GET_INTRINSIC_MODREF_BEHAVIOR
1226#define ModRefBehavior IntrinsicKind
1227#include "llvm/Intrinsics.gen"
1228#undef ModRefBehavior
1229#undef GET_INTRINSIC_MODREF_BEHAVIOR
1230 }
1231
1232 /// \brief Handle vector store-like intrinsics.
1233 ///
1234 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1235 /// has 1 pointer argument and 1 vector argument, returns void.
1236 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1237 IRBuilder<> IRB(&I);
1238 Value* Addr = I.getArgOperand(0);
1239 Value *Shadow = getShadow(&I, 1);
1240 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1241
1242 // We don't know the pointer alignment (could be unaligned SSE store!).
1243 // Have to assume to worst case.
1244 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1245
1246 if (ClCheckAccessAddress)
1247 insertCheck(Addr, &I);
1248
1249 // FIXME: use ClStoreCleanOrigin
1250 // FIXME: factor out common code from materializeStores
1251 if (ClTrackOrigins)
1252 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1253 return true;
1254 }
1255
1256 /// \brief Handle vector load-like intrinsics.
1257 ///
1258 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1259 /// has 1 pointer argument, returns a vector.
1260 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1261 IRBuilder<> IRB(&I);
1262 Value *Addr = I.getArgOperand(0);
1263
1264 Type *ShadowTy = getShadowTy(&I);
1265 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1266 // We don't know the pointer alignment (could be unaligned SSE load!).
1267 // Have to assume to worst case.
1268 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1269
1270 if (ClCheckAccessAddress)
1271 insertCheck(Addr, &I);
1272
1273 if (ClTrackOrigins)
1274 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1275 return true;
1276 }
1277
1278 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1279 ///
1280 /// Instrument intrinsics with any number of arguments of the same type,
1281 /// equal to the return type. The type should be simple (no aggregates or
1282 /// pointers; vectors are fine).
1283 /// Caller guarantees that this intrinsic does not access memory.
1284 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1285 Type *RetTy = I.getType();
1286 if (!(RetTy->isIntOrIntVectorTy() ||
1287 RetTy->isFPOrFPVectorTy() ||
1288 RetTy->isX86_MMXTy()))
1289 return false;
1290
1291 unsigned NumArgOperands = I.getNumArgOperands();
1292
1293 for (unsigned i = 0; i < NumArgOperands; ++i) {
1294 Type *Ty = I.getArgOperand(i)->getType();
1295 if (Ty != RetTy)
1296 return false;
1297 }
1298
1299 IRBuilder<> IRB(&I);
1300 ShadowAndOriginCombiner SC(this, IRB);
1301 for (unsigned i = 0; i < NumArgOperands; ++i)
1302 SC.Add(I.getArgOperand(i));
1303 SC.Done(&I);
1304
1305 return true;
1306 }
1307
1308 /// \brief Heuristically instrument unknown intrinsics.
1309 ///
1310 /// The main purpose of this code is to do something reasonable with all
1311 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1312 /// We recognize several classes of intrinsics by their argument types and
1313 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1314 /// sure that we know what the intrinsic does.
1315 ///
1316 /// We special-case intrinsics where this approach fails. See llvm.bswap
1317 /// handling as an example of that.
1318 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1319 unsigned NumArgOperands = I.getNumArgOperands();
1320 if (NumArgOperands == 0)
1321 return false;
1322
1323 Intrinsic::ID iid = I.getIntrinsicID();
1324 IntrinsicKind IK = getIntrinsicKind(iid);
1325 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1326 bool WritesMemory = IK == IK_WritesMemory;
1327 assert(!(OnlyReadsMemory && WritesMemory));
1328
1329 if (NumArgOperands == 2 &&
1330 I.getArgOperand(0)->getType()->isPointerTy() &&
1331 I.getArgOperand(1)->getType()->isVectorTy() &&
1332 I.getType()->isVoidTy() &&
1333 WritesMemory) {
1334 // This looks like a vector store.
1335 return handleVectorStoreIntrinsic(I);
1336 }
1337
1338 if (NumArgOperands == 1 &&
1339 I.getArgOperand(0)->getType()->isPointerTy() &&
1340 I.getType()->isVectorTy() &&
1341 OnlyReadsMemory) {
1342 // This looks like a vector load.
1343 return handleVectorLoadIntrinsic(I);
1344 }
1345
1346 if (!OnlyReadsMemory && !WritesMemory)
1347 if (maybeHandleSimpleNomemIntrinsic(I))
1348 return true;
1349
1350 // FIXME: detect and handle SSE maskstore/maskload
1351 return false;
1352 }
1353
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001354 void handleBswap(IntrinsicInst &I) {
1355 IRBuilder<> IRB(&I);
1356 Value *Op = I.getArgOperand(0);
1357 Type *OpType = Op->getType();
1358 Function *BswapFunc = Intrinsic::getDeclaration(
1359 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1360 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1361 setOrigin(&I, getOrigin(Op));
1362 }
1363
1364 void visitIntrinsicInst(IntrinsicInst &I) {
1365 switch (I.getIntrinsicID()) {
1366 case llvm::Intrinsic::bswap:
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001367 handleBswap(I);
1368 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001369 default:
Evgeniy Stepanovd7571cd2012-12-19 11:22:04 +00001370 if (!handleUnknownIntrinsic(I))
1371 visitInstruction(I);
Evgeniy Stepanov88b8dce2012-12-17 16:30:05 +00001372 break;
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001373 }
1374 }
1375
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001376 void visitCallSite(CallSite CS) {
1377 Instruction &I = *CS.getInstruction();
1378 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1379 if (CS.isCall()) {
Evgeniy Stepanov7ad7e832012-11-29 14:32:03 +00001380 CallInst *Call = cast<CallInst>(&I);
1381
1382 // For inline asm, do the usual thing: check argument shadow and mark all
1383 // outputs as clean. Note that any side effects of the inline asm that are
1384 // not immediately visible in its constraints are not handled.
1385 if (Call->isInlineAsm()) {
1386 visitInstruction(I);
1387 return;
1388 }
1389
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001390 // Allow only tail calls with the same types, otherwise
1391 // we may have a false positive: shadow for a non-void RetVal
1392 // will get propagated to a void RetVal.
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001393 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1394 Call->setTailCall(false);
Evgeniy Stepanov8b51bab2012-12-05 14:39:55 +00001395
1396 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00001397
1398 // We are going to insert code that relies on the fact that the callee
1399 // will become a non-readonly function after it is instrumented by us. To
1400 // prevent this code from being optimized out, mark that function
1401 // non-readonly in advance.
1402 if (Function *Func = Call->getCalledFunction()) {
1403 // Clear out readonly/readnone attributes.
1404 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001405 B.addAttribute(Attribute::ReadOnly)
1406 .addAttribute(Attribute::ReadNone);
Bill Wendlinge94d8432012-12-07 23:16:57 +00001407 Func->removeAttribute(AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001408 Attribute::get(Func->getContext(), B));
Evgeniy Stepanov383b61e2012-12-07 09:08:32 +00001409 }
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001410 }
1411 IRBuilder<> IRB(&I);
1412 unsigned ArgOffset = 0;
1413 DEBUG(dbgs() << " CallSite: " << I << "\n");
1414 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1415 ArgIt != End; ++ArgIt) {
1416 Value *A = *ArgIt;
1417 unsigned i = ArgIt - CS.arg_begin();
1418 if (!A->getType()->isSized()) {
1419 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1420 continue;
1421 }
1422 unsigned Size = 0;
1423 Value *Store = 0;
1424 // Compute the Shadow for arg even if it is ByVal, because
1425 // in that case getShadow() will copy the actual arg shadow to
1426 // __msan_param_tls.
1427 Value *ArgShadow = getShadow(A);
1428 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1429 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1430 " Shadow: " << *ArgShadow << "\n");
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001431 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001432 assert(A->getType()->isPointerTy() &&
1433 "ByVal argument is not a pointer!");
1434 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1435 unsigned Alignment = CS.getParamAlignment(i + 1);
1436 Store = IRB.CreateMemCpy(ArgShadowBase,
1437 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1438 Size, Alignment);
1439 } else {
1440 Size = MS.TD->getTypeAllocSize(A->getType());
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001441 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1442 kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001443 }
1444 if (ClTrackOrigins)
Evgeniy Stepanov49175b22012-12-14 13:43:11 +00001445 IRB.CreateStore(getOrigin(A),
1446 getOriginPtrForArgument(A, IRB, ArgOffset));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001447 assert(Size != 0 && Store != 0);
1448 DEBUG(dbgs() << " Param:" << *Store << "\n");
1449 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1450 }
1451 DEBUG(dbgs() << " done with call args\n");
1452
1453 FunctionType *FT =
1454 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1455 if (FT->isVarArg()) {
1456 VAHelper->visitCallSite(CS, IRB);
1457 }
1458
1459 // Now, get the shadow for the RetVal.
1460 if (!I.getType()->isSized()) return;
1461 IRBuilder<> IRBBefore(&I);
1462 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1463 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001464 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001465 Instruction *NextInsn = 0;
1466 if (CS.isCall()) {
1467 NextInsn = I.getNextNode();
1468 } else {
1469 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1470 if (!NormalDest->getSinglePredecessor()) {
1471 // FIXME: this case is tricky, so we are just conservative here.
1472 // Perhaps we need to split the edge between this BB and NormalDest,
1473 // but a naive attempt to use SplitEdge leads to a crash.
1474 setShadow(&I, getCleanShadow(&I));
1475 setOrigin(&I, getCleanOrigin());
1476 return;
1477 }
1478 NextInsn = NormalDest->getFirstInsertionPt();
1479 assert(NextInsn &&
1480 "Could not find insertion point for retval shadow load");
1481 }
1482 IRBuilder<> IRBAfter(NextInsn);
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001483 Value *RetvalShadow =
1484 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1485 kShadowTLSAlignment, "_msret");
1486 setShadow(&I, RetvalShadow);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001487 if (ClTrackOrigins)
1488 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1489 }
1490
1491 void visitReturnInst(ReturnInst &I) {
1492 IRBuilder<> IRB(&I);
1493 if (Value *RetVal = I.getReturnValue()) {
1494 // Set the shadow for the RetVal.
1495 Value *Shadow = getShadow(RetVal);
1496 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1497 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001498 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001499 if (ClTrackOrigins)
1500 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1501 }
1502 }
1503
1504 void visitPHINode(PHINode &I) {
1505 IRBuilder<> IRB(&I);
1506 ShadowPHINodes.push_back(&I);
1507 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1508 "_msphi_s"));
1509 if (ClTrackOrigins)
1510 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1511 "_msphi_o"));
1512 }
1513
1514 void visitAllocaInst(AllocaInst &I) {
1515 setShadow(&I, getCleanShadow(&I));
1516 if (!ClPoisonStack) return;
1517 IRBuilder<> IRB(I.getNextNode());
1518 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1519 if (ClPoisonStackWithCall) {
1520 IRB.CreateCall2(MS.MsanPoisonStackFn,
1521 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1522 ConstantInt::get(MS.IntptrTy, Size));
1523 } else {
1524 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1525 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1526 Size, I.getAlignment());
1527 }
1528
1529 if (ClTrackOrigins) {
1530 setOrigin(&I, getCleanOrigin());
1531 SmallString<2048> StackDescriptionStorage;
1532 raw_svector_ostream StackDescription(StackDescriptionStorage);
1533 // We create a string with a description of the stack allocation and
1534 // pass it into __msan_set_alloca_origin.
1535 // It will be printed by the run-time if stack-originated UMR is found.
1536 // The first 4 bytes of the string are set to '----' and will be replaced
1537 // by __msan_va_arg_overflow_size_tls at the first call.
1538 StackDescription << "----" << I.getName() << "@" << F.getName();
1539 Value *Descr =
1540 createPrivateNonConstGlobalForString(*F.getParent(),
1541 StackDescription.str());
1542 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1543 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1544 ConstantInt::get(MS.IntptrTy, Size),
1545 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1546 }
1547 }
1548
1549 void visitSelectInst(SelectInst& I) {
1550 IRBuilder<> IRB(&I);
1551 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1552 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1553 "_msprop"));
1554 if (ClTrackOrigins)
1555 setOrigin(&I, IRB.CreateSelect(I.getCondition(),
1556 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1557 }
1558
1559 void visitLandingPadInst(LandingPadInst &I) {
1560 // Do nothing.
1561 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1562 setShadow(&I, getCleanShadow(&I));
1563 setOrigin(&I, getCleanOrigin());
1564 }
1565
1566 void visitGetElementPtrInst(GetElementPtrInst &I) {
1567 handleShadowOr(I);
1568 }
1569
1570 void visitExtractValueInst(ExtractValueInst &I) {
1571 IRBuilder<> IRB(&I);
1572 Value *Agg = I.getAggregateOperand();
1573 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1574 Value *AggShadow = getShadow(Agg);
1575 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1576 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1577 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1578 setShadow(&I, ResShadow);
1579 setOrigin(&I, getCleanOrigin());
1580 }
1581
1582 void visitInsertValueInst(InsertValueInst &I) {
1583 IRBuilder<> IRB(&I);
1584 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1585 Value *AggShadow = getShadow(I.getAggregateOperand());
1586 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1587 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1588 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1589 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1590 DEBUG(dbgs() << " Res: " << *Res << "\n");
1591 setShadow(&I, Res);
1592 setOrigin(&I, getCleanOrigin());
1593 }
1594
1595 void dumpInst(Instruction &I) {
1596 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1597 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1598 } else {
1599 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1600 }
1601 errs() << "QQQ " << I << "\n";
1602 }
1603
1604 void visitResumeInst(ResumeInst &I) {
1605 DEBUG(dbgs() << "Resume: " << I << "\n");
1606 // Nothing to do here.
1607 }
1608
1609 void visitInstruction(Instruction &I) {
1610 // Everything else: stop propagating and check for poisoned shadow.
1611 if (ClDumpStrictInstructions)
1612 dumpInst(I);
1613 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1614 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1615 insertCheck(I.getOperand(i), &I);
1616 setShadow(&I, getCleanShadow(&I));
1617 setOrigin(&I, getCleanOrigin());
1618 }
1619};
1620
1621/// \brief AMD64-specific implementation of VarArgHelper.
1622struct VarArgAMD64Helper : public VarArgHelper {
1623 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1624 // See a comment in visitCallSite for more details.
Evgeniy Stepanov9b72e992012-12-14 13:48:31 +00001625 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001626 static const unsigned AMD64FpEndOffset = 176;
1627
1628 Function &F;
1629 MemorySanitizer &MS;
1630 MemorySanitizerVisitor &MSV;
1631 Value *VAArgTLSCopy;
1632 Value *VAArgOverflowSize;
1633
1634 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1635
1636 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1637 MemorySanitizerVisitor &MSV)
1638 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1639
1640 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1641
1642 ArgKind classifyArgument(Value* arg) {
1643 // A very rough approximation of X86_64 argument classification rules.
1644 Type *T = arg->getType();
1645 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1646 return AK_FloatingPoint;
1647 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1648 return AK_GeneralPurpose;
1649 if (T->isPointerTy())
1650 return AK_GeneralPurpose;
1651 return AK_Memory;
1652 }
1653
1654 // For VarArg functions, store the argument shadow in an ABI-specific format
1655 // that corresponds to va_list layout.
1656 // We do this because Clang lowers va_arg in the frontend, and this pass
1657 // only sees the low level code that deals with va_list internals.
1658 // A much easier alternative (provided that Clang emits va_arg instructions)
1659 // would have been to associate each live instance of va_list with a copy of
1660 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1661 // order.
1662 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1663 unsigned GpOffset = 0;
1664 unsigned FpOffset = AMD64GpEndOffset;
1665 unsigned OverflowOffset = AMD64FpEndOffset;
1666 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1667 ArgIt != End; ++ArgIt) {
1668 Value *A = *ArgIt;
1669 ArgKind AK = classifyArgument(A);
1670 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1671 AK = AK_Memory;
1672 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1673 AK = AK_Memory;
1674 Value *Base;
1675 switch (AK) {
1676 case AK_GeneralPurpose:
1677 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1678 GpOffset += 8;
1679 break;
1680 case AK_FloatingPoint:
1681 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1682 FpOffset += 16;
1683 break;
1684 case AK_Memory:
1685 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1686 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1687 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1688 }
Evgeniy Stepanovd2bd3192012-12-11 12:34:09 +00001689 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001690 }
1691 Constant *OverflowSize =
1692 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1693 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1694 }
1695
1696 /// \brief Compute the shadow address for a given va_arg.
1697 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1698 int ArgOffset) {
1699 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1700 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1701 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1702 "_msarg");
1703 }
1704
1705 void visitVAStartInst(VAStartInst &I) {
1706 IRBuilder<> IRB(&I);
1707 VAStartInstrumentationList.push_back(&I);
1708 Value *VAListTag = I.getArgOperand(0);
1709 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1710
1711 // Unpoison the whole __va_list_tag.
1712 // FIXME: magic ABI constants.
1713 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1714 /* size */24, /* alignment */16, false);
1715 }
1716
1717 void visitVACopyInst(VACopyInst &I) {
1718 IRBuilder<> IRB(&I);
1719 Value *VAListTag = I.getArgOperand(0);
1720 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1721
1722 // Unpoison the whole __va_list_tag.
1723 // FIXME: magic ABI constants.
1724 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1725 /* size */ 24, /* alignment */ 16, false);
1726 }
1727
1728 void finalizeInstrumentation() {
1729 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1730 "finalizeInstrumentation called twice");
1731 if (!VAStartInstrumentationList.empty()) {
1732 // If there is a va_start in this function, make a backup copy of
1733 // va_arg_tls somewhere in the function entry block.
1734 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1735 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1736 Value *CopySize =
1737 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1738 VAArgOverflowSize);
1739 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1740 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1741 }
1742
1743 // Instrument va_start.
1744 // Copy va_list shadow from the backup copy of the TLS contents.
1745 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1746 CallInst *OrigInst = VAStartInstrumentationList[i];
1747 IRBuilder<> IRB(OrigInst->getNextNode());
1748 Value *VAListTag = OrigInst->getArgOperand(0);
1749
1750 Value *RegSaveAreaPtrPtr =
1751 IRB.CreateIntToPtr(
1752 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1753 ConstantInt::get(MS.IntptrTy, 16)),
1754 Type::getInt64PtrTy(*MS.C));
1755 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1756 Value *RegSaveAreaShadowPtr =
1757 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1758 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1759 AMD64FpEndOffset, 16);
1760
1761 Value *OverflowArgAreaPtrPtr =
1762 IRB.CreateIntToPtr(
1763 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1764 ConstantInt::get(MS.IntptrTy, 8)),
1765 Type::getInt64PtrTy(*MS.C));
1766 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1767 Value *OverflowArgAreaShadowPtr =
1768 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1769 Value *SrcPtr =
1770 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1771 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1772 }
1773 }
1774};
1775
1776VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1777 MemorySanitizerVisitor &Visitor) {
1778 return new VarArgAMD64Helper(Func, Msan, Visitor);
1779}
1780
1781} // namespace
1782
1783bool MemorySanitizer::runOnFunction(Function &F) {
1784 MemorySanitizerVisitor Visitor(F, *this);
1785
1786 // Clear out readonly/readnone attributes.
1787 AttrBuilder B;
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001788 B.addAttribute(Attribute::ReadOnly)
1789 .addAttribute(Attribute::ReadNone);
Bill Wendlinge94d8432012-12-07 23:16:57 +00001790 F.removeAttribute(AttributeSet::FunctionIndex,
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001791 Attribute::get(F.getContext(), B));
Evgeniy Stepanovd4bd7b72012-11-29 09:57:20 +00001792
1793 return Visitor.runOnFunction();
1794}