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/Triple.h"
78 #include "llvm/ADT/ValueMap.h"
79 #include "llvm/IR/DataLayout.h"
80 #include "llvm/IR/Function.h"
81 #include "llvm/IR/IRBuilder.h"
82 #include "llvm/IR/InlineAsm.h"
83 #include "llvm/IR/IntrinsicInst.h"
84 #include "llvm/IR/LLVMContext.h"
85 #include "llvm/IR/MDBuilder.h"
86 #include "llvm/IR/Module.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/InstVisitor.h"
89 #include "llvm/Support/CommandLine.h"
90 #include "llvm/Support/Compiler.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/raw_ostream.h"
93 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
94 #include "llvm/Transforms/Utils/BlackList.h"
95 #include "llvm/Transforms/Utils/Local.h"
96 #include "llvm/Transforms/Utils/ModuleUtils.h"
100 static const uint64_t kShadowMask32 = 1ULL << 31;
101 static const uint64_t kShadowMask64 = 1ULL << 46;
102 static const uint64_t kOriginOffset32 = 1ULL << 30;
103 static const uint64_t kOriginOffset64 = 1ULL << 45;
104 static const unsigned kMinOriginAlignment = 4;
105 static const unsigned kShadowTLSAlignment = 8;
107 /// \brief Track origins of uninitialized values.
109 /// Adds a section to MemorySanitizer report that points to the allocation
110 /// (stack or heap) the uninitialized bits came from originally.
111 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
112 cl::desc("Track origins (allocation sites) of poisoned memory"),
113 cl::Hidden, cl::init(false));
114 static cl::opt<bool> ClKeepGoing("msan-keep-going",
115 cl::desc("keep going after reporting a UMR"),
116 cl::Hidden, cl::init(false));
117 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
118 cl::desc("poison uninitialized stack variables"),
119 cl::Hidden, cl::init(true));
120 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
121 cl::desc("poison uninitialized stack variables with a call"),
122 cl::Hidden, cl::init(false));
123 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
124 cl::desc("poison uninitialized stack variables with the given patter"),
125 cl::Hidden, cl::init(0xff));
126 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
127 cl::desc("poison undef temps"),
128 cl::Hidden, cl::init(true));
130 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
131 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
132 cl::Hidden, cl::init(true));
134 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
135 cl::desc("exact handling of relational integer ICmp"),
136 cl::Hidden, cl::init(false));
138 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
139 cl::desc("store origin for clean (fully initialized) values"),
140 cl::Hidden, cl::init(false));
142 // This flag controls whether we check the shadow of the address
143 // operand of load or store. Such bugs are very rare, since load from
144 // a garbage address typically results in SEGV, but still happen
145 // (e.g. only lower bits of address are garbage, or the access happens
146 // early at program startup where malloc-ed memory is more likely to
147 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
148 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
149 cl::desc("report accesses through a pointer which has poisoned shadow"),
150 cl::Hidden, cl::init(true));
152 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
153 cl::desc("print out instructions with default strict semantics"),
154 cl::Hidden, cl::init(false));
156 static cl::opt<std::string> ClBlacklistFile("msan-blacklist",
157 cl::desc("File containing the list of functions where MemorySanitizer "
158 "should not report bugs"), cl::Hidden);
162 /// \brief An instrumentation pass implementing detection of uninitialized
165 /// MemorySanitizer: instrument the code in module to find
166 /// uninitialized reads.
167 class MemorySanitizer : public FunctionPass {
169 MemorySanitizer(bool TrackOrigins = false,
170 StringRef BlacklistFile = StringRef())
172 TrackOrigins(TrackOrigins || ClTrackOrigins),
175 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
177 const char *getPassName() const { return "MemorySanitizer"; }
178 bool runOnFunction(Function &F);
179 bool doInitialization(Module &M);
180 static char ID; // Pass identification, replacement for typeid.
183 void initializeCallbacks(Module &M);
185 /// \brief Track origins (allocation points) of uninitialized values.
192 /// \brief Thread-local shadow storage for function parameters.
193 GlobalVariable *ParamTLS;
194 /// \brief Thread-local origin storage for function parameters.
195 GlobalVariable *ParamOriginTLS;
196 /// \brief Thread-local shadow storage for function return value.
197 GlobalVariable *RetvalTLS;
198 /// \brief Thread-local origin storage for function return value.
199 GlobalVariable *RetvalOriginTLS;
200 /// \brief Thread-local shadow storage for in-register va_arg function
201 /// parameters (x86_64-specific).
202 GlobalVariable *VAArgTLS;
203 /// \brief Thread-local shadow storage for va_arg overflow area
204 /// (x86_64-specific).
205 GlobalVariable *VAArgOverflowSizeTLS;
206 /// \brief Thread-local space used to pass origin value to the UMR reporting
208 GlobalVariable *OriginTLS;
210 /// \brief The run-time callback to print a warning.
212 /// \brief Run-time helper that copies origin info for a memory range.
213 Value *MsanCopyOriginFn;
214 /// \brief Run-time helper that generates a new origin value for a stack
216 Value *MsanSetAllocaOriginFn;
217 /// \brief Run-time helper that poisons stack on function entry.
218 Value *MsanPoisonStackFn;
219 /// \brief MSan runtime replacements for memmove, memcpy and memset.
220 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
222 /// \brief Address mask used in application-to-shadow address calculation.
223 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
225 /// \brief Offset of the origin shadow from the "normal" shadow.
226 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
227 uint64_t OriginOffset;
228 /// \brief Branch weights for error reporting.
229 MDNode *ColdCallWeights;
230 /// \brief Branch weights for origin store.
231 MDNode *OriginStoreWeights;
232 /// \brief Path to blacklist file.
233 SmallString<64> BlacklistFile;
234 /// \brief The blacklist.
235 OwningPtr<BlackList> BL;
236 /// \brief An empty volatile inline asm that prevents callback merge.
239 friend struct MemorySanitizerVisitor;
240 friend struct VarArgAMD64Helper;
244 char MemorySanitizer::ID = 0;
245 INITIALIZE_PASS(MemorySanitizer, "msan",
246 "MemorySanitizer: detects uninitialized reads.",
249 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
250 StringRef BlacklistFile) {
251 return new MemorySanitizer(TrackOrigins, BlacklistFile);
254 /// \brief Create a non-const global initialized with the given string.
256 /// Creates a writable global for Str so that we can pass it to the
257 /// run-time lib. Runtime uses first 4 bytes of the string to store the
258 /// frame ID, so the string needs to be mutable.
259 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
261 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
262 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
263 GlobalValue::PrivateLinkage, StrConst, "");
267 /// \brief Insert extern declaration of runtime-provided functions and globals.
268 void MemorySanitizer::initializeCallbacks(Module &M) {
269 // Only do this once.
274 // Create the callback.
275 // FIXME: this function should have "Cold" calling conv,
276 // which is not yet implemented.
277 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
278 : "__msan_warning_noreturn";
279 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
281 MsanCopyOriginFn = M.getOrInsertFunction(
282 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
283 IRB.getInt8PtrTy(), IntptrTy, NULL);
284 MsanSetAllocaOriginFn = M.getOrInsertFunction(
285 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
286 IRB.getInt8PtrTy(), NULL);
287 MsanPoisonStackFn = M.getOrInsertFunction(
288 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
289 MemmoveFn = M.getOrInsertFunction(
290 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
291 IRB.getInt8PtrTy(), IntptrTy, NULL);
292 MemcpyFn = M.getOrInsertFunction(
293 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
295 MemsetFn = M.getOrInsertFunction(
296 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
300 RetvalTLS = new GlobalVariable(
301 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
302 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
303 GlobalVariable::InitialExecTLSModel);
304 RetvalOriginTLS = new GlobalVariable(
305 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
306 "__msan_retval_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
308 ParamTLS = new GlobalVariable(
309 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
310 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
311 GlobalVariable::InitialExecTLSModel);
312 ParamOriginTLS = new GlobalVariable(
313 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
314 0, "__msan_param_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
316 VAArgTLS = new GlobalVariable(
317 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
318 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
319 GlobalVariable::InitialExecTLSModel);
320 VAArgOverflowSizeTLS = new GlobalVariable(
321 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
322 "__msan_va_arg_overflow_size_tls", 0,
323 GlobalVariable::InitialExecTLSModel);
324 OriginTLS = new GlobalVariable(
325 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
326 "__msan_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
328 // We insert an empty inline asm after __msan_report* to avoid callback merge.
329 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
330 StringRef(""), StringRef(""),
331 /*hasSideEffects=*/true);
334 /// \brief Module-level initialization.
336 /// inserts a call to __msan_init to the module's constructor list.
337 bool MemorySanitizer::doInitialization(Module &M) {
338 TD = getAnalysisIfAvailable<DataLayout>();
341 BL.reset(new BlackList(BlacklistFile));
342 C = &(M.getContext());
343 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
346 ShadowMask = kShadowMask64;
347 OriginOffset = kOriginOffset64;
350 ShadowMask = kShadowMask32;
351 OriginOffset = kOriginOffset32;
354 report_fatal_error("unsupported pointer size");
359 IntptrTy = IRB.getIntPtrTy(TD);
360 OriginTy = IRB.getInt32Ty();
362 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
363 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
365 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
366 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
367 "__msan_init", IRB.getVoidTy(), NULL)), 0);
369 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
370 IRB.getInt32(TrackOrigins), "__msan_track_origins");
372 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
373 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
380 /// \brief A helper class that handles instrumentation of VarArg
381 /// functions on a particular platform.
383 /// Implementations are expected to insert the instrumentation
384 /// necessary to propagate argument shadow through VarArg function
385 /// calls. Visit* methods are called during an InstVisitor pass over
386 /// the function, and should avoid creating new basic blocks. A new
387 /// instance of this class is created for each instrumented function.
388 struct VarArgHelper {
389 /// \brief Visit a CallSite.
390 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
392 /// \brief Visit a va_start call.
393 virtual void visitVAStartInst(VAStartInst &I) = 0;
395 /// \brief Visit a va_copy call.
396 virtual void visitVACopyInst(VACopyInst &I) = 0;
398 /// \brief Finalize function instrumentation.
400 /// This method is called after visiting all interesting (see above)
401 /// instructions in a function.
402 virtual void finalizeInstrumentation() = 0;
404 virtual ~VarArgHelper() {}
407 struct MemorySanitizerVisitor;
410 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
411 MemorySanitizerVisitor &Visitor);
413 /// This class does all the work for a given function. Store and Load
414 /// instructions store and load corresponding shadow and origin
415 /// values. Most instructions propagate shadow from arguments to their
416 /// return values. Certain instructions (most importantly, BranchInst)
417 /// test their argument shadow and print reports (with a runtime call) if it's
419 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
422 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
423 ValueMap<Value*, Value*> ShadowMap, OriginMap;
426 OwningPtr<VarArgHelper> VAHelper;
428 struct ShadowOriginAndInsertPoint {
431 Instruction *OrigIns;
432 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
433 : Shadow(S), Origin(O), OrigIns(I) { }
434 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
436 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
437 SmallVector<Instruction*, 16> StoreList;
439 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
440 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
441 LoadShadow = InsertChecks =
443 F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
444 Attribute::SanitizeMemory);
446 DEBUG(if (!InsertChecks)
447 dbgs() << "MemorySanitizer is not inserting checks into '"
448 << F.getName() << "'\n");
451 void materializeStores() {
452 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
453 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
456 Value *Val = I.getValueOperand();
457 Value *Addr = I.getPointerOperand();
458 Value *Shadow = getShadow(Val);
459 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
462 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
463 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
466 if (ClCheckAccessAddress)
467 insertCheck(Addr, &I);
469 if (MS.TrackOrigins) {
470 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
471 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
472 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
475 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
477 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
478 // TODO(eugenis): handle non-zero constant shadow by inserting an
479 // unconditional check (can not simply fail compilation as this could
480 // be in the dead code).
484 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
485 getCleanShadow(ConvertedShadow), "_mscmp");
486 Instruction *CheckTerm =
487 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
488 MS.OriginStoreWeights);
489 IRBuilder<> IRBNew(CheckTerm);
490 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
497 void materializeChecks() {
498 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
499 Instruction *Shadow = InstrumentationList[i].Shadow;
500 Instruction *OrigIns = InstrumentationList[i].OrigIns;
501 IRBuilder<> IRB(OrigIns);
502 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
503 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
504 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
505 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
506 getCleanShadow(ConvertedShadow), "_mscmp");
507 Instruction *CheckTerm =
508 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
509 /* Unreachable */ !ClKeepGoing,
512 IRB.SetInsertPoint(CheckTerm);
513 if (MS.TrackOrigins) {
514 Instruction *Origin = InstrumentationList[i].Origin;
515 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
518 CallInst *Call = IRB.CreateCall(MS.WarningFn);
519 Call->setDebugLoc(OrigIns->getDebugLoc());
520 IRB.CreateCall(MS.EmptyAsm);
521 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
523 DEBUG(dbgs() << "DONE:\n" << F);
526 /// \brief Add MemorySanitizer instrumentation to a function.
527 bool runOnFunction() {
528 MS.initializeCallbacks(*F.getParent());
529 if (!MS.TD) return false;
531 // In the presence of unreachable blocks, we may see Phi nodes with
532 // incoming nodes from such blocks. Since InstVisitor skips unreachable
533 // blocks, such nodes will not have any shadow value associated with them.
534 // It's easier to remove unreachable blocks than deal with missing shadow.
535 removeUnreachableBlocks(F);
537 // Iterate all BBs in depth-first order and create shadow instructions
538 // for all instructions (where applicable).
539 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
540 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
541 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
542 BasicBlock *BB = *DI;
546 // Finalize PHI nodes.
547 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
548 PHINode *PN = ShadowPHINodes[i];
549 PHINode *PNS = cast<PHINode>(getShadow(PN));
550 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
551 size_t NumValues = PN->getNumIncomingValues();
552 for (size_t v = 0; v < NumValues; v++) {
553 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
555 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
559 VAHelper->finalizeInstrumentation();
561 // Delayed instrumentation of StoreInst.
562 // This may add new checks to be inserted later.
565 // Insert shadow value checks.
571 /// \brief Compute the shadow type that corresponds to a given Value.
572 Type *getShadowTy(Value *V) {
573 return getShadowTy(V->getType());
576 /// \brief Compute the shadow type that corresponds to a given Type.
577 Type *getShadowTy(Type *OrigTy) {
578 if (!OrigTy->isSized()) {
581 // For integer type, shadow is the same as the original type.
582 // This may return weird-sized types like i1.
583 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
585 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
586 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
587 return VectorType::get(IntegerType::get(*MS.C, EltSize),
588 VT->getNumElements());
590 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
591 SmallVector<Type*, 4> Elements;
592 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
593 Elements.push_back(getShadowTy(ST->getElementType(i)));
594 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
595 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
598 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
599 return IntegerType::get(*MS.C, TypeSize);
602 /// \brief Flatten a vector type.
603 Type *getShadowTyNoVec(Type *ty) {
604 if (VectorType *vt = dyn_cast<VectorType>(ty))
605 return IntegerType::get(*MS.C, vt->getBitWidth());
609 /// \brief Convert a shadow value to it's flattened variant.
610 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
611 Type *Ty = V->getType();
612 Type *NoVecTy = getShadowTyNoVec(Ty);
613 if (Ty == NoVecTy) return V;
614 return IRB.CreateBitCast(V, NoVecTy);
617 /// \brief Compute the shadow address that corresponds to a given application
620 /// Shadow = Addr & ~ShadowMask.
621 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
624 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
625 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
626 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
629 /// \brief Compute the origin address that corresponds to a given application
632 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
633 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
635 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
636 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
638 IRB.CreateAdd(ShadowLong,
639 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
641 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
642 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
645 /// \brief Compute the shadow address for a given function argument.
647 /// Shadow = ParamTLS+ArgOffset.
648 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
650 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
651 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
652 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
656 /// \brief Compute the origin address for a given function argument.
657 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
659 if (!MS.TrackOrigins) return 0;
660 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
661 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
662 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
666 /// \brief Compute the shadow address for a retval.
667 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
668 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
669 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
673 /// \brief Compute the origin address for a retval.
674 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
675 // We keep a single origin for the entire retval. Might be too optimistic.
676 return MS.RetvalOriginTLS;
679 /// \brief Set SV to be the shadow value for V.
680 void setShadow(Value *V, Value *SV) {
681 assert(!ShadowMap.count(V) && "Values may only have one shadow");
685 /// \brief Set Origin to be the origin value for V.
686 void setOrigin(Value *V, Value *Origin) {
687 if (!MS.TrackOrigins) return;
688 assert(!OriginMap.count(V) && "Values may only have one origin");
689 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
690 OriginMap[V] = Origin;
693 /// \brief Create a clean shadow value for a given value.
695 /// Clean shadow (all zeroes) means all bits of the value are defined
697 Constant *getCleanShadow(Value *V) {
698 Type *ShadowTy = getShadowTy(V);
701 return Constant::getNullValue(ShadowTy);
704 /// \brief Create a dirty shadow of a given shadow type.
705 Constant *getPoisonedShadow(Type *ShadowTy) {
707 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
708 return Constant::getAllOnesValue(ShadowTy);
709 StructType *ST = cast<StructType>(ShadowTy);
710 SmallVector<Constant *, 4> Vals;
711 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
712 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
713 return ConstantStruct::get(ST, Vals);
716 /// \brief Create a dirty shadow for a given value.
717 Constant *getPoisonedShadow(Value *V) {
718 Type *ShadowTy = getShadowTy(V);
721 return getPoisonedShadow(ShadowTy);
724 /// \brief Create a clean (zero) origin.
725 Value *getCleanOrigin() {
726 return Constant::getNullValue(MS.OriginTy);
729 /// \brief Get the shadow value for a given Value.
731 /// This function either returns the value set earlier with setShadow,
732 /// or extracts if from ParamTLS (for function arguments).
733 Value *getShadow(Value *V) {
734 if (Instruction *I = dyn_cast<Instruction>(V)) {
735 // For instructions the shadow is already stored in the map.
736 Value *Shadow = ShadowMap[V];
738 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
740 assert(Shadow && "No shadow for a value");
744 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
745 Value *AllOnes = ClPoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
746 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
750 if (Argument *A = dyn_cast<Argument>(V)) {
751 // For arguments we compute the shadow on demand and store it in the map.
752 Value **ShadowPtr = &ShadowMap[V];
755 Function *F = A->getParent();
756 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
757 unsigned ArgOffset = 0;
758 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
760 if (!AI->getType()->isSized()) {
761 DEBUG(dbgs() << "Arg is not sized\n");
764 unsigned Size = AI->hasByValAttr()
765 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
766 : MS.TD->getTypeAllocSize(AI->getType());
768 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
769 if (AI->hasByValAttr()) {
770 // ByVal pointer itself has clean shadow. We copy the actual
771 // argument shadow to the underlying memory.
772 Value *Cpy = EntryIRB.CreateMemCpy(
773 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
774 Base, Size, AI->getParamAlignment());
775 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
777 *ShadowPtr = getCleanShadow(V);
779 *ShadowPtr = EntryIRB.CreateLoad(Base);
781 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
782 **ShadowPtr << "\n");
783 if (MS.TrackOrigins) {
784 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
785 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
788 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
790 assert(*ShadowPtr && "Could not find shadow for an argument");
793 // For everything else the shadow is zero.
794 return getCleanShadow(V);
797 /// \brief Get the shadow for i-th argument of the instruction I.
798 Value *getShadow(Instruction *I, int i) {
799 return getShadow(I->getOperand(i));
802 /// \brief Get the origin for a value.
803 Value *getOrigin(Value *V) {
804 if (!MS.TrackOrigins) return 0;
805 if (isa<Instruction>(V) || isa<Argument>(V)) {
806 Value *Origin = OriginMap[V];
808 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
809 Origin = getCleanOrigin();
813 return getCleanOrigin();
816 /// \brief Get the origin for i-th argument of the instruction I.
817 Value *getOrigin(Instruction *I, int i) {
818 return getOrigin(I->getOperand(i));
821 /// \brief Remember the place where a shadow check should be inserted.
823 /// This location will be later instrumented with a check that will print a
824 /// UMR warning in runtime if the value is not fully defined.
825 void insertCheck(Value *Val, Instruction *OrigIns) {
827 if (!InsertChecks) return;
828 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
831 Type *ShadowTy = Shadow->getType();
832 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
833 "Can only insert checks for integer and vector shadow types");
835 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
836 InstrumentationList.push_back(
837 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
840 // ------------------- Visitors.
842 /// \brief Instrument LoadInst
844 /// Loads the corresponding shadow and (optionally) origin.
845 /// Optionally, checks that the load address is fully defined.
846 void visitLoadInst(LoadInst &I) {
847 assert(I.getType()->isSized() && "Load type must have size");
849 Type *ShadowTy = getShadowTy(&I);
850 Value *Addr = I.getPointerOperand();
852 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
854 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
856 setShadow(&I, getCleanShadow(&I));
859 if (ClCheckAccessAddress)
860 insertCheck(I.getPointerOperand(), &I);
862 if (MS.TrackOrigins) {
864 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
866 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
868 setOrigin(&I, getCleanOrigin());
873 /// \brief Instrument StoreInst
875 /// Stores the corresponding shadow and (optionally) origin.
876 /// Optionally, checks that the store address is fully defined.
877 void visitStoreInst(StoreInst &I) {
878 StoreList.push_back(&I);
881 // Vector manipulation.
882 void visitExtractElementInst(ExtractElementInst &I) {
883 insertCheck(I.getOperand(1), &I);
885 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
887 setOrigin(&I, getOrigin(&I, 0));
890 void visitInsertElementInst(InsertElementInst &I) {
891 insertCheck(I.getOperand(2), &I);
893 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
894 I.getOperand(2), "_msprop"));
895 setOriginForNaryOp(I);
898 void visitShuffleVectorInst(ShuffleVectorInst &I) {
899 insertCheck(I.getOperand(2), &I);
901 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
902 I.getOperand(2), "_msprop"));
903 setOriginForNaryOp(I);
907 void visitSExtInst(SExtInst &I) {
909 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
910 setOrigin(&I, getOrigin(&I, 0));
913 void visitZExtInst(ZExtInst &I) {
915 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
916 setOrigin(&I, getOrigin(&I, 0));
919 void visitTruncInst(TruncInst &I) {
921 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
922 setOrigin(&I, getOrigin(&I, 0));
925 void visitBitCastInst(BitCastInst &I) {
927 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
928 setOrigin(&I, getOrigin(&I, 0));
931 void visitPtrToIntInst(PtrToIntInst &I) {
933 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
934 "_msprop_ptrtoint"));
935 setOrigin(&I, getOrigin(&I, 0));
938 void visitIntToPtrInst(IntToPtrInst &I) {
940 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
941 "_msprop_inttoptr"));
942 setOrigin(&I, getOrigin(&I, 0));
945 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
946 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
947 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
948 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
949 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
950 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
952 /// \brief Propagate shadow for bitwise AND.
954 /// This code is exact, i.e. if, for example, a bit in the left argument
955 /// is defined and 0, then neither the value not definedness of the
956 /// corresponding bit in B don't affect the resulting shadow.
957 void visitAnd(BinaryOperator &I) {
959 // "And" of 0 and a poisoned value results in unpoisoned value.
960 // 1&1 => 1; 0&1 => 0; p&1 => p;
961 // 1&0 => 0; 0&0 => 0; p&0 => 0;
962 // 1&p => p; 0&p => 0; p&p => p;
963 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
964 Value *S1 = getShadow(&I, 0);
965 Value *S2 = getShadow(&I, 1);
966 Value *V1 = I.getOperand(0);
967 Value *V2 = I.getOperand(1);
968 if (V1->getType() != S1->getType()) {
969 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
970 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
972 Value *S1S2 = IRB.CreateAnd(S1, S2);
973 Value *V1S2 = IRB.CreateAnd(V1, S2);
974 Value *S1V2 = IRB.CreateAnd(S1, V2);
975 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
976 setOriginForNaryOp(I);
979 void visitOr(BinaryOperator &I) {
981 // "Or" of 1 and a poisoned value results in unpoisoned value.
982 // 1|1 => 1; 0|1 => 1; p|1 => 1;
983 // 1|0 => 1; 0|0 => 0; p|0 => p;
984 // 1|p => 1; 0|p => p; p|p => p;
985 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
986 Value *S1 = getShadow(&I, 0);
987 Value *S2 = getShadow(&I, 1);
988 Value *V1 = IRB.CreateNot(I.getOperand(0));
989 Value *V2 = IRB.CreateNot(I.getOperand(1));
990 if (V1->getType() != S1->getType()) {
991 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
992 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
994 Value *S1S2 = IRB.CreateAnd(S1, S2);
995 Value *V1S2 = IRB.CreateAnd(V1, S2);
996 Value *S1V2 = IRB.CreateAnd(S1, V2);
997 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
998 setOriginForNaryOp(I);
1001 /// \brief Default propagation of shadow and/or origin.
1003 /// This class implements the general case of shadow propagation, used in all
1004 /// cases where we don't know and/or don't care about what the operation
1005 /// actually does. It converts all input shadow values to a common type
1006 /// (extending or truncating as necessary), and bitwise OR's them.
1008 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1009 /// fully initialized), and less prone to false positives.
1011 /// This class also implements the general case of origin propagation. For a
1012 /// Nary operation, result origin is set to the origin of an argument that is
1013 /// not entirely initialized. If there is more than one such arguments, the
1014 /// rightmost of them is picked. It does not matter which one is picked if all
1015 /// arguments are initialized.
1016 template <bool CombineShadow>
1021 MemorySanitizerVisitor *MSV;
1024 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1025 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1027 /// \brief Add a pair of shadow and origin values to the mix.
1028 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1029 if (CombineShadow) {
1034 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1035 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1039 if (MSV->MS.TrackOrigins) {
1044 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1045 Value *Cond = IRB.CreateICmpNE(FlatShadow,
1046 MSV->getCleanShadow(FlatShadow));
1047 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1053 /// \brief Add an application value to the mix.
1054 Combiner &Add(Value *V) {
1055 Value *OpShadow = MSV->getShadow(V);
1056 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1057 return Add(OpShadow, OpOrigin);
1060 /// \brief Set the current combined values as the given instruction's shadow
1062 void Done(Instruction *I) {
1063 if (CombineShadow) {
1065 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1066 MSV->setShadow(I, Shadow);
1068 if (MSV->MS.TrackOrigins) {
1070 MSV->setOrigin(I, Origin);
1075 typedef Combiner<true> ShadowAndOriginCombiner;
1076 typedef Combiner<false> OriginCombiner;
1078 /// \brief Propagate origin for arbitrary operation.
1079 void setOriginForNaryOp(Instruction &I) {
1080 if (!MS.TrackOrigins) return;
1081 IRBuilder<> IRB(&I);
1082 OriginCombiner OC(this, IRB);
1083 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1088 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1089 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1090 "Vector of pointers is not a valid shadow type");
1091 return Ty->isVectorTy() ?
1092 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1093 Ty->getPrimitiveSizeInBits();
1096 /// \brief Cast between two shadow types, extending or truncating as
1098 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1099 Type *srcTy = V->getType();
1100 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1101 return IRB.CreateIntCast(V, dstTy, false);
1102 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1103 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1104 return IRB.CreateIntCast(V, dstTy, false);
1105 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1106 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1107 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1109 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1110 return IRB.CreateBitCast(V2, dstTy);
1111 // TODO: handle struct types.
1114 /// \brief Propagate shadow for arbitrary operation.
1115 void handleShadowOr(Instruction &I) {
1116 IRBuilder<> IRB(&I);
1117 ShadowAndOriginCombiner SC(this, IRB);
1118 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1123 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1124 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1125 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1126 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1127 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1128 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1129 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1131 void handleDiv(Instruction &I) {
1132 IRBuilder<> IRB(&I);
1133 // Strict on the second argument.
1134 insertCheck(I.getOperand(1), &I);
1135 setShadow(&I, getShadow(&I, 0));
1136 setOrigin(&I, getOrigin(&I, 0));
1139 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1140 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1141 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1142 void visitURem(BinaryOperator &I) { handleDiv(I); }
1143 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1144 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1146 /// \brief Instrument == and != comparisons.
1148 /// Sometimes the comparison result is known even if some of the bits of the
1149 /// arguments are not.
1150 void handleEqualityComparison(ICmpInst &I) {
1151 IRBuilder<> IRB(&I);
1152 Value *A = I.getOperand(0);
1153 Value *B = I.getOperand(1);
1154 Value *Sa = getShadow(A);
1155 Value *Sb = getShadow(B);
1157 // Get rid of pointers and vectors of pointers.
1158 // For ints (and vectors of ints), types of A and Sa match,
1159 // and this is a no-op.
1160 A = IRB.CreatePointerCast(A, Sa->getType());
1161 B = IRB.CreatePointerCast(B, Sb->getType());
1163 // A == B <==> (C = A^B) == 0
1164 // A != B <==> (C = A^B) != 0
1166 Value *C = IRB.CreateXor(A, B);
1167 Value *Sc = IRB.CreateOr(Sa, Sb);
1168 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1169 // Result is defined if one of the following is true
1170 // * there is a defined 1 bit in C
1171 // * C is fully defined
1172 // Si = !(C & ~Sc) && Sc
1173 Value *Zero = Constant::getNullValue(Sc->getType());
1174 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1176 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1178 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1179 Si->setName("_msprop_icmp");
1181 setOriginForNaryOp(I);
1184 /// \brief Build the lowest possible value of V, taking into account V's
1185 /// uninitialized bits.
1186 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1189 // Split shadow into sign bit and other bits.
1190 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1191 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1192 // Maximise the undefined shadow bit, minimize other undefined bits.
1194 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1196 // Minimize undefined bits.
1197 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1201 /// \brief Build the highest possible value of V, taking into account V's
1202 /// uninitialized bits.
1203 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1206 // Split shadow into sign bit and other bits.
1207 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1208 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1209 // Minimise the undefined shadow bit, maximise other undefined bits.
1211 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1213 // Maximize undefined bits.
1214 return IRB.CreateOr(A, Sa);
1218 /// \brief Instrument relational comparisons.
1220 /// This function does exact shadow propagation for all relational
1221 /// comparisons of integers, pointers and vectors of those.
1222 /// FIXME: output seems suboptimal when one of the operands is a constant
1223 void handleRelationalComparisonExact(ICmpInst &I) {
1224 IRBuilder<> IRB(&I);
1225 Value *A = I.getOperand(0);
1226 Value *B = I.getOperand(1);
1227 Value *Sa = getShadow(A);
1228 Value *Sb = getShadow(B);
1230 // Get rid of pointers and vectors of pointers.
1231 // For ints (and vectors of ints), types of A and Sa match,
1232 // and this is a no-op.
1233 A = IRB.CreatePointerCast(A, Sa->getType());
1234 B = IRB.CreatePointerCast(B, Sb->getType());
1236 // Let [a0, a1] be the interval of possible values of A, taking into account
1237 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1238 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1239 bool IsSigned = I.isSigned();
1240 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1241 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1242 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1243 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1244 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1245 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1246 Value *Si = IRB.CreateXor(S1, S2);
1248 setOriginForNaryOp(I);
1251 /// \brief Instrument signed relational comparisons.
1253 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1254 /// propagating the highest bit of the shadow. Everything else is delegated
1255 /// to handleShadowOr().
1256 void handleSignedRelationalComparison(ICmpInst &I) {
1257 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1258 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1260 CmpInst::Predicate pre = I.getPredicate();
1261 if (constOp0 && constOp0->isNullValue() &&
1262 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1263 op = I.getOperand(1);
1264 } else if (constOp1 && constOp1->isNullValue() &&
1265 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1266 op = I.getOperand(0);
1269 IRBuilder<> IRB(&I);
1271 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1272 setShadow(&I, Shadow);
1273 setOrigin(&I, getOrigin(op));
1279 void visitICmpInst(ICmpInst &I) {
1280 if (!ClHandleICmp) {
1284 if (I.isEquality()) {
1285 handleEqualityComparison(I);
1289 assert(I.isRelational());
1290 if (ClHandleICmpExact) {
1291 handleRelationalComparisonExact(I);
1295 handleSignedRelationalComparison(I);
1299 assert(I.isUnsigned());
1300 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1301 handleRelationalComparisonExact(I);
1308 void visitFCmpInst(FCmpInst &I) {
1312 void handleShift(BinaryOperator &I) {
1313 IRBuilder<> IRB(&I);
1314 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1315 // Otherwise perform the same shift on S1.
1316 Value *S1 = getShadow(&I, 0);
1317 Value *S2 = getShadow(&I, 1);
1318 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1320 Value *V2 = I.getOperand(1);
1321 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1322 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1323 setOriginForNaryOp(I);
1326 void visitShl(BinaryOperator &I) { handleShift(I); }
1327 void visitAShr(BinaryOperator &I) { handleShift(I); }
1328 void visitLShr(BinaryOperator &I) { handleShift(I); }
1330 /// \brief Instrument llvm.memmove
1332 /// At this point we don't know if llvm.memmove will be inlined or not.
1333 /// If we don't instrument it and it gets inlined,
1334 /// our interceptor will not kick in and we will lose the memmove.
1335 /// If we instrument the call here, but it does not get inlined,
1336 /// we will memove the shadow twice: which is bad in case
1337 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1339 /// Similar situation exists for memcpy and memset.
1340 void visitMemMoveInst(MemMoveInst &I) {
1341 IRBuilder<> IRB(&I);
1344 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1345 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1346 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1347 I.eraseFromParent();
1350 // Similar to memmove: avoid copying shadow twice.
1351 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1352 // FIXME: consider doing manual inline for small constant sizes and proper
1354 void visitMemCpyInst(MemCpyInst &I) {
1355 IRBuilder<> IRB(&I);
1358 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1359 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1360 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1361 I.eraseFromParent();
1365 void visitMemSetInst(MemSetInst &I) {
1366 IRBuilder<> IRB(&I);
1369 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1370 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1371 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1372 I.eraseFromParent();
1375 void visitVAStartInst(VAStartInst &I) {
1376 VAHelper->visitVAStartInst(I);
1379 void visitVACopyInst(VACopyInst &I) {
1380 VAHelper->visitVACopyInst(I);
1383 enum IntrinsicKind {
1384 IK_DoesNotAccessMemory,
1389 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1390 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1391 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1392 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1393 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1394 const int UnknownModRefBehavior = IK_WritesMemory;
1395 #define GET_INTRINSIC_MODREF_BEHAVIOR
1396 #define ModRefBehavior IntrinsicKind
1397 #include "llvm/IR/Intrinsics.gen"
1398 #undef ModRefBehavior
1399 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1402 /// \brief Handle vector store-like intrinsics.
1404 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1405 /// has 1 pointer argument and 1 vector argument, returns void.
1406 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1407 IRBuilder<> IRB(&I);
1408 Value* Addr = I.getArgOperand(0);
1409 Value *Shadow = getShadow(&I, 1);
1410 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1412 // We don't know the pointer alignment (could be unaligned SSE store!).
1413 // Have to assume to worst case.
1414 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1416 if (ClCheckAccessAddress)
1417 insertCheck(Addr, &I);
1419 // FIXME: use ClStoreCleanOrigin
1420 // FIXME: factor out common code from materializeStores
1421 if (MS.TrackOrigins)
1422 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1426 /// \brief Handle vector load-like intrinsics.
1428 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1429 /// has 1 pointer argument, returns a vector.
1430 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1431 IRBuilder<> IRB(&I);
1432 Value *Addr = I.getArgOperand(0);
1434 Type *ShadowTy = getShadowTy(&I);
1436 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1437 // We don't know the pointer alignment (could be unaligned SSE load!).
1438 // Have to assume to worst case.
1439 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1441 setShadow(&I, getCleanShadow(&I));
1445 if (ClCheckAccessAddress)
1446 insertCheck(Addr, &I);
1448 if (MS.TrackOrigins) {
1450 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1452 setOrigin(&I, getCleanOrigin());
1457 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1459 /// Instrument intrinsics with any number of arguments of the same type,
1460 /// equal to the return type. The type should be simple (no aggregates or
1461 /// pointers; vectors are fine).
1462 /// Caller guarantees that this intrinsic does not access memory.
1463 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1464 Type *RetTy = I.getType();
1465 if (!(RetTy->isIntOrIntVectorTy() ||
1466 RetTy->isFPOrFPVectorTy() ||
1467 RetTy->isX86_MMXTy()))
1470 unsigned NumArgOperands = I.getNumArgOperands();
1472 for (unsigned i = 0; i < NumArgOperands; ++i) {
1473 Type *Ty = I.getArgOperand(i)->getType();
1478 IRBuilder<> IRB(&I);
1479 ShadowAndOriginCombiner SC(this, IRB);
1480 for (unsigned i = 0; i < NumArgOperands; ++i)
1481 SC.Add(I.getArgOperand(i));
1487 /// \brief Heuristically instrument unknown intrinsics.
1489 /// The main purpose of this code is to do something reasonable with all
1490 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1491 /// We recognize several classes of intrinsics by their argument types and
1492 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1493 /// sure that we know what the intrinsic does.
1495 /// We special-case intrinsics where this approach fails. See llvm.bswap
1496 /// handling as an example of that.
1497 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1498 unsigned NumArgOperands = I.getNumArgOperands();
1499 if (NumArgOperands == 0)
1502 Intrinsic::ID iid = I.getIntrinsicID();
1503 IntrinsicKind IK = getIntrinsicKind(iid);
1504 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1505 bool WritesMemory = IK == IK_WritesMemory;
1506 assert(!(OnlyReadsMemory && WritesMemory));
1508 if (NumArgOperands == 2 &&
1509 I.getArgOperand(0)->getType()->isPointerTy() &&
1510 I.getArgOperand(1)->getType()->isVectorTy() &&
1511 I.getType()->isVoidTy() &&
1513 // This looks like a vector store.
1514 return handleVectorStoreIntrinsic(I);
1517 if (NumArgOperands == 1 &&
1518 I.getArgOperand(0)->getType()->isPointerTy() &&
1519 I.getType()->isVectorTy() &&
1521 // This looks like a vector load.
1522 return handleVectorLoadIntrinsic(I);
1525 if (!OnlyReadsMemory && !WritesMemory)
1526 if (maybeHandleSimpleNomemIntrinsic(I))
1529 // FIXME: detect and handle SSE maskstore/maskload
1533 void handleBswap(IntrinsicInst &I) {
1534 IRBuilder<> IRB(&I);
1535 Value *Op = I.getArgOperand(0);
1536 Type *OpType = Op->getType();
1537 Function *BswapFunc = Intrinsic::getDeclaration(
1538 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1539 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1540 setOrigin(&I, getOrigin(Op));
1543 void visitIntrinsicInst(IntrinsicInst &I) {
1544 switch (I.getIntrinsicID()) {
1545 case llvm::Intrinsic::bswap:
1549 if (!handleUnknownIntrinsic(I))
1550 visitInstruction(I);
1555 void visitCallSite(CallSite CS) {
1556 Instruction &I = *CS.getInstruction();
1557 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1559 CallInst *Call = cast<CallInst>(&I);
1561 // For inline asm, do the usual thing: check argument shadow and mark all
1562 // outputs as clean. Note that any side effects of the inline asm that are
1563 // not immediately visible in its constraints are not handled.
1564 if (Call->isInlineAsm()) {
1565 visitInstruction(I);
1569 // Allow only tail calls with the same types, otherwise
1570 // we may have a false positive: shadow for a non-void RetVal
1571 // will get propagated to a void RetVal.
1572 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1573 Call->setTailCall(false);
1575 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1577 // We are going to insert code that relies on the fact that the callee
1578 // will become a non-readonly function after it is instrumented by us. To
1579 // prevent this code from being optimized out, mark that function
1580 // non-readonly in advance.
1581 if (Function *Func = Call->getCalledFunction()) {
1582 // Clear out readonly/readnone attributes.
1584 B.addAttribute(Attribute::ReadOnly)
1585 .addAttribute(Attribute::ReadNone);
1586 Func->removeAttributes(AttributeSet::FunctionIndex,
1587 AttributeSet::get(Func->getContext(),
1588 AttributeSet::FunctionIndex,
1592 IRBuilder<> IRB(&I);
1593 unsigned ArgOffset = 0;
1594 DEBUG(dbgs() << " CallSite: " << I << "\n");
1595 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1596 ArgIt != End; ++ArgIt) {
1598 unsigned i = ArgIt - CS.arg_begin();
1599 if (!A->getType()->isSized()) {
1600 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1605 // Compute the Shadow for arg even if it is ByVal, because
1606 // in that case getShadow() will copy the actual arg shadow to
1607 // __msan_param_tls.
1608 Value *ArgShadow = getShadow(A);
1609 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1610 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1611 " Shadow: " << *ArgShadow << "\n");
1612 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1613 assert(A->getType()->isPointerTy() &&
1614 "ByVal argument is not a pointer!");
1615 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1616 unsigned Alignment = CS.getParamAlignment(i + 1);
1617 Store = IRB.CreateMemCpy(ArgShadowBase,
1618 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1621 Size = MS.TD->getTypeAllocSize(A->getType());
1622 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1623 kShadowTLSAlignment);
1625 if (MS.TrackOrigins)
1626 IRB.CreateStore(getOrigin(A),
1627 getOriginPtrForArgument(A, IRB, ArgOffset));
1629 assert(Size != 0 && Store != 0);
1630 DEBUG(dbgs() << " Param:" << *Store << "\n");
1631 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1633 DEBUG(dbgs() << " done with call args\n");
1636 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1637 if (FT->isVarArg()) {
1638 VAHelper->visitCallSite(CS, IRB);
1641 // Now, get the shadow for the RetVal.
1642 if (!I.getType()->isSized()) return;
1643 IRBuilder<> IRBBefore(&I);
1644 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1645 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1646 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1647 Instruction *NextInsn = 0;
1649 NextInsn = I.getNextNode();
1651 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1652 if (!NormalDest->getSinglePredecessor()) {
1653 // FIXME: this case is tricky, so we are just conservative here.
1654 // Perhaps we need to split the edge between this BB and NormalDest,
1655 // but a naive attempt to use SplitEdge leads to a crash.
1656 setShadow(&I, getCleanShadow(&I));
1657 setOrigin(&I, getCleanOrigin());
1660 NextInsn = NormalDest->getFirstInsertionPt();
1662 "Could not find insertion point for retval shadow load");
1664 IRBuilder<> IRBAfter(NextInsn);
1665 Value *RetvalShadow =
1666 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1667 kShadowTLSAlignment, "_msret");
1668 setShadow(&I, RetvalShadow);
1669 if (MS.TrackOrigins)
1670 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1673 void visitReturnInst(ReturnInst &I) {
1674 IRBuilder<> IRB(&I);
1675 if (Value *RetVal = I.getReturnValue()) {
1676 // Set the shadow for the RetVal.
1677 Value *Shadow = getShadow(RetVal);
1678 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1679 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1680 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1681 if (MS.TrackOrigins)
1682 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1686 void visitPHINode(PHINode &I) {
1687 IRBuilder<> IRB(&I);
1688 ShadowPHINodes.push_back(&I);
1689 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1691 if (MS.TrackOrigins)
1692 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1696 void visitAllocaInst(AllocaInst &I) {
1697 setShadow(&I, getCleanShadow(&I));
1698 if (!ClPoisonStack) return;
1699 IRBuilder<> IRB(I.getNextNode());
1700 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1701 if (ClPoisonStackWithCall) {
1702 IRB.CreateCall2(MS.MsanPoisonStackFn,
1703 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1704 ConstantInt::get(MS.IntptrTy, Size));
1706 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1707 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1708 Size, I.getAlignment());
1711 if (MS.TrackOrigins) {
1712 setOrigin(&I, getCleanOrigin());
1713 SmallString<2048> StackDescriptionStorage;
1714 raw_svector_ostream StackDescription(StackDescriptionStorage);
1715 // We create a string with a description of the stack allocation and
1716 // pass it into __msan_set_alloca_origin.
1717 // It will be printed by the run-time if stack-originated UMR is found.
1718 // The first 4 bytes of the string are set to '----' and will be replaced
1719 // by __msan_va_arg_overflow_size_tls at the first call.
1720 StackDescription << "----" << I.getName() << "@" << F.getName();
1722 createPrivateNonConstGlobalForString(*F.getParent(),
1723 StackDescription.str());
1724 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1725 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1726 ConstantInt::get(MS.IntptrTy, Size),
1727 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1731 void visitSelectInst(SelectInst& I) {
1732 IRBuilder<> IRB(&I);
1733 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1734 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1736 if (MS.TrackOrigins) {
1737 // Origins are always i32, so any vector conditions must be flattened.
1738 // FIXME: consider tracking vector origins for app vectors?
1739 Value *Cond = I.getCondition();
1740 if (Cond->getType()->isVectorTy()) {
1741 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1742 Cond = IRB.CreateICmpNE(ConvertedShadow,
1743 getCleanShadow(ConvertedShadow), "_mso_select");
1745 setOrigin(&I, IRB.CreateSelect(Cond,
1746 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1750 void visitLandingPadInst(LandingPadInst &I) {
1752 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1753 setShadow(&I, getCleanShadow(&I));
1754 setOrigin(&I, getCleanOrigin());
1757 void visitGetElementPtrInst(GetElementPtrInst &I) {
1761 void visitExtractValueInst(ExtractValueInst &I) {
1762 IRBuilder<> IRB(&I);
1763 Value *Agg = I.getAggregateOperand();
1764 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1765 Value *AggShadow = getShadow(Agg);
1766 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1767 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1768 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1769 setShadow(&I, ResShadow);
1770 setOrigin(&I, getCleanOrigin());
1773 void visitInsertValueInst(InsertValueInst &I) {
1774 IRBuilder<> IRB(&I);
1775 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1776 Value *AggShadow = getShadow(I.getAggregateOperand());
1777 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1778 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1779 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1780 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1781 DEBUG(dbgs() << " Res: " << *Res << "\n");
1783 setOrigin(&I, getCleanOrigin());
1786 void dumpInst(Instruction &I) {
1787 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1788 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1790 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1792 errs() << "QQQ " << I << "\n";
1795 void visitResumeInst(ResumeInst &I) {
1796 DEBUG(dbgs() << "Resume: " << I << "\n");
1797 // Nothing to do here.
1800 void visitInstruction(Instruction &I) {
1801 // Everything else: stop propagating and check for poisoned shadow.
1802 if (ClDumpStrictInstructions)
1804 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1805 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1806 insertCheck(I.getOperand(i), &I);
1807 setShadow(&I, getCleanShadow(&I));
1808 setOrigin(&I, getCleanOrigin());
1812 /// \brief AMD64-specific implementation of VarArgHelper.
1813 struct VarArgAMD64Helper : public VarArgHelper {
1814 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1815 // See a comment in visitCallSite for more details.
1816 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1817 static const unsigned AMD64FpEndOffset = 176;
1820 MemorySanitizer &MS;
1821 MemorySanitizerVisitor &MSV;
1822 Value *VAArgTLSCopy;
1823 Value *VAArgOverflowSize;
1825 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1827 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1828 MemorySanitizerVisitor &MSV)
1829 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1831 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1833 ArgKind classifyArgument(Value* arg) {
1834 // A very rough approximation of X86_64 argument classification rules.
1835 Type *T = arg->getType();
1836 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1837 return AK_FloatingPoint;
1838 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1839 return AK_GeneralPurpose;
1840 if (T->isPointerTy())
1841 return AK_GeneralPurpose;
1845 // For VarArg functions, store the argument shadow in an ABI-specific format
1846 // that corresponds to va_list layout.
1847 // We do this because Clang lowers va_arg in the frontend, and this pass
1848 // only sees the low level code that deals with va_list internals.
1849 // A much easier alternative (provided that Clang emits va_arg instructions)
1850 // would have been to associate each live instance of va_list with a copy of
1851 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1853 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1854 unsigned GpOffset = 0;
1855 unsigned FpOffset = AMD64GpEndOffset;
1856 unsigned OverflowOffset = AMD64FpEndOffset;
1857 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1858 ArgIt != End; ++ArgIt) {
1860 ArgKind AK = classifyArgument(A);
1861 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1863 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1867 case AK_GeneralPurpose:
1868 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1871 case AK_FloatingPoint:
1872 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1876 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1877 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1878 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1880 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1882 Constant *OverflowSize =
1883 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1884 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1887 /// \brief Compute the shadow address for a given va_arg.
1888 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1890 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1891 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1892 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1896 void visitVAStartInst(VAStartInst &I) {
1897 IRBuilder<> IRB(&I);
1898 VAStartInstrumentationList.push_back(&I);
1899 Value *VAListTag = I.getArgOperand(0);
1900 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1902 // Unpoison the whole __va_list_tag.
1903 // FIXME: magic ABI constants.
1904 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1905 /* size */24, /* alignment */8, false);
1908 void visitVACopyInst(VACopyInst &I) {
1909 IRBuilder<> IRB(&I);
1910 Value *VAListTag = I.getArgOperand(0);
1911 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1913 // Unpoison the whole __va_list_tag.
1914 // FIXME: magic ABI constants.
1915 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1916 /* size */24, /* alignment */8, false);
1919 void finalizeInstrumentation() {
1920 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1921 "finalizeInstrumentation called twice");
1922 if (!VAStartInstrumentationList.empty()) {
1923 // If there is a va_start in this function, make a backup copy of
1924 // va_arg_tls somewhere in the function entry block.
1925 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1926 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1928 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1930 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1931 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1934 // Instrument va_start.
1935 // Copy va_list shadow from the backup copy of the TLS contents.
1936 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1937 CallInst *OrigInst = VAStartInstrumentationList[i];
1938 IRBuilder<> IRB(OrigInst->getNextNode());
1939 Value *VAListTag = OrigInst->getArgOperand(0);
1941 Value *RegSaveAreaPtrPtr =
1943 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1944 ConstantInt::get(MS.IntptrTy, 16)),
1945 Type::getInt64PtrTy(*MS.C));
1946 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1947 Value *RegSaveAreaShadowPtr =
1948 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1949 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1950 AMD64FpEndOffset, 16);
1952 Value *OverflowArgAreaPtrPtr =
1954 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1955 ConstantInt::get(MS.IntptrTy, 8)),
1956 Type::getInt64PtrTy(*MS.C));
1957 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1958 Value *OverflowArgAreaShadowPtr =
1959 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1961 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1962 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1967 /// \brief A no-op implementation of VarArgHelper.
1968 struct VarArgNoOpHelper : public VarArgHelper {
1969 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
1970 MemorySanitizerVisitor &MSV) {}
1972 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {}
1974 void visitVAStartInst(VAStartInst &I) {}
1976 void visitVACopyInst(VACopyInst &I) {}
1978 void finalizeInstrumentation() {}
1981 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1982 MemorySanitizerVisitor &Visitor) {
1983 // VarArg handling is only implemented on AMD64. False positives are possible
1984 // on other platforms.
1985 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
1986 if (TargetTriple.getArch() == llvm::Triple::x86_64)
1987 return new VarArgAMD64Helper(Func, Msan, Visitor);
1989 return new VarArgNoOpHelper(Func, Msan, Visitor);
1994 bool MemorySanitizer::runOnFunction(Function &F) {
1995 MemorySanitizerVisitor Visitor(F, *this);
1997 // Clear out readonly/readnone attributes.
1999 B.addAttribute(Attribute::ReadOnly)
2000 .addAttribute(Attribute::ReadNone);
2001 F.removeAttributes(AttributeSet::FunctionIndex,
2002 AttributeSet::get(F.getContext(),
2003 AttributeSet::FunctionIndex, B));
2005 return Visitor.runOnFunction();