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/Local.h"
95 #include "llvm/Transforms/Utils/ModuleUtils.h"
96 #include "llvm/Transforms/Utils/SpecialCaseList.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 *MsanSetAllocaOrigin4Fn;
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<SpecialCaseList> 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 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
285 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
286 IRB.getInt8PtrTy(), IntptrTy, 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(SpecialCaseList::createOrDie(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);
370 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
371 IRB.getInt32(TrackOrigins), "__msan_track_origins");
374 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
375 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
382 /// \brief A helper class that handles instrumentation of VarArg
383 /// functions on a particular platform.
385 /// Implementations are expected to insert the instrumentation
386 /// necessary to propagate argument shadow through VarArg function
387 /// calls. Visit* methods are called during an InstVisitor pass over
388 /// the function, and should avoid creating new basic blocks. A new
389 /// instance of this class is created for each instrumented function.
390 struct VarArgHelper {
391 /// \brief Visit a CallSite.
392 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
394 /// \brief Visit a va_start call.
395 virtual void visitVAStartInst(VAStartInst &I) = 0;
397 /// \brief Visit a va_copy call.
398 virtual void visitVACopyInst(VACopyInst &I) = 0;
400 /// \brief Finalize function instrumentation.
402 /// This method is called after visiting all interesting (see above)
403 /// instructions in a function.
404 virtual void finalizeInstrumentation() = 0;
406 virtual ~VarArgHelper() {}
409 struct MemorySanitizerVisitor;
412 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
413 MemorySanitizerVisitor &Visitor);
415 /// This class does all the work for a given function. Store and Load
416 /// instructions store and load corresponding shadow and origin
417 /// values. Most instructions propagate shadow from arguments to their
418 /// return values. Certain instructions (most importantly, BranchInst)
419 /// test their argument shadow and print reports (with a runtime call) if it's
421 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
424 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
425 ValueMap<Value*, Value*> ShadowMap, OriginMap;
430 bool CheckReturnValue;
431 OwningPtr<VarArgHelper> VAHelper;
433 struct ShadowOriginAndInsertPoint {
436 Instruction *OrigIns;
437 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
438 : Shadow(S), Origin(O), OrigIns(I) { }
439 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
441 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
442 SmallVector<Instruction*, 16> StoreList;
444 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
445 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
446 bool SanitizeFunction = !MS.BL->isIn(F) && F.getAttributes().hasAttribute(
447 AttributeSet::FunctionIndex,
448 Attribute::SanitizeMemory);
449 InsertChecks = SanitizeFunction;
450 LoadShadow = SanitizeFunction;
451 PoisonStack = SanitizeFunction && ClPoisonStack;
452 PoisonUndef = SanitizeFunction && ClPoisonUndef;
453 // FIXME: Consider using SpecialCaseList to specify a list of functions that
454 // must always return fully initialized values. For now, we hardcode "main".
455 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
457 DEBUG(if (!InsertChecks)
458 dbgs() << "MemorySanitizer is not inserting checks into '"
459 << F.getName() << "'\n");
462 void materializeStores() {
463 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
464 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
467 Value *Val = I.getValueOperand();
468 Value *Addr = I.getPointerOperand();
469 Value *Shadow = getShadow(Val);
470 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
473 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
474 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
477 if (ClCheckAccessAddress)
478 insertCheck(Addr, &I);
480 if (MS.TrackOrigins) {
481 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
482 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
483 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
486 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
488 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
489 // TODO(eugenis): handle non-zero constant shadow by inserting an
490 // unconditional check (can not simply fail compilation as this could
491 // be in the dead code).
495 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
496 getCleanShadow(ConvertedShadow), "_mscmp");
497 Instruction *CheckTerm =
498 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
499 MS.OriginStoreWeights);
500 IRBuilder<> IRBNew(CheckTerm);
501 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
508 void materializeChecks() {
509 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
510 Instruction *Shadow = InstrumentationList[i].Shadow;
511 Instruction *OrigIns = InstrumentationList[i].OrigIns;
512 IRBuilder<> IRB(OrigIns);
513 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
514 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
515 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
516 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
517 getCleanShadow(ConvertedShadow), "_mscmp");
518 Instruction *CheckTerm =
519 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
520 /* Unreachable */ !ClKeepGoing,
523 IRB.SetInsertPoint(CheckTerm);
524 if (MS.TrackOrigins) {
525 Instruction *Origin = InstrumentationList[i].Origin;
526 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
529 CallInst *Call = IRB.CreateCall(MS.WarningFn);
530 Call->setDebugLoc(OrigIns->getDebugLoc());
531 IRB.CreateCall(MS.EmptyAsm);
532 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
534 DEBUG(dbgs() << "DONE:\n" << F);
537 /// \brief Add MemorySanitizer instrumentation to a function.
538 bool runOnFunction() {
539 MS.initializeCallbacks(*F.getParent());
540 if (!MS.TD) return false;
542 // In the presence of unreachable blocks, we may see Phi nodes with
543 // incoming nodes from such blocks. Since InstVisitor skips unreachable
544 // blocks, such nodes will not have any shadow value associated with them.
545 // It's easier to remove unreachable blocks than deal with missing shadow.
546 removeUnreachableBlocks(F);
548 // Iterate all BBs in depth-first order and create shadow instructions
549 // for all instructions (where applicable).
550 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
551 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
552 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
553 BasicBlock *BB = *DI;
557 // Finalize PHI nodes.
558 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
559 PHINode *PN = ShadowPHINodes[i];
560 PHINode *PNS = cast<PHINode>(getShadow(PN));
561 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
562 size_t NumValues = PN->getNumIncomingValues();
563 for (size_t v = 0; v < NumValues; v++) {
564 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
566 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
570 VAHelper->finalizeInstrumentation();
572 // Delayed instrumentation of StoreInst.
573 // This may add new checks to be inserted later.
576 // Insert shadow value checks.
582 /// \brief Compute the shadow type that corresponds to a given Value.
583 Type *getShadowTy(Value *V) {
584 return getShadowTy(V->getType());
587 /// \brief Compute the shadow type that corresponds to a given Type.
588 Type *getShadowTy(Type *OrigTy) {
589 if (!OrigTy->isSized()) {
592 // For integer type, shadow is the same as the original type.
593 // This may return weird-sized types like i1.
594 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
596 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
597 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
598 return VectorType::get(IntegerType::get(*MS.C, EltSize),
599 VT->getNumElements());
601 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
602 SmallVector<Type*, 4> Elements;
603 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
604 Elements.push_back(getShadowTy(ST->getElementType(i)));
605 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
606 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
609 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
610 return IntegerType::get(*MS.C, TypeSize);
613 /// \brief Flatten a vector type.
614 Type *getShadowTyNoVec(Type *ty) {
615 if (VectorType *vt = dyn_cast<VectorType>(ty))
616 return IntegerType::get(*MS.C, vt->getBitWidth());
620 /// \brief Convert a shadow value to it's flattened variant.
621 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
622 Type *Ty = V->getType();
623 Type *NoVecTy = getShadowTyNoVec(Ty);
624 if (Ty == NoVecTy) return V;
625 return IRB.CreateBitCast(V, NoVecTy);
628 /// \brief Compute the shadow address that corresponds to a given application
631 /// Shadow = Addr & ~ShadowMask.
632 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
635 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
636 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
637 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
640 /// \brief Compute the origin address that corresponds to a given application
643 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
644 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
646 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
647 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
649 IRB.CreateAdd(ShadowLong,
650 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
652 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
653 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
656 /// \brief Compute the shadow address for a given function argument.
658 /// Shadow = ParamTLS+ArgOffset.
659 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
661 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
662 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
663 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
667 /// \brief Compute the origin address for a given function argument.
668 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
670 if (!MS.TrackOrigins) return 0;
671 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
672 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
673 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
677 /// \brief Compute the shadow address for a retval.
678 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
679 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
680 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
684 /// \brief Compute the origin address for a retval.
685 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
686 // We keep a single origin for the entire retval. Might be too optimistic.
687 return MS.RetvalOriginTLS;
690 /// \brief Set SV to be the shadow value for V.
691 void setShadow(Value *V, Value *SV) {
692 assert(!ShadowMap.count(V) && "Values may only have one shadow");
696 /// \brief Set Origin to be the origin value for V.
697 void setOrigin(Value *V, Value *Origin) {
698 if (!MS.TrackOrigins) return;
699 assert(!OriginMap.count(V) && "Values may only have one origin");
700 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
701 OriginMap[V] = Origin;
704 /// \brief Create a clean shadow value for a given value.
706 /// Clean shadow (all zeroes) means all bits of the value are defined
708 Constant *getCleanShadow(Value *V) {
709 Type *ShadowTy = getShadowTy(V);
712 return Constant::getNullValue(ShadowTy);
715 /// \brief Create a dirty shadow of a given shadow type.
716 Constant *getPoisonedShadow(Type *ShadowTy) {
718 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
719 return Constant::getAllOnesValue(ShadowTy);
720 StructType *ST = cast<StructType>(ShadowTy);
721 SmallVector<Constant *, 4> Vals;
722 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
723 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
724 return ConstantStruct::get(ST, Vals);
727 /// \brief Create a dirty shadow for a given value.
728 Constant *getPoisonedShadow(Value *V) {
729 Type *ShadowTy = getShadowTy(V);
732 return getPoisonedShadow(ShadowTy);
735 /// \brief Create a clean (zero) origin.
736 Value *getCleanOrigin() {
737 return Constant::getNullValue(MS.OriginTy);
740 /// \brief Get the shadow value for a given Value.
742 /// This function either returns the value set earlier with setShadow,
743 /// or extracts if from ParamTLS (for function arguments).
744 Value *getShadow(Value *V) {
745 if (Instruction *I = dyn_cast<Instruction>(V)) {
746 // For instructions the shadow is already stored in the map.
747 Value *Shadow = ShadowMap[V];
749 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
751 assert(Shadow && "No shadow for a value");
755 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
756 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
757 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
761 if (Argument *A = dyn_cast<Argument>(V)) {
762 // For arguments we compute the shadow on demand and store it in the map.
763 Value **ShadowPtr = &ShadowMap[V];
766 Function *F = A->getParent();
767 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
768 unsigned ArgOffset = 0;
769 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
771 if (!AI->getType()->isSized()) {
772 DEBUG(dbgs() << "Arg is not sized\n");
775 unsigned Size = AI->hasByValAttr()
776 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
777 : MS.TD->getTypeAllocSize(AI->getType());
779 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
780 if (AI->hasByValAttr()) {
781 // ByVal pointer itself has clean shadow. We copy the actual
782 // argument shadow to the underlying memory.
783 // Figure out maximal valid memcpy alignment.
784 unsigned ArgAlign = AI->getParamAlignment();
786 Type *EltType = A->getType()->getPointerElementType();
787 ArgAlign = MS.TD->getABITypeAlignment(EltType);
789 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
790 Value *Cpy = EntryIRB.CreateMemCpy(
791 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
793 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
795 *ShadowPtr = getCleanShadow(V);
797 *ShadowPtr = EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
799 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
800 **ShadowPtr << "\n");
801 if (MS.TrackOrigins) {
802 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
803 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
806 ArgOffset += DataLayout::RoundUpAlignment(Size, kShadowTLSAlignment);
808 assert(*ShadowPtr && "Could not find shadow for an argument");
811 // For everything else the shadow is zero.
812 return getCleanShadow(V);
815 /// \brief Get the shadow for i-th argument of the instruction I.
816 Value *getShadow(Instruction *I, int i) {
817 return getShadow(I->getOperand(i));
820 /// \brief Get the origin for a value.
821 Value *getOrigin(Value *V) {
822 if (!MS.TrackOrigins) return 0;
823 if (isa<Instruction>(V) || isa<Argument>(V)) {
824 Value *Origin = OriginMap[V];
826 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
827 Origin = getCleanOrigin();
831 return getCleanOrigin();
834 /// \brief Get the origin for i-th argument of the instruction I.
835 Value *getOrigin(Instruction *I, int i) {
836 return getOrigin(I->getOperand(i));
839 /// \brief Remember the place where a shadow check should be inserted.
841 /// This location will be later instrumented with a check that will print a
842 /// UMR warning in runtime if the value is not fully defined.
843 void insertCheck(Value *Val, Instruction *OrigIns) {
845 if (!InsertChecks) return;
846 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
849 Type *ShadowTy = Shadow->getType();
850 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
851 "Can only insert checks for integer and vector shadow types");
853 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
854 InstrumentationList.push_back(
855 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
858 // ------------------- Visitors.
860 /// \brief Instrument LoadInst
862 /// Loads the corresponding shadow and (optionally) origin.
863 /// Optionally, checks that the load address is fully defined.
864 void visitLoadInst(LoadInst &I) {
865 assert(I.getType()->isSized() && "Load type must have size");
867 Type *ShadowTy = getShadowTy(&I);
868 Value *Addr = I.getPointerOperand();
870 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
872 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
874 setShadow(&I, getCleanShadow(&I));
877 if (ClCheckAccessAddress)
878 insertCheck(I.getPointerOperand(), &I);
880 if (MS.TrackOrigins) {
882 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
884 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
886 setOrigin(&I, getCleanOrigin());
891 /// \brief Instrument StoreInst
893 /// Stores the corresponding shadow and (optionally) origin.
894 /// Optionally, checks that the store address is fully defined.
895 void visitStoreInst(StoreInst &I) {
896 StoreList.push_back(&I);
899 // Vector manipulation.
900 void visitExtractElementInst(ExtractElementInst &I) {
901 insertCheck(I.getOperand(1), &I);
903 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
905 setOrigin(&I, getOrigin(&I, 0));
908 void visitInsertElementInst(InsertElementInst &I) {
909 insertCheck(I.getOperand(2), &I);
911 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
912 I.getOperand(2), "_msprop"));
913 setOriginForNaryOp(I);
916 void visitShuffleVectorInst(ShuffleVectorInst &I) {
917 insertCheck(I.getOperand(2), &I);
919 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
920 I.getOperand(2), "_msprop"));
921 setOriginForNaryOp(I);
925 void visitSExtInst(SExtInst &I) {
927 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
928 setOrigin(&I, getOrigin(&I, 0));
931 void visitZExtInst(ZExtInst &I) {
933 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
934 setOrigin(&I, getOrigin(&I, 0));
937 void visitTruncInst(TruncInst &I) {
939 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
940 setOrigin(&I, getOrigin(&I, 0));
943 void visitBitCastInst(BitCastInst &I) {
945 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
946 setOrigin(&I, getOrigin(&I, 0));
949 void visitPtrToIntInst(PtrToIntInst &I) {
951 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
952 "_msprop_ptrtoint"));
953 setOrigin(&I, getOrigin(&I, 0));
956 void visitIntToPtrInst(IntToPtrInst &I) {
958 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
959 "_msprop_inttoptr"));
960 setOrigin(&I, getOrigin(&I, 0));
963 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
964 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
965 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
966 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
967 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
968 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
970 /// \brief Propagate shadow for bitwise AND.
972 /// This code is exact, i.e. if, for example, a bit in the left argument
973 /// is defined and 0, then neither the value not definedness of the
974 /// corresponding bit in B don't affect the resulting shadow.
975 void visitAnd(BinaryOperator &I) {
977 // "And" of 0 and a poisoned value results in unpoisoned value.
978 // 1&1 => 1; 0&1 => 0; p&1 => p;
979 // 1&0 => 0; 0&0 => 0; p&0 => 0;
980 // 1&p => p; 0&p => 0; p&p => p;
981 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
982 Value *S1 = getShadow(&I, 0);
983 Value *S2 = getShadow(&I, 1);
984 Value *V1 = I.getOperand(0);
985 Value *V2 = I.getOperand(1);
986 if (V1->getType() != S1->getType()) {
987 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
988 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
990 Value *S1S2 = IRB.CreateAnd(S1, S2);
991 Value *V1S2 = IRB.CreateAnd(V1, S2);
992 Value *S1V2 = IRB.CreateAnd(S1, V2);
993 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
994 setOriginForNaryOp(I);
997 void visitOr(BinaryOperator &I) {
999 // "Or" of 1 and a poisoned value results in unpoisoned value.
1000 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1001 // 1|0 => 1; 0|0 => 0; p|0 => p;
1002 // 1|p => 1; 0|p => p; p|p => p;
1003 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1004 Value *S1 = getShadow(&I, 0);
1005 Value *S2 = getShadow(&I, 1);
1006 Value *V1 = IRB.CreateNot(I.getOperand(0));
1007 Value *V2 = IRB.CreateNot(I.getOperand(1));
1008 if (V1->getType() != S1->getType()) {
1009 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1010 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1012 Value *S1S2 = IRB.CreateAnd(S1, S2);
1013 Value *V1S2 = IRB.CreateAnd(V1, S2);
1014 Value *S1V2 = IRB.CreateAnd(S1, V2);
1015 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1016 setOriginForNaryOp(I);
1019 /// \brief Default propagation of shadow and/or origin.
1021 /// This class implements the general case of shadow propagation, used in all
1022 /// cases where we don't know and/or don't care about what the operation
1023 /// actually does. It converts all input shadow values to a common type
1024 /// (extending or truncating as necessary), and bitwise OR's them.
1026 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1027 /// fully initialized), and less prone to false positives.
1029 /// This class also implements the general case of origin propagation. For a
1030 /// Nary operation, result origin is set to the origin of an argument that is
1031 /// not entirely initialized. If there is more than one such arguments, the
1032 /// rightmost of them is picked. It does not matter which one is picked if all
1033 /// arguments are initialized.
1034 template <bool CombineShadow>
1039 MemorySanitizerVisitor *MSV;
1042 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1043 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1045 /// \brief Add a pair of shadow and origin values to the mix.
1046 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1047 if (CombineShadow) {
1052 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1053 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1057 if (MSV->MS.TrackOrigins) {
1062 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1063 Value *Cond = IRB.CreateICmpNE(FlatShadow,
1064 MSV->getCleanShadow(FlatShadow));
1065 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1071 /// \brief Add an application value to the mix.
1072 Combiner &Add(Value *V) {
1073 Value *OpShadow = MSV->getShadow(V);
1074 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1075 return Add(OpShadow, OpOrigin);
1078 /// \brief Set the current combined values as the given instruction's shadow
1080 void Done(Instruction *I) {
1081 if (CombineShadow) {
1083 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1084 MSV->setShadow(I, Shadow);
1086 if (MSV->MS.TrackOrigins) {
1088 MSV->setOrigin(I, Origin);
1093 typedef Combiner<true> ShadowAndOriginCombiner;
1094 typedef Combiner<false> OriginCombiner;
1096 /// \brief Propagate origin for arbitrary operation.
1097 void setOriginForNaryOp(Instruction &I) {
1098 if (!MS.TrackOrigins) return;
1099 IRBuilder<> IRB(&I);
1100 OriginCombiner OC(this, IRB);
1101 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1106 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1107 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1108 "Vector of pointers is not a valid shadow type");
1109 return Ty->isVectorTy() ?
1110 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1111 Ty->getPrimitiveSizeInBits();
1114 /// \brief Cast between two shadow types, extending or truncating as
1116 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1117 Type *srcTy = V->getType();
1118 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1119 return IRB.CreateIntCast(V, dstTy, false);
1120 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1121 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1122 return IRB.CreateIntCast(V, dstTy, false);
1123 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1124 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1125 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1127 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1128 return IRB.CreateBitCast(V2, dstTy);
1129 // TODO: handle struct types.
1132 /// \brief Propagate shadow for arbitrary operation.
1133 void handleShadowOr(Instruction &I) {
1134 IRBuilder<> IRB(&I);
1135 ShadowAndOriginCombiner SC(this, IRB);
1136 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1141 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1142 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1143 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1144 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1145 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1146 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1147 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1149 void handleDiv(Instruction &I) {
1150 IRBuilder<> IRB(&I);
1151 // Strict on the second argument.
1152 insertCheck(I.getOperand(1), &I);
1153 setShadow(&I, getShadow(&I, 0));
1154 setOrigin(&I, getOrigin(&I, 0));
1157 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1158 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1159 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1160 void visitURem(BinaryOperator &I) { handleDiv(I); }
1161 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1162 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1164 /// \brief Instrument == and != comparisons.
1166 /// Sometimes the comparison result is known even if some of the bits of the
1167 /// arguments are not.
1168 void handleEqualityComparison(ICmpInst &I) {
1169 IRBuilder<> IRB(&I);
1170 Value *A = I.getOperand(0);
1171 Value *B = I.getOperand(1);
1172 Value *Sa = getShadow(A);
1173 Value *Sb = getShadow(B);
1175 // Get rid of pointers and vectors of pointers.
1176 // For ints (and vectors of ints), types of A and Sa match,
1177 // and this is a no-op.
1178 A = IRB.CreatePointerCast(A, Sa->getType());
1179 B = IRB.CreatePointerCast(B, Sb->getType());
1181 // A == B <==> (C = A^B) == 0
1182 // A != B <==> (C = A^B) != 0
1184 Value *C = IRB.CreateXor(A, B);
1185 Value *Sc = IRB.CreateOr(Sa, Sb);
1186 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1187 // Result is defined if one of the following is true
1188 // * there is a defined 1 bit in C
1189 // * C is fully defined
1190 // Si = !(C & ~Sc) && Sc
1191 Value *Zero = Constant::getNullValue(Sc->getType());
1192 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1194 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1196 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1197 Si->setName("_msprop_icmp");
1199 setOriginForNaryOp(I);
1202 /// \brief Build the lowest possible value of V, taking into account V's
1203 /// uninitialized bits.
1204 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1207 // Split shadow into sign bit and other bits.
1208 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1209 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1210 // Maximise the undefined shadow bit, minimize other undefined bits.
1212 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1214 // Minimize undefined bits.
1215 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1219 /// \brief Build the highest possible value of V, taking into account V's
1220 /// uninitialized bits.
1221 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1224 // Split shadow into sign bit and other bits.
1225 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1226 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1227 // Minimise the undefined shadow bit, maximise other undefined bits.
1229 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1231 // Maximize undefined bits.
1232 return IRB.CreateOr(A, Sa);
1236 /// \brief Instrument relational comparisons.
1238 /// This function does exact shadow propagation for all relational
1239 /// comparisons of integers, pointers and vectors of those.
1240 /// FIXME: output seems suboptimal when one of the operands is a constant
1241 void handleRelationalComparisonExact(ICmpInst &I) {
1242 IRBuilder<> IRB(&I);
1243 Value *A = I.getOperand(0);
1244 Value *B = I.getOperand(1);
1245 Value *Sa = getShadow(A);
1246 Value *Sb = getShadow(B);
1248 // Get rid of pointers and vectors of pointers.
1249 // For ints (and vectors of ints), types of A and Sa match,
1250 // and this is a no-op.
1251 A = IRB.CreatePointerCast(A, Sa->getType());
1252 B = IRB.CreatePointerCast(B, Sb->getType());
1254 // Let [a0, a1] be the interval of possible values of A, taking into account
1255 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1256 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1257 bool IsSigned = I.isSigned();
1258 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1259 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1260 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1261 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1262 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1263 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1264 Value *Si = IRB.CreateXor(S1, S2);
1266 setOriginForNaryOp(I);
1269 /// \brief Instrument signed relational comparisons.
1271 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1272 /// propagating the highest bit of the shadow. Everything else is delegated
1273 /// to handleShadowOr().
1274 void handleSignedRelationalComparison(ICmpInst &I) {
1275 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1276 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1278 CmpInst::Predicate pre = I.getPredicate();
1279 if (constOp0 && constOp0->isNullValue() &&
1280 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1281 op = I.getOperand(1);
1282 } else if (constOp1 && constOp1->isNullValue() &&
1283 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1284 op = I.getOperand(0);
1287 IRBuilder<> IRB(&I);
1289 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1290 setShadow(&I, Shadow);
1291 setOrigin(&I, getOrigin(op));
1297 void visitICmpInst(ICmpInst &I) {
1298 if (!ClHandleICmp) {
1302 if (I.isEquality()) {
1303 handleEqualityComparison(I);
1307 assert(I.isRelational());
1308 if (ClHandleICmpExact) {
1309 handleRelationalComparisonExact(I);
1313 handleSignedRelationalComparison(I);
1317 assert(I.isUnsigned());
1318 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1319 handleRelationalComparisonExact(I);
1326 void visitFCmpInst(FCmpInst &I) {
1330 void handleShift(BinaryOperator &I) {
1331 IRBuilder<> IRB(&I);
1332 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1333 // Otherwise perform the same shift on S1.
1334 Value *S1 = getShadow(&I, 0);
1335 Value *S2 = getShadow(&I, 1);
1336 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1338 Value *V2 = I.getOperand(1);
1339 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1340 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1341 setOriginForNaryOp(I);
1344 void visitShl(BinaryOperator &I) { handleShift(I); }
1345 void visitAShr(BinaryOperator &I) { handleShift(I); }
1346 void visitLShr(BinaryOperator &I) { handleShift(I); }
1348 /// \brief Instrument llvm.memmove
1350 /// At this point we don't know if llvm.memmove will be inlined or not.
1351 /// If we don't instrument it and it gets inlined,
1352 /// our interceptor will not kick in and we will lose the memmove.
1353 /// If we instrument the call here, but it does not get inlined,
1354 /// we will memove the shadow twice: which is bad in case
1355 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1357 /// Similar situation exists for memcpy and memset.
1358 void visitMemMoveInst(MemMoveInst &I) {
1359 IRBuilder<> IRB(&I);
1362 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1363 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1364 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1365 I.eraseFromParent();
1368 // Similar to memmove: avoid copying shadow twice.
1369 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1370 // FIXME: consider doing manual inline for small constant sizes and proper
1372 void visitMemCpyInst(MemCpyInst &I) {
1373 IRBuilder<> IRB(&I);
1376 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1377 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1378 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1379 I.eraseFromParent();
1383 void visitMemSetInst(MemSetInst &I) {
1384 IRBuilder<> IRB(&I);
1387 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1388 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1389 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1390 I.eraseFromParent();
1393 void visitVAStartInst(VAStartInst &I) {
1394 VAHelper->visitVAStartInst(I);
1397 void visitVACopyInst(VACopyInst &I) {
1398 VAHelper->visitVACopyInst(I);
1401 enum IntrinsicKind {
1402 IK_DoesNotAccessMemory,
1407 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1408 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1409 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1410 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1411 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1412 const int UnknownModRefBehavior = IK_WritesMemory;
1413 #define GET_INTRINSIC_MODREF_BEHAVIOR
1414 #define ModRefBehavior IntrinsicKind
1415 #include "llvm/IR/Intrinsics.gen"
1416 #undef ModRefBehavior
1417 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1420 /// \brief Handle vector store-like intrinsics.
1422 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1423 /// has 1 pointer argument and 1 vector argument, returns void.
1424 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1425 IRBuilder<> IRB(&I);
1426 Value* Addr = I.getArgOperand(0);
1427 Value *Shadow = getShadow(&I, 1);
1428 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1430 // We don't know the pointer alignment (could be unaligned SSE store!).
1431 // Have to assume to worst case.
1432 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1434 if (ClCheckAccessAddress)
1435 insertCheck(Addr, &I);
1437 // FIXME: use ClStoreCleanOrigin
1438 // FIXME: factor out common code from materializeStores
1439 if (MS.TrackOrigins)
1440 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1444 /// \brief Handle vector load-like intrinsics.
1446 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1447 /// has 1 pointer argument, returns a vector.
1448 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1449 IRBuilder<> IRB(&I);
1450 Value *Addr = I.getArgOperand(0);
1452 Type *ShadowTy = getShadowTy(&I);
1454 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1455 // We don't know the pointer alignment (could be unaligned SSE load!).
1456 // Have to assume to worst case.
1457 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1459 setShadow(&I, getCleanShadow(&I));
1463 if (ClCheckAccessAddress)
1464 insertCheck(Addr, &I);
1466 if (MS.TrackOrigins) {
1468 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1470 setOrigin(&I, getCleanOrigin());
1475 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1477 /// Instrument intrinsics with any number of arguments of the same type,
1478 /// equal to the return type. The type should be simple (no aggregates or
1479 /// pointers; vectors are fine).
1480 /// Caller guarantees that this intrinsic does not access memory.
1481 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1482 Type *RetTy = I.getType();
1483 if (!(RetTy->isIntOrIntVectorTy() ||
1484 RetTy->isFPOrFPVectorTy() ||
1485 RetTy->isX86_MMXTy()))
1488 unsigned NumArgOperands = I.getNumArgOperands();
1490 for (unsigned i = 0; i < NumArgOperands; ++i) {
1491 Type *Ty = I.getArgOperand(i)->getType();
1496 IRBuilder<> IRB(&I);
1497 ShadowAndOriginCombiner SC(this, IRB);
1498 for (unsigned i = 0; i < NumArgOperands; ++i)
1499 SC.Add(I.getArgOperand(i));
1505 /// \brief Heuristically instrument unknown intrinsics.
1507 /// The main purpose of this code is to do something reasonable with all
1508 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1509 /// We recognize several classes of intrinsics by their argument types and
1510 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1511 /// sure that we know what the intrinsic does.
1513 /// We special-case intrinsics where this approach fails. See llvm.bswap
1514 /// handling as an example of that.
1515 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1516 unsigned NumArgOperands = I.getNumArgOperands();
1517 if (NumArgOperands == 0)
1520 Intrinsic::ID iid = I.getIntrinsicID();
1521 IntrinsicKind IK = getIntrinsicKind(iid);
1522 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1523 bool WritesMemory = IK == IK_WritesMemory;
1524 assert(!(OnlyReadsMemory && WritesMemory));
1526 if (NumArgOperands == 2 &&
1527 I.getArgOperand(0)->getType()->isPointerTy() &&
1528 I.getArgOperand(1)->getType()->isVectorTy() &&
1529 I.getType()->isVoidTy() &&
1531 // This looks like a vector store.
1532 return handleVectorStoreIntrinsic(I);
1535 if (NumArgOperands == 1 &&
1536 I.getArgOperand(0)->getType()->isPointerTy() &&
1537 I.getType()->isVectorTy() &&
1539 // This looks like a vector load.
1540 return handleVectorLoadIntrinsic(I);
1543 if (!OnlyReadsMemory && !WritesMemory)
1544 if (maybeHandleSimpleNomemIntrinsic(I))
1547 // FIXME: detect and handle SSE maskstore/maskload
1551 void handleBswap(IntrinsicInst &I) {
1552 IRBuilder<> IRB(&I);
1553 Value *Op = I.getArgOperand(0);
1554 Type *OpType = Op->getType();
1555 Function *BswapFunc = Intrinsic::getDeclaration(
1556 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1557 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1558 setOrigin(&I, getOrigin(Op));
1561 void visitIntrinsicInst(IntrinsicInst &I) {
1562 switch (I.getIntrinsicID()) {
1563 case llvm::Intrinsic::bswap:
1567 if (!handleUnknownIntrinsic(I))
1568 visitInstruction(I);
1573 void visitCallSite(CallSite CS) {
1574 Instruction &I = *CS.getInstruction();
1575 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1577 CallInst *Call = cast<CallInst>(&I);
1579 // For inline asm, do the usual thing: check argument shadow and mark all
1580 // outputs as clean. Note that any side effects of the inline asm that are
1581 // not immediately visible in its constraints are not handled.
1582 if (Call->isInlineAsm()) {
1583 visitInstruction(I);
1587 // Allow only tail calls with the same types, otherwise
1588 // we may have a false positive: shadow for a non-void RetVal
1589 // will get propagated to a void RetVal.
1590 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1591 Call->setTailCall(false);
1593 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1595 // We are going to insert code that relies on the fact that the callee
1596 // will become a non-readonly function after it is instrumented by us. To
1597 // prevent this code from being optimized out, mark that function
1598 // non-readonly in advance.
1599 if (Function *Func = Call->getCalledFunction()) {
1600 // Clear out readonly/readnone attributes.
1602 B.addAttribute(Attribute::ReadOnly)
1603 .addAttribute(Attribute::ReadNone);
1604 Func->removeAttributes(AttributeSet::FunctionIndex,
1605 AttributeSet::get(Func->getContext(),
1606 AttributeSet::FunctionIndex,
1610 IRBuilder<> IRB(&I);
1611 unsigned ArgOffset = 0;
1612 DEBUG(dbgs() << " CallSite: " << I << "\n");
1613 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1614 ArgIt != End; ++ArgIt) {
1616 unsigned i = ArgIt - CS.arg_begin();
1617 if (!A->getType()->isSized()) {
1618 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1623 // Compute the Shadow for arg even if it is ByVal, because
1624 // in that case getShadow() will copy the actual arg shadow to
1625 // __msan_param_tls.
1626 Value *ArgShadow = getShadow(A);
1627 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1628 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1629 " Shadow: " << *ArgShadow << "\n");
1630 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1631 assert(A->getType()->isPointerTy() &&
1632 "ByVal argument is not a pointer!");
1633 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1634 unsigned Alignment = CS.getParamAlignment(i + 1);
1635 Store = IRB.CreateMemCpy(ArgShadowBase,
1636 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1639 Size = MS.TD->getTypeAllocSize(A->getType());
1640 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1641 kShadowTLSAlignment);
1643 if (MS.TrackOrigins)
1644 IRB.CreateStore(getOrigin(A),
1645 getOriginPtrForArgument(A, IRB, ArgOffset));
1647 assert(Size != 0 && Store != 0);
1648 DEBUG(dbgs() << " Param:" << *Store << "\n");
1649 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1651 DEBUG(dbgs() << " done with call args\n");
1654 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1655 if (FT->isVarArg()) {
1656 VAHelper->visitCallSite(CS, IRB);
1659 // Now, get the shadow for the RetVal.
1660 if (!I.getType()->isSized()) return;
1661 IRBuilder<> IRBBefore(&I);
1662 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1663 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1664 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1665 Instruction *NextInsn = 0;
1667 NextInsn = I.getNextNode();
1669 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1670 if (!NormalDest->getSinglePredecessor()) {
1671 // FIXME: this case is tricky, so we are just conservative here.
1672 // Perhaps we need to split the edge between this BB and NormalDest,
1673 // but a naive attempt to use SplitEdge leads to a crash.
1674 setShadow(&I, getCleanShadow(&I));
1675 setOrigin(&I, getCleanOrigin());
1678 NextInsn = NormalDest->getFirstInsertionPt();
1680 "Could not find insertion point for retval shadow load");
1682 IRBuilder<> IRBAfter(NextInsn);
1683 Value *RetvalShadow =
1684 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1685 kShadowTLSAlignment, "_msret");
1686 setShadow(&I, RetvalShadow);
1687 if (MS.TrackOrigins)
1688 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1691 void visitReturnInst(ReturnInst &I) {
1692 IRBuilder<> IRB(&I);
1693 Value *RetVal = I.getReturnValue();
1694 if (!RetVal) return;
1695 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1696 if (CheckReturnValue) {
1697 insertCheck(RetVal, &I);
1698 Value *Shadow = getCleanShadow(RetVal);
1699 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1701 Value *Shadow = getShadow(RetVal);
1702 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1703 // FIXME: make it conditional if ClStoreCleanOrigin==0
1704 if (MS.TrackOrigins)
1705 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1709 void visitPHINode(PHINode &I) {
1710 IRBuilder<> IRB(&I);
1711 ShadowPHINodes.push_back(&I);
1712 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1714 if (MS.TrackOrigins)
1715 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1719 void visitAllocaInst(AllocaInst &I) {
1720 setShadow(&I, getCleanShadow(&I));
1721 IRBuilder<> IRB(I.getNextNode());
1722 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1723 if (PoisonStack && ClPoisonStackWithCall) {
1724 IRB.CreateCall2(MS.MsanPoisonStackFn,
1725 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1726 ConstantInt::get(MS.IntptrTy, Size));
1728 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1729 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
1730 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
1733 if (PoisonStack && MS.TrackOrigins) {
1734 setOrigin(&I, getCleanOrigin());
1735 SmallString<2048> StackDescriptionStorage;
1736 raw_svector_ostream StackDescription(StackDescriptionStorage);
1737 // We create a string with a description of the stack allocation and
1738 // pass it into __msan_set_alloca_origin.
1739 // It will be printed by the run-time if stack-originated UMR is found.
1740 // The first 4 bytes of the string are set to '----' and will be replaced
1741 // by __msan_va_arg_overflow_size_tls at the first call.
1742 StackDescription << "----" << I.getName() << "@" << F.getName();
1744 createPrivateNonConstGlobalForString(*F.getParent(),
1745 StackDescription.str());
1747 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
1748 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1749 ConstantInt::get(MS.IntptrTy, Size),
1750 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
1751 IRB.CreatePointerCast(&F, MS.IntptrTy));
1755 void visitSelectInst(SelectInst& I) {
1756 IRBuilder<> IRB(&I);
1757 // a = select b, c, d
1758 Value *S = IRB.CreateSelect(I.getCondition(), getShadow(I.getTrueValue()),
1759 getShadow(I.getFalseValue()));
1760 if (I.getType()->isAggregateType()) {
1761 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
1762 // an extra "select". This results in much more compact IR.
1763 // Sa = select Sb, poisoned, (select b, Sc, Sd)
1764 S = IRB.CreateSelect(getShadow(I.getCondition()),
1765 getPoisonedShadow(getShadowTy(I.getType())), S,
1766 "_msprop_select_agg");
1768 // Sa = (sext Sb) | (select b, Sc, Sd)
1770 S, IRB.CreateSExt(getShadow(I.getCondition()), S->getType()),
1774 if (MS.TrackOrigins) {
1775 // Origins are always i32, so any vector conditions must be flattened.
1776 // FIXME: consider tracking vector origins for app vectors?
1777 Value *Cond = I.getCondition();
1778 if (Cond->getType()->isVectorTy()) {
1779 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1780 Cond = IRB.CreateICmpNE(ConvertedShadow,
1781 getCleanShadow(ConvertedShadow), "_mso_select");
1783 setOrigin(&I, IRB.CreateSelect(Cond,
1784 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1788 void visitLandingPadInst(LandingPadInst &I) {
1790 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1791 setShadow(&I, getCleanShadow(&I));
1792 setOrigin(&I, getCleanOrigin());
1795 void visitGetElementPtrInst(GetElementPtrInst &I) {
1799 void visitExtractValueInst(ExtractValueInst &I) {
1800 IRBuilder<> IRB(&I);
1801 Value *Agg = I.getAggregateOperand();
1802 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1803 Value *AggShadow = getShadow(Agg);
1804 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1805 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1806 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1807 setShadow(&I, ResShadow);
1808 setOrigin(&I, getCleanOrigin());
1811 void visitInsertValueInst(InsertValueInst &I) {
1812 IRBuilder<> IRB(&I);
1813 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1814 Value *AggShadow = getShadow(I.getAggregateOperand());
1815 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1816 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1817 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1818 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1819 DEBUG(dbgs() << " Res: " << *Res << "\n");
1821 setOrigin(&I, getCleanOrigin());
1824 void dumpInst(Instruction &I) {
1825 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1826 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1828 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1830 errs() << "QQQ " << I << "\n";
1833 void visitResumeInst(ResumeInst &I) {
1834 DEBUG(dbgs() << "Resume: " << I << "\n");
1835 // Nothing to do here.
1838 void visitInstruction(Instruction &I) {
1839 // Everything else: stop propagating and check for poisoned shadow.
1840 if (ClDumpStrictInstructions)
1842 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1843 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1844 insertCheck(I.getOperand(i), &I);
1845 setShadow(&I, getCleanShadow(&I));
1846 setOrigin(&I, getCleanOrigin());
1850 /// \brief AMD64-specific implementation of VarArgHelper.
1851 struct VarArgAMD64Helper : public VarArgHelper {
1852 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1853 // See a comment in visitCallSite for more details.
1854 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1855 static const unsigned AMD64FpEndOffset = 176;
1858 MemorySanitizer &MS;
1859 MemorySanitizerVisitor &MSV;
1860 Value *VAArgTLSCopy;
1861 Value *VAArgOverflowSize;
1863 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1865 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1866 MemorySanitizerVisitor &MSV)
1867 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1869 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1871 ArgKind classifyArgument(Value* arg) {
1872 // A very rough approximation of X86_64 argument classification rules.
1873 Type *T = arg->getType();
1874 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1875 return AK_FloatingPoint;
1876 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1877 return AK_GeneralPurpose;
1878 if (T->isPointerTy())
1879 return AK_GeneralPurpose;
1883 // For VarArg functions, store the argument shadow in an ABI-specific format
1884 // that corresponds to va_list layout.
1885 // We do this because Clang lowers va_arg in the frontend, and this pass
1886 // only sees the low level code that deals with va_list internals.
1887 // A much easier alternative (provided that Clang emits va_arg instructions)
1888 // would have been to associate each live instance of va_list with a copy of
1889 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1891 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1892 unsigned GpOffset = 0;
1893 unsigned FpOffset = AMD64GpEndOffset;
1894 unsigned OverflowOffset = AMD64FpEndOffset;
1895 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1896 ArgIt != End; ++ArgIt) {
1898 ArgKind AK = classifyArgument(A);
1899 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1901 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1905 case AK_GeneralPurpose:
1906 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1909 case AK_FloatingPoint:
1910 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1914 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1915 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1916 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1918 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1920 Constant *OverflowSize =
1921 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1922 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1925 /// \brief Compute the shadow address for a given va_arg.
1926 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1928 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1929 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1930 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1934 void visitVAStartInst(VAStartInst &I) {
1935 IRBuilder<> IRB(&I);
1936 VAStartInstrumentationList.push_back(&I);
1937 Value *VAListTag = I.getArgOperand(0);
1938 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1940 // Unpoison the whole __va_list_tag.
1941 // FIXME: magic ABI constants.
1942 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1943 /* size */24, /* alignment */8, false);
1946 void visitVACopyInst(VACopyInst &I) {
1947 IRBuilder<> IRB(&I);
1948 Value *VAListTag = I.getArgOperand(0);
1949 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1951 // Unpoison the whole __va_list_tag.
1952 // FIXME: magic ABI constants.
1953 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1954 /* size */24, /* alignment */8, false);
1957 void finalizeInstrumentation() {
1958 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1959 "finalizeInstrumentation called twice");
1960 if (!VAStartInstrumentationList.empty()) {
1961 // If there is a va_start in this function, make a backup copy of
1962 // va_arg_tls somewhere in the function entry block.
1963 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1964 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1966 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1968 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1969 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1972 // Instrument va_start.
1973 // Copy va_list shadow from the backup copy of the TLS contents.
1974 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1975 CallInst *OrigInst = VAStartInstrumentationList[i];
1976 IRBuilder<> IRB(OrigInst->getNextNode());
1977 Value *VAListTag = OrigInst->getArgOperand(0);
1979 Value *RegSaveAreaPtrPtr =
1981 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1982 ConstantInt::get(MS.IntptrTy, 16)),
1983 Type::getInt64PtrTy(*MS.C));
1984 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1985 Value *RegSaveAreaShadowPtr =
1986 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1987 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1988 AMD64FpEndOffset, 16);
1990 Value *OverflowArgAreaPtrPtr =
1992 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1993 ConstantInt::get(MS.IntptrTy, 8)),
1994 Type::getInt64PtrTy(*MS.C));
1995 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1996 Value *OverflowArgAreaShadowPtr =
1997 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1998 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
1999 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2004 /// \brief A no-op implementation of VarArgHelper.
2005 struct VarArgNoOpHelper : public VarArgHelper {
2006 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2007 MemorySanitizerVisitor &MSV) {}
2009 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {}
2011 void visitVAStartInst(VAStartInst &I) {}
2013 void visitVACopyInst(VACopyInst &I) {}
2015 void finalizeInstrumentation() {}
2018 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2019 MemorySanitizerVisitor &Visitor) {
2020 // VarArg handling is only implemented on AMD64. False positives are possible
2021 // on other platforms.
2022 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2023 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2024 return new VarArgAMD64Helper(Func, Msan, Visitor);
2026 return new VarArgNoOpHelper(Func, Msan, Visitor);
2031 bool MemorySanitizer::runOnFunction(Function &F) {
2032 MemorySanitizerVisitor Visitor(F, *this);
2034 // Clear out readonly/readnone attributes.
2036 B.addAttribute(Attribute::ReadOnly)
2037 .addAttribute(Attribute::ReadNone);
2038 F.removeAttributes(AttributeSet::FunctionIndex,
2039 AttributeSet::get(F.getContext(),
2040 AttributeSet::FunctionIndex, B));
2042 return Visitor.runOnFunction();