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.
72 /// Ideally, every atomic store of application value should update the
73 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
74 /// of two disjoint locations can not be done without severe slowdown.
76 /// Therefore, we implement an approximation that may err on the safe side.
77 /// In this implementation, every atomically accessed location in the program
78 /// may only change from (partially) uninitialized to fully initialized, but
79 /// not the other way around. We load the shadow _after_ the application load,
80 /// and we store the shadow _before_ the app store. Also, we always store clean
81 /// shadow (if the application store is atomic). This way, if the store-load
82 /// pair constitutes a happens-before arc, shadow store and load are correctly
83 /// ordered such that the load will get either the value that was stored, or
84 /// some later value (which is always clean).
86 /// This does not work very well with Compare-And-Swap (CAS) and
87 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
88 /// must store the new shadow before the app operation, and load the shadow
89 /// after the app operation. Computers don't work this way. Current
90 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
91 /// value. It implements the store part as a simple atomic store by storing a
94 //===----------------------------------------------------------------------===//
96 #define DEBUG_TYPE "msan"
98 #include "llvm/Transforms/Instrumentation.h"
99 #include "llvm/ADT/DepthFirstIterator.h"
100 #include "llvm/ADT/SmallString.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/Triple.h"
103 #include "llvm/ADT/ValueMap.h"
104 #include "llvm/IR/DataLayout.h"
105 #include "llvm/IR/Function.h"
106 #include "llvm/IR/IRBuilder.h"
107 #include "llvm/IR/InlineAsm.h"
108 #include "llvm/IR/IntrinsicInst.h"
109 #include "llvm/IR/LLVMContext.h"
110 #include "llvm/IR/MDBuilder.h"
111 #include "llvm/IR/Module.h"
112 #include "llvm/IR/Type.h"
113 #include "llvm/InstVisitor.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/raw_ostream.h"
118 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
119 #include "llvm/Transforms/Utils/Local.h"
120 #include "llvm/Transforms/Utils/ModuleUtils.h"
121 #include "llvm/Transforms/Utils/SpecialCaseList.h"
123 using namespace llvm;
125 static const uint64_t kShadowMask32 = 1ULL << 31;
126 static const uint64_t kShadowMask64 = 1ULL << 46;
127 static const uint64_t kOriginOffset32 = 1ULL << 30;
128 static const uint64_t kOriginOffset64 = 1ULL << 45;
129 static const unsigned kMinOriginAlignment = 4;
130 static const unsigned kShadowTLSAlignment = 8;
132 /// \brief Track origins of uninitialized values.
134 /// Adds a section to MemorySanitizer report that points to the allocation
135 /// (stack or heap) the uninitialized bits came from originally.
136 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
137 cl::desc("Track origins (allocation sites) of poisoned memory"),
138 cl::Hidden, cl::init(false));
139 static cl::opt<bool> ClKeepGoing("msan-keep-going",
140 cl::desc("keep going after reporting a UMR"),
141 cl::Hidden, cl::init(false));
142 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
143 cl::desc("poison uninitialized stack variables"),
144 cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
146 cl::desc("poison uninitialized stack variables with a call"),
147 cl::Hidden, cl::init(false));
148 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
149 cl::desc("poison uninitialized stack variables with the given patter"),
150 cl::Hidden, cl::init(0xff));
151 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
152 cl::desc("poison undef temps"),
153 cl::Hidden, cl::init(true));
155 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
156 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
157 cl::Hidden, cl::init(true));
159 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
160 cl::desc("exact handling of relational integer ICmp"),
161 cl::Hidden, cl::init(false));
163 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
164 cl::desc("store origin for clean (fully initialized) values"),
165 cl::Hidden, cl::init(false));
167 // This flag controls whether we check the shadow of the address
168 // operand of load or store. Such bugs are very rare, since load from
169 // a garbage address typically results in SEGV, but still happen
170 // (e.g. only lower bits of address are garbage, or the access happens
171 // early at program startup where malloc-ed memory is more likely to
172 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
173 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
174 cl::desc("report accesses through a pointer which has poisoned shadow"),
175 cl::Hidden, cl::init(true));
177 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
178 cl::desc("print out instructions with default strict semantics"),
179 cl::Hidden, cl::init(false));
181 static cl::opt<std::string> ClBlacklistFile("msan-blacklist",
182 cl::desc("File containing the list of functions where MemorySanitizer "
183 "should not report bugs"), cl::Hidden);
185 // Experimental. Wraps all indirect calls in the instrumented code with
186 // a call to the given function. This is needed to assist the dynamic
187 // helper tool (MSanDR) to regain control on transition between instrumented and
188 // non-instrumented code.
189 static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
190 cl::desc("Wrap indirect calls with a given function"),
193 static cl::opt<bool> ClWrapIndirectCallsFast("msan-wrap-indirect-calls-fast",
194 cl::desc("Do not wrap indirect calls with target in the same module"),
195 cl::Hidden, cl::init(true));
199 /// \brief An instrumentation pass implementing detection of uninitialized
202 /// MemorySanitizer: instrument the code in module to find
203 /// uninitialized reads.
204 class MemorySanitizer : public FunctionPass {
206 MemorySanitizer(bool TrackOrigins = false,
207 StringRef BlacklistFile = StringRef())
209 TrackOrigins(TrackOrigins || ClTrackOrigins),
212 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile : BlacklistFile),
213 WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
214 const char *getPassName() const { return "MemorySanitizer"; }
215 bool runOnFunction(Function &F);
216 bool doInitialization(Module &M);
217 static char ID; // Pass identification, replacement for typeid.
220 void initializeCallbacks(Module &M);
222 /// \brief Track origins (allocation points) of uninitialized values.
229 /// \brief Thread-local shadow storage for function parameters.
230 GlobalVariable *ParamTLS;
231 /// \brief Thread-local origin storage for function parameters.
232 GlobalVariable *ParamOriginTLS;
233 /// \brief Thread-local shadow storage for function return value.
234 GlobalVariable *RetvalTLS;
235 /// \brief Thread-local origin storage for function return value.
236 GlobalVariable *RetvalOriginTLS;
237 /// \brief Thread-local shadow storage for in-register va_arg function
238 /// parameters (x86_64-specific).
239 GlobalVariable *VAArgTLS;
240 /// \brief Thread-local shadow storage for va_arg overflow area
241 /// (x86_64-specific).
242 GlobalVariable *VAArgOverflowSizeTLS;
243 /// \brief Thread-local space used to pass origin value to the UMR reporting
245 GlobalVariable *OriginTLS;
247 GlobalVariable *MsandrModuleStart;
248 GlobalVariable *MsandrModuleEnd;
250 /// \brief The run-time callback to print a warning.
252 /// \brief Run-time helper that copies origin info for a memory range.
253 Value *MsanCopyOriginFn;
254 /// \brief Run-time helper that generates a new origin value for a stack
256 Value *MsanSetAllocaOrigin4Fn;
257 /// \brief Run-time helper that poisons stack on function entry.
258 Value *MsanPoisonStackFn;
259 /// \brief MSan runtime replacements for memmove, memcpy and memset.
260 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
262 /// \brief Address mask used in application-to-shadow address calculation.
263 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
265 /// \brief Offset of the origin shadow from the "normal" shadow.
266 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
267 uint64_t OriginOffset;
268 /// \brief Branch weights for error reporting.
269 MDNode *ColdCallWeights;
270 /// \brief Branch weights for origin store.
271 MDNode *OriginStoreWeights;
272 /// \brief Path to blacklist file.
273 SmallString<64> BlacklistFile;
274 /// \brief The blacklist.
275 OwningPtr<SpecialCaseList> BL;
276 /// \brief An empty volatile inline asm that prevents callback merge.
279 bool WrapIndirectCalls;
280 /// \brief Run-time wrapper for indirect calls.
281 Value *IndirectCallWrapperFn;
282 // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
283 Type *AnyFunctionPtrTy;
285 friend struct MemorySanitizerVisitor;
286 friend struct VarArgAMD64Helper;
290 char MemorySanitizer::ID = 0;
291 INITIALIZE_PASS(MemorySanitizer, "msan",
292 "MemorySanitizer: detects uninitialized reads.",
295 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
296 StringRef BlacklistFile) {
297 return new MemorySanitizer(TrackOrigins, BlacklistFile);
300 /// \brief Create a non-const global initialized with the given string.
302 /// Creates a writable global for Str so that we can pass it to the
303 /// run-time lib. Runtime uses first 4 bytes of the string to store the
304 /// frame ID, so the string needs to be mutable.
305 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
307 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
308 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
309 GlobalValue::PrivateLinkage, StrConst, "");
313 /// \brief Insert extern declaration of runtime-provided functions and globals.
314 void MemorySanitizer::initializeCallbacks(Module &M) {
315 // Only do this once.
320 // Create the callback.
321 // FIXME: this function should have "Cold" calling conv,
322 // which is not yet implemented.
323 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
324 : "__msan_warning_noreturn";
325 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
327 MsanCopyOriginFn = M.getOrInsertFunction(
328 "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
329 IRB.getInt8PtrTy(), IntptrTy, NULL);
330 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
331 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
332 IRB.getInt8PtrTy(), IntptrTy, NULL);
333 MsanPoisonStackFn = M.getOrInsertFunction(
334 "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
335 MemmoveFn = M.getOrInsertFunction(
336 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
337 IRB.getInt8PtrTy(), IntptrTy, NULL);
338 MemcpyFn = M.getOrInsertFunction(
339 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
341 MemsetFn = M.getOrInsertFunction(
342 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
346 RetvalTLS = new GlobalVariable(
347 M, ArrayType::get(IRB.getInt64Ty(), 8), false,
348 GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
349 GlobalVariable::InitialExecTLSModel);
350 RetvalOriginTLS = new GlobalVariable(
351 M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
352 "__msan_retval_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
354 ParamTLS = new GlobalVariable(
355 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
356 GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
357 GlobalVariable::InitialExecTLSModel);
358 ParamOriginTLS = new GlobalVariable(
359 M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
360 0, "__msan_param_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
362 VAArgTLS = new GlobalVariable(
363 M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
364 GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
365 GlobalVariable::InitialExecTLSModel);
366 VAArgOverflowSizeTLS = new GlobalVariable(
367 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
368 "__msan_va_arg_overflow_size_tls", 0,
369 GlobalVariable::InitialExecTLSModel);
370 OriginTLS = new GlobalVariable(
371 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
372 "__msan_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
374 // We insert an empty inline asm after __msan_report* to avoid callback merge.
375 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
376 StringRef(""), StringRef(""),
377 /*hasSideEffects=*/true);
379 if (WrapIndirectCalls) {
381 PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
382 IndirectCallWrapperFn = M.getOrInsertFunction(
383 ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, NULL);
386 if (ClWrapIndirectCallsFast) {
387 MsandrModuleStart = new GlobalVariable(
388 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
389 0, "__executable_start");
390 MsandrModuleStart->setVisibility(GlobalVariable::HiddenVisibility);
391 MsandrModuleEnd = new GlobalVariable(
392 M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
394 MsandrModuleEnd->setVisibility(GlobalVariable::HiddenVisibility);
398 /// \brief Module-level initialization.
400 /// inserts a call to __msan_init to the module's constructor list.
401 bool MemorySanitizer::doInitialization(Module &M) {
402 TD = getAnalysisIfAvailable<DataLayout>();
405 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
406 C = &(M.getContext());
407 unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
410 ShadowMask = kShadowMask64;
411 OriginOffset = kOriginOffset64;
414 ShadowMask = kShadowMask32;
415 OriginOffset = kOriginOffset32;
418 report_fatal_error("unsupported pointer size");
423 IntptrTy = IRB.getIntPtrTy(TD);
424 OriginTy = IRB.getInt32Ty();
426 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
427 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
429 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
430 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
431 "__msan_init", IRB.getVoidTy(), NULL)), 0);
434 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
435 IRB.getInt32(TrackOrigins), "__msan_track_origins");
438 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
439 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
446 /// \brief A helper class that handles instrumentation of VarArg
447 /// functions on a particular platform.
449 /// Implementations are expected to insert the instrumentation
450 /// necessary to propagate argument shadow through VarArg function
451 /// calls. Visit* methods are called during an InstVisitor pass over
452 /// the function, and should avoid creating new basic blocks. A new
453 /// instance of this class is created for each instrumented function.
454 struct VarArgHelper {
455 /// \brief Visit a CallSite.
456 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
458 /// \brief Visit a va_start call.
459 virtual void visitVAStartInst(VAStartInst &I) = 0;
461 /// \brief Visit a va_copy call.
462 virtual void visitVACopyInst(VACopyInst &I) = 0;
464 /// \brief Finalize function instrumentation.
466 /// This method is called after visiting all interesting (see above)
467 /// instructions in a function.
468 virtual void finalizeInstrumentation() = 0;
470 virtual ~VarArgHelper() {}
473 struct MemorySanitizerVisitor;
476 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
477 MemorySanitizerVisitor &Visitor);
479 /// This class does all the work for a given function. Store and Load
480 /// instructions store and load corresponding shadow and origin
481 /// values. Most instructions propagate shadow from arguments to their
482 /// return values. Certain instructions (most importantly, BranchInst)
483 /// test their argument shadow and print reports (with a runtime call) if it's
485 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
488 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
489 ValueMap<Value*, Value*> ShadowMap, OriginMap;
490 OwningPtr<VarArgHelper> VAHelper;
492 // The following flags disable parts of MSan instrumentation based on
493 // blacklist contents and command-line options.
498 bool CheckReturnValue;
500 struct ShadowOriginAndInsertPoint {
503 Instruction *OrigIns;
504 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
505 : Shadow(S), Origin(O), OrigIns(I) { }
506 ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
508 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
509 SmallVector<Instruction*, 16> StoreList;
510 SmallVector<CallSite, 16> IndirectCallList;
512 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
513 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
514 bool SanitizeFunction = !MS.BL->isIn(F) && F.getAttributes().hasAttribute(
515 AttributeSet::FunctionIndex,
516 Attribute::SanitizeMemory);
517 InsertChecks = SanitizeFunction;
518 LoadShadow = SanitizeFunction;
519 PoisonStack = SanitizeFunction && ClPoisonStack;
520 PoisonUndef = SanitizeFunction && ClPoisonUndef;
521 // FIXME: Consider using SpecialCaseList to specify a list of functions that
522 // must always return fully initialized values. For now, we hardcode "main".
523 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
525 DEBUG(if (!InsertChecks)
526 dbgs() << "MemorySanitizer is not inserting checks into '"
527 << F.getName() << "'\n");
530 void materializeStores() {
531 for (size_t i = 0, n = StoreList.size(); i < n; i++) {
532 StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
535 Value *Val = I.getValueOperand();
536 Value *Addr = I.getPointerOperand();
537 Value *Shadow = I.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
538 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
541 IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
542 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
545 if (ClCheckAccessAddress)
546 insertShadowCheck(Addr, &I);
549 I.setOrdering(addReleaseOrdering(I.getOrdering()));
551 if (MS.TrackOrigins) {
552 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
553 if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
554 IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
557 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
559 // TODO(eugenis): handle non-zero constant shadow by inserting an
560 // unconditional check (can not simply fail compilation as this could
561 // be in the dead code).
562 if (isa<Constant>(ConvertedShadow))
565 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
566 getCleanShadow(ConvertedShadow), "_mscmp");
567 Instruction *CheckTerm =
568 SplitBlockAndInsertIfThen(Cmp, &I, false, MS.OriginStoreWeights);
569 IRBuilder<> IRBNew(CheckTerm);
570 IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
577 void materializeChecks() {
578 for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
579 Value *Shadow = InstrumentationList[i].Shadow;
580 Instruction *OrigIns = InstrumentationList[i].OrigIns;
581 IRBuilder<> IRB(OrigIns);
582 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
583 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
584 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
585 // See the comment in materializeStores().
586 if (isa<Constant>(ConvertedShadow))
588 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
589 getCleanShadow(ConvertedShadow), "_mscmp");
590 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
592 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
594 IRB.SetInsertPoint(CheckTerm);
595 if (MS.TrackOrigins) {
596 Value *Origin = InstrumentationList[i].Origin;
597 IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
600 CallInst *Call = IRB.CreateCall(MS.WarningFn);
601 Call->setDebugLoc(OrigIns->getDebugLoc());
602 IRB.CreateCall(MS.EmptyAsm);
603 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
605 DEBUG(dbgs() << "DONE:\n" << F);
608 void materializeIndirectCalls() {
609 for (size_t i = 0, n = IndirectCallList.size(); i < n; i++) {
610 CallSite CS = IndirectCallList[i];
611 Instruction *I = CS.getInstruction();
612 BasicBlock *B = I->getParent();
614 Value *Fn0 = CS.getCalledValue();
615 Value *Fn = IRB.CreateBitCast(Fn0, MS.AnyFunctionPtrTy);
617 if (ClWrapIndirectCallsFast) {
618 // Check that call target is inside this module limits.
620 IRB.CreateBitCast(MS.MsandrModuleStart, MS.AnyFunctionPtrTy);
621 Value *End = IRB.CreateBitCast(MS.MsandrModuleEnd, MS.AnyFunctionPtrTy);
623 Value *NotInThisModule = IRB.CreateOr(IRB.CreateICmpULT(Fn, Start),
624 IRB.CreateICmpUGE(Fn, End));
627 IRB.CreatePHI(Fn0->getType(), 2, "msandr.indirect_target");
629 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
630 NotInThisModule, NewFnPhi,
631 /* Unreachable */ false, MS.ColdCallWeights);
633 IRB.SetInsertPoint(CheckTerm);
634 // Slow path: call wrapper function to possibly transform the call
636 Value *NewFn = IRB.CreateBitCast(
637 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
639 NewFnPhi->addIncoming(Fn0, B);
640 NewFnPhi->addIncoming(NewFn, dyn_cast<Instruction>(NewFn)->getParent());
641 CS.setCalledFunction(NewFnPhi);
643 Value *NewFn = IRB.CreateBitCast(
644 IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
645 CS.setCalledFunction(NewFn);
650 /// \brief Add MemorySanitizer instrumentation to a function.
651 bool runOnFunction() {
652 MS.initializeCallbacks(*F.getParent());
653 if (!MS.TD) return false;
655 // In the presence of unreachable blocks, we may see Phi nodes with
656 // incoming nodes from such blocks. Since InstVisitor skips unreachable
657 // blocks, such nodes will not have any shadow value associated with them.
658 // It's easier to remove unreachable blocks than deal with missing shadow.
659 removeUnreachableBlocks(F);
661 // Iterate all BBs in depth-first order and create shadow instructions
662 // for all instructions (where applicable).
663 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
664 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
665 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
666 BasicBlock *BB = *DI;
670 // Finalize PHI nodes.
671 for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
672 PHINode *PN = ShadowPHINodes[i];
673 PHINode *PNS = cast<PHINode>(getShadow(PN));
674 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
675 size_t NumValues = PN->getNumIncomingValues();
676 for (size_t v = 0; v < NumValues; v++) {
677 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
679 PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
683 VAHelper->finalizeInstrumentation();
685 // Delayed instrumentation of StoreInst.
686 // This may add new checks to be inserted later.
689 // Insert shadow value checks.
692 // Wrap indirect calls.
693 materializeIndirectCalls();
698 /// \brief Compute the shadow type that corresponds to a given Value.
699 Type *getShadowTy(Value *V) {
700 return getShadowTy(V->getType());
703 /// \brief Compute the shadow type that corresponds to a given Type.
704 Type *getShadowTy(Type *OrigTy) {
705 if (!OrigTy->isSized()) {
708 // For integer type, shadow is the same as the original type.
709 // This may return weird-sized types like i1.
710 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
712 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
713 uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
714 return VectorType::get(IntegerType::get(*MS.C, EltSize),
715 VT->getNumElements());
717 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
718 SmallVector<Type*, 4> Elements;
719 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
720 Elements.push_back(getShadowTy(ST->getElementType(i)));
721 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
722 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
725 uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
726 return IntegerType::get(*MS.C, TypeSize);
729 /// \brief Flatten a vector type.
730 Type *getShadowTyNoVec(Type *ty) {
731 if (VectorType *vt = dyn_cast<VectorType>(ty))
732 return IntegerType::get(*MS.C, vt->getBitWidth());
736 /// \brief Convert a shadow value to it's flattened variant.
737 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
738 Type *Ty = V->getType();
739 Type *NoVecTy = getShadowTyNoVec(Ty);
740 if (Ty == NoVecTy) return V;
741 return IRB.CreateBitCast(V, NoVecTy);
744 /// \brief Compute the shadow address that corresponds to a given application
747 /// Shadow = Addr & ~ShadowMask.
748 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
751 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
752 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
753 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
756 /// \brief Compute the origin address that corresponds to a given application
759 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
760 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
762 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
763 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
765 IRB.CreateAdd(ShadowLong,
766 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
768 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
769 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
772 /// \brief Compute the shadow address for a given function argument.
774 /// Shadow = ParamTLS+ArgOffset.
775 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
777 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
778 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
779 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
783 /// \brief Compute the origin address for a given function argument.
784 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
786 if (!MS.TrackOrigins) return 0;
787 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
788 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
789 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
793 /// \brief Compute the shadow address for a retval.
794 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
795 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
796 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
800 /// \brief Compute the origin address for a retval.
801 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
802 // We keep a single origin for the entire retval. Might be too optimistic.
803 return MS.RetvalOriginTLS;
806 /// \brief Set SV to be the shadow value for V.
807 void setShadow(Value *V, Value *SV) {
808 assert(!ShadowMap.count(V) && "Values may only have one shadow");
812 /// \brief Set Origin to be the origin value for V.
813 void setOrigin(Value *V, Value *Origin) {
814 if (!MS.TrackOrigins) return;
815 assert(!OriginMap.count(V) && "Values may only have one origin");
816 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
817 OriginMap[V] = Origin;
820 /// \brief Create a clean shadow value for a given value.
822 /// Clean shadow (all zeroes) means all bits of the value are defined
824 Constant *getCleanShadow(Value *V) {
825 Type *ShadowTy = getShadowTy(V);
828 return Constant::getNullValue(ShadowTy);
831 /// \brief Create a dirty shadow of a given shadow type.
832 Constant *getPoisonedShadow(Type *ShadowTy) {
834 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
835 return Constant::getAllOnesValue(ShadowTy);
836 StructType *ST = cast<StructType>(ShadowTy);
837 SmallVector<Constant *, 4> Vals;
838 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
839 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
840 return ConstantStruct::get(ST, Vals);
843 /// \brief Create a dirty shadow for a given value.
844 Constant *getPoisonedShadow(Value *V) {
845 Type *ShadowTy = getShadowTy(V);
848 return getPoisonedShadow(ShadowTy);
851 /// \brief Create a clean (zero) origin.
852 Value *getCleanOrigin() {
853 return Constant::getNullValue(MS.OriginTy);
856 /// \brief Get the shadow value for a given Value.
858 /// This function either returns the value set earlier with setShadow,
859 /// or extracts if from ParamTLS (for function arguments).
860 Value *getShadow(Value *V) {
861 if (Instruction *I = dyn_cast<Instruction>(V)) {
862 // For instructions the shadow is already stored in the map.
863 Value *Shadow = ShadowMap[V];
865 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
867 assert(Shadow && "No shadow for a value");
871 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
872 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
873 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
877 if (Argument *A = dyn_cast<Argument>(V)) {
878 // For arguments we compute the shadow on demand and store it in the map.
879 Value **ShadowPtr = &ShadowMap[V];
882 Function *F = A->getParent();
883 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
884 unsigned ArgOffset = 0;
885 for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
887 if (!AI->getType()->isSized()) {
888 DEBUG(dbgs() << "Arg is not sized\n");
891 unsigned Size = AI->hasByValAttr()
892 ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
893 : MS.TD->getTypeAllocSize(AI->getType());
895 Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
896 if (AI->hasByValAttr()) {
897 // ByVal pointer itself has clean shadow. We copy the actual
898 // argument shadow to the underlying memory.
899 // Figure out maximal valid memcpy alignment.
900 unsigned ArgAlign = AI->getParamAlignment();
902 Type *EltType = A->getType()->getPointerElementType();
903 ArgAlign = MS.TD->getABITypeAlignment(EltType);
905 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
906 Value *Cpy = EntryIRB.CreateMemCpy(
907 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
909 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
911 *ShadowPtr = getCleanShadow(V);
913 *ShadowPtr = EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
915 DEBUG(dbgs() << " ARG: " << *AI << " ==> " <<
916 **ShadowPtr << "\n");
917 if (MS.TrackOrigins) {
918 Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
919 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
922 ArgOffset += DataLayout::RoundUpAlignment(Size, kShadowTLSAlignment);
924 assert(*ShadowPtr && "Could not find shadow for an argument");
927 // For everything else the shadow is zero.
928 return getCleanShadow(V);
931 /// \brief Get the shadow for i-th argument of the instruction I.
932 Value *getShadow(Instruction *I, int i) {
933 return getShadow(I->getOperand(i));
936 /// \brief Get the origin for a value.
937 Value *getOrigin(Value *V) {
938 if (!MS.TrackOrigins) return 0;
939 if (isa<Instruction>(V) || isa<Argument>(V)) {
940 Value *Origin = OriginMap[V];
942 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
943 Origin = getCleanOrigin();
947 return getCleanOrigin();
950 /// \brief Get the origin for i-th argument of the instruction I.
951 Value *getOrigin(Instruction *I, int i) {
952 return getOrigin(I->getOperand(i));
955 /// \brief Remember the place where a shadow check should be inserted.
957 /// This location will be later instrumented with a check that will print a
958 /// UMR warning in runtime if the shadow value is not 0.
959 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
961 if (!InsertChecks) return;
963 Type *ShadowTy = Shadow->getType();
964 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
965 "Can only insert checks for integer and vector shadow types");
967 InstrumentationList.push_back(
968 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
971 /// \brief Remember the place where a shadow check should be inserted.
973 /// This location will be later instrumented with a check that will print a
974 /// UMR warning in runtime if the value is not fully defined.
975 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
977 Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
979 Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
980 insertShadowCheck(Shadow, Origin, OrigIns);
983 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
993 return AcquireRelease;
994 case SequentiallyConsistent:
995 return SequentiallyConsistent;
997 llvm_unreachable("Unknown ordering");
1000 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1009 case AcquireRelease:
1010 return AcquireRelease;
1011 case SequentiallyConsistent:
1012 return SequentiallyConsistent;
1014 llvm_unreachable("Unknown ordering");
1017 // ------------------- Visitors.
1019 /// \brief Instrument LoadInst
1021 /// Loads the corresponding shadow and (optionally) origin.
1022 /// Optionally, checks that the load address is fully defined.
1023 void visitLoadInst(LoadInst &I) {
1024 assert(I.getType()->isSized() && "Load type must have size");
1025 IRBuilder<> IRB(I.getNextNode());
1026 Type *ShadowTy = getShadowTy(&I);
1027 Value *Addr = I.getPointerOperand();
1029 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1031 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1033 setShadow(&I, getCleanShadow(&I));
1036 if (ClCheckAccessAddress)
1037 insertShadowCheck(I.getPointerOperand(), &I);
1040 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1042 if (MS.TrackOrigins) {
1044 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1046 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1048 setOrigin(&I, getCleanOrigin());
1053 /// \brief Instrument StoreInst
1055 /// Stores the corresponding shadow and (optionally) origin.
1056 /// Optionally, checks that the store address is fully defined.
1057 void visitStoreInst(StoreInst &I) {
1058 StoreList.push_back(&I);
1061 void handleCASOrRMW(Instruction &I) {
1062 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1064 IRBuilder<> IRB(&I);
1065 Value *Addr = I.getOperand(0);
1066 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1068 if (ClCheckAccessAddress)
1069 insertShadowCheck(Addr, &I);
1071 // Only test the conditional argument of cmpxchg instruction.
1072 // The other argument can potentially be uninitialized, but we can not
1073 // detect this situation reliably without possible false positives.
1074 if (isa<AtomicCmpXchgInst>(I))
1075 insertShadowCheck(I.getOperand(1), &I);
1077 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1079 setShadow(&I, getCleanShadow(&I));
1082 void visitAtomicRMWInst(AtomicRMWInst &I) {
1084 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1087 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1089 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1092 // Vector manipulation.
1093 void visitExtractElementInst(ExtractElementInst &I) {
1094 insertShadowCheck(I.getOperand(1), &I);
1095 IRBuilder<> IRB(&I);
1096 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1098 setOrigin(&I, getOrigin(&I, 0));
1101 void visitInsertElementInst(InsertElementInst &I) {
1102 insertShadowCheck(I.getOperand(2), &I);
1103 IRBuilder<> IRB(&I);
1104 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1105 I.getOperand(2), "_msprop"));
1106 setOriginForNaryOp(I);
1109 void visitShuffleVectorInst(ShuffleVectorInst &I) {
1110 insertShadowCheck(I.getOperand(2), &I);
1111 IRBuilder<> IRB(&I);
1112 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1113 I.getOperand(2), "_msprop"));
1114 setOriginForNaryOp(I);
1118 void visitSExtInst(SExtInst &I) {
1119 IRBuilder<> IRB(&I);
1120 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1121 setOrigin(&I, getOrigin(&I, 0));
1124 void visitZExtInst(ZExtInst &I) {
1125 IRBuilder<> IRB(&I);
1126 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1127 setOrigin(&I, getOrigin(&I, 0));
1130 void visitTruncInst(TruncInst &I) {
1131 IRBuilder<> IRB(&I);
1132 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1133 setOrigin(&I, getOrigin(&I, 0));
1136 void visitBitCastInst(BitCastInst &I) {
1137 IRBuilder<> IRB(&I);
1138 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1139 setOrigin(&I, getOrigin(&I, 0));
1142 void visitPtrToIntInst(PtrToIntInst &I) {
1143 IRBuilder<> IRB(&I);
1144 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1145 "_msprop_ptrtoint"));
1146 setOrigin(&I, getOrigin(&I, 0));
1149 void visitIntToPtrInst(IntToPtrInst &I) {
1150 IRBuilder<> IRB(&I);
1151 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1152 "_msprop_inttoptr"));
1153 setOrigin(&I, getOrigin(&I, 0));
1156 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1157 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1158 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1159 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1160 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1161 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1163 /// \brief Propagate shadow for bitwise AND.
1165 /// This code is exact, i.e. if, for example, a bit in the left argument
1166 /// is defined and 0, then neither the value not definedness of the
1167 /// corresponding bit in B don't affect the resulting shadow.
1168 void visitAnd(BinaryOperator &I) {
1169 IRBuilder<> IRB(&I);
1170 // "And" of 0 and a poisoned value results in unpoisoned value.
1171 // 1&1 => 1; 0&1 => 0; p&1 => p;
1172 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1173 // 1&p => p; 0&p => 0; p&p => p;
1174 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1175 Value *S1 = getShadow(&I, 0);
1176 Value *S2 = getShadow(&I, 1);
1177 Value *V1 = I.getOperand(0);
1178 Value *V2 = I.getOperand(1);
1179 if (V1->getType() != S1->getType()) {
1180 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1181 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1183 Value *S1S2 = IRB.CreateAnd(S1, S2);
1184 Value *V1S2 = IRB.CreateAnd(V1, S2);
1185 Value *S1V2 = IRB.CreateAnd(S1, V2);
1186 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1187 setOriginForNaryOp(I);
1190 void visitOr(BinaryOperator &I) {
1191 IRBuilder<> IRB(&I);
1192 // "Or" of 1 and a poisoned value results in unpoisoned value.
1193 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1194 // 1|0 => 1; 0|0 => 0; p|0 => p;
1195 // 1|p => 1; 0|p => p; p|p => p;
1196 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1197 Value *S1 = getShadow(&I, 0);
1198 Value *S2 = getShadow(&I, 1);
1199 Value *V1 = IRB.CreateNot(I.getOperand(0));
1200 Value *V2 = IRB.CreateNot(I.getOperand(1));
1201 if (V1->getType() != S1->getType()) {
1202 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1203 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1205 Value *S1S2 = IRB.CreateAnd(S1, S2);
1206 Value *V1S2 = IRB.CreateAnd(V1, S2);
1207 Value *S1V2 = IRB.CreateAnd(S1, V2);
1208 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1209 setOriginForNaryOp(I);
1212 /// \brief Default propagation of shadow and/or origin.
1214 /// This class implements the general case of shadow propagation, used in all
1215 /// cases where we don't know and/or don't care about what the operation
1216 /// actually does. It converts all input shadow values to a common type
1217 /// (extending or truncating as necessary), and bitwise OR's them.
1219 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1220 /// fully initialized), and less prone to false positives.
1222 /// This class also implements the general case of origin propagation. For a
1223 /// Nary operation, result origin is set to the origin of an argument that is
1224 /// not entirely initialized. If there is more than one such arguments, the
1225 /// rightmost of them is picked. It does not matter which one is picked if all
1226 /// arguments are initialized.
1227 template <bool CombineShadow>
1232 MemorySanitizerVisitor *MSV;
1235 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1236 Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1238 /// \brief Add a pair of shadow and origin values to the mix.
1239 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1240 if (CombineShadow) {
1245 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1246 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1250 if (MSV->MS.TrackOrigins) {
1255 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1256 Value *Cond = IRB.CreateICmpNE(FlatShadow,
1257 MSV->getCleanShadow(FlatShadow));
1258 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1264 /// \brief Add an application value to the mix.
1265 Combiner &Add(Value *V) {
1266 Value *OpShadow = MSV->getShadow(V);
1267 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1268 return Add(OpShadow, OpOrigin);
1271 /// \brief Set the current combined values as the given instruction's shadow
1273 void Done(Instruction *I) {
1274 if (CombineShadow) {
1276 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1277 MSV->setShadow(I, Shadow);
1279 if (MSV->MS.TrackOrigins) {
1281 MSV->setOrigin(I, Origin);
1286 typedef Combiner<true> ShadowAndOriginCombiner;
1287 typedef Combiner<false> OriginCombiner;
1289 /// \brief Propagate origin for arbitrary operation.
1290 void setOriginForNaryOp(Instruction &I) {
1291 if (!MS.TrackOrigins) return;
1292 IRBuilder<> IRB(&I);
1293 OriginCombiner OC(this, IRB);
1294 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1299 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1300 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1301 "Vector of pointers is not a valid shadow type");
1302 return Ty->isVectorTy() ?
1303 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1304 Ty->getPrimitiveSizeInBits();
1307 /// \brief Cast between two shadow types, extending or truncating as
1309 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1310 bool Signed = false) {
1311 Type *srcTy = V->getType();
1312 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1313 return IRB.CreateIntCast(V, dstTy, Signed);
1314 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1315 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1316 return IRB.CreateIntCast(V, dstTy, Signed);
1317 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1318 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1319 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1321 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1322 return IRB.CreateBitCast(V2, dstTy);
1323 // TODO: handle struct types.
1326 /// \brief Propagate shadow for arbitrary operation.
1327 void handleShadowOr(Instruction &I) {
1328 IRBuilder<> IRB(&I);
1329 ShadowAndOriginCombiner SC(this, IRB);
1330 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1335 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1336 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1337 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1338 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1339 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1340 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1341 void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1343 void handleDiv(Instruction &I) {
1344 IRBuilder<> IRB(&I);
1345 // Strict on the second argument.
1346 insertShadowCheck(I.getOperand(1), &I);
1347 setShadow(&I, getShadow(&I, 0));
1348 setOrigin(&I, getOrigin(&I, 0));
1351 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1352 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1353 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1354 void visitURem(BinaryOperator &I) { handleDiv(I); }
1355 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1356 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1358 /// \brief Instrument == and != comparisons.
1360 /// Sometimes the comparison result is known even if some of the bits of the
1361 /// arguments are not.
1362 void handleEqualityComparison(ICmpInst &I) {
1363 IRBuilder<> IRB(&I);
1364 Value *A = I.getOperand(0);
1365 Value *B = I.getOperand(1);
1366 Value *Sa = getShadow(A);
1367 Value *Sb = getShadow(B);
1369 // Get rid of pointers and vectors of pointers.
1370 // For ints (and vectors of ints), types of A and Sa match,
1371 // and this is a no-op.
1372 A = IRB.CreatePointerCast(A, Sa->getType());
1373 B = IRB.CreatePointerCast(B, Sb->getType());
1375 // A == B <==> (C = A^B) == 0
1376 // A != B <==> (C = A^B) != 0
1378 Value *C = IRB.CreateXor(A, B);
1379 Value *Sc = IRB.CreateOr(Sa, Sb);
1380 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1381 // Result is defined if one of the following is true
1382 // * there is a defined 1 bit in C
1383 // * C is fully defined
1384 // Si = !(C & ~Sc) && Sc
1385 Value *Zero = Constant::getNullValue(Sc->getType());
1386 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1388 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1390 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1391 Si->setName("_msprop_icmp");
1393 setOriginForNaryOp(I);
1396 /// \brief Build the lowest possible value of V, taking into account V's
1397 /// uninitialized bits.
1398 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1401 // Split shadow into sign bit and other bits.
1402 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1403 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1404 // Maximise the undefined shadow bit, minimize other undefined bits.
1406 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1408 // Minimize undefined bits.
1409 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1413 /// \brief Build the highest possible value of V, taking into account V's
1414 /// uninitialized bits.
1415 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1418 // Split shadow into sign bit and other bits.
1419 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1420 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1421 // Minimise the undefined shadow bit, maximise other undefined bits.
1423 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1425 // Maximize undefined bits.
1426 return IRB.CreateOr(A, Sa);
1430 /// \brief Instrument relational comparisons.
1432 /// This function does exact shadow propagation for all relational
1433 /// comparisons of integers, pointers and vectors of those.
1434 /// FIXME: output seems suboptimal when one of the operands is a constant
1435 void handleRelationalComparisonExact(ICmpInst &I) {
1436 IRBuilder<> IRB(&I);
1437 Value *A = I.getOperand(0);
1438 Value *B = I.getOperand(1);
1439 Value *Sa = getShadow(A);
1440 Value *Sb = getShadow(B);
1442 // Get rid of pointers and vectors of pointers.
1443 // For ints (and vectors of ints), types of A and Sa match,
1444 // and this is a no-op.
1445 A = IRB.CreatePointerCast(A, Sa->getType());
1446 B = IRB.CreatePointerCast(B, Sb->getType());
1448 // Let [a0, a1] be the interval of possible values of A, taking into account
1449 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1450 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1451 bool IsSigned = I.isSigned();
1452 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1453 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1454 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1455 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1456 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1457 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1458 Value *Si = IRB.CreateXor(S1, S2);
1460 setOriginForNaryOp(I);
1463 /// \brief Instrument signed relational comparisons.
1465 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1466 /// propagating the highest bit of the shadow. Everything else is delegated
1467 /// to handleShadowOr().
1468 void handleSignedRelationalComparison(ICmpInst &I) {
1469 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1470 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1472 CmpInst::Predicate pre = I.getPredicate();
1473 if (constOp0 && constOp0->isNullValue() &&
1474 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1475 op = I.getOperand(1);
1476 } else if (constOp1 && constOp1->isNullValue() &&
1477 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1478 op = I.getOperand(0);
1481 IRBuilder<> IRB(&I);
1483 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1484 setShadow(&I, Shadow);
1485 setOrigin(&I, getOrigin(op));
1491 void visitICmpInst(ICmpInst &I) {
1492 if (!ClHandleICmp) {
1496 if (I.isEquality()) {
1497 handleEqualityComparison(I);
1501 assert(I.isRelational());
1502 if (ClHandleICmpExact) {
1503 handleRelationalComparisonExact(I);
1507 handleSignedRelationalComparison(I);
1511 assert(I.isUnsigned());
1512 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1513 handleRelationalComparisonExact(I);
1520 void visitFCmpInst(FCmpInst &I) {
1524 void handleShift(BinaryOperator &I) {
1525 IRBuilder<> IRB(&I);
1526 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1527 // Otherwise perform the same shift on S1.
1528 Value *S1 = getShadow(&I, 0);
1529 Value *S2 = getShadow(&I, 1);
1530 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1532 Value *V2 = I.getOperand(1);
1533 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1534 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1535 setOriginForNaryOp(I);
1538 void visitShl(BinaryOperator &I) { handleShift(I); }
1539 void visitAShr(BinaryOperator &I) { handleShift(I); }
1540 void visitLShr(BinaryOperator &I) { handleShift(I); }
1542 /// \brief Instrument llvm.memmove
1544 /// At this point we don't know if llvm.memmove will be inlined or not.
1545 /// If we don't instrument it and it gets inlined,
1546 /// our interceptor will not kick in and we will lose the memmove.
1547 /// If we instrument the call here, but it does not get inlined,
1548 /// we will memove the shadow twice: which is bad in case
1549 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1551 /// Similar situation exists for memcpy and memset.
1552 void visitMemMoveInst(MemMoveInst &I) {
1553 IRBuilder<> IRB(&I);
1556 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1557 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1558 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1559 I.eraseFromParent();
1562 // Similar to memmove: avoid copying shadow twice.
1563 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1564 // FIXME: consider doing manual inline for small constant sizes and proper
1566 void visitMemCpyInst(MemCpyInst &I) {
1567 IRBuilder<> IRB(&I);
1570 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1571 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1572 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1573 I.eraseFromParent();
1577 void visitMemSetInst(MemSetInst &I) {
1578 IRBuilder<> IRB(&I);
1581 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1582 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1583 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1584 I.eraseFromParent();
1587 void visitVAStartInst(VAStartInst &I) {
1588 VAHelper->visitVAStartInst(I);
1591 void visitVACopyInst(VACopyInst &I) {
1592 VAHelper->visitVACopyInst(I);
1595 enum IntrinsicKind {
1596 IK_DoesNotAccessMemory,
1601 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1602 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1603 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1604 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1605 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1606 const int UnknownModRefBehavior = IK_WritesMemory;
1607 #define GET_INTRINSIC_MODREF_BEHAVIOR
1608 #define ModRefBehavior IntrinsicKind
1609 #include "llvm/IR/Intrinsics.gen"
1610 #undef ModRefBehavior
1611 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1614 /// \brief Handle vector store-like intrinsics.
1616 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1617 /// has 1 pointer argument and 1 vector argument, returns void.
1618 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1619 IRBuilder<> IRB(&I);
1620 Value* Addr = I.getArgOperand(0);
1621 Value *Shadow = getShadow(&I, 1);
1622 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1624 // We don't know the pointer alignment (could be unaligned SSE store!).
1625 // Have to assume to worst case.
1626 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1628 if (ClCheckAccessAddress)
1629 insertShadowCheck(Addr, &I);
1631 // FIXME: use ClStoreCleanOrigin
1632 // FIXME: factor out common code from materializeStores
1633 if (MS.TrackOrigins)
1634 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1638 /// \brief Handle vector load-like intrinsics.
1640 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1641 /// has 1 pointer argument, returns a vector.
1642 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1643 IRBuilder<> IRB(&I);
1644 Value *Addr = I.getArgOperand(0);
1646 Type *ShadowTy = getShadowTy(&I);
1648 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1649 // We don't know the pointer alignment (could be unaligned SSE load!).
1650 // Have to assume to worst case.
1651 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1653 setShadow(&I, getCleanShadow(&I));
1656 if (ClCheckAccessAddress)
1657 insertShadowCheck(Addr, &I);
1659 if (MS.TrackOrigins) {
1661 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1663 setOrigin(&I, getCleanOrigin());
1668 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1670 /// Instrument intrinsics with any number of arguments of the same type,
1671 /// equal to the return type. The type should be simple (no aggregates or
1672 /// pointers; vectors are fine).
1673 /// Caller guarantees that this intrinsic does not access memory.
1674 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1675 Type *RetTy = I.getType();
1676 if (!(RetTy->isIntOrIntVectorTy() ||
1677 RetTy->isFPOrFPVectorTy() ||
1678 RetTy->isX86_MMXTy()))
1681 unsigned NumArgOperands = I.getNumArgOperands();
1683 for (unsigned i = 0; i < NumArgOperands; ++i) {
1684 Type *Ty = I.getArgOperand(i)->getType();
1689 IRBuilder<> IRB(&I);
1690 ShadowAndOriginCombiner SC(this, IRB);
1691 for (unsigned i = 0; i < NumArgOperands; ++i)
1692 SC.Add(I.getArgOperand(i));
1698 /// \brief Heuristically instrument unknown intrinsics.
1700 /// The main purpose of this code is to do something reasonable with all
1701 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1702 /// We recognize several classes of intrinsics by their argument types and
1703 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1704 /// sure that we know what the intrinsic does.
1706 /// We special-case intrinsics where this approach fails. See llvm.bswap
1707 /// handling as an example of that.
1708 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1709 unsigned NumArgOperands = I.getNumArgOperands();
1710 if (NumArgOperands == 0)
1713 Intrinsic::ID iid = I.getIntrinsicID();
1714 IntrinsicKind IK = getIntrinsicKind(iid);
1715 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1716 bool WritesMemory = IK == IK_WritesMemory;
1717 assert(!(OnlyReadsMemory && WritesMemory));
1719 if (NumArgOperands == 2 &&
1720 I.getArgOperand(0)->getType()->isPointerTy() &&
1721 I.getArgOperand(1)->getType()->isVectorTy() &&
1722 I.getType()->isVoidTy() &&
1724 // This looks like a vector store.
1725 return handleVectorStoreIntrinsic(I);
1728 if (NumArgOperands == 1 &&
1729 I.getArgOperand(0)->getType()->isPointerTy() &&
1730 I.getType()->isVectorTy() &&
1732 // This looks like a vector load.
1733 return handleVectorLoadIntrinsic(I);
1736 if (!OnlyReadsMemory && !WritesMemory)
1737 if (maybeHandleSimpleNomemIntrinsic(I))
1740 // FIXME: detect and handle SSE maskstore/maskload
1744 void handleBswap(IntrinsicInst &I) {
1745 IRBuilder<> IRB(&I);
1746 Value *Op = I.getArgOperand(0);
1747 Type *OpType = Op->getType();
1748 Function *BswapFunc = Intrinsic::getDeclaration(
1749 F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1750 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1751 setOrigin(&I, getOrigin(Op));
1754 // \brief Instrument vector convert instrinsic.
1756 // This function instruments intrinsics like cvtsi2ss:
1757 // %Out = int_xxx_cvtyyy(%ConvertOp)
1759 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1760 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1761 // number \p Out elements, and (if has 2 arguments) copies the rest of the
1762 // elements from \p CopyOp.
1763 // In most cases conversion involves floating-point value which may trigger a
1764 // hardware exception when not fully initialized. For this reason we require
1765 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1766 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1767 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1768 // return a fully initialized value.
1769 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1770 IRBuilder<> IRB(&I);
1771 Value *CopyOp, *ConvertOp;
1773 switch (I.getNumArgOperands()) {
1775 CopyOp = I.getArgOperand(0);
1776 ConvertOp = I.getArgOperand(1);
1779 ConvertOp = I.getArgOperand(0);
1783 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1786 // The first *NumUsedElements* elements of ConvertOp are converted to the
1787 // same number of output elements. The rest of the output is copied from
1788 // CopyOp, or (if not available) filled with zeroes.
1789 // Combine shadow for elements of ConvertOp that are used in this operation,
1790 // and insert a check.
1791 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1792 // int->any conversion.
1793 Value *ConvertShadow = getShadow(ConvertOp);
1794 Value *AggShadow = 0;
1795 if (ConvertOp->getType()->isVectorTy()) {
1796 AggShadow = IRB.CreateExtractElement(
1797 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1798 for (int i = 1; i < NumUsedElements; ++i) {
1799 Value *MoreShadow = IRB.CreateExtractElement(
1800 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1801 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1804 AggShadow = ConvertShadow;
1806 assert(AggShadow->getType()->isIntegerTy());
1807 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1809 // Build result shadow by zero-filling parts of CopyOp shadow that come from
1812 assert(CopyOp->getType() == I.getType());
1813 assert(CopyOp->getType()->isVectorTy());
1814 Value *ResultShadow = getShadow(CopyOp);
1815 Type *EltTy = ResultShadow->getType()->getVectorElementType();
1816 for (int i = 0; i < NumUsedElements; ++i) {
1817 ResultShadow = IRB.CreateInsertElement(
1818 ResultShadow, ConstantInt::getNullValue(EltTy),
1819 ConstantInt::get(IRB.getInt32Ty(), i));
1821 setShadow(&I, ResultShadow);
1822 setOrigin(&I, getOrigin(CopyOp));
1824 setShadow(&I, getCleanShadow(&I));
1828 void visitIntrinsicInst(IntrinsicInst &I) {
1829 switch (I.getIntrinsicID()) {
1830 case llvm::Intrinsic::bswap:
1833 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
1834 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
1835 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
1836 case llvm::Intrinsic::x86_avx512_cvtss2usi:
1837 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
1838 case llvm::Intrinsic::x86_avx512_cvttss2usi:
1839 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
1840 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
1841 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
1842 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
1843 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
1844 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
1845 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
1846 case llvm::Intrinsic::x86_sse2_cvtsd2si:
1847 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
1848 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
1849 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
1850 case llvm::Intrinsic::x86_sse2_cvtss2sd:
1851 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
1852 case llvm::Intrinsic::x86_sse2_cvttsd2si:
1853 case llvm::Intrinsic::x86_sse_cvtsi2ss:
1854 case llvm::Intrinsic::x86_sse_cvtsi642ss:
1855 case llvm::Intrinsic::x86_sse_cvtss2si64:
1856 case llvm::Intrinsic::x86_sse_cvtss2si:
1857 case llvm::Intrinsic::x86_sse_cvttss2si64:
1858 case llvm::Intrinsic::x86_sse_cvttss2si:
1859 handleVectorConvertIntrinsic(I, 1);
1861 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
1862 case llvm::Intrinsic::x86_sse2_cvtps2pd:
1863 case llvm::Intrinsic::x86_sse_cvtps2pi:
1864 case llvm::Intrinsic::x86_sse_cvttps2pi:
1865 handleVectorConvertIntrinsic(I, 2);
1868 if (!handleUnknownIntrinsic(I))
1869 visitInstruction(I);
1874 void visitCallSite(CallSite CS) {
1875 Instruction &I = *CS.getInstruction();
1876 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1878 CallInst *Call = cast<CallInst>(&I);
1880 // For inline asm, do the usual thing: check argument shadow and mark all
1881 // outputs as clean. Note that any side effects of the inline asm that are
1882 // not immediately visible in its constraints are not handled.
1883 if (Call->isInlineAsm()) {
1884 visitInstruction(I);
1888 // Allow only tail calls with the same types, otherwise
1889 // we may have a false positive: shadow for a non-void RetVal
1890 // will get propagated to a void RetVal.
1891 if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1892 Call->setTailCall(false);
1894 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1896 // We are going to insert code that relies on the fact that the callee
1897 // will become a non-readonly function after it is instrumented by us. To
1898 // prevent this code from being optimized out, mark that function
1899 // non-readonly in advance.
1900 if (Function *Func = Call->getCalledFunction()) {
1901 // Clear out readonly/readnone attributes.
1903 B.addAttribute(Attribute::ReadOnly)
1904 .addAttribute(Attribute::ReadNone);
1905 Func->removeAttributes(AttributeSet::FunctionIndex,
1906 AttributeSet::get(Func->getContext(),
1907 AttributeSet::FunctionIndex,
1911 IRBuilder<> IRB(&I);
1913 if (MS.WrapIndirectCalls && !CS.getCalledFunction())
1914 IndirectCallList.push_back(CS);
1916 unsigned ArgOffset = 0;
1917 DEBUG(dbgs() << " CallSite: " << I << "\n");
1918 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1919 ArgIt != End; ++ArgIt) {
1921 unsigned i = ArgIt - CS.arg_begin();
1922 if (!A->getType()->isSized()) {
1923 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1928 // Compute the Shadow for arg even if it is ByVal, because
1929 // in that case getShadow() will copy the actual arg shadow to
1930 // __msan_param_tls.
1931 Value *ArgShadow = getShadow(A);
1932 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1933 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
1934 " Shadow: " << *ArgShadow << "\n");
1935 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1936 assert(A->getType()->isPointerTy() &&
1937 "ByVal argument is not a pointer!");
1938 Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1939 unsigned Alignment = CS.getParamAlignment(i + 1);
1940 Store = IRB.CreateMemCpy(ArgShadowBase,
1941 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1944 Size = MS.TD->getTypeAllocSize(A->getType());
1945 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1946 kShadowTLSAlignment);
1948 if (MS.TrackOrigins)
1949 IRB.CreateStore(getOrigin(A),
1950 getOriginPtrForArgument(A, IRB, ArgOffset));
1952 assert(Size != 0 && Store != 0);
1953 DEBUG(dbgs() << " Param:" << *Store << "\n");
1954 ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1956 DEBUG(dbgs() << " done with call args\n");
1959 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
1960 if (FT->isVarArg()) {
1961 VAHelper->visitCallSite(CS, IRB);
1964 // Now, get the shadow for the RetVal.
1965 if (!I.getType()->isSized()) return;
1966 IRBuilder<> IRBBefore(&I);
1967 // Until we have full dynamic coverage, make sure the retval shadow is 0.
1968 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1969 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1970 Instruction *NextInsn = 0;
1972 NextInsn = I.getNextNode();
1974 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1975 if (!NormalDest->getSinglePredecessor()) {
1976 // FIXME: this case is tricky, so we are just conservative here.
1977 // Perhaps we need to split the edge between this BB and NormalDest,
1978 // but a naive attempt to use SplitEdge leads to a crash.
1979 setShadow(&I, getCleanShadow(&I));
1980 setOrigin(&I, getCleanOrigin());
1983 NextInsn = NormalDest->getFirstInsertionPt();
1985 "Could not find insertion point for retval shadow load");
1987 IRBuilder<> IRBAfter(NextInsn);
1988 Value *RetvalShadow =
1989 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1990 kShadowTLSAlignment, "_msret");
1991 setShadow(&I, RetvalShadow);
1992 if (MS.TrackOrigins)
1993 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1996 void visitReturnInst(ReturnInst &I) {
1997 IRBuilder<> IRB(&I);
1998 Value *RetVal = I.getReturnValue();
1999 if (!RetVal) return;
2000 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2001 if (CheckReturnValue) {
2002 insertShadowCheck(RetVal, &I);
2003 Value *Shadow = getCleanShadow(RetVal);
2004 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2006 Value *Shadow = getShadow(RetVal);
2007 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2008 // FIXME: make it conditional if ClStoreCleanOrigin==0
2009 if (MS.TrackOrigins)
2010 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2014 void visitPHINode(PHINode &I) {
2015 IRBuilder<> IRB(&I);
2016 ShadowPHINodes.push_back(&I);
2017 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2019 if (MS.TrackOrigins)
2020 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2024 void visitAllocaInst(AllocaInst &I) {
2025 setShadow(&I, getCleanShadow(&I));
2026 IRBuilder<> IRB(I.getNextNode());
2027 uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
2028 if (PoisonStack && ClPoisonStackWithCall) {
2029 IRB.CreateCall2(MS.MsanPoisonStackFn,
2030 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2031 ConstantInt::get(MS.IntptrTy, Size));
2033 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2034 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2035 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2038 if (PoisonStack && MS.TrackOrigins) {
2039 setOrigin(&I, getCleanOrigin());
2040 SmallString<2048> StackDescriptionStorage;
2041 raw_svector_ostream StackDescription(StackDescriptionStorage);
2042 // We create a string with a description of the stack allocation and
2043 // pass it into __msan_set_alloca_origin.
2044 // It will be printed by the run-time if stack-originated UMR is found.
2045 // The first 4 bytes of the string are set to '----' and will be replaced
2046 // by __msan_va_arg_overflow_size_tls at the first call.
2047 StackDescription << "----" << I.getName() << "@" << F.getName();
2049 createPrivateNonConstGlobalForString(*F.getParent(),
2050 StackDescription.str());
2052 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
2053 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2054 ConstantInt::get(MS.IntptrTy, Size),
2055 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2056 IRB.CreatePointerCast(&F, MS.IntptrTy));
2060 void visitSelectInst(SelectInst& I) {
2061 IRBuilder<> IRB(&I);
2062 // a = select b, c, d
2063 Value *S = IRB.CreateSelect(I.getCondition(), getShadow(I.getTrueValue()),
2064 getShadow(I.getFalseValue()));
2065 if (I.getType()->isAggregateType()) {
2066 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2067 // an extra "select". This results in much more compact IR.
2068 // Sa = select Sb, poisoned, (select b, Sc, Sd)
2069 S = IRB.CreateSelect(getShadow(I.getCondition()),
2070 getPoisonedShadow(getShadowTy(I.getType())), S,
2071 "_msprop_select_agg");
2073 // Sa = (sext Sb) | (select b, Sc, Sd)
2074 S = IRB.CreateOr(S, CreateShadowCast(IRB, getShadow(I.getCondition()),
2075 S->getType(), true),
2079 if (MS.TrackOrigins) {
2080 // Origins are always i32, so any vector conditions must be flattened.
2081 // FIXME: consider tracking vector origins for app vectors?
2082 Value *Cond = I.getCondition();
2083 Value *CondShadow = getShadow(Cond);
2084 if (Cond->getType()->isVectorTy()) {
2085 Type *FlatTy = getShadowTyNoVec(Cond->getType());
2086 Cond = IRB.CreateICmpNE(IRB.CreateBitCast(Cond, FlatTy),
2087 ConstantInt::getNullValue(FlatTy));
2088 CondShadow = IRB.CreateICmpNE(IRB.CreateBitCast(CondShadow, FlatTy),
2089 ConstantInt::getNullValue(FlatTy));
2091 // a = select b, c, d
2092 // Oa = Sb ? Ob : (b ? Oc : Od)
2093 setOrigin(&I, IRB.CreateSelect(
2094 CondShadow, getOrigin(I.getCondition()),
2095 IRB.CreateSelect(Cond, getOrigin(I.getTrueValue()),
2096 getOrigin(I.getFalseValue()))));
2100 void visitLandingPadInst(LandingPadInst &I) {
2102 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2103 setShadow(&I, getCleanShadow(&I));
2104 setOrigin(&I, getCleanOrigin());
2107 void visitGetElementPtrInst(GetElementPtrInst &I) {
2111 void visitExtractValueInst(ExtractValueInst &I) {
2112 IRBuilder<> IRB(&I);
2113 Value *Agg = I.getAggregateOperand();
2114 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2115 Value *AggShadow = getShadow(Agg);
2116 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2117 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2118 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2119 setShadow(&I, ResShadow);
2120 setOriginForNaryOp(I);
2123 void visitInsertValueInst(InsertValueInst &I) {
2124 IRBuilder<> IRB(&I);
2125 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2126 Value *AggShadow = getShadow(I.getAggregateOperand());
2127 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2128 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2129 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2130 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2131 DEBUG(dbgs() << " Res: " << *Res << "\n");
2133 setOriginForNaryOp(I);
2136 void dumpInst(Instruction &I) {
2137 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2138 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2140 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2142 errs() << "QQQ " << I << "\n";
2145 void visitResumeInst(ResumeInst &I) {
2146 DEBUG(dbgs() << "Resume: " << I << "\n");
2147 // Nothing to do here.
2150 void visitInstruction(Instruction &I) {
2151 // Everything else: stop propagating and check for poisoned shadow.
2152 if (ClDumpStrictInstructions)
2154 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2155 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2156 insertShadowCheck(I.getOperand(i), &I);
2157 setShadow(&I, getCleanShadow(&I));
2158 setOrigin(&I, getCleanOrigin());
2162 /// \brief AMD64-specific implementation of VarArgHelper.
2163 struct VarArgAMD64Helper : public VarArgHelper {
2164 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2165 // See a comment in visitCallSite for more details.
2166 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
2167 static const unsigned AMD64FpEndOffset = 176;
2170 MemorySanitizer &MS;
2171 MemorySanitizerVisitor &MSV;
2172 Value *VAArgTLSCopy;
2173 Value *VAArgOverflowSize;
2175 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2177 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2178 MemorySanitizerVisitor &MSV)
2179 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
2181 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2183 ArgKind classifyArgument(Value* arg) {
2184 // A very rough approximation of X86_64 argument classification rules.
2185 Type *T = arg->getType();
2186 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2187 return AK_FloatingPoint;
2188 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2189 return AK_GeneralPurpose;
2190 if (T->isPointerTy())
2191 return AK_GeneralPurpose;
2195 // For VarArg functions, store the argument shadow in an ABI-specific format
2196 // that corresponds to va_list layout.
2197 // We do this because Clang lowers va_arg in the frontend, and this pass
2198 // only sees the low level code that deals with va_list internals.
2199 // A much easier alternative (provided that Clang emits va_arg instructions)
2200 // would have been to associate each live instance of va_list with a copy of
2201 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2203 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
2204 unsigned GpOffset = 0;
2205 unsigned FpOffset = AMD64GpEndOffset;
2206 unsigned OverflowOffset = AMD64FpEndOffset;
2207 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2208 ArgIt != End; ++ArgIt) {
2210 ArgKind AK = classifyArgument(A);
2211 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2213 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2217 case AK_GeneralPurpose:
2218 Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
2221 case AK_FloatingPoint:
2222 Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
2226 uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
2227 Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
2228 OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
2230 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2232 Constant *OverflowSize =
2233 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2234 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2237 /// \brief Compute the shadow address for a given va_arg.
2238 Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
2240 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2241 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2242 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
2246 void visitVAStartInst(VAStartInst &I) {
2247 IRBuilder<> IRB(&I);
2248 VAStartInstrumentationList.push_back(&I);
2249 Value *VAListTag = I.getArgOperand(0);
2250 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2252 // Unpoison the whole __va_list_tag.
2253 // FIXME: magic ABI constants.
2254 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2255 /* size */24, /* alignment */8, false);
2258 void visitVACopyInst(VACopyInst &I) {
2259 IRBuilder<> IRB(&I);
2260 Value *VAListTag = I.getArgOperand(0);
2261 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2263 // Unpoison the whole __va_list_tag.
2264 // FIXME: magic ABI constants.
2265 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2266 /* size */24, /* alignment */8, false);
2269 void finalizeInstrumentation() {
2270 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2271 "finalizeInstrumentation called twice");
2272 if (!VAStartInstrumentationList.empty()) {
2273 // If there is a va_start in this function, make a backup copy of
2274 // va_arg_tls somewhere in the function entry block.
2275 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2276 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2278 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2280 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2281 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2284 // Instrument va_start.
2285 // Copy va_list shadow from the backup copy of the TLS contents.
2286 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2287 CallInst *OrigInst = VAStartInstrumentationList[i];
2288 IRBuilder<> IRB(OrigInst->getNextNode());
2289 Value *VAListTag = OrigInst->getArgOperand(0);
2291 Value *RegSaveAreaPtrPtr =
2293 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2294 ConstantInt::get(MS.IntptrTy, 16)),
2295 Type::getInt64PtrTy(*MS.C));
2296 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2297 Value *RegSaveAreaShadowPtr =
2298 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2299 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2300 AMD64FpEndOffset, 16);
2302 Value *OverflowArgAreaPtrPtr =
2304 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2305 ConstantInt::get(MS.IntptrTy, 8)),
2306 Type::getInt64PtrTy(*MS.C));
2307 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2308 Value *OverflowArgAreaShadowPtr =
2309 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2310 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2311 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2316 /// \brief A no-op implementation of VarArgHelper.
2317 struct VarArgNoOpHelper : public VarArgHelper {
2318 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2319 MemorySanitizerVisitor &MSV) {}
2321 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {}
2323 void visitVAStartInst(VAStartInst &I) {}
2325 void visitVACopyInst(VACopyInst &I) {}
2327 void finalizeInstrumentation() {}
2330 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2331 MemorySanitizerVisitor &Visitor) {
2332 // VarArg handling is only implemented on AMD64. False positives are possible
2333 // on other platforms.
2334 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2335 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2336 return new VarArgAMD64Helper(Func, Msan, Visitor);
2338 return new VarArgNoOpHelper(Func, Msan, Visitor);
2343 bool MemorySanitizer::runOnFunction(Function &F) {
2344 MemorySanitizerVisitor Visitor(F, *this);
2346 // Clear out readonly/readnone attributes.
2348 B.addAttribute(Attribute::ReadOnly)
2349 .addAttribute(Attribute::ReadNone);
2350 F.removeAttributes(AttributeSet::FunctionIndex,
2351 AttributeSet::get(F.getContext(),
2352 AttributeSet::FunctionIndex, B));
2354 return Visitor.runOnFunction();