1 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
13 /// Status: early prototype.
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.
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).
39 /// The default value of shadow is 0, which means "clean" (not poisoned).
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).
49 /// MemorySanitizer can track origins (allocation points) of all uninitialized
50 /// values. This behavior is controlled with a flag (msan-track-origins) and is
51 /// disabled by default.
53 /// Origins are 4-byte values created and interpreted by the runtime library.
54 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
55 /// of application memory. Propagation of origins is basically a bunch of
56 /// "select" instructions that pick the origin of a dirty argument, if an
57 /// instruction has one.
59 /// Every 4 aligned, consecutive bytes of application memory have one origin
60 /// value associated with them. If these bytes contain uninitialized data
61 /// coming from 2 different allocations, the last store wins. Because of this,
62 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
65 /// Origins are meaningless for fully initialized values, so MemorySanitizer
66 /// avoids storing origin to memory when a fully initialized value is stored.
67 /// This way it avoids needless overwritting origin of the 4-byte region on
68 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
69 //===----------------------------------------------------------------------===//
71 #define DEBUG_TYPE "msan"
73 #include "llvm/Transforms/Instrumentation.h"
74 #include "llvm/ADT/DepthFirstIterator.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/ValueMap.h"
78 #include "llvm/IR/DataLayout.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/IRBuilder.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/IntrinsicInst.h"
83 #include "llvm/IR/LLVMContext.h"
84 #include "llvm/IR/MDBuilder.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Type.h"
87 #include "llvm/InstVisitor.h"
88 #include "llvm/Support/CommandLine.h"
89 #include "llvm/Support/Compiler.h"
90 #include "llvm/Support/Debug.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
93 #include "llvm/Transforms/Utils/BlackList.h"
94 #include "llvm/Transforms/Utils/Local.h"
95 #include "llvm/Transforms/Utils/ModuleUtils.h"
99 static const uint64_t kShadowMask32 = 1ULL << 31;
100 static const uint64_t kShadowMask64 = 1ULL << 46;
101 static const uint64_t kOriginOffset32 = 1ULL << 30;
102 static const uint64_t kOriginOffset64 = 1ULL << 45;
103 static const unsigned kMinOriginAlignment = 4;
104 static const unsigned kShadowTLSAlignment = 8;
106 /// \brief Track origins of uninitialized values.
108 /// Adds a section to MemorySanitizer report that points to the allocation
109 /// (stack or heap) the uninitialized bits came from originally.
110 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
111 cl::desc("Track origins (allocation sites) of poisoned memory"),
112 cl::Hidden, cl::init(false));
113 static cl::opt<bool> ClKeepGoing("msan-keep-going",
114 cl::desc("keep going after reporting a UMR"),
115 cl::Hidden, cl::init(false));
116 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
117 cl::desc("poison uninitialized stack variables"),
118 cl::Hidden, cl::init(true));
119 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
120 cl::desc("poison uninitialized stack variables with a call"),
121 cl::Hidden, cl::init(false));
122 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
123 cl::desc("poison uninitialized stack variables with the given patter"),
124 cl::Hidden, cl::init(0xff));
126 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
127 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
128 cl::Hidden, cl::init(true));
130 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
131 cl::desc("exact handling of relational integer ICmp"),
132 cl::Hidden, cl::init(false));
134 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
135 cl::desc("store origin for clean (fully initialized) values"),
136 cl::Hidden, cl::init(false));
138 // This flag controls whether we check the shadow of the address
139 // operand of load or store. Such bugs are very rare, since load from
140 // a garbage address typically results in SEGV, but still happen
141 // (e.g. only lower bits of address are garbage, or the access happens
142 // early at program startup where malloc-ed memory is more likely to
143 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
144 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
145 cl::desc("report accesses through a pointer which has poisoned shadow"),
146 cl::Hidden, cl::init(true));
148 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
149 cl::desc("print out instructions with default strict semantics"),
150 cl::Hidden, cl::init(false));
152 static cl::opt<std::string> ClBlacklistFile("msan-blacklist",
153 cl::desc("File containing the list of functions where MemorySanitizer "
154 "should not report bugs"), cl::Hidden);
158 /// \brief An instrumentation pass implementing detection of uninitialized
161 /// MemorySanitizer: instrument the code in module to find
162 /// uninitialized reads.
163 class MemorySanitizer : public FunctionPass {
165 MemorySanitizer(bool TrackOrigins = false,
166 StringRef BlacklistFile = StringRef())
168 TrackOrigins(TrackOrigins || ClTrackOrigins),
171 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
173 const char *getPassName() const { return "MemorySanitizer"; }
174 bool runOnFunction(Function &F);
175 bool doInitialization(Module &M);
176 static char ID; // Pass identification, replacement for typeid.
179 void initializeCallbacks(Module &M);
181 /// \brief Track origins (allocation points) of uninitialized values.
188 /// \brief Thread-local shadow storage for function parameters.
189 GlobalVariable *ParamTLS;
190 /// \brief Thread-local origin storage for function parameters.
191 GlobalVariable *ParamOriginTLS;
192 /// \brief Thread-local shadow storage for function return value.
193 GlobalVariable *RetvalTLS;
194 /// \brief Thread-local origin storage for function return value.
195 GlobalVariable *RetvalOriginTLS;
196 /// \brief Thread-local shadow storage for in-register va_arg function
197 /// parameters (x86_64-specific).
198 GlobalVariable *VAArgTLS;
199 /// \brief Thread-local shadow storage for va_arg overflow area
200 /// (x86_64-specific).
201 GlobalVariable *VAArgOverflowSizeTLS;
202 /// \brief Thread-local space used to pass origin value to the UMR reporting
204 GlobalVariable *OriginTLS;
206 /// \brief The run-time callback to print a warning.
208 /// \brief Run-time helper that copies origin info for a memory range.
209 Value *MsanCopyOriginFn;
210 /// \brief Run-time helper that generates a new origin value for a stack
212 Value *MsanSetAllocaOriginFn;
213 /// \brief Run-time helper that poisons stack on function entry.
214 Value *MsanPoisonStackFn;
215 /// \brief MSan runtime replacements for memmove, memcpy and memset.
216 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
218 /// \brief Address mask used in application-to-shadow address calculation.
219 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
221 /// \brief Offset of the origin shadow from the "normal" shadow.
222 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
223 uint64_t OriginOffset;
224 /// \brief Branch weights for error reporting.
225 MDNode *ColdCallWeights;
226 /// \brief Branch weights for origin store.
227 MDNode *OriginStoreWeights;
228 /// \bried Path to blacklist file.
229 SmallString<64> BlacklistFile;
230 /// \brief The blacklist.
231 OwningPtr<BlackList> BL;
232 /// \brief An empty volatile inline asm that prevents callback merge.
235 friend struct MemorySanitizerVisitor;
236 friend struct VarArgAMD64Helper;
240 char MemorySanitizer::ID = 0;
241 INITIALIZE_PASS(MemorySanitizer, "msan",
242 "MemorySanitizer: detects uninitialized reads.",
245 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
246 StringRef BlacklistFile) {
247 return new MemorySanitizer(TrackOrigins, BlacklistFile);
250 /// \brief Create a non-const global initialized with the given string.
252 /// Creates a writable global for Str so that we can pass it to the
253 /// run-time lib. Runtime uses first 4 bytes of the string to store the
254 /// frame ID, so the string needs to be mutable.
255 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
257 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
258 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
259 GlobalValue::PrivateLinkage, StrConst, "");
263 /// \brief Insert extern declaration of runtime-provided functions and globals.
264 void MemorySanitizer::initializeCallbacks(Module &M) {
265 // Only do this once.
270 // Create the callback.
271 // FIXME: this function should have "Cold" calling conv,
272 // which is not yet implemented.
273 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
274 : "__msan_warning_noreturn";
275 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
277 MsanCopyOriginFn = M.getOrInsertFunction(
278 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
279 IRB.getInt8PtrTy(), IntptrTy, NULL);
280 MsanSetAllocaOriginFn = M.getOrInsertFunction(
281 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
282 IRB.getInt8PtrTy(), NULL);
283 MsanPoisonStackFn = M.getOrInsertFunction(
284 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
285 MemmoveFn = M.getOrInsertFunction(
286 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
287 IRB.getInt8PtrTy(), IntptrTy, NULL);
288 MemcpyFn = M.getOrInsertFunction(
289 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
291 MemsetFn = M.getOrInsertFunction(
292 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
296 RetvalTLS = new GlobalVariable(
297 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
298 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
299 GlobalVariable::GeneralDynamicTLSModel);
300 RetvalOriginTLS = new GlobalVariable(
301 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
302 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
304 ParamTLS = new GlobalVariable(
305 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
306 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
307 GlobalVariable::GeneralDynamicTLSModel);
308 ParamOriginTLS = new GlobalVariable(
309 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
310 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
312 VAArgTLS = new GlobalVariable(
313 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
314 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
315 GlobalVariable::GeneralDynamicTLSModel);
316 VAArgOverflowSizeTLS = new GlobalVariable(
317 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
318 "__msan_va_arg_overflow_size_tls", 0,
319 GlobalVariable::GeneralDynamicTLSModel);
320 OriginTLS = new GlobalVariable(
321 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
322 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
324 // We insert an empty inline asm after __msan_report* to avoid callback merge.
325 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
326 StringRef(""), StringRef(""),
327 /*hasSideEffects=*/true);
330 /// \brief Module-level initialization.
332 /// inserts a call to __msan_init to the module's constructor list.
333 bool MemorySanitizer::doInitialization(Module &M) {
334 TD = getAnalysisIfAvailable<DataLayout>();
337 BL.reset(new BlackList(BlacklistFile));
338 C = &(M.getContext());
339 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
342 ShadowMask = kShadowMask64;
343 OriginOffset = kOriginOffset64;
346 ShadowMask = kShadowMask32;
347 OriginOffset = kOriginOffset32;
350 report_fatal_error("unsupported pointer size");
355 IntptrTy = IRB.getIntPtrTy(TD);
356 OriginTy = IRB.getInt32Ty();
358 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
359 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
361 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
362 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
363 "__msan_init", IRB.getVoidTy(), NULL)), 0);
365 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
366 IRB.getInt32(TrackOrigins), "__msan_track_origins");
368 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
369 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
376 /// \brief A helper class that handles instrumentation of VarArg
377 /// functions on a particular platform.
379 /// Implementations are expected to insert the instrumentation
380 /// necessary to propagate argument shadow through VarArg function
381 /// calls. Visit* methods are called during an InstVisitor pass over
382 /// the function, and should avoid creating new basic blocks. A new
383 /// instance of this class is created for each instrumented function.
384 struct VarArgHelper {
385 /// \brief Visit a CallSite.
386 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
388 /// \brief Visit a va_start call.
389 virtual void visitVAStartInst(VAStartInst &I) = 0;
391 /// \brief Visit a va_copy call.
392 virtual void visitVACopyInst(VACopyInst &I) = 0;
394 /// \brief Finalize function instrumentation.
396 /// This method is called after visiting all interesting (see above)
397 /// instructions in a function.
398 virtual void finalizeInstrumentation() = 0;
400 virtual ~VarArgHelper() {}
403 struct MemorySanitizerVisitor;
406 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
407 MemorySanitizerVisitor &Visitor);
409 /// This class does all the work for a given function. Store and Load
410 /// instructions store and load corresponding shadow and origin
411 /// values. Most instructions propagate shadow from arguments to their
412 /// return values. Certain instructions (most importantly, BranchInst)
413 /// test their argument shadow and print reports (with a runtime call) if it's
415 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
418 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
419 ValueMap<Value*, Value*> ShadowMap, OriginMap;
421 OwningPtr<VarArgHelper> VAHelper;
423 struct ShadowOriginAndInsertPoint {
426 Instruction *OrigIns;
427 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
428 : Shadow(S), Origin(O), OrigIns(I) { }
429 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
431 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
432 SmallVector<Instruction*, 16> StoreList;
434 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
435 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
436 InsertChecks = !MS.BL->isIn(F);
437 DEBUG(if (!InsertChecks)
438 dbgs() << "MemorySanitizer is not inserting checks into '"
439 << F.getName() << "'\n");
442 void materializeStores() {
443 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
444 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
447 Value *Val = I.getValueOperand();
448 Value *Addr = I.getPointerOperand();
449 Value *Shadow = getShadow(Val);
450 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
453 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
454 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
457 if (ClCheckAccessAddress)
458 insertCheck(Addr, &I);
460 if (MS.TrackOrigins) {
461 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
462 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
463 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
466 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
468 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
469 // TODO(eugenis): handle non-zero constant shadow by inserting an
470 // unconditional check (can not simply fail compilation as this could
471 // be in the dead code).
475 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
476 getCleanShadow(ConvertedShadow), "_mscmp");
477 Instruction *CheckTerm =
478 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
479 MS.OriginStoreWeights);
480 IRBuilder<> IRBNew(CheckTerm);
481 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
488 void materializeChecks() {
489 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
490 Instruction *Shadow = InstrumentationList[i].Shadow;
491 Instruction *OrigIns = InstrumentationList[i].OrigIns;
492 IRBuilder<> IRB(OrigIns);
493 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
494 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
495 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
496 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
497 getCleanShadow(ConvertedShadow), "_mscmp");
498 Instruction *CheckTerm =
499 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
500 /* Unreachable */ !ClKeepGoing,
503 IRB.SetInsertPoint(CheckTerm);
504 if (MS.TrackOrigins) {
505 Instruction *Origin = InstrumentationList[i].Origin;
506 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
509 CallInst *Call = IRB.CreateCall(MS.WarningFn);
510 Call->setDebugLoc(OrigIns->getDebugLoc());
511 IRB.CreateCall(MS.EmptyAsm);
512 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
514 DEBUG(dbgs() << "DONE:\n" << F);
517 /// \brief Add MemorySanitizer instrumentation to a function.
518 bool runOnFunction() {
519 MS.initializeCallbacks(*F.getParent());
520 if (!MS.TD) return false;
522 // In the presence of unreachable blocks, we may see Phi nodes with
523 // incoming nodes from such blocks. Since InstVisitor skips unreachable
524 // blocks, such nodes will not have any shadow value associated with them.
525 // It's easier to remove unreachable blocks than deal with missing shadow.
526 removeUnreachableBlocks(F);
528 // Iterate all BBs in depth-first order and create shadow instructions
529 // for all instructions (where applicable).
530 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
531 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
532 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
533 BasicBlock *BB = *DI;
537 // Finalize PHI nodes.
538 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
539 PHINode *PN = ShadowPHINodes[i];
540 PHINode *PNS = cast<PHINode>(getShadow(PN));
541 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
542 size_t NumValues = PN->getNumIncomingValues();
543 for (size_t v = 0; v < NumValues; v++) {
544 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
546 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
550 VAHelper->finalizeInstrumentation();
552 // Delayed instrumentation of StoreInst.
553 // This may add new checks to be inserted later.
556 // Insert shadow value checks.
562 /// \brief Compute the shadow type that corresponds to a given Value.
563 Type *getShadowTy(Value *V) {
564 return getShadowTy(V->getType());
567 /// \brief Compute the shadow type that corresponds to a given Type.
568 Type *getShadowTy(Type *OrigTy) {
569 if (!OrigTy->isSized()) {
572 // For integer type, shadow is the same as the original type.
573 // This may return weird-sized types like i1.
574 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
576 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
577 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
578 return VectorType::get(IntegerType::get(*MS.C, EltSize),
579 VT->getNumElements());
581 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
582 SmallVector<Type*, 4> Elements;
583 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
584 Elements.push_back(getShadowTy(ST->getElementType(i)));
585 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
586 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
589 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
590 return IntegerType::get(*MS.C, TypeSize);
593 /// \brief Flatten a vector type.
594 Type *getShadowTyNoVec(Type *ty) {
595 if (VectorType *vt = dyn_cast<VectorType>(ty))
596 return IntegerType::get(*MS.C, vt->getBitWidth());
600 /// \brief Convert a shadow value to it's flattened variant.
601 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
602 Type *Ty = V->getType();
603 Type *NoVecTy = getShadowTyNoVec(Ty);
604 if (Ty == NoVecTy) return V;
605 return IRB.CreateBitCast(V, NoVecTy);
608 /// \brief Compute the shadow address that corresponds to a given application
611 /// Shadow = Addr & ~ShadowMask.
612 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
615 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
616 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
617 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
620 /// \brief Compute the origin address that corresponds to a given application
623 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
624 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
626 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
627 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
629 IRB.CreateAdd(ShadowLong,
630 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
632 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
633 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
636 /// \brief Compute the shadow address for a given function argument.
638 /// Shadow = ParamTLS+ArgOffset.
639 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
641 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
642 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
643 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
647 /// \brief Compute the origin address for a given function argument.
648 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
650 if (!MS.TrackOrigins) return 0;
651 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
652 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
653 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
657 /// \brief Compute the shadow address for a retval.
658 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
659 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
660 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
664 /// \brief Compute the origin address for a retval.
665 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
666 // We keep a single origin for the entire retval. Might be too optimistic.
667 return MS.RetvalOriginTLS;
670 /// \brief Set SV to be the shadow value for V.
671 void setShadow(Value *V, Value *SV) {
672 assert(!ShadowMap.count(V) && "Values may only have one shadow");
676 /// \brief Set Origin to be the origin value for V.
677 void setOrigin(Value *V, Value *Origin) {
678 if (!MS.TrackOrigins) return;
679 assert(!OriginMap.count(V) && "Values may only have one origin");
680 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
681 OriginMap[V] = Origin;
684 /// \brief Create a clean shadow value for a given value.
686 /// Clean shadow (all zeroes) means all bits of the value are defined
688 Value *getCleanShadow(Value *V) {
689 Type *ShadowTy = getShadowTy(V);
692 return Constant::getNullValue(ShadowTy);
695 /// \brief Create a dirty shadow of a given shadow type.
696 Constant *getPoisonedShadow(Type *ShadowTy) {
698 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
699 return Constant::getAllOnesValue(ShadowTy);
700 StructType *ST = cast<StructType>(ShadowTy);
701 SmallVector<Constant *, 4> Vals;
702 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
703 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
704 return ConstantStruct::get(ST, Vals);
707 /// \brief Create a clean (zero) origin.
708 Value *getCleanOrigin() {
709 return Constant::getNullValue(MS.OriginTy);
712 /// \brief Get the shadow value for a given Value.
714 /// This function either returns the value set earlier with setShadow,
715 /// or extracts if from ParamTLS (for function arguments).
716 Value *getShadow(Value *V) {
717 if (Instruction *I = dyn_cast<Instruction>(V)) {
718 // For instructions the shadow is already stored in the map.
719 Value *Shadow = ShadowMap[V];
721 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
723 assert(Shadow && "No shadow for a value");
727 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
728 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
729 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
733 if (Argument *A = dyn_cast<Argument>(V)) {
734 // For arguments we compute the shadow on demand and store it in the map.
735 Value **ShadowPtr = &ShadowMap[V];
738 Function *F = A->getParent();
739 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
740 unsigned ArgOffset = 0;
741 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
743 if (!AI->getType()->isSized()) {
744 DEBUG(dbgs() << "Arg is not sized\n");
747 unsigned Size = AI->hasByValAttr()
748 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
749 : MS.TD->getTypeAllocSize(AI->getType());
751 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
752 if (AI->hasByValAttr()) {
753 // ByVal pointer itself has clean shadow. We copy the actual
754 // argument shadow to the underlying memory.
755 Value *Cpy = EntryIRB.CreateMemCpy(
756 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
757 Base, Size, AI->getParamAlignment());
758 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
760 *ShadowPtr = getCleanShadow(V);
762 *ShadowPtr = EntryIRB.CreateLoad(Base);
764 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
765 **ShadowPtr << "\n");
766 if (MS.TrackOrigins) {
767 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
768 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
771 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
773 assert(*ShadowPtr && "Could not find shadow for an argument");
776 // For everything else the shadow is zero.
777 return getCleanShadow(V);
780 /// \brief Get the shadow for i-th argument of the instruction I.
781 Value *getShadow(Instruction *I, int i) {
782 return getShadow(I->getOperand(i));
785 /// \brief Get the origin for a value.
786 Value *getOrigin(Value *V) {
787 if (!MS.TrackOrigins) return 0;
788 if (isa<Instruction>(V) || isa<Argument>(V)) {
789 Value *Origin = OriginMap[V];
791 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
792 Origin = getCleanOrigin();
796 return getCleanOrigin();
799 /// \brief Get the origin for i-th argument of the instruction I.
800 Value *getOrigin(Instruction *I, int i) {
801 return getOrigin(I->getOperand(i));
804 /// \brief Remember the place where a shadow check should be inserted.
806 /// This location will be later instrumented with a check that will print a
807 /// UMR warning in runtime if the value is not fully defined.
808 void insertCheck(Value *Val, Instruction *OrigIns) {
810 if (!InsertChecks) return;
811 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
814 Type *ShadowTy = Shadow->getType();
815 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
816 "Can only insert checks for integer and vector shadow types");
818 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
819 InstrumentationList.push_back(
820 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
823 // ------------------- Visitors.
825 /// \brief Instrument LoadInst
827 /// Loads the corresponding shadow and (optionally) origin.
828 /// Optionally, checks that the load address is fully defined.
829 void visitLoadInst(LoadInst &I) {
830 assert(I.getType()->isSized() && "Load type must have size");
832 Type *ShadowTy = getShadowTy(&I);
833 Value *Addr = I.getPointerOperand();
834 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
835 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
837 if (ClCheckAccessAddress)
838 insertCheck(I.getPointerOperand(), &I);
840 if (MS.TrackOrigins) {
841 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
842 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
846 /// \brief Instrument StoreInst
848 /// Stores the corresponding shadow and (optionally) origin.
849 /// Optionally, checks that the store address is fully defined.
850 void visitStoreInst(StoreInst &I) {
851 StoreList.push_back(&I);
854 // Vector manipulation.
855 void visitExtractElementInst(ExtractElementInst &I) {
856 insertCheck(I.getOperand(1), &I);
858 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
860 setOrigin(&I, getOrigin(&I, 0));
863 void visitInsertElementInst(InsertElementInst &I) {
864 insertCheck(I.getOperand(2), &I);
866 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
867 I.getOperand(2), "_msprop"));
868 setOriginForNaryOp(I);
871 void visitShuffleVectorInst(ShuffleVectorInst &I) {
872 insertCheck(I.getOperand(2), &I);
874 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
875 I.getOperand(2), "_msprop"));
876 setOriginForNaryOp(I);
880 void visitSExtInst(SExtInst &I) {
882 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
883 setOrigin(&I, getOrigin(&I, 0));
886 void visitZExtInst(ZExtInst &I) {
888 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
889 setOrigin(&I, getOrigin(&I, 0));
892 void visitTruncInst(TruncInst &I) {
894 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
895 setOrigin(&I, getOrigin(&I, 0));
898 void visitBitCastInst(BitCastInst &I) {
900 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
901 setOrigin(&I, getOrigin(&I, 0));
904 void visitPtrToIntInst(PtrToIntInst &I) {
906 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
907 "_msprop_ptrtoint"));
908 setOrigin(&I, getOrigin(&I, 0));
911 void visitIntToPtrInst(IntToPtrInst &I) {
913 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
914 "_msprop_inttoptr"));
915 setOrigin(&I, getOrigin(&I, 0));
918 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
919 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
920 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
921 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
922 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
923 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
925 /// \brief Propagate shadow for bitwise AND.
927 /// This code is exact, i.e. if, for example, a bit in the left argument
928 /// is defined and 0, then neither the value not definedness of the
929 /// corresponding bit in B don't affect the resulting shadow.
930 void visitAnd(BinaryOperator &I) {
932 // "And" of 0 and a poisoned value results in unpoisoned value.
933 // 1&1 => 1; 0&1 => 0; p&1 => p;
934 // 1&0 => 0; 0&0 => 0; p&0 => 0;
935 // 1&p => p; 0&p => 0; p&p => p;
936 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
937 Value *S1 = getShadow(&I, 0);
938 Value *S2 = getShadow(&I, 1);
939 Value *V1 = I.getOperand(0);
940 Value *V2 = I.getOperand(1);
941 if (V1->getType() != S1->getType()) {
942 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
943 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
945 Value *S1S2 = IRB.CreateAnd(S1, S2);
946 Value *V1S2 = IRB.CreateAnd(V1, S2);
947 Value *S1V2 = IRB.CreateAnd(S1, V2);
948 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
949 setOriginForNaryOp(I);
952 void visitOr(BinaryOperator &I) {
954 // "Or" of 1 and a poisoned value results in unpoisoned value.
955 // 1|1 => 1; 0|1 => 1; p|1 => 1;
956 // 1|0 => 1; 0|0 => 0; p|0 => p;
957 // 1|p => 1; 0|p => p; p|p => p;
958 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
959 Value *S1 = getShadow(&I, 0);
960 Value *S2 = getShadow(&I, 1);
961 Value *V1 = IRB.CreateNot(I.getOperand(0));
962 Value *V2 = IRB.CreateNot(I.getOperand(1));
963 if (V1->getType() != S1->getType()) {
964 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
965 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
967 Value *S1S2 = IRB.CreateAnd(S1, S2);
968 Value *V1S2 = IRB.CreateAnd(V1, S2);
969 Value *S1V2 = IRB.CreateAnd(S1, V2);
970 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
971 setOriginForNaryOp(I);
974 /// \brief Default propagation of shadow and/or origin.
976 /// This class implements the general case of shadow propagation, used in all
977 /// cases where we don't know and/or don't care about what the operation
978 /// actually does. It converts all input shadow values to a common type
979 /// (extending or truncating as necessary), and bitwise OR's them.
981 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
982 /// fully initialized), and less prone to false positives.
984 /// This class also implements the general case of origin propagation. For a
985 /// Nary operation, result origin is set to the origin of an argument that is
986 /// not entirely initialized. If there is more than one such arguments, the
987 /// rightmost of them is picked. It does not matter which one is picked if all
988 /// arguments are initialized.
989 template <bool CombineShadow>
994 MemorySanitizerVisitor *MSV;
997 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
998 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1000 /// \brief Add a pair of shadow and origin values to the mix.
1001 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1002 if (CombineShadow) {
1007 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1008 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1012 if (MSV->MS.TrackOrigins) {
1017 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1018 Value *Cond = IRB.CreateICmpNE(FlatShadow,
1019 MSV->getCleanShadow(FlatShadow));
1020 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1026 /// \brief Add an application value to the mix.
1027 Combiner &Add(Value *V) {
1028 Value *OpShadow = MSV->getShadow(V);
1029 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1030 return Add(OpShadow, OpOrigin);
1033 /// \brief Set the current combined values as the given instruction's shadow
1035 void Done(Instruction *I) {
1036 if (CombineShadow) {
1038 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1039 MSV->setShadow(I, Shadow);
1041 if (MSV->MS.TrackOrigins) {
1043 MSV->setOrigin(I, Origin);
1048 typedef Combiner<true> ShadowAndOriginCombiner;
1049 typedef Combiner<false> OriginCombiner;
1051 /// \brief Propagate origin for arbitrary operation.
1052 void setOriginForNaryOp(Instruction &I) {
1053 if (!MS.TrackOrigins) return;
1054 IRBuilder<> IRB(&I);
1055 OriginCombiner OC(this, IRB);
1056 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1061 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1062 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1063 "Vector of pointers is not a valid shadow type");
1064 return Ty->isVectorTy() ?
1065 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1066 Ty->getPrimitiveSizeInBits();
1069 /// \brief Cast between two shadow types, extending or truncating as
1071 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1072 Type *srcTy = V->getType();
1073 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1074 return IRB.CreateIntCast(V, dstTy, false);
1075 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1076 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1077 return IRB.CreateIntCast(V, dstTy, false);
1078 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1079 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1080 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1082 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1083 return IRB.CreateBitCast(V2, dstTy);
1084 // TODO: handle struct types.
1087 /// \brief Propagate shadow for arbitrary operation.
1088 void handleShadowOr(Instruction &I) {
1089 IRBuilder<> IRB(&I);
1090 ShadowAndOriginCombiner SC(this, IRB);
1091 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1096 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1097 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1098 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1099 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1100 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1101 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1102 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1104 void handleDiv(Instruction &I) {
1105 IRBuilder<> IRB(&I);
1106 // Strict on the second argument.
1107 insertCheck(I.getOperand(1), &I);
1108 setShadow(&I, getShadow(&I, 0));
1109 setOrigin(&I, getOrigin(&I, 0));
1112 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1113 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1114 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1115 void visitURem(BinaryOperator &I) { handleDiv(I); }
1116 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1117 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1119 /// \brief Instrument == and != comparisons.
1121 /// Sometimes the comparison result is known even if some of the bits of the
1122 /// arguments are not.
1123 void handleEqualityComparison(ICmpInst &I) {
1124 IRBuilder<> IRB(&I);
1125 Value *A = I.getOperand(0);
1126 Value *B = I.getOperand(1);
1127 Value *Sa = getShadow(A);
1128 Value *Sb = getShadow(B);
1130 // Get rid of pointers and vectors of pointers.
1131 // For ints (and vectors of ints), types of A and Sa match,
1132 // and this is a no-op.
1133 A = IRB.CreatePointerCast(A, Sa->getType());
1134 B = IRB.CreatePointerCast(B, Sb->getType());
1136 // A == B <==> (C = A^B) == 0
1137 // A != B <==> (C = A^B) != 0
1139 Value *C = IRB.CreateXor(A, B);
1140 Value *Sc = IRB.CreateOr(Sa, Sb);
1141 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1142 // Result is defined if one of the following is true
1143 // * there is a defined 1 bit in C
1144 // * C is fully defined
1145 // Si = !(C & ~Sc) && Sc
1146 Value *Zero = Constant::getNullValue(Sc->getType());
1147 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1149 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1151 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1152 Si->setName("_msprop_icmp");
1154 setOriginForNaryOp(I);
1157 /// \brief Build the lowest possible value of V, taking into account V's
1158 /// uninitialized bits.
1159 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1162 // Split shadow into sign bit and other bits.
1163 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1164 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1165 // Maximise the undefined shadow bit, minimize other undefined bits.
1167 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1169 // Minimize undefined bits.
1170 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1174 /// \brief Build the highest possible value of V, taking into account V's
1175 /// uninitialized bits.
1176 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1179 // Split shadow into sign bit and other bits.
1180 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1181 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1182 // Minimise the undefined shadow bit, maximise other undefined bits.
1184 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1186 // Maximize undefined bits.
1187 return IRB.CreateOr(A, Sa);
1191 /// \brief Instrument relational comparisons.
1193 /// This function does exact shadow propagation for all relational
1194 /// comparisons of integers, pointers and vectors of those.
1195 /// FIXME: output seems suboptimal when one of the operands is a constant
1196 void handleRelationalComparisonExact(ICmpInst &I) {
1197 IRBuilder<> IRB(&I);
1198 Value *A = I.getOperand(0);
1199 Value *B = I.getOperand(1);
1200 Value *Sa = getShadow(A);
1201 Value *Sb = getShadow(B);
1203 // Get rid of pointers and vectors of pointers.
1204 // For ints (and vectors of ints), types of A and Sa match,
1205 // and this is a no-op.
1206 A = IRB.CreatePointerCast(A, Sa->getType());
1207 B = IRB.CreatePointerCast(B, Sb->getType());
1209 // Let [a0, a1] be the interval of possible values of A, taking into account
1210 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1211 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1212 bool IsSigned = I.isSigned();
1213 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1214 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1215 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1216 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1217 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1218 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1219 Value *Si = IRB.CreateXor(S1, S2);
1221 setOriginForNaryOp(I);
1224 /// \brief Instrument signed relational comparisons.
1226 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1227 /// propagating the highest bit of the shadow. Everything else is delegated
1228 /// to handleShadowOr().
1229 void handleSignedRelationalComparison(ICmpInst &I) {
1230 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1231 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1233 CmpInst::Predicate pre = I.getPredicate();
1234 if (constOp0 && constOp0->isNullValue() &&
1235 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1236 op = I.getOperand(1);
1237 } else if (constOp1 && constOp1->isNullValue() &&
1238 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1239 op = I.getOperand(0);
1242 IRBuilder<> IRB(&I);
1244 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1245 setShadow(&I, Shadow);
1246 setOrigin(&I, getOrigin(op));
1252 void visitICmpInst(ICmpInst &I) {
1253 if (!ClHandleICmp) {
1257 if (I.isEquality()) {
1258 handleEqualityComparison(I);
1262 assert(I.isRelational());
1263 if (ClHandleICmpExact) {
1264 handleRelationalComparisonExact(I);
1268 handleSignedRelationalComparison(I);
1272 assert(I.isUnsigned());
1273 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1274 handleRelationalComparisonExact(I);
1281 void visitFCmpInst(FCmpInst &I) {
1285 void handleShift(BinaryOperator &I) {
1286 IRBuilder<> IRB(&I);
1287 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1288 // Otherwise perform the same shift on S1.
1289 Value *S1 = getShadow(&I, 0);
1290 Value *S2 = getShadow(&I, 1);
1291 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1293 Value *V2 = I.getOperand(1);
1294 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1295 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1296 setOriginForNaryOp(I);
1299 void visitShl(BinaryOperator &I) { handleShift(I); }
1300 void visitAShr(BinaryOperator &I) { handleShift(I); }
1301 void visitLShr(BinaryOperator &I) { handleShift(I); }
1303 /// \brief Instrument llvm.memmove
1305 /// At this point we don't know if llvm.memmove will be inlined or not.
1306 /// If we don't instrument it and it gets inlined,
1307 /// our interceptor will not kick in and we will lose the memmove.
1308 /// If we instrument the call here, but it does not get inlined,
1309 /// we will memove the shadow twice: which is bad in case
1310 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1312 /// Similar situation exists for memcpy and memset.
1313 void visitMemMoveInst(MemMoveInst &I) {
1314 IRBuilder<> IRB(&I);
1317 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1318 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1319 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1320 I.eraseFromParent();
1323 // Similar to memmove: avoid copying shadow twice.
1324 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1325 // FIXME: consider doing manual inline for small constant sizes and proper
1327 void visitMemCpyInst(MemCpyInst &I) {
1328 IRBuilder<> IRB(&I);
1331 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1332 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1333 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1334 I.eraseFromParent();
1338 void visitMemSetInst(MemSetInst &I) {
1339 IRBuilder<> IRB(&I);
1342 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1343 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1344 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1345 I.eraseFromParent();
1348 void visitVAStartInst(VAStartInst &I) {
1349 VAHelper->visitVAStartInst(I);
1352 void visitVACopyInst(VACopyInst &I) {
1353 VAHelper->visitVACopyInst(I);
1356 enum IntrinsicKind {
1357 IK_DoesNotAccessMemory,
1362 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1363 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1364 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1365 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1366 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1367 const int UnknownModRefBehavior = IK_WritesMemory;
1368 #define GET_INTRINSIC_MODREF_BEHAVIOR
1369 #define ModRefBehavior IntrinsicKind
1370 #include "llvm/IR/Intrinsics.gen"
1371 #undef ModRefBehavior
1372 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1375 /// \brief Handle vector store-like intrinsics.
1377 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1378 /// has 1 pointer argument and 1 vector argument, returns void.
1379 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1380 IRBuilder<> IRB(&I);
1381 Value* Addr = I.getArgOperand(0);
1382 Value *Shadow = getShadow(&I, 1);
1383 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1385 // We don't know the pointer alignment (could be unaligned SSE store!).
1386 // Have to assume to worst case.
1387 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1389 if (ClCheckAccessAddress)
1390 insertCheck(Addr, &I);
1392 // FIXME: use ClStoreCleanOrigin
1393 // FIXME: factor out common code from materializeStores
1394 if (MS.TrackOrigins)
1395 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1399 /// \brief Handle vector load-like intrinsics.
1401 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1402 /// has 1 pointer argument, returns a vector.
1403 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1404 IRBuilder<> IRB(&I);
1405 Value *Addr = I.getArgOperand(0);
1407 Type *ShadowTy = getShadowTy(&I);
1408 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1409 // We don't know the pointer alignment (could be unaligned SSE load!).
1410 // Have to assume to worst case.
1411 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1413 if (ClCheckAccessAddress)
1414 insertCheck(Addr, &I);
1416 if (MS.TrackOrigins)
1417 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1421 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1423 /// Instrument intrinsics with any number of arguments of the same type,
1424 /// equal to the return type. The type should be simple (no aggregates or
1425 /// pointers; vectors are fine).
1426 /// Caller guarantees that this intrinsic does not access memory.
1427 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1428 Type *RetTy = I.getType();
1429 if (!(RetTy->isIntOrIntVectorTy() ||
1430 RetTy->isFPOrFPVectorTy() ||
1431 RetTy->isX86_MMXTy()))
1434 unsigned NumArgOperands = I.getNumArgOperands();
1436 for (unsigned i = 0; i < NumArgOperands; ++i) {
1437 Type *Ty = I.getArgOperand(i)->getType();
1442 IRBuilder<> IRB(&I);
1443 ShadowAndOriginCombiner SC(this, IRB);
1444 for (unsigned i = 0; i < NumArgOperands; ++i)
1445 SC.Add(I.getArgOperand(i));
1451 /// \brief Heuristically instrument unknown intrinsics.
1453 /// The main purpose of this code is to do something reasonable with all
1454 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1455 /// We recognize several classes of intrinsics by their argument types and
1456 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1457 /// sure that we know what the intrinsic does.
1459 /// We special-case intrinsics where this approach fails. See llvm.bswap
1460 /// handling as an example of that.
1461 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1462 unsigned NumArgOperands = I.getNumArgOperands();
1463 if (NumArgOperands == 0)
1466 Intrinsic::ID iid = I.getIntrinsicID();
1467 IntrinsicKind IK = getIntrinsicKind(iid);
1468 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1469 bool WritesMemory = IK == IK_WritesMemory;
1470 assert(!(OnlyReadsMemory && WritesMemory));
1472 if (NumArgOperands == 2 &&
1473 I.getArgOperand(0)->getType()->isPointerTy() &&
1474 I.getArgOperand(1)->getType()->isVectorTy() &&
1475 I.getType()->isVoidTy() &&
1477 // This looks like a vector store.
1478 return handleVectorStoreIntrinsic(I);
1481 if (NumArgOperands == 1 &&
1482 I.getArgOperand(0)->getType()->isPointerTy() &&
1483 I.getType()->isVectorTy() &&
1485 // This looks like a vector load.
1486 return handleVectorLoadIntrinsic(I);
1489 if (!OnlyReadsMemory && !WritesMemory)
1490 if (maybeHandleSimpleNomemIntrinsic(I))
1493 // FIXME: detect and handle SSE maskstore/maskload
1497 void handleBswap(IntrinsicInst &I) {
1498 IRBuilder<> IRB(&I);
1499 Value *Op = I.getArgOperand(0);
1500 Type *OpType = Op->getType();
1501 Function *BswapFunc = Intrinsic::getDeclaration(
1502 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1503 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1504 setOrigin(&I, getOrigin(Op));
1507 void visitIntrinsicInst(IntrinsicInst &I) {
1508 switch (I.getIntrinsicID()) {
1509 case llvm::Intrinsic::bswap:
1513 if (!handleUnknownIntrinsic(I))
1514 visitInstruction(I);
1519 void visitCallSite(CallSite CS) {
1520 Instruction &I = *CS.getInstruction();
1521 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1523 CallInst *Call = cast<CallInst>(&I);
1525 // For inline asm, do the usual thing: check argument shadow and mark all
1526 // outputs as clean. Note that any side effects of the inline asm that are
1527 // not immediately visible in its constraints are not handled.
1528 if (Call->isInlineAsm()) {
1529 visitInstruction(I);
1533 // Allow only tail calls with the same types, otherwise
1534 // we may have a false positive: shadow for a non-void RetVal
1535 // will get propagated to a void RetVal.
1536 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1537 Call->setTailCall(false);
1539 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1541 // We are going to insert code that relies on the fact that the callee
1542 // will become a non-readonly function after it is instrumented by us. To
1543 // prevent this code from being optimized out, mark that function
1544 // non-readonly in advance.
1545 if (Function *Func = Call->getCalledFunction()) {
1546 // Clear out readonly/readnone attributes.
1548 B.addAttribute(Attribute::ReadOnly)
1549 .addAttribute(Attribute::ReadNone);
1550 Func->removeAttributes(AttributeSet::FunctionIndex,
1551 AttributeSet::get(Func->getContext(),
1552 AttributeSet::FunctionIndex,
1556 IRBuilder<> IRB(&I);
1557 unsigned ArgOffset = 0;
1558 DEBUG(dbgs() << " CallSite: " << I << "\n");
1559 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1560 ArgIt != End; ++ArgIt) {
1562 unsigned i = ArgIt - CS.arg_begin();
1563 if (!A->getType()->isSized()) {
1564 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1569 // Compute the Shadow for arg even if it is ByVal, because
1570 // in that case getShadow() will copy the actual arg shadow to
1571 // __msan_param_tls.
1572 Value *ArgShadow = getShadow(A);
1573 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1574 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1575 " Shadow: " << *ArgShadow << "\n");
1576 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1577 assert(A->getType()->isPointerTy() &&
1578 "ByVal argument is not a pointer!");
1579 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1580 unsigned Alignment = CS.getParamAlignment(i + 1);
1581 Store = IRB.CreateMemCpy(ArgShadowBase,
1582 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1585 Size = MS.TD->getTypeAllocSize(A->getType());
1586 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1587 kShadowTLSAlignment);
1589 if (MS.TrackOrigins)
1590 IRB.CreateStore(getOrigin(A),
1591 getOriginPtrForArgument(A, IRB, ArgOffset));
1593 assert(Size != 0 && Store != 0);
1594 DEBUG(dbgs() << " Param:" << *Store << "\n");
1595 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1597 DEBUG(dbgs() << " done with call args\n");
1600 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1601 if (FT->isVarArg()) {
1602 VAHelper->visitCallSite(CS, IRB);
1605 // Now, get the shadow for the RetVal.
1606 if (!I.getType()->isSized()) return;
1607 IRBuilder<> IRBBefore(&I);
1608 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1609 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1610 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1611 Instruction *NextInsn = 0;
1613 NextInsn = I.getNextNode();
1615 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1616 if (!NormalDest->getSinglePredecessor()) {
1617 // FIXME: this case is tricky, so we are just conservative here.
1618 // Perhaps we need to split the edge between this BB and NormalDest,
1619 // but a naive attempt to use SplitEdge leads to a crash.
1620 setShadow(&I, getCleanShadow(&I));
1621 setOrigin(&I, getCleanOrigin());
1624 NextInsn = NormalDest->getFirstInsertionPt();
1626 "Could not find insertion point for retval shadow load");
1628 IRBuilder<> IRBAfter(NextInsn);
1629 Value *RetvalShadow =
1630 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1631 kShadowTLSAlignment, "_msret");
1632 setShadow(&I, RetvalShadow);
1633 if (MS.TrackOrigins)
1634 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1637 void visitReturnInst(ReturnInst &I) {
1638 IRBuilder<> IRB(&I);
1639 if (Value *RetVal = I.getReturnValue()) {
1640 // Set the shadow for the RetVal.
1641 Value *Shadow = getShadow(RetVal);
1642 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1643 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1644 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1645 if (MS.TrackOrigins)
1646 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1650 void visitPHINode(PHINode &I) {
1651 IRBuilder<> IRB(&I);
1652 ShadowPHINodes.push_back(&I);
1653 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1655 if (MS.TrackOrigins)
1656 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1660 void visitAllocaInst(AllocaInst &I) {
1661 setShadow(&I, getCleanShadow(&I));
1662 if (!ClPoisonStack) return;
1663 IRBuilder<> IRB(I.getNextNode());
1664 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1665 if (ClPoisonStackWithCall) {
1666 IRB.CreateCall2(MS.MsanPoisonStackFn,
1667 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1668 ConstantInt::get(MS.IntptrTy, Size));
1670 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1671 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1672 Size, I.getAlignment());
1675 if (MS.TrackOrigins) {
1676 setOrigin(&I, getCleanOrigin());
1677 SmallString<2048> StackDescriptionStorage;
1678 raw_svector_ostream StackDescription(StackDescriptionStorage);
1679 // We create a string with a description of the stack allocation and
1680 // pass it into __msan_set_alloca_origin.
1681 // It will be printed by the run-time if stack-originated UMR is found.
1682 // The first 4 bytes of the string are set to '----' and will be replaced
1683 // by __msan_va_arg_overflow_size_tls at the first call.
1684 StackDescription << "----" << I.getName() << "@" << F.getName();
1686 createPrivateNonConstGlobalForString(*F.getParent(),
1687 StackDescription.str());
1688 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1689 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1690 ConstantInt::get(MS.IntptrTy, Size),
1691 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1695 void visitSelectInst(SelectInst& I) {
1696 IRBuilder<> IRB(&I);
1697 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1698 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1700 if (MS.TrackOrigins) {
1701 // Origins are always i32, so any vector conditions must be flattened.
1702 // FIXME: consider tracking vector origins for app vectors?
1703 Value *Cond = I.getCondition();
1704 if (Cond->getType()->isVectorTy()) {
1705 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1706 Cond = IRB.CreateICmpNE(ConvertedShadow,
1707 getCleanShadow(ConvertedShadow), "_mso_select");
1709 setOrigin(&I, IRB.CreateSelect(Cond,
1710 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1714 void visitLandingPadInst(LandingPadInst &I) {
1716 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1717 setShadow(&I, getCleanShadow(&I));
1718 setOrigin(&I, getCleanOrigin());
1721 void visitGetElementPtrInst(GetElementPtrInst &I) {
1725 void visitExtractValueInst(ExtractValueInst &I) {
1726 IRBuilder<> IRB(&I);
1727 Value *Agg = I.getAggregateOperand();
1728 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1729 Value *AggShadow = getShadow(Agg);
1730 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1731 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1732 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1733 setShadow(&I, ResShadow);
1734 setOrigin(&I, getCleanOrigin());
1737 void visitInsertValueInst(InsertValueInst &I) {
1738 IRBuilder<> IRB(&I);
1739 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1740 Value *AggShadow = getShadow(I.getAggregateOperand());
1741 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1742 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1743 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1744 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1745 DEBUG(dbgs() << " Res: " << *Res << "\n");
1747 setOrigin(&I, getCleanOrigin());
1750 void dumpInst(Instruction &I) {
1751 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1752 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1754 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1756 errs() << "QQQ " << I << "\n";
1759 void visitResumeInst(ResumeInst &I) {
1760 DEBUG(dbgs() << "Resume: " << I << "\n");
1761 // Nothing to do here.
1764 void visitInstruction(Instruction &I) {
1765 // Everything else: stop propagating and check for poisoned shadow.
1766 if (ClDumpStrictInstructions)
1768 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1769 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1770 insertCheck(I.getOperand(i), &I);
1771 setShadow(&I, getCleanShadow(&I));
1772 setOrigin(&I, getCleanOrigin());
1776 /// \brief AMD64-specific implementation of VarArgHelper.
1777 struct VarArgAMD64Helper : public VarArgHelper {
1778 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1779 // See a comment in visitCallSite for more details.
1780 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1781 static const unsigned AMD64FpEndOffset = 176;
1784 MemorySanitizer &MS;
1785 MemorySanitizerVisitor &MSV;
1786 Value *VAArgTLSCopy;
1787 Value *VAArgOverflowSize;
1789 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1791 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1792 MemorySanitizerVisitor &MSV)
1793 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1795 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1797 ArgKind classifyArgument(Value* arg) {
1798 // A very rough approximation of X86_64 argument classification rules.
1799 Type *T = arg->getType();
1800 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1801 return AK_FloatingPoint;
1802 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1803 return AK_GeneralPurpose;
1804 if (T->isPointerTy())
1805 return AK_GeneralPurpose;
1809 // For VarArg functions, store the argument shadow in an ABI-specific format
1810 // that corresponds to va_list layout.
1811 // We do this because Clang lowers va_arg in the frontend, and this pass
1812 // only sees the low level code that deals with va_list internals.
1813 // A much easier alternative (provided that Clang emits va_arg instructions)
1814 // would have been to associate each live instance of va_list with a copy of
1815 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1817 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1818 unsigned GpOffset = 0;
1819 unsigned FpOffset = AMD64GpEndOffset;
1820 unsigned OverflowOffset = AMD64FpEndOffset;
1821 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1822 ArgIt != End; ++ArgIt) {
1824 ArgKind AK = classifyArgument(A);
1825 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1827 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1831 case AK_GeneralPurpose:
1832 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1835 case AK_FloatingPoint:
1836 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1840 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1841 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1842 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1844 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1846 Constant *OverflowSize =
1847 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1848 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1851 /// \brief Compute the shadow address for a given va_arg.
1852 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1854 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1855 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1856 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1860 void visitVAStartInst(VAStartInst &I) {
1861 IRBuilder<> IRB(&I);
1862 VAStartInstrumentationList.push_back(&I);
1863 Value *VAListTag = I.getArgOperand(0);
1864 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1866 // Unpoison the whole __va_list_tag.
1867 // FIXME: magic ABI constants.
1868 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1869 /* size */24, /* alignment */8, false);
1872 void visitVACopyInst(VACopyInst &I) {
1873 IRBuilder<> IRB(&I);
1874 Value *VAListTag = I.getArgOperand(0);
1875 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1877 // Unpoison the whole __va_list_tag.
1878 // FIXME: magic ABI constants.
1879 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1880 /* size */24, /* alignment */8, false);
1883 void finalizeInstrumentation() {
1884 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1885 "finalizeInstrumentation called twice");
1886 if (!VAStartInstrumentationList.empty()) {
1887 // If there is a va_start in this function, make a backup copy of
1888 // va_arg_tls somewhere in the function entry block.
1889 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1890 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1892 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1894 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1895 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1898 // Instrument va_start.
1899 // Copy va_list shadow from the backup copy of the TLS contents.
1900 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1901 CallInst *OrigInst = VAStartInstrumentationList[i];
1902 IRBuilder<> IRB(OrigInst->getNextNode());
1903 Value *VAListTag = OrigInst->getArgOperand(0);
1905 Value *RegSaveAreaPtrPtr =
1907 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1908 ConstantInt::get(MS.IntptrTy, 16)),
1909 Type::getInt64PtrTy(*MS.C));
1910 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1911 Value *RegSaveAreaShadowPtr =
1912 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1913 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1914 AMD64FpEndOffset, 16);
1916 Value *OverflowArgAreaPtrPtr =
1918 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1919 ConstantInt::get(MS.IntptrTy, 8)),
1920 Type::getInt64PtrTy(*MS.C));
1921 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1922 Value *OverflowArgAreaShadowPtr =
1923 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1925 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1926 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1931 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1932 MemorySanitizerVisitor &Visitor) {
1933 return new VarArgAMD64Helper(Func, Msan, Visitor);
1938 bool MemorySanitizer::runOnFunction(Function &F) {
1939 MemorySanitizerVisitor Visitor(F, *this);
1941 // Clear out readonly/readnone attributes.
1943 B.addAttribute(Attribute::ReadOnly)
1944 .addAttribute(Attribute::ReadNone);
1945 F.removeAttributes(AttributeSet::FunctionIndex,
1946 AttributeSet::get(F.getContext(),
1947 AttributeSet::FunctionIndex, B));
1949 return Visitor.runOnFunction();