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).
46 //===----------------------------------------------------------------------===//
48 #define DEBUG_TYPE "msan"
50 #include "llvm/Transforms/Instrumentation.h"
51 #include "BlackList.h"
52 #include "llvm/ADT/DepthFirstIterator.h"
53 #include "llvm/ADT/SmallString.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/ValueMap.h"
56 #include "llvm/DataLayout.h"
57 #include "llvm/Function.h"
58 #include "llvm/IRBuilder.h"
59 #include "llvm/InlineAsm.h"
60 #include "llvm/InstVisitor.h"
61 #include "llvm/IntrinsicInst.h"
62 #include "llvm/LLVMContext.h"
63 #include "llvm/MDBuilder.h"
64 #include "llvm/Module.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Compiler.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
70 #include "llvm/Transforms/Utils/Local.h"
71 #include "llvm/Transforms/Utils/ModuleUtils.h"
72 #include "llvm/Type.h"
76 static const uint64_t kShadowMask32 = 1ULL << 31;
77 static const uint64_t kShadowMask64 = 1ULL << 46;
78 static const uint64_t kOriginOffset32 = 1ULL << 30;
79 static const uint64_t kOriginOffset64 = 1ULL << 45;
80 static const uint64_t kShadowTLSAlignment = 8;
82 // This is an important flag that makes the reports much more
83 // informative at the cost of greater slowdown. Not fully implemented
85 // FIXME: this should be a top-level clang flag, e.g.
86 // -fmemory-sanitizer-full.
87 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
88 cl::desc("Track origins (allocation sites) of poisoned memory"),
89 cl::Hidden, cl::init(false));
90 static cl::opt<bool> ClKeepGoing("msan-keep-going",
91 cl::desc("keep going after reporting a UMR"),
92 cl::Hidden, cl::init(false));
93 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
94 cl::desc("poison uninitialized stack variables"),
95 cl::Hidden, cl::init(true));
96 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
97 cl::desc("poison uninitialized stack variables with a call"),
98 cl::Hidden, cl::init(false));
99 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
100 cl::desc("poison uninitialized stack variables with the given patter"),
101 cl::Hidden, cl::init(0xff));
103 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
104 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
105 cl::Hidden, cl::init(true));
107 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
108 cl::desc("store origin for clean (fully initialized) values"),
109 cl::Hidden, cl::init(false));
111 // This flag controls whether we check the shadow of the address
112 // operand of load or store. Such bugs are very rare, since load from
113 // a garbage address typically results in SEGV, but still happen
114 // (e.g. only lower bits of address are garbage, or the access happens
115 // early at program startup where malloc-ed memory is more likely to
116 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
117 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
118 cl::desc("report accesses through a pointer which has poisoned shadow"),
119 cl::Hidden, cl::init(true));
121 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
122 cl::desc("print out instructions with default strict semantics"),
123 cl::Hidden, cl::init(false));
125 static cl::opt<std::string> ClBlackListFile("msan-blacklist",
126 cl::desc("File containing the list of functions where MemorySanitizer "
127 "should not report bugs"), cl::Hidden);
131 /// \brief An instrumentation pass implementing detection of uninitialized
134 /// MemorySanitizer: instrument the code in module to find
135 /// uninitialized reads.
136 class MemorySanitizer : public FunctionPass {
138 MemorySanitizer(bool TrackOrigins = false)
140 TrackOrigins(TrackOrigins || ClTrackOrigins),
143 const char *getPassName() const { return "MemorySanitizer"; }
144 bool runOnFunction(Function &F);
145 bool doInitialization(Module &M);
146 static char ID; // Pass identification, replacement for typeid.
149 void initializeCallbacks(Module &M);
151 /// \brief Track origins (allocation points) of uninitialized values.
158 /// \brief Thread-local shadow storage for function parameters.
159 GlobalVariable *ParamTLS;
160 /// \brief Thread-local origin storage for function parameters.
161 GlobalVariable *ParamOriginTLS;
162 /// \brief Thread-local shadow storage for function return value.
163 GlobalVariable *RetvalTLS;
164 /// \brief Thread-local origin storage for function return value.
165 GlobalVariable *RetvalOriginTLS;
166 /// \brief Thread-local shadow storage for in-register va_arg function
167 /// parameters (x86_64-specific).
168 GlobalVariable *VAArgTLS;
169 /// \brief Thread-local shadow storage for va_arg overflow area
170 /// (x86_64-specific).
171 GlobalVariable *VAArgOverflowSizeTLS;
172 /// \brief Thread-local space used to pass origin value to the UMR reporting
174 GlobalVariable *OriginTLS;
176 /// \brief The run-time callback to print a warning.
178 /// \brief Run-time helper that copies origin info for a memory range.
179 Value *MsanCopyOriginFn;
180 /// \brief Run-time helper that generates a new origin value for a stack
182 Value *MsanSetAllocaOriginFn;
183 /// \brief Run-time helper that poisons stack on function entry.
184 Value *MsanPoisonStackFn;
185 /// \brief MSan runtime replacements for memmove, memcpy and memset.
186 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
188 /// \brief Address mask used in application-to-shadow address calculation.
189 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
191 /// \brief Offset of the origin shadow from the "normal" shadow.
192 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
193 uint64_t OriginOffset;
194 /// \brief Branch weights for error reporting.
195 MDNode *ColdCallWeights;
196 /// \brief Branch weights for origin store.
197 MDNode *OriginStoreWeights;
198 /// \brief The blacklist.
199 OwningPtr<BlackList> BL;
200 /// \brief An empty volatile inline asm that prevents callback merge.
203 friend struct MemorySanitizerVisitor;
204 friend struct VarArgAMD64Helper;
208 char MemorySanitizer::ID = 0;
209 INITIALIZE_PASS(MemorySanitizer, "msan",
210 "MemorySanitizer: detects uninitialized reads.",
213 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins) {
214 return new MemorySanitizer(TrackOrigins);
217 /// \brief Create a non-const global initialized with the given string.
219 /// Creates a writable global for Str so that we can pass it to the
220 /// run-time lib. Runtime uses first 4 bytes of the string to store the
221 /// frame ID, so the string needs to be mutable.
222 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
224 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
225 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
226 GlobalValue::PrivateLinkage, StrConst, "");
230 /// \brief Insert extern declaration of runtime-provided functions and globals.
231 void MemorySanitizer::initializeCallbacks(Module &M) {
232 // Only do this once.
237 // Create the callback.
238 // FIXME: this function should have "Cold" calling conv,
239 // which is not yet implemented.
240 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
241 : "__msan_warning_noreturn";
242 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
244 MsanCopyOriginFn = M.getOrInsertFunction(
245 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
246 IRB.getInt8PtrTy(), IntptrTy, NULL);
247 MsanSetAllocaOriginFn = M.getOrInsertFunction(
248 "__msan_set_alloca_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
249 IRB.getInt8PtrTy(), NULL);
250 MsanPoisonStackFn = M.getOrInsertFunction(
251 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
252 MemmoveFn = M.getOrInsertFunction(
253 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
254 IRB.getInt8PtrTy(), IntptrTy, NULL);
255 MemcpyFn = M.getOrInsertFunction(
256 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
258 MemsetFn = M.getOrInsertFunction(
259 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
263 RetvalTLS = new GlobalVariable(
264 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
265 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
266 GlobalVariable::GeneralDynamicTLSModel);
267 RetvalOriginTLS = new GlobalVariable(
268 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
269 "__msan_retval_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
271 ParamTLS = new GlobalVariable(
272 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
273 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
274 GlobalVariable::GeneralDynamicTLSModel);
275 ParamOriginTLS = new GlobalVariable(
276 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
277 0, "__msan_param_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
279 VAArgTLS = new GlobalVariable(
280 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
281 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
282 GlobalVariable::GeneralDynamicTLSModel);
283 VAArgOverflowSizeTLS = new GlobalVariable(
284 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
285 "__msan_va_arg_overflow_size_tls", 0,
286 GlobalVariable::GeneralDynamicTLSModel);
287 OriginTLS = new GlobalVariable(
288 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
289 "__msan_origin_tls", 0, GlobalVariable::GeneralDynamicTLSModel);
291 // We insert an empty inline asm after __msan_report* to avoid callback merge.
292 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
293 StringRef(""), StringRef(""),
294 /*hasSideEffects=*/true);
297 /// \brief Module-level initialization.
299 /// inserts a call to __msan_init to the module's constructor list.
300 bool MemorySanitizer::doInitialization(Module &M) {
301 TD = getAnalysisIfAvailable<DataLayout>();
304 BL.reset(new BlackList(ClBlackListFile));
305 C = &(M.getContext());
306 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
309 ShadowMask = kShadowMask64;
310 OriginOffset = kOriginOffset64;
313 ShadowMask = kShadowMask32;
314 OriginOffset = kOriginOffset32;
317 report_fatal_error("unsupported pointer size");
322 IntptrTy = IRB.getIntPtrTy(TD);
323 OriginTy = IRB.getInt32Ty();
325 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
326 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
328 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
329 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
330 "__msan_init", IRB.getVoidTy(), NULL)), 0);
332 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
333 IRB.getInt32(TrackOrigins), "__msan_track_origins");
340 /// \brief A helper class that handles instrumentation of VarArg
341 /// functions on a particular platform.
343 /// Implementations are expected to insert the instrumentation
344 /// necessary to propagate argument shadow through VarArg function
345 /// calls. Visit* methods are called during an InstVisitor pass over
346 /// the function, and should avoid creating new basic blocks. A new
347 /// instance of this class is created for each instrumented function.
348 struct VarArgHelper {
349 /// \brief Visit a CallSite.
350 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
352 /// \brief Visit a va_start call.
353 virtual void visitVAStartInst(VAStartInst &I) = 0;
355 /// \brief Visit a va_copy call.
356 virtual void visitVACopyInst(VACopyInst &I) = 0;
358 /// \brief Finalize function instrumentation.
360 /// This method is called after visiting all interesting (see above)
361 /// instructions in a function.
362 virtual void finalizeInstrumentation() = 0;
364 virtual ~VarArgHelper() {}
367 struct MemorySanitizerVisitor;
370 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
371 MemorySanitizerVisitor &Visitor);
373 /// This class does all the work for a given function. Store and Load
374 /// instructions store and load corresponding shadow and origin
375 /// values. Most instructions propagate shadow from arguments to their
376 /// return values. Certain instructions (most importantly, BranchInst)
377 /// test their argument shadow and print reports (with a runtime call) if it's
379 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
382 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
383 ValueMap<Value*, Value*> ShadowMap, OriginMap;
385 OwningPtr<VarArgHelper> VAHelper;
387 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
388 // See a comment in visitCallSite for more details.
389 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
390 static const unsigned AMD64FpEndOffset = 176;
392 struct ShadowOriginAndInsertPoint {
395 Instruction *OrigIns;
396 ShadowOriginAndInsertPoint(Instruction *S, Instruction *O, Instruction *I)
397 : Shadow(S), Origin(O), OrigIns(I) { }
398 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
400 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
401 SmallVector<Instruction*, 16> StoreList;
403 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
404 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
405 InsertChecks = !MS.BL->isIn(F);
406 DEBUG(if (!InsertChecks)
407 dbgs() << "MemorySanitizer is not inserting checks into '"
408 << F.getName() << "'\n");
411 void materializeStores() {
412 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
413 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
416 Value *Val = I.getValueOperand();
417 Value *Addr = I.getPointerOperand();
418 Value *Shadow = getShadow(Val);
419 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
422 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
423 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
425 // If the store is volatile, add a check.
427 insertCheck(Val, &I);
428 if (ClCheckAccessAddress)
429 insertCheck(Addr, &I);
431 if (MS.TrackOrigins) {
432 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
433 IRB.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRB));
435 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
437 Constant *Cst = dyn_cast_or_null<Constant>(ConvertedShadow);
438 // TODO(eugenis): handle non-zero constant shadow by inserting an
439 // unconditional check (can not simply fail compilation as this could
440 // be in the dead code).
444 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
445 getCleanShadow(ConvertedShadow), "_mscmp");
446 Instruction *CheckTerm =
447 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
448 MS.OriginStoreWeights);
449 IRBuilder<> IRBNew(CheckTerm);
450 IRBNew.CreateStore(getOrigin(Val), getOriginPtr(Addr, IRBNew));
456 void materializeChecks() {
457 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
458 Instruction *Shadow = InstrumentationList[i].Shadow;
459 Instruction *OrigIns = InstrumentationList[i].OrigIns;
460 IRBuilder<> IRB(OrigIns);
461 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
462 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
463 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
464 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
465 getCleanShadow(ConvertedShadow), "_mscmp");
466 Instruction *CheckTerm =
467 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
468 /* Unreachable */ !ClKeepGoing,
471 IRB.SetInsertPoint(CheckTerm);
472 if (MS.TrackOrigins) {
473 Instruction *Origin = InstrumentationList[i].Origin;
474 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
477 CallInst *Call = IRB.CreateCall(MS.WarningFn);
478 Call->setDebugLoc(OrigIns->getDebugLoc());
479 IRB.CreateCall(MS.EmptyAsm);
480 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
482 DEBUG(dbgs() << "DONE:\n" << F);
485 /// \brief Add MemorySanitizer instrumentation to a function.
486 bool runOnFunction() {
487 MS.initializeCallbacks(*F.getParent());
488 if (!MS.TD) return false;
490 // In the presence of unreachable blocks, we may see Phi nodes with
491 // incoming nodes from such blocks. Since InstVisitor skips unreachable
492 // blocks, such nodes will not have any shadow value associated with them.
493 // It's easier to remove unreachable blocks than deal with missing shadow.
494 removeUnreachableBlocks(F);
496 // Iterate all BBs in depth-first order and create shadow instructions
497 // for all instructions (where applicable).
498 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
499 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
500 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
501 BasicBlock *BB = *DI;
505 // Finalize PHI nodes.
506 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
507 PHINode *PN = ShadowPHINodes[i];
508 PHINode *PNS = cast<PHINode>(getShadow(PN));
509 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
510 size_t NumValues = PN->getNumIncomingValues();
511 for (size_t v = 0; v < NumValues; v++) {
512 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
514 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
518 VAHelper->finalizeInstrumentation();
520 // Delayed instrumentation of StoreInst.
521 // This may add new checks to be inserted later.
524 // Insert shadow value checks.
530 /// \brief Compute the shadow type that corresponds to a given Value.
531 Type *getShadowTy(Value *V) {
532 return getShadowTy(V->getType());
535 /// \brief Compute the shadow type that corresponds to a given Type.
536 Type *getShadowTy(Type *OrigTy) {
537 if (!OrigTy->isSized()) {
540 // For integer type, shadow is the same as the original type.
541 // This may return weird-sized types like i1.
542 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
544 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
545 uint32_t EltSize = MS.TD->getTypeStoreSizeInBits(VT->getElementType());
546 return VectorType::get(IntegerType::get(*MS.C, EltSize),
547 VT->getNumElements());
549 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
550 SmallVector<Type*, 4> Elements;
551 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
552 Elements.push_back(getShadowTy(ST->getElementType(i)));
553 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
554 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
557 uint32_t TypeSize = MS.TD->getTypeStoreSizeInBits(OrigTy);
558 return IntegerType::get(*MS.C, TypeSize);
561 /// \brief Flatten a vector type.
562 Type *getShadowTyNoVec(Type *ty) {
563 if (VectorType *vt = dyn_cast<VectorType>(ty))
564 return IntegerType::get(*MS.C, vt->getBitWidth());
568 /// \brief Convert a shadow value to it's flattened variant.
569 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
570 Type *Ty = V->getType();
571 Type *NoVecTy = getShadowTyNoVec(Ty);
572 if (Ty == NoVecTy) return V;
573 return IRB.CreateBitCast(V, NoVecTy);
576 /// \brief Compute the shadow address that corresponds to a given application
579 /// Shadow = Addr & ~ShadowMask.
580 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
583 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
584 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
585 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
588 /// \brief Compute the origin address that corresponds to a given application
591 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
592 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
594 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
595 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
597 IRB.CreateAdd(ShadowLong,
598 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
600 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
601 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
604 /// \brief Compute the shadow address for a given function argument.
606 /// Shadow = ParamTLS+ArgOffset.
607 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
609 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
610 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
611 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
615 /// \brief Compute the origin address for a given function argument.
616 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
618 if (!MS.TrackOrigins) return 0;
619 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
620 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
621 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
625 /// \brief Compute the shadow address for a retval.
626 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
627 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
628 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
632 /// \brief Compute the origin address for a retval.
633 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
634 // We keep a single origin for the entire retval. Might be too optimistic.
635 return MS.RetvalOriginTLS;
638 /// \brief Set SV to be the shadow value for V.
639 void setShadow(Value *V, Value *SV) {
640 assert(!ShadowMap.count(V) && "Values may only have one shadow");
644 /// \brief Set Origin to be the origin value for V.
645 void setOrigin(Value *V, Value *Origin) {
646 if (!MS.TrackOrigins) return;
647 assert(!OriginMap.count(V) && "Values may only have one origin");
648 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
649 OriginMap[V] = Origin;
652 /// \brief Create a clean shadow value for a given value.
654 /// Clean shadow (all zeroes) means all bits of the value are defined
656 Value *getCleanShadow(Value *V) {
657 Type *ShadowTy = getShadowTy(V);
660 return Constant::getNullValue(ShadowTy);
663 /// \brief Create a dirty shadow of a given shadow type.
664 Constant *getPoisonedShadow(Type *ShadowTy) {
666 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
667 return Constant::getAllOnesValue(ShadowTy);
668 StructType *ST = cast<StructType>(ShadowTy);
669 SmallVector<Constant *, 4> Vals;
670 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
671 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
672 return ConstantStruct::get(ST, Vals);
675 /// \brief Create a clean (zero) origin.
676 Value *getCleanOrigin() {
677 return Constant::getNullValue(MS.OriginTy);
680 /// \brief Get the shadow value for a given Value.
682 /// This function either returns the value set earlier with setShadow,
683 /// or extracts if from ParamTLS (for function arguments).
684 Value *getShadow(Value *V) {
685 if (Instruction *I = dyn_cast<Instruction>(V)) {
686 // For instructions the shadow is already stored in the map.
687 Value *Shadow = ShadowMap[V];
689 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
691 assert(Shadow && "No shadow for a value");
695 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
696 Value *AllOnes = getPoisonedShadow(getShadowTy(V));
697 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
701 if (Argument *A = dyn_cast<Argument>(V)) {
702 // For arguments we compute the shadow on demand and store it in the map.
703 Value **ShadowPtr = &ShadowMap[V];
706 Function *F = A->getParent();
707 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
708 unsigned ArgOffset = 0;
709 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
711 if (!AI->getType()->isSized()) {
712 DEBUG(dbgs() << "Arg is not sized\n");
715 unsigned Size = AI->hasByValAttr()
716 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
717 : MS.TD->getTypeAllocSize(AI->getType());
719 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
720 if (AI->hasByValAttr()) {
721 // ByVal pointer itself has clean shadow. We copy the actual
722 // argument shadow to the underlying memory.
723 Value *Cpy = EntryIRB.CreateMemCpy(
724 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
725 Base, Size, AI->getParamAlignment());
726 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
728 *ShadowPtr = getCleanShadow(V);
730 *ShadowPtr = EntryIRB.CreateLoad(Base);
732 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
733 **ShadowPtr << "\n");
734 if (MS.TrackOrigins) {
735 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
736 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
739 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
741 assert(*ShadowPtr && "Could not find shadow for an argument");
744 // For everything else the shadow is zero.
745 return getCleanShadow(V);
748 /// \brief Get the shadow for i-th argument of the instruction I.
749 Value *getShadow(Instruction *I, int i) {
750 return getShadow(I->getOperand(i));
753 /// \brief Get the origin for a value.
754 Value *getOrigin(Value *V) {
755 if (!MS.TrackOrigins) return 0;
756 if (isa<Instruction>(V) || isa<Argument>(V)) {
757 Value *Origin = OriginMap[V];
759 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
760 Origin = getCleanOrigin();
764 return getCleanOrigin();
767 /// \brief Get the origin for i-th argument of the instruction I.
768 Value *getOrigin(Instruction *I, int i) {
769 return getOrigin(I->getOperand(i));
772 /// \brief Remember the place where a shadow check should be inserted.
774 /// This location will be later instrumented with a check that will print a
775 /// UMR warning in runtime if the value is not fully defined.
776 void insertCheck(Value *Val, Instruction *OrigIns) {
778 if (!InsertChecks) return;
779 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
782 Type *ShadowTy = Shadow->getType();
783 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
784 "Can only insert checks for integer and vector shadow types");
786 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
787 InstrumentationList.push_back(
788 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
791 // ------------------- Visitors.
793 /// \brief Instrument LoadInst
795 /// Loads the corresponding shadow and (optionally) origin.
796 /// Optionally, checks that the load address is fully defined.
797 void visitLoadInst(LoadInst &I) {
798 assert(I.getType()->isSized() && "Load type must have size");
800 Type *ShadowTy = getShadowTy(&I);
801 Value *Addr = I.getPointerOperand();
802 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
803 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
805 if (ClCheckAccessAddress)
806 insertCheck(I.getPointerOperand(), &I);
809 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
812 /// \brief Instrument StoreInst
814 /// Stores the corresponding shadow and (optionally) origin.
815 /// Optionally, checks that the store address is fully defined.
816 /// Volatile stores check that the value being stored is fully defined.
817 void visitStoreInst(StoreInst &I) {
818 StoreList.push_back(&I);
821 // Vector manipulation.
822 void visitExtractElementInst(ExtractElementInst &I) {
823 insertCheck(I.getOperand(1), &I);
825 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
827 setOrigin(&I, getOrigin(&I, 0));
830 void visitInsertElementInst(InsertElementInst &I) {
831 insertCheck(I.getOperand(2), &I);
833 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
834 I.getOperand(2), "_msprop"));
835 setOriginForNaryOp(I);
838 void visitShuffleVectorInst(ShuffleVectorInst &I) {
839 insertCheck(I.getOperand(2), &I);
841 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
842 I.getOperand(2), "_msprop"));
843 setOriginForNaryOp(I);
847 void visitSExtInst(SExtInst &I) {
849 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
850 setOrigin(&I, getOrigin(&I, 0));
853 void visitZExtInst(ZExtInst &I) {
855 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
856 setOrigin(&I, getOrigin(&I, 0));
859 void visitTruncInst(TruncInst &I) {
861 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
862 setOrigin(&I, getOrigin(&I, 0));
865 void visitBitCastInst(BitCastInst &I) {
867 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
868 setOrigin(&I, getOrigin(&I, 0));
871 void visitPtrToIntInst(PtrToIntInst &I) {
873 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
874 "_msprop_ptrtoint"));
875 setOrigin(&I, getOrigin(&I, 0));
878 void visitIntToPtrInst(IntToPtrInst &I) {
880 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
881 "_msprop_inttoptr"));
882 setOrigin(&I, getOrigin(&I, 0));
885 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
886 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
887 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
888 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
889 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
890 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
892 /// \brief Propagate shadow for bitwise AND.
894 /// This code is exact, i.e. if, for example, a bit in the left argument
895 /// is defined and 0, then neither the value not definedness of the
896 /// corresponding bit in B don't affect the resulting shadow.
897 void visitAnd(BinaryOperator &I) {
899 // "And" of 0 and a poisoned value results in unpoisoned value.
900 // 1&1 => 1; 0&1 => 0; p&1 => p;
901 // 1&0 => 0; 0&0 => 0; p&0 => 0;
902 // 1&p => p; 0&p => 0; p&p => p;
903 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
904 Value *S1 = getShadow(&I, 0);
905 Value *S2 = getShadow(&I, 1);
906 Value *V1 = I.getOperand(0);
907 Value *V2 = I.getOperand(1);
908 if (V1->getType() != S1->getType()) {
909 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
910 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
912 Value *S1S2 = IRB.CreateAnd(S1, S2);
913 Value *V1S2 = IRB.CreateAnd(V1, S2);
914 Value *S1V2 = IRB.CreateAnd(S1, V2);
915 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
916 setOriginForNaryOp(I);
919 void visitOr(BinaryOperator &I) {
921 // "Or" of 1 and a poisoned value results in unpoisoned value.
922 // 1|1 => 1; 0|1 => 1; p|1 => 1;
923 // 1|0 => 1; 0|0 => 0; p|0 => p;
924 // 1|p => 1; 0|p => p; p|p => p;
925 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
926 Value *S1 = getShadow(&I, 0);
927 Value *S2 = getShadow(&I, 1);
928 Value *V1 = IRB.CreateNot(I.getOperand(0));
929 Value *V2 = IRB.CreateNot(I.getOperand(1));
930 if (V1->getType() != S1->getType()) {
931 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
932 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
934 Value *S1S2 = IRB.CreateAnd(S1, S2);
935 Value *V1S2 = IRB.CreateAnd(V1, S2);
936 Value *S1V2 = IRB.CreateAnd(S1, V2);
937 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
938 setOriginForNaryOp(I);
941 /// \brief Default propagation of shadow and/or origin.
943 /// This class implements the general case of shadow propagation, used in all
944 /// cases where we don't know and/or don't care about what the operation
945 /// actually does. It converts all input shadow values to a common type
946 /// (extending or truncating as necessary), and bitwise OR's them.
948 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
949 /// fully initialized), and less prone to false positives.
951 /// This class also implements the general case of origin propagation. For a
952 /// Nary operation, result origin is set to the origin of an argument that is
953 /// not entirely initialized. If there is more than one such arguments, the
954 /// rightmost of them is picked. It does not matter which one is picked if all
955 /// arguments are initialized.
956 template <bool CombineShadow>
961 MemorySanitizerVisitor *MSV;
964 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
965 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
967 /// \brief Add a pair of shadow and origin values to the mix.
968 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
974 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
975 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
979 if (MSV->MS.TrackOrigins) {
984 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
985 Value *Cond = IRB.CreateICmpNE(FlatShadow,
986 MSV->getCleanShadow(FlatShadow));
987 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
993 /// \brief Add an application value to the mix.
994 Combiner &Add(Value *V) {
995 Value *OpShadow = MSV->getShadow(V);
996 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
997 return Add(OpShadow, OpOrigin);
1000 /// \brief Set the current combined values as the given instruction's shadow
1002 void Done(Instruction *I) {
1003 if (CombineShadow) {
1005 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1006 MSV->setShadow(I, Shadow);
1008 if (MSV->MS.TrackOrigins) {
1010 MSV->setOrigin(I, Origin);
1015 typedef Combiner<true> ShadowAndOriginCombiner;
1016 typedef Combiner<false> OriginCombiner;
1018 /// \brief Propagate origin for arbitrary operation.
1019 void setOriginForNaryOp(Instruction &I) {
1020 if (!MS.TrackOrigins) return;
1021 IRBuilder<> IRB(&I);
1022 OriginCombiner OC(this, IRB);
1023 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1028 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1029 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1030 "Vector of pointers is not a valid shadow type");
1031 return Ty->isVectorTy() ?
1032 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1033 Ty->getPrimitiveSizeInBits();
1036 /// \brief Cast between two shadow types, extending or truncating as
1038 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy) {
1039 Type *srcTy = V->getType();
1040 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1041 return IRB.CreateIntCast(V, dstTy, false);
1042 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1043 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1044 return IRB.CreateIntCast(V, dstTy, false);
1045 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1046 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1047 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1049 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), false);
1050 return IRB.CreateBitCast(V2, dstTy);
1051 // TODO: handle struct types.
1054 /// \brief Propagate shadow for arbitrary operation.
1055 void handleShadowOr(Instruction &I) {
1056 IRBuilder<> IRB(&I);
1057 ShadowAndOriginCombiner SC(this, IRB);
1058 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1063 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1064 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1065 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1066 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1067 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1068 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1069 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1071 void handleDiv(Instruction &I) {
1072 IRBuilder<> IRB(&I);
1073 // Strict on the second argument.
1074 insertCheck(I.getOperand(1), &I);
1075 setShadow(&I, getShadow(&I, 0));
1076 setOrigin(&I, getOrigin(&I, 0));
1079 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1080 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1081 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1082 void visitURem(BinaryOperator &I) { handleDiv(I); }
1083 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1084 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1086 /// \brief Instrument == and != comparisons.
1088 /// Sometimes the comparison result is known even if some of the bits of the
1089 /// arguments are not.
1090 void handleEqualityComparison(ICmpInst &I) {
1091 IRBuilder<> IRB(&I);
1092 Value *A = I.getOperand(0);
1093 Value *B = I.getOperand(1);
1094 Value *Sa = getShadow(A);
1095 Value *Sb = getShadow(B);
1096 if (A->getType()->isPointerTy())
1097 A = IRB.CreatePointerCast(A, MS.IntptrTy);
1098 if (B->getType()->isPointerTy())
1099 B = IRB.CreatePointerCast(B, MS.IntptrTy);
1100 // A == B <==> (C = A^B) == 0
1101 // A != B <==> (C = A^B) != 0
1103 Value *C = IRB.CreateXor(A, B);
1104 Value *Sc = IRB.CreateOr(Sa, Sb);
1105 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1106 // Result is defined if one of the following is true
1107 // * there is a defined 1 bit in C
1108 // * C is fully defined
1109 // Si = !(C & ~Sc) && Sc
1110 Value *Zero = Constant::getNullValue(Sc->getType());
1111 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1113 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1115 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1116 Si->setName("_msprop_icmp");
1118 setOriginForNaryOp(I);
1121 /// \brief Instrument signed relational comparisons.
1123 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1124 /// propagating the highest bit of the shadow. Everything else is delegated
1125 /// to handleShadowOr().
1126 void handleSignedRelationalComparison(ICmpInst &I) {
1127 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1128 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1130 CmpInst::Predicate pre = I.getPredicate();
1131 if (constOp0 && constOp0->isNullValue() &&
1132 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1133 op = I.getOperand(1);
1134 } else if (constOp1 && constOp1->isNullValue() &&
1135 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1136 op = I.getOperand(0);
1139 IRBuilder<> IRB(&I);
1141 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1142 setShadow(&I, Shadow);
1143 setOrigin(&I, getOrigin(op));
1149 void visitICmpInst(ICmpInst &I) {
1150 if (ClHandleICmp && I.isEquality())
1151 handleEqualityComparison(I);
1152 else if (ClHandleICmp && I.isSigned() && I.isRelational())
1153 handleSignedRelationalComparison(I);
1158 void visitFCmpInst(FCmpInst &I) {
1162 void handleShift(BinaryOperator &I) {
1163 IRBuilder<> IRB(&I);
1164 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1165 // Otherwise perform the same shift on S1.
1166 Value *S1 = getShadow(&I, 0);
1167 Value *S2 = getShadow(&I, 1);
1168 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1170 Value *V2 = I.getOperand(1);
1171 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1172 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1173 setOriginForNaryOp(I);
1176 void visitShl(BinaryOperator &I) { handleShift(I); }
1177 void visitAShr(BinaryOperator &I) { handleShift(I); }
1178 void visitLShr(BinaryOperator &I) { handleShift(I); }
1180 /// \brief Instrument llvm.memmove
1182 /// At this point we don't know if llvm.memmove will be inlined or not.
1183 /// If we don't instrument it and it gets inlined,
1184 /// our interceptor will not kick in and we will lose the memmove.
1185 /// If we instrument the call here, but it does not get inlined,
1186 /// we will memove the shadow twice: which is bad in case
1187 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1189 /// Similar situation exists for memcpy and memset.
1190 void visitMemMoveInst(MemMoveInst &I) {
1191 IRBuilder<> IRB(&I);
1194 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1195 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1196 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1197 I.eraseFromParent();
1200 // Similar to memmove: avoid copying shadow twice.
1201 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1202 // FIXME: consider doing manual inline for small constant sizes and proper
1204 void visitMemCpyInst(MemCpyInst &I) {
1205 IRBuilder<> IRB(&I);
1208 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1209 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1210 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1211 I.eraseFromParent();
1215 void visitMemSetInst(MemSetInst &I) {
1216 IRBuilder<> IRB(&I);
1219 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1220 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1221 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1222 I.eraseFromParent();
1225 void visitVAStartInst(VAStartInst &I) {
1226 VAHelper->visitVAStartInst(I);
1229 void visitVACopyInst(VACopyInst &I) {
1230 VAHelper->visitVACopyInst(I);
1233 enum IntrinsicKind {
1234 IK_DoesNotAccessMemory,
1239 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1240 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1241 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1242 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1243 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1244 const int UnknownModRefBehavior = IK_WritesMemory;
1245 #define GET_INTRINSIC_MODREF_BEHAVIOR
1246 #define ModRefBehavior IntrinsicKind
1247 #include "llvm/Intrinsics.gen"
1248 #undef ModRefBehavior
1249 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1252 /// \brief Handle vector store-like intrinsics.
1254 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1255 /// has 1 pointer argument and 1 vector argument, returns void.
1256 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1257 IRBuilder<> IRB(&I);
1258 Value* Addr = I.getArgOperand(0);
1259 Value *Shadow = getShadow(&I, 1);
1260 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1262 // We don't know the pointer alignment (could be unaligned SSE store!).
1263 // Have to assume to worst case.
1264 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1266 if (ClCheckAccessAddress)
1267 insertCheck(Addr, &I);
1269 // FIXME: use ClStoreCleanOrigin
1270 // FIXME: factor out common code from materializeStores
1271 if (MS.TrackOrigins)
1272 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1276 /// \brief Handle vector load-like intrinsics.
1278 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1279 /// has 1 pointer argument, returns a vector.
1280 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1281 IRBuilder<> IRB(&I);
1282 Value *Addr = I.getArgOperand(0);
1284 Type *ShadowTy = getShadowTy(&I);
1285 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1286 // We don't know the pointer alignment (could be unaligned SSE load!).
1287 // Have to assume to worst case.
1288 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1290 if (ClCheckAccessAddress)
1291 insertCheck(Addr, &I);
1293 if (MS.TrackOrigins)
1294 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1298 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1300 /// Instrument intrinsics with any number of arguments of the same type,
1301 /// equal to the return type. The type should be simple (no aggregates or
1302 /// pointers; vectors are fine).
1303 /// Caller guarantees that this intrinsic does not access memory.
1304 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1305 Type *RetTy = I.getType();
1306 if (!(RetTy->isIntOrIntVectorTy() ||
1307 RetTy->isFPOrFPVectorTy() ||
1308 RetTy->isX86_MMXTy()))
1311 unsigned NumArgOperands = I.getNumArgOperands();
1313 for (unsigned i = 0; i < NumArgOperands; ++i) {
1314 Type *Ty = I.getArgOperand(i)->getType();
1319 IRBuilder<> IRB(&I);
1320 ShadowAndOriginCombiner SC(this, IRB);
1321 for (unsigned i = 0; i < NumArgOperands; ++i)
1322 SC.Add(I.getArgOperand(i));
1328 /// \brief Heuristically instrument unknown intrinsics.
1330 /// The main purpose of this code is to do something reasonable with all
1331 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1332 /// We recognize several classes of intrinsics by their argument types and
1333 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1334 /// sure that we know what the intrinsic does.
1336 /// We special-case intrinsics where this approach fails. See llvm.bswap
1337 /// handling as an example of that.
1338 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1339 unsigned NumArgOperands = I.getNumArgOperands();
1340 if (NumArgOperands == 0)
1343 Intrinsic::ID iid = I.getIntrinsicID();
1344 IntrinsicKind IK = getIntrinsicKind(iid);
1345 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1346 bool WritesMemory = IK == IK_WritesMemory;
1347 assert(!(OnlyReadsMemory && WritesMemory));
1349 if (NumArgOperands == 2 &&
1350 I.getArgOperand(0)->getType()->isPointerTy() &&
1351 I.getArgOperand(1)->getType()->isVectorTy() &&
1352 I.getType()->isVoidTy() &&
1354 // This looks like a vector store.
1355 return handleVectorStoreIntrinsic(I);
1358 if (NumArgOperands == 1 &&
1359 I.getArgOperand(0)->getType()->isPointerTy() &&
1360 I.getType()->isVectorTy() &&
1362 // This looks like a vector load.
1363 return handleVectorLoadIntrinsic(I);
1366 if (!OnlyReadsMemory && !WritesMemory)
1367 if (maybeHandleSimpleNomemIntrinsic(I))
1370 // FIXME: detect and handle SSE maskstore/maskload
1374 void handleBswap(IntrinsicInst &I) {
1375 IRBuilder<> IRB(&I);
1376 Value *Op = I.getArgOperand(0);
1377 Type *OpType = Op->getType();
1378 Function *BswapFunc = Intrinsic::getDeclaration(
1379 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1380 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1381 setOrigin(&I, getOrigin(Op));
1384 void visitIntrinsicInst(IntrinsicInst &I) {
1385 switch (I.getIntrinsicID()) {
1386 case llvm::Intrinsic::bswap:
1390 if (!handleUnknownIntrinsic(I))
1391 visitInstruction(I);
1396 void visitCallSite(CallSite CS) {
1397 Instruction &I = *CS.getInstruction();
1398 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1400 CallInst *Call = cast<CallInst>(&I);
1402 // For inline asm, do the usual thing: check argument shadow and mark all
1403 // outputs as clean. Note that any side effects of the inline asm that are
1404 // not immediately visible in its constraints are not handled.
1405 if (Call->isInlineAsm()) {
1406 visitInstruction(I);
1410 // Allow only tail calls with the same types, otherwise
1411 // we may have a false positive: shadow for a non-void RetVal
1412 // will get propagated to a void RetVal.
1413 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1414 Call->setTailCall(false);
1416 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1418 // We are going to insert code that relies on the fact that the callee
1419 // will become a non-readonly function after it is instrumented by us. To
1420 // prevent this code from being optimized out, mark that function
1421 // non-readonly in advance.
1422 if (Function *Func = Call->getCalledFunction()) {
1423 // Clear out readonly/readnone attributes.
1425 B.addAttribute(Attribute::ReadOnly)
1426 .addAttribute(Attribute::ReadNone);
1427 Func->removeAttribute(AttributeSet::FunctionIndex,
1428 Attribute::get(Func->getContext(), B));
1431 IRBuilder<> IRB(&I);
1432 unsigned ArgOffset = 0;
1433 DEBUG(dbgs() << " CallSite: " << I << "\n");
1434 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1435 ArgIt != End; ++ArgIt) {
1437 unsigned i = ArgIt - CS.arg_begin();
1438 if (!A->getType()->isSized()) {
1439 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1444 // Compute the Shadow for arg even if it is ByVal, because
1445 // in that case getShadow() will copy the actual arg shadow to
1446 // __msan_param_tls.
1447 Value *ArgShadow = getShadow(A);
1448 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1449 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1450 " Shadow: " << *ArgShadow << "\n");
1451 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1452 assert(A->getType()->isPointerTy() &&
1453 "ByVal argument is not a pointer!");
1454 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1455 unsigned Alignment = CS.getParamAlignment(i + 1);
1456 Store = IRB.CreateMemCpy(ArgShadowBase,
1457 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1460 Size = MS.TD->getTypeAllocSize(A->getType());
1461 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1462 kShadowTLSAlignment);
1464 if (MS.TrackOrigins)
1465 IRB.CreateStore(getOrigin(A),
1466 getOriginPtrForArgument(A, IRB, ArgOffset));
1467 assert(Size != 0 && Store != 0);
1468 DEBUG(dbgs() << " Param:" << *Store << "\n");
1469 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1471 DEBUG(dbgs() << " done with call args\n");
1474 cast<FunctionType>(CS.getCalledValue()->getType()-> getContainedType(0));
1475 if (FT->isVarArg()) {
1476 VAHelper->visitCallSite(CS, IRB);
1479 // Now, get the shadow for the RetVal.
1480 if (!I.getType()->isSized()) return;
1481 IRBuilder<> IRBBefore(&I);
1482 // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1483 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1484 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1485 Instruction *NextInsn = 0;
1487 NextInsn = I.getNextNode();
1489 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1490 if (!NormalDest->getSinglePredecessor()) {
1491 // FIXME: this case is tricky, so we are just conservative here.
1492 // Perhaps we need to split the edge between this BB and NormalDest,
1493 // but a naive attempt to use SplitEdge leads to a crash.
1494 setShadow(&I, getCleanShadow(&I));
1495 setOrigin(&I, getCleanOrigin());
1498 NextInsn = NormalDest->getFirstInsertionPt();
1500 "Could not find insertion point for retval shadow load");
1502 IRBuilder<> IRBAfter(NextInsn);
1503 Value *RetvalShadow =
1504 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1505 kShadowTLSAlignment, "_msret");
1506 setShadow(&I, RetvalShadow);
1507 if (MS.TrackOrigins)
1508 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1511 void visitReturnInst(ReturnInst &I) {
1512 IRBuilder<> IRB(&I);
1513 if (Value *RetVal = I.getReturnValue()) {
1514 // Set the shadow for the RetVal.
1515 Value *Shadow = getShadow(RetVal);
1516 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1517 DEBUG(dbgs() << "Return: " << *Shadow << "\n" << *ShadowPtr << "\n");
1518 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1519 if (MS.TrackOrigins)
1520 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1524 void visitPHINode(PHINode &I) {
1525 IRBuilder<> IRB(&I);
1526 ShadowPHINodes.push_back(&I);
1527 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1529 if (MS.TrackOrigins)
1530 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1534 void visitAllocaInst(AllocaInst &I) {
1535 setShadow(&I, getCleanShadow(&I));
1536 if (!ClPoisonStack) return;
1537 IRBuilder<> IRB(I.getNextNode());
1538 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1539 if (ClPoisonStackWithCall) {
1540 IRB.CreateCall2(MS.MsanPoisonStackFn,
1541 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1542 ConstantInt::get(MS.IntptrTy, Size));
1544 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1545 IRB.CreateMemSet(ShadowBase, IRB.getInt8(ClPoisonStackPattern),
1546 Size, I.getAlignment());
1549 if (MS.TrackOrigins) {
1550 setOrigin(&I, getCleanOrigin());
1551 SmallString<2048> StackDescriptionStorage;
1552 raw_svector_ostream StackDescription(StackDescriptionStorage);
1553 // We create a string with a description of the stack allocation and
1554 // pass it into __msan_set_alloca_origin.
1555 // It will be printed by the run-time if stack-originated UMR is found.
1556 // The first 4 bytes of the string are set to '----' and will be replaced
1557 // by __msan_va_arg_overflow_size_tls at the first call.
1558 StackDescription << "----" << I.getName() << "@" << F.getName();
1560 createPrivateNonConstGlobalForString(*F.getParent(),
1561 StackDescription.str());
1562 IRB.CreateCall3(MS.MsanSetAllocaOriginFn,
1563 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1564 ConstantInt::get(MS.IntptrTy, Size),
1565 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()));
1569 void visitSelectInst(SelectInst& I) {
1570 IRBuilder<> IRB(&I);
1571 setShadow(&I, IRB.CreateSelect(I.getCondition(),
1572 getShadow(I.getTrueValue()), getShadow(I.getFalseValue()),
1574 if (MS.TrackOrigins) {
1575 // Origins are always i32, so any vector conditions must be flattened.
1576 // FIXME: consider tracking vector origins for app vectors?
1577 Value *Cond = I.getCondition();
1578 if (Cond->getType()->isVectorTy()) {
1579 Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
1580 Cond = IRB.CreateICmpNE(ConvertedShadow,
1581 getCleanShadow(ConvertedShadow), "_mso_select");
1583 setOrigin(&I, IRB.CreateSelect(Cond,
1584 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
1588 void visitLandingPadInst(LandingPadInst &I) {
1590 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
1591 setShadow(&I, getCleanShadow(&I));
1592 setOrigin(&I, getCleanOrigin());
1595 void visitGetElementPtrInst(GetElementPtrInst &I) {
1599 void visitExtractValueInst(ExtractValueInst &I) {
1600 IRBuilder<> IRB(&I);
1601 Value *Agg = I.getAggregateOperand();
1602 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
1603 Value *AggShadow = getShadow(Agg);
1604 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1605 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
1606 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
1607 setShadow(&I, ResShadow);
1608 setOrigin(&I, getCleanOrigin());
1611 void visitInsertValueInst(InsertValueInst &I) {
1612 IRBuilder<> IRB(&I);
1613 DEBUG(dbgs() << "InsertValue: " << I << "\n");
1614 Value *AggShadow = getShadow(I.getAggregateOperand());
1615 Value *InsShadow = getShadow(I.getInsertedValueOperand());
1616 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
1617 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
1618 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
1619 DEBUG(dbgs() << " Res: " << *Res << "\n");
1621 setOrigin(&I, getCleanOrigin());
1624 void dumpInst(Instruction &I) {
1625 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1626 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
1628 errs() << "ZZZ " << I.getOpcodeName() << "\n";
1630 errs() << "QQQ " << I << "\n";
1633 void visitResumeInst(ResumeInst &I) {
1634 DEBUG(dbgs() << "Resume: " << I << "\n");
1635 // Nothing to do here.
1638 void visitInstruction(Instruction &I) {
1639 // Everything else: stop propagating and check for poisoned shadow.
1640 if (ClDumpStrictInstructions)
1642 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
1643 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
1644 insertCheck(I.getOperand(i), &I);
1645 setShadow(&I, getCleanShadow(&I));
1646 setOrigin(&I, getCleanOrigin());
1650 /// \brief AMD64-specific implementation of VarArgHelper.
1651 struct VarArgAMD64Helper : public VarArgHelper {
1652 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
1653 // See a comment in visitCallSite for more details.
1654 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
1655 static const unsigned AMD64FpEndOffset = 176;
1658 MemorySanitizer &MS;
1659 MemorySanitizerVisitor &MSV;
1660 Value *VAArgTLSCopy;
1661 Value *VAArgOverflowSize;
1663 SmallVector<CallInst*, 16> VAStartInstrumentationList;
1665 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
1666 MemorySanitizerVisitor &MSV)
1667 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
1669 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
1671 ArgKind classifyArgument(Value* arg) {
1672 // A very rough approximation of X86_64 argument classification rules.
1673 Type *T = arg->getType();
1674 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
1675 return AK_FloatingPoint;
1676 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
1677 return AK_GeneralPurpose;
1678 if (T->isPointerTy())
1679 return AK_GeneralPurpose;
1683 // For VarArg functions, store the argument shadow in an ABI-specific format
1684 // that corresponds to va_list layout.
1685 // We do this because Clang lowers va_arg in the frontend, and this pass
1686 // only sees the low level code that deals with va_list internals.
1687 // A much easier alternative (provided that Clang emits va_arg instructions)
1688 // would have been to associate each live instance of va_list with a copy of
1689 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
1691 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
1692 unsigned GpOffset = 0;
1693 unsigned FpOffset = AMD64GpEndOffset;
1694 unsigned OverflowOffset = AMD64FpEndOffset;
1695 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1696 ArgIt != End; ++ArgIt) {
1698 ArgKind AK = classifyArgument(A);
1699 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
1701 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
1705 case AK_GeneralPurpose:
1706 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
1709 case AK_FloatingPoint:
1710 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
1714 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
1715 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
1716 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
1718 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
1720 Constant *OverflowSize =
1721 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
1722 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
1725 /// \brief Compute the shadow address for a given va_arg.
1726 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
1728 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
1729 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1730 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
1734 void visitVAStartInst(VAStartInst &I) {
1735 IRBuilder<> IRB(&I);
1736 VAStartInstrumentationList.push_back(&I);
1737 Value *VAListTag = I.getArgOperand(0);
1738 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1740 // Unpoison the whole __va_list_tag.
1741 // FIXME: magic ABI constants.
1742 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1743 /* size */24, /* alignment */16, false);
1746 void visitVACopyInst(VACopyInst &I) {
1747 IRBuilder<> IRB(&I);
1748 Value *VAListTag = I.getArgOperand(0);
1749 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
1751 // Unpoison the whole __va_list_tag.
1752 // FIXME: magic ABI constants.
1753 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
1754 /* size */ 24, /* alignment */ 16, false);
1757 void finalizeInstrumentation() {
1758 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
1759 "finalizeInstrumentation called twice");
1760 if (!VAStartInstrumentationList.empty()) {
1761 // If there is a va_start in this function, make a backup copy of
1762 // va_arg_tls somewhere in the function entry block.
1763 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1764 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
1766 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
1768 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
1769 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
1772 // Instrument va_start.
1773 // Copy va_list shadow from the backup copy of the TLS contents.
1774 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
1775 CallInst *OrigInst = VAStartInstrumentationList[i];
1776 IRBuilder<> IRB(OrigInst->getNextNode());
1777 Value *VAListTag = OrigInst->getArgOperand(0);
1779 Value *RegSaveAreaPtrPtr =
1781 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1782 ConstantInt::get(MS.IntptrTy, 16)),
1783 Type::getInt64PtrTy(*MS.C));
1784 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
1785 Value *RegSaveAreaShadowPtr =
1786 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
1787 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
1788 AMD64FpEndOffset, 16);
1790 Value *OverflowArgAreaPtrPtr =
1792 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
1793 ConstantInt::get(MS.IntptrTy, 8)),
1794 Type::getInt64PtrTy(*MS.C));
1795 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
1796 Value *OverflowArgAreaShadowPtr =
1797 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
1799 getShadowPtrForVAArgument(VAArgTLSCopy, IRB, AMD64FpEndOffset);
1800 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
1805 VarArgHelper* CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
1806 MemorySanitizerVisitor &Visitor) {
1807 return new VarArgAMD64Helper(Func, Msan, Visitor);
1812 bool MemorySanitizer::runOnFunction(Function &F) {
1813 MemorySanitizerVisitor Visitor(F, *this);
1815 // Clear out readonly/readnone attributes.
1817 B.addAttribute(Attribute::ReadOnly)
1818 .addAttribute(Attribute::ReadNone);
1819 F.removeAttribute(AttributeSet::FunctionIndex,
1820 Attribute::get(F.getContext(), B));
1822 return Visitor.runOnFunction();