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 /// The algorithm of the tool is similar to Memcheck
14 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
15 /// byte of the application memory, poison the shadow of the malloc-ed
16 /// or alloca-ed memory, load the shadow bits on every memory read,
17 /// propagate the shadow bits through some of the arithmetic
18 /// instruction (including MOV), store the shadow bits on every memory
19 /// write, report a bug on some other instructions (e.g. JMP) if the
20 /// associated shadow is poisoned.
22 /// But there are differences too. The first and the major one:
23 /// compiler instrumentation instead of binary instrumentation. This
24 /// gives us much better register allocation, possible compiler
25 /// optimizations and a fast start-up. But this brings the major issue
26 /// as well: msan needs to see all program events, including system
27 /// calls and reads/writes in system libraries, so we either need to
28 /// compile *everything* with msan or use a binary translation
29 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
30 /// Another difference from Memcheck is that we use 8 shadow bits per
31 /// byte of application memory and use a direct shadow mapping. This
32 /// greatly simplifies the instrumentation code and avoids races on
33 /// shadow updates (Memcheck is single-threaded so races are not a
34 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
35 /// path storage that uses 8 bits per byte).
37 /// The default value of shadow is 0, which means "clean" (not poisoned).
39 /// Every module initializer should call __msan_init to ensure that the
40 /// shadow memory is ready. On error, __msan_warning is called. Since
41 /// parameters and return values may be passed via registers, we have a
42 /// specialized thread-local shadow for return values
43 /// (__msan_retval_tls) and parameters (__msan_param_tls).
47 /// MemorySanitizer can track origins (allocation points) of all uninitialized
48 /// values. This behavior is controlled with a flag (msan-track-origins) and is
49 /// disabled by default.
51 /// Origins are 4-byte values created and interpreted by the runtime library.
52 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
53 /// of application memory. Propagation of origins is basically a bunch of
54 /// "select" instructions that pick the origin of a dirty argument, if an
55 /// instruction has one.
57 /// Every 4 aligned, consecutive bytes of application memory have one origin
58 /// value associated with them. If these bytes contain uninitialized data
59 /// coming from 2 different allocations, the last store wins. Because of this,
60 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
63 /// Origins are meaningless for fully initialized values, so MemorySanitizer
64 /// avoids storing origin to memory when a fully initialized value is stored.
65 /// This way it avoids needless overwritting origin of the 4-byte region on
66 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
70 /// Ideally, every atomic store of application value should update the
71 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
72 /// of two disjoint locations can not be done without severe slowdown.
74 /// Therefore, we implement an approximation that may err on the safe side.
75 /// In this implementation, every atomically accessed location in the program
76 /// may only change from (partially) uninitialized to fully initialized, but
77 /// not the other way around. We load the shadow _after_ the application load,
78 /// and we store the shadow _before_ the app store. Also, we always store clean
79 /// shadow (if the application store is atomic). This way, if the store-load
80 /// pair constitutes a happens-before arc, shadow store and load are correctly
81 /// ordered such that the load will get either the value that was stored, or
82 /// some later value (which is always clean).
84 /// This does not work very well with Compare-And-Swap (CAS) and
85 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
86 /// must store the new shadow before the app operation, and load the shadow
87 /// after the app operation. Computers don't work this way. Current
88 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
89 /// value. It implements the store part as a simple atomic store by storing a
92 //===----------------------------------------------------------------------===//
94 #include "llvm/Transforms/Instrumentation.h"
95 #include "llvm/ADT/DepthFirstIterator.h"
96 #include "llvm/ADT/SmallString.h"
97 #include "llvm/ADT/SmallVector.h"
98 #include "llvm/ADT/StringExtras.h"
99 #include "llvm/ADT/Triple.h"
100 #include "llvm/IR/DataLayout.h"
101 #include "llvm/IR/Function.h"
102 #include "llvm/IR/IRBuilder.h"
103 #include "llvm/IR/InlineAsm.h"
104 #include "llvm/IR/InstVisitor.h"
105 #include "llvm/IR/IntrinsicInst.h"
106 #include "llvm/IR/LLVMContext.h"
107 #include "llvm/IR/MDBuilder.h"
108 #include "llvm/IR/Module.h"
109 #include "llvm/IR/Type.h"
110 #include "llvm/IR/ValueMap.h"
111 #include "llvm/Support/CommandLine.h"
112 #include "llvm/Support/Compiler.h"
113 #include "llvm/Support/Debug.h"
114 #include "llvm/Support/raw_ostream.h"
115 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include "llvm/Transforms/Utils/ModuleUtils.h"
119 using namespace llvm;
121 #define DEBUG_TYPE "msan"
123 static const uint64_t kShadowMask32 = 1ULL << 31;
124 static const uint64_t kShadowMask64 = 1ULL << 46;
125 static const uint64_t kOriginOffset32 = 1ULL << 30;
126 static const uint64_t kOriginOffset64 = 1ULL << 45;
127 static const unsigned kMinOriginAlignment = 4;
128 static const unsigned kShadowTLSAlignment = 8;
130 // These constants must be kept in sync with the ones in msan.h.
131 static const unsigned kParamTLSSize = 800;
132 static const unsigned kRetvalTLSSize = 800;
134 // Accesses sizes are powers of two: 1, 2, 4, 8.
135 static const size_t kNumberOfAccessSizes = 4;
137 /// \brief Track origins of uninitialized values.
139 /// Adds a section to MemorySanitizer report that points to the allocation
140 /// (stack or heap) the uninitialized bits came from originally.
141 static cl::opt<int> ClTrackOrigins("msan-track-origins",
142 cl::desc("Track origins (allocation sites) of poisoned memory"),
143 cl::Hidden, cl::init(0));
144 static cl::opt<bool> ClKeepGoing("msan-keep-going",
145 cl::desc("keep going after reporting a UMR"),
146 cl::Hidden, cl::init(false));
147 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
148 cl::desc("poison uninitialized stack variables"),
149 cl::Hidden, cl::init(true));
150 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
151 cl::desc("poison uninitialized stack variables with a call"),
152 cl::Hidden, cl::init(false));
153 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
154 cl::desc("poison uninitialized stack variables with the given patter"),
155 cl::Hidden, cl::init(0xff));
156 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
157 cl::desc("poison undef temps"),
158 cl::Hidden, cl::init(true));
160 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
161 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
162 cl::Hidden, cl::init(true));
164 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
165 cl::desc("exact handling of relational integer ICmp"),
166 cl::Hidden, cl::init(false));
168 // This flag controls whether we check the shadow of the address
169 // operand of load or store. Such bugs are very rare, since load from
170 // a garbage address typically results in SEGV, but still happen
171 // (e.g. only lower bits of address are garbage, or the access happens
172 // early at program startup where malloc-ed memory is more likely to
173 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
174 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
175 cl::desc("report accesses through a pointer which has poisoned shadow"),
176 cl::Hidden, cl::init(true));
178 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
179 cl::desc("print out instructions with default strict semantics"),
180 cl::Hidden, cl::init(false));
182 static cl::opt<int> ClInstrumentationWithCallThreshold(
183 "msan-instrumentation-with-call-threshold",
185 "If the function being instrumented requires more than "
186 "this number of checks and origin stores, use callbacks instead of "
187 "inline checks (-1 means never use callbacks)."),
188 cl::Hidden, cl::init(3500));
190 // This is an experiment to enable handling of cases where shadow is a non-zero
191 // compile-time constant. For some unexplainable reason they were silently
192 // ignored in the instrumentation.
193 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
194 cl::desc("Insert checks for constant shadow values"),
195 cl::Hidden, cl::init(false));
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(int TrackOrigins = 0)
208 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
210 WarningFn(nullptr) {}
211 const char *getPassName() const override { return "MemorySanitizer"; }
212 bool runOnFunction(Function &F) override;
213 bool doInitialization(Module &M) override;
214 static char ID; // Pass identification, replacement for typeid.
217 void initializeCallbacks(Module &M);
219 /// \brief Track origins (allocation points) of uninitialized values.
222 const DataLayout *DL;
226 /// \brief Thread-local shadow storage for function parameters.
227 GlobalVariable *ParamTLS;
228 /// \brief Thread-local origin storage for function parameters.
229 GlobalVariable *ParamOriginTLS;
230 /// \brief Thread-local shadow storage for function return value.
231 GlobalVariable *RetvalTLS;
232 /// \brief Thread-local origin storage for function return value.
233 GlobalVariable *RetvalOriginTLS;
234 /// \brief Thread-local shadow storage for in-register va_arg function
235 /// parameters (x86_64-specific).
236 GlobalVariable *VAArgTLS;
237 /// \brief Thread-local shadow storage for va_arg overflow area
238 /// (x86_64-specific).
239 GlobalVariable *VAArgOverflowSizeTLS;
240 /// \brief Thread-local space used to pass origin value to the UMR reporting
242 GlobalVariable *OriginTLS;
244 /// \brief The run-time callback to print a warning.
246 // These arrays are indexed by log2(AccessSize).
247 Value *MaybeWarningFn[kNumberOfAccessSizes];
248 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
250 /// \brief Run-time helper that generates a new origin value for a stack
252 Value *MsanSetAllocaOrigin4Fn;
253 /// \brief Run-time helper that poisons stack on function entry.
254 Value *MsanPoisonStackFn;
255 /// \brief Run-time helper that records a store (or any event) of an
256 /// uninitialized value and returns an updated origin id encoding this info.
257 Value *MsanChainOriginFn;
258 /// \brief MSan runtime replacements for memmove, memcpy and memset.
259 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
261 /// \brief Address mask used in application-to-shadow address calculation.
262 /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
264 /// \brief Offset of the origin shadow from the "normal" shadow.
265 /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
266 uint64_t OriginOffset;
267 /// \brief Branch weights for error reporting.
268 MDNode *ColdCallWeights;
269 /// \brief Branch weights for origin store.
270 MDNode *OriginStoreWeights;
271 /// \brief An empty volatile inline asm that prevents callback merge.
274 friend struct MemorySanitizerVisitor;
275 friend struct VarArgAMD64Helper;
279 char MemorySanitizer::ID = 0;
280 INITIALIZE_PASS(MemorySanitizer, "msan",
281 "MemorySanitizer: detects uninitialized reads.",
284 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
285 return new MemorySanitizer(TrackOrigins);
288 /// \brief Create a non-const global initialized with the given string.
290 /// Creates a writable global for Str so that we can pass it to the
291 /// run-time lib. Runtime uses first 4 bytes of the string to store the
292 /// frame ID, so the string needs to be mutable.
293 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
295 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
296 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
297 GlobalValue::PrivateLinkage, StrConst, "");
301 /// \brief Insert extern declaration of runtime-provided functions and globals.
302 void MemorySanitizer::initializeCallbacks(Module &M) {
303 // Only do this once.
308 // Create the callback.
309 // FIXME: this function should have "Cold" calling conv,
310 // which is not yet implemented.
311 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
312 : "__msan_warning_noreturn";
313 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
315 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
317 unsigned AccessSize = 1 << AccessSizeIndex;
318 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
319 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
320 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
321 IRB.getInt32Ty(), nullptr);
323 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
324 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
325 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
326 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
329 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
330 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
331 IRB.getInt8PtrTy(), IntptrTy, nullptr);
333 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
334 IRB.getInt8PtrTy(), IntptrTy, nullptr);
335 MsanChainOriginFn = M.getOrInsertFunction(
336 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
337 MemmoveFn = M.getOrInsertFunction(
338 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
339 IRB.getInt8PtrTy(), IntptrTy, nullptr);
340 MemcpyFn = M.getOrInsertFunction(
341 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
343 MemsetFn = M.getOrInsertFunction(
344 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
348 RetvalTLS = new GlobalVariable(
349 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
350 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
351 GlobalVariable::InitialExecTLSModel);
352 RetvalOriginTLS = new GlobalVariable(
353 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
354 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
356 ParamTLS = new GlobalVariable(
357 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
358 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
359 GlobalVariable::InitialExecTLSModel);
360 ParamOriginTLS = new GlobalVariable(
361 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
362 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
363 nullptr, GlobalVariable::InitialExecTLSModel);
365 VAArgTLS = new GlobalVariable(
366 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
367 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
368 GlobalVariable::InitialExecTLSModel);
369 VAArgOverflowSizeTLS = new GlobalVariable(
370 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
371 "__msan_va_arg_overflow_size_tls", nullptr,
372 GlobalVariable::InitialExecTLSModel);
373 OriginTLS = new GlobalVariable(
374 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
375 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
377 // We insert an empty inline asm after __msan_report* to avoid callback merge.
378 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
379 StringRef(""), StringRef(""),
380 /*hasSideEffects=*/true);
383 /// \brief Module-level initialization.
385 /// inserts a call to __msan_init to the module's constructor list.
386 bool MemorySanitizer::doInitialization(Module &M) {
387 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
389 report_fatal_error("data layout missing");
390 DL = &DLP->getDataLayout();
392 C = &(M.getContext());
393 unsigned PtrSize = DL->getPointerSizeInBits(/* AddressSpace */0);
396 ShadowMask = kShadowMask64;
397 OriginOffset = kOriginOffset64;
400 ShadowMask = kShadowMask32;
401 OriginOffset = kOriginOffset32;
404 report_fatal_error("unsupported pointer size");
409 IntptrTy = IRB.getIntPtrTy(DL);
410 OriginTy = IRB.getInt32Ty();
412 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
413 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
415 // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
416 appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
417 "__msan_init", IRB.getVoidTy(), nullptr)), 0);
420 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
421 IRB.getInt32(TrackOrigins), "__msan_track_origins");
424 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
425 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
432 /// \brief A helper class that handles instrumentation of VarArg
433 /// functions on a particular platform.
435 /// Implementations are expected to insert the instrumentation
436 /// necessary to propagate argument shadow through VarArg function
437 /// calls. Visit* methods are called during an InstVisitor pass over
438 /// the function, and should avoid creating new basic blocks. A new
439 /// instance of this class is created for each instrumented function.
440 struct VarArgHelper {
441 /// \brief Visit a CallSite.
442 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
444 /// \brief Visit a va_start call.
445 virtual void visitVAStartInst(VAStartInst &I) = 0;
447 /// \brief Visit a va_copy call.
448 virtual void visitVACopyInst(VACopyInst &I) = 0;
450 /// \brief Finalize function instrumentation.
452 /// This method is called after visiting all interesting (see above)
453 /// instructions in a function.
454 virtual void finalizeInstrumentation() = 0;
456 virtual ~VarArgHelper() {}
459 struct MemorySanitizerVisitor;
462 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
463 MemorySanitizerVisitor &Visitor);
465 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
466 if (TypeSize <= 8) return 0;
467 return Log2_32_Ceil(TypeSize / 8);
470 /// This class does all the work for a given function. Store and Load
471 /// instructions store and load corresponding shadow and origin
472 /// values. Most instructions propagate shadow from arguments to their
473 /// return values. Certain instructions (most importantly, BranchInst)
474 /// test their argument shadow and print reports (with a runtime call) if it's
476 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
479 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
480 ValueMap<Value*, Value*> ShadowMap, OriginMap;
481 std::unique_ptr<VarArgHelper> VAHelper;
483 // The following flags disable parts of MSan instrumentation based on
484 // blacklist contents and command-line options.
486 bool PropagateShadow;
489 bool CheckReturnValue;
491 struct ShadowOriginAndInsertPoint {
494 Instruction *OrigIns;
495 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
496 : Shadow(S), Origin(O), OrigIns(I) { }
498 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
499 SmallVector<Instruction*, 16> StoreList;
501 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
502 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
503 bool SanitizeFunction = F.getAttributes().hasAttribute(
504 AttributeSet::FunctionIndex, Attribute::SanitizeMemory);
505 InsertChecks = SanitizeFunction;
506 PropagateShadow = SanitizeFunction;
507 PoisonStack = SanitizeFunction && ClPoisonStack;
508 PoisonUndef = SanitizeFunction && ClPoisonUndef;
509 // FIXME: Consider using SpecialCaseList to specify a list of functions that
510 // must always return fully initialized values. For now, we hardcode "main".
511 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
513 DEBUG(if (!InsertChecks)
514 dbgs() << "MemorySanitizer is not inserting checks into '"
515 << F.getName() << "'\n");
518 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
519 if (MS.TrackOrigins <= 1) return V;
520 return IRB.CreateCall(MS.MsanChainOriginFn, V);
523 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
524 unsigned Alignment, bool AsCall) {
525 if (isa<StructType>(Shadow->getType())) {
526 IRB.CreateAlignedStore(updateOrigin(Origin, IRB), getOriginPtr(Addr, IRB),
529 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
530 // TODO(eugenis): handle non-zero constant shadow by inserting an
531 // unconditional check (can not simply fail compilation as this could
532 // be in the dead code).
533 if (!ClCheckConstantShadow)
534 if (isa<Constant>(ConvertedShadow)) return;
535 unsigned TypeSizeInBits =
536 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
537 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
538 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
539 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
540 Value *ConvertedShadow2 = IRB.CreateZExt(
541 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
542 IRB.CreateCall3(Fn, ConvertedShadow2,
543 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
546 Value *Cmp = IRB.CreateICmpNE(
547 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
548 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
549 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
550 IRBuilder<> IRBNew(CheckTerm);
551 IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
552 getOriginPtr(Addr, IRBNew), Alignment);
557 void materializeStores(bool InstrumentWithCalls) {
558 for (auto Inst : StoreList) {
559 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
561 IRBuilder<> IRB(&SI);
562 Value *Val = SI.getValueOperand();
563 Value *Addr = SI.getPointerOperand();
564 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
565 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
568 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
569 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
572 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
574 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
576 if (MS.TrackOrigins) {
577 unsigned Alignment = std::max(kMinOriginAlignment, SI.getAlignment());
578 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), Alignment,
579 InstrumentWithCalls);
584 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
586 IRBuilder<> IRB(OrigIns);
587 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
588 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
589 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
590 // See the comment in storeOrigin().
591 if (!ClCheckConstantShadow)
592 if (isa<Constant>(ConvertedShadow)) return;
593 unsigned TypeSizeInBits =
594 MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
595 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
596 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
597 Value *Fn = MS.MaybeWarningFn[SizeIndex];
598 Value *ConvertedShadow2 =
599 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
600 IRB.CreateCall2(Fn, ConvertedShadow2, MS.TrackOrigins && Origin
602 : (Value *)IRB.getInt32(0));
604 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
605 getCleanShadow(ConvertedShadow), "_mscmp");
606 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
608 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
610 IRB.SetInsertPoint(CheckTerm);
611 if (MS.TrackOrigins) {
612 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
615 IRB.CreateCall(MS.WarningFn);
616 IRB.CreateCall(MS.EmptyAsm);
617 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
621 void materializeChecks(bool InstrumentWithCalls) {
622 for (const auto &ShadowData : InstrumentationList) {
623 Instruction *OrigIns = ShadowData.OrigIns;
624 Value *Shadow = ShadowData.Shadow;
625 Value *Origin = ShadowData.Origin;
626 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
628 DEBUG(dbgs() << "DONE:\n" << F);
631 /// \brief Add MemorySanitizer instrumentation to a function.
632 bool runOnFunction() {
633 MS.initializeCallbacks(*F.getParent());
634 if (!MS.DL) return false;
636 // In the presence of unreachable blocks, we may see Phi nodes with
637 // incoming nodes from such blocks. Since InstVisitor skips unreachable
638 // blocks, such nodes will not have any shadow value associated with them.
639 // It's easier to remove unreachable blocks than deal with missing shadow.
640 removeUnreachableBlocks(F);
642 // Iterate all BBs in depth-first order and create shadow instructions
643 // for all instructions (where applicable).
644 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
645 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
649 // Finalize PHI nodes.
650 for (PHINode *PN : ShadowPHINodes) {
651 PHINode *PNS = cast<PHINode>(getShadow(PN));
652 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
653 size_t NumValues = PN->getNumIncomingValues();
654 for (size_t v = 0; v < NumValues; v++) {
655 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
656 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
660 VAHelper->finalizeInstrumentation();
662 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
663 InstrumentationList.size() + StoreList.size() >
664 (unsigned)ClInstrumentationWithCallThreshold;
666 // Delayed instrumentation of StoreInst.
667 // This may add new checks to be inserted later.
668 materializeStores(InstrumentWithCalls);
670 // Insert shadow value checks.
671 materializeChecks(InstrumentWithCalls);
676 /// \brief Compute the shadow type that corresponds to a given Value.
677 Type *getShadowTy(Value *V) {
678 return getShadowTy(V->getType());
681 /// \brief Compute the shadow type that corresponds to a given Type.
682 Type *getShadowTy(Type *OrigTy) {
683 if (!OrigTy->isSized()) {
686 // For integer type, shadow is the same as the original type.
687 // This may return weird-sized types like i1.
688 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
690 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
691 uint32_t EltSize = MS.DL->getTypeSizeInBits(VT->getElementType());
692 return VectorType::get(IntegerType::get(*MS.C, EltSize),
693 VT->getNumElements());
695 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
696 return ArrayType::get(getShadowTy(AT->getElementType()),
697 AT->getNumElements());
699 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
700 SmallVector<Type*, 4> Elements;
701 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
702 Elements.push_back(getShadowTy(ST->getElementType(i)));
703 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
704 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
707 uint32_t TypeSize = MS.DL->getTypeSizeInBits(OrigTy);
708 return IntegerType::get(*MS.C, TypeSize);
711 /// \brief Flatten a vector type.
712 Type *getShadowTyNoVec(Type *ty) {
713 if (VectorType *vt = dyn_cast<VectorType>(ty))
714 return IntegerType::get(*MS.C, vt->getBitWidth());
718 /// \brief Convert a shadow value to it's flattened variant.
719 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
720 Type *Ty = V->getType();
721 Type *NoVecTy = getShadowTyNoVec(Ty);
722 if (Ty == NoVecTy) return V;
723 return IRB.CreateBitCast(V, NoVecTy);
726 /// \brief Compute the shadow address that corresponds to a given application
729 /// Shadow = Addr & ~ShadowMask.
730 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
733 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
734 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
735 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
738 /// \brief Compute the origin address that corresponds to a given application
741 /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
742 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
744 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
745 ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
747 IRB.CreateAdd(ShadowLong,
748 ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
750 IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
751 return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
754 /// \brief Compute the shadow address for a given function argument.
756 /// Shadow = ParamTLS+ArgOffset.
757 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
759 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
760 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
761 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
765 /// \brief Compute the origin address for a given function argument.
766 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
768 if (!MS.TrackOrigins) return nullptr;
769 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
770 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
771 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
775 /// \brief Compute the shadow address for a retval.
776 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
777 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
778 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
782 /// \brief Compute the origin address for a retval.
783 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
784 // We keep a single origin for the entire retval. Might be too optimistic.
785 return MS.RetvalOriginTLS;
788 /// \brief Set SV to be the shadow value for V.
789 void setShadow(Value *V, Value *SV) {
790 assert(!ShadowMap.count(V) && "Values may only have one shadow");
791 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
794 /// \brief Set Origin to be the origin value for V.
795 void setOrigin(Value *V, Value *Origin) {
796 if (!MS.TrackOrigins) return;
797 assert(!OriginMap.count(V) && "Values may only have one origin");
798 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
799 OriginMap[V] = Origin;
802 /// \brief Create a clean shadow value for a given value.
804 /// Clean shadow (all zeroes) means all bits of the value are defined
806 Constant *getCleanShadow(Value *V) {
807 Type *ShadowTy = getShadowTy(V);
810 return Constant::getNullValue(ShadowTy);
813 /// \brief Create a dirty shadow of a given shadow type.
814 Constant *getPoisonedShadow(Type *ShadowTy) {
816 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
817 return Constant::getAllOnesValue(ShadowTy);
818 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
819 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
820 getPoisonedShadow(AT->getElementType()));
821 return ConstantArray::get(AT, Vals);
823 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
824 SmallVector<Constant *, 4> Vals;
825 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
826 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
827 return ConstantStruct::get(ST, Vals);
829 llvm_unreachable("Unexpected shadow type");
832 /// \brief Create a dirty shadow for a given value.
833 Constant *getPoisonedShadow(Value *V) {
834 Type *ShadowTy = getShadowTy(V);
837 return getPoisonedShadow(ShadowTy);
840 /// \brief Create a clean (zero) origin.
841 Value *getCleanOrigin() {
842 return Constant::getNullValue(MS.OriginTy);
845 /// \brief Get the shadow value for a given Value.
847 /// This function either returns the value set earlier with setShadow,
848 /// or extracts if from ParamTLS (for function arguments).
849 Value *getShadow(Value *V) {
850 if (!PropagateShadow) return getCleanShadow(V);
851 if (Instruction *I = dyn_cast<Instruction>(V)) {
852 // For instructions the shadow is already stored in the map.
853 Value *Shadow = ShadowMap[V];
855 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
857 assert(Shadow && "No shadow for a value");
861 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
862 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
863 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
867 if (Argument *A = dyn_cast<Argument>(V)) {
868 // For arguments we compute the shadow on demand and store it in the map.
869 Value **ShadowPtr = &ShadowMap[V];
872 Function *F = A->getParent();
873 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
874 unsigned ArgOffset = 0;
875 for (auto &FArg : F->args()) {
876 if (!FArg.getType()->isSized()) {
877 DEBUG(dbgs() << "Arg is not sized\n");
880 unsigned Size = FArg.hasByValAttr()
881 ? MS.DL->getTypeAllocSize(FArg.getType()->getPointerElementType())
882 : MS.DL->getTypeAllocSize(FArg.getType());
884 bool Overflow = ArgOffset + Size > kParamTLSSize;
885 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
886 if (FArg.hasByValAttr()) {
887 // ByVal pointer itself has clean shadow. We copy the actual
888 // argument shadow to the underlying memory.
889 // Figure out maximal valid memcpy alignment.
890 unsigned ArgAlign = FArg.getParamAlignment();
892 Type *EltType = A->getType()->getPointerElementType();
893 ArgAlign = MS.DL->getABITypeAlignment(EltType);
896 // ParamTLS overflow.
897 EntryIRB.CreateMemSet(
898 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
899 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
901 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
902 Value *Cpy = EntryIRB.CreateMemCpy(
903 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
905 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
908 *ShadowPtr = getCleanShadow(V);
911 // ParamTLS overflow.
912 *ShadowPtr = getCleanShadow(V);
915 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
918 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
919 **ShadowPtr << "\n");
920 if (MS.TrackOrigins && !Overflow) {
922 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
923 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
925 setOrigin(A, getCleanOrigin());
928 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
930 assert(*ShadowPtr && "Could not find shadow for an argument");
933 // For everything else the shadow is zero.
934 return getCleanShadow(V);
937 /// \brief Get the shadow for i-th argument of the instruction I.
938 Value *getShadow(Instruction *I, int i) {
939 return getShadow(I->getOperand(i));
942 /// \brief Get the origin for a value.
943 Value *getOrigin(Value *V) {
944 if (!MS.TrackOrigins) return nullptr;
945 if (!PropagateShadow) return getCleanOrigin();
946 if (isa<Constant>(V)) return getCleanOrigin();
947 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
948 "Unexpected value type in getOrigin()");
949 Value *Origin = OriginMap[V];
950 assert(Origin && "Missing origin");
954 /// \brief Get the origin for i-th argument of the instruction I.
955 Value *getOrigin(Instruction *I, int i) {
956 return getOrigin(I->getOperand(i));
959 /// \brief Remember the place where a shadow check should be inserted.
961 /// This location will be later instrumented with a check that will print a
962 /// UMR warning in runtime if the shadow value is not 0.
963 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
965 if (!InsertChecks) return;
967 Type *ShadowTy = Shadow->getType();
968 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
969 "Can only insert checks for integer and vector shadow types");
971 InstrumentationList.push_back(
972 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
975 /// \brief Remember the place where a shadow check should be inserted.
977 /// This location will be later instrumented with a check that will print a
978 /// UMR warning in runtime if the value is not fully defined.
979 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
981 Value *Shadow, *Origin;
982 if (ClCheckConstantShadow) {
983 Shadow = getShadow(Val);
985 Origin = getOrigin(Val);
987 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
989 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
991 insertShadowCheck(Shadow, Origin, OrigIns);
994 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1003 case AcquireRelease:
1004 return AcquireRelease;
1005 case SequentiallyConsistent:
1006 return SequentiallyConsistent;
1008 llvm_unreachable("Unknown ordering");
1011 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1020 case AcquireRelease:
1021 return AcquireRelease;
1022 case SequentiallyConsistent:
1023 return SequentiallyConsistent;
1025 llvm_unreachable("Unknown ordering");
1028 // ------------------- Visitors.
1030 /// \brief Instrument LoadInst
1032 /// Loads the corresponding shadow and (optionally) origin.
1033 /// Optionally, checks that the load address is fully defined.
1034 void visitLoadInst(LoadInst &I) {
1035 assert(I.getType()->isSized() && "Load type must have size");
1036 IRBuilder<> IRB(I.getNextNode());
1037 Type *ShadowTy = getShadowTy(&I);
1038 Value *Addr = I.getPointerOperand();
1039 if (PropagateShadow && !I.getMetadata("nosanitize")) {
1040 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1042 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1044 setShadow(&I, getCleanShadow(&I));
1047 if (ClCheckAccessAddress)
1048 insertShadowCheck(I.getPointerOperand(), &I);
1051 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1053 if (MS.TrackOrigins) {
1054 if (PropagateShadow) {
1055 unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1057 IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1059 setOrigin(&I, getCleanOrigin());
1064 /// \brief Instrument StoreInst
1066 /// Stores the corresponding shadow and (optionally) origin.
1067 /// Optionally, checks that the store address is fully defined.
1068 void visitStoreInst(StoreInst &I) {
1069 StoreList.push_back(&I);
1072 void handleCASOrRMW(Instruction &I) {
1073 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1075 IRBuilder<> IRB(&I);
1076 Value *Addr = I.getOperand(0);
1077 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1079 if (ClCheckAccessAddress)
1080 insertShadowCheck(Addr, &I);
1082 // Only test the conditional argument of cmpxchg instruction.
1083 // The other argument can potentially be uninitialized, but we can not
1084 // detect this situation reliably without possible false positives.
1085 if (isa<AtomicCmpXchgInst>(I))
1086 insertShadowCheck(I.getOperand(1), &I);
1088 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1090 setShadow(&I, getCleanShadow(&I));
1091 setOrigin(&I, getCleanOrigin());
1094 void visitAtomicRMWInst(AtomicRMWInst &I) {
1096 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1099 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1101 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1104 // Vector manipulation.
1105 void visitExtractElementInst(ExtractElementInst &I) {
1106 insertShadowCheck(I.getOperand(1), &I);
1107 IRBuilder<> IRB(&I);
1108 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1110 setOrigin(&I, getOrigin(&I, 0));
1113 void visitInsertElementInst(InsertElementInst &I) {
1114 insertShadowCheck(I.getOperand(2), &I);
1115 IRBuilder<> IRB(&I);
1116 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1117 I.getOperand(2), "_msprop"));
1118 setOriginForNaryOp(I);
1121 void visitShuffleVectorInst(ShuffleVectorInst &I) {
1122 insertShadowCheck(I.getOperand(2), &I);
1123 IRBuilder<> IRB(&I);
1124 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1125 I.getOperand(2), "_msprop"));
1126 setOriginForNaryOp(I);
1130 void visitSExtInst(SExtInst &I) {
1131 IRBuilder<> IRB(&I);
1132 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1133 setOrigin(&I, getOrigin(&I, 0));
1136 void visitZExtInst(ZExtInst &I) {
1137 IRBuilder<> IRB(&I);
1138 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1139 setOrigin(&I, getOrigin(&I, 0));
1142 void visitTruncInst(TruncInst &I) {
1143 IRBuilder<> IRB(&I);
1144 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1145 setOrigin(&I, getOrigin(&I, 0));
1148 void visitBitCastInst(BitCastInst &I) {
1149 IRBuilder<> IRB(&I);
1150 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1151 setOrigin(&I, getOrigin(&I, 0));
1154 void visitPtrToIntInst(PtrToIntInst &I) {
1155 IRBuilder<> IRB(&I);
1156 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1157 "_msprop_ptrtoint"));
1158 setOrigin(&I, getOrigin(&I, 0));
1161 void visitIntToPtrInst(IntToPtrInst &I) {
1162 IRBuilder<> IRB(&I);
1163 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1164 "_msprop_inttoptr"));
1165 setOrigin(&I, getOrigin(&I, 0));
1168 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1169 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1170 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1171 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1172 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1173 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1175 /// \brief Propagate shadow for bitwise AND.
1177 /// This code is exact, i.e. if, for example, a bit in the left argument
1178 /// is defined and 0, then neither the value not definedness of the
1179 /// corresponding bit in B don't affect the resulting shadow.
1180 void visitAnd(BinaryOperator &I) {
1181 IRBuilder<> IRB(&I);
1182 // "And" of 0 and a poisoned value results in unpoisoned value.
1183 // 1&1 => 1; 0&1 => 0; p&1 => p;
1184 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1185 // 1&p => p; 0&p => 0; p&p => p;
1186 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1187 Value *S1 = getShadow(&I, 0);
1188 Value *S2 = getShadow(&I, 1);
1189 Value *V1 = I.getOperand(0);
1190 Value *V2 = I.getOperand(1);
1191 if (V1->getType() != S1->getType()) {
1192 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1193 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1195 Value *S1S2 = IRB.CreateAnd(S1, S2);
1196 Value *V1S2 = IRB.CreateAnd(V1, S2);
1197 Value *S1V2 = IRB.CreateAnd(S1, V2);
1198 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1199 setOriginForNaryOp(I);
1202 void visitOr(BinaryOperator &I) {
1203 IRBuilder<> IRB(&I);
1204 // "Or" of 1 and a poisoned value results in unpoisoned value.
1205 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1206 // 1|0 => 1; 0|0 => 0; p|0 => p;
1207 // 1|p => 1; 0|p => p; p|p => p;
1208 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1209 Value *S1 = getShadow(&I, 0);
1210 Value *S2 = getShadow(&I, 1);
1211 Value *V1 = IRB.CreateNot(I.getOperand(0));
1212 Value *V2 = IRB.CreateNot(I.getOperand(1));
1213 if (V1->getType() != S1->getType()) {
1214 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1215 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1217 Value *S1S2 = IRB.CreateAnd(S1, S2);
1218 Value *V1S2 = IRB.CreateAnd(V1, S2);
1219 Value *S1V2 = IRB.CreateAnd(S1, V2);
1220 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1221 setOriginForNaryOp(I);
1224 /// \brief Default propagation of shadow and/or origin.
1226 /// This class implements the general case of shadow propagation, used in all
1227 /// cases where we don't know and/or don't care about what the operation
1228 /// actually does. It converts all input shadow values to a common type
1229 /// (extending or truncating as necessary), and bitwise OR's them.
1231 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1232 /// fully initialized), and less prone to false positives.
1234 /// This class also implements the general case of origin propagation. For a
1235 /// Nary operation, result origin is set to the origin of an argument that is
1236 /// not entirely initialized. If there is more than one such arguments, the
1237 /// rightmost of them is picked. It does not matter which one is picked if all
1238 /// arguments are initialized.
1239 template <bool CombineShadow>
1244 MemorySanitizerVisitor *MSV;
1247 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1248 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1250 /// \brief Add a pair of shadow and origin values to the mix.
1251 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1252 if (CombineShadow) {
1257 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1258 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1262 if (MSV->MS.TrackOrigins) {
1267 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1268 // No point in adding something that might result in 0 origin value.
1269 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1270 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1272 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1273 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1280 /// \brief Add an application value to the mix.
1281 Combiner &Add(Value *V) {
1282 Value *OpShadow = MSV->getShadow(V);
1283 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1284 return Add(OpShadow, OpOrigin);
1287 /// \brief Set the current combined values as the given instruction's shadow
1289 void Done(Instruction *I) {
1290 if (CombineShadow) {
1292 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1293 MSV->setShadow(I, Shadow);
1295 if (MSV->MS.TrackOrigins) {
1297 MSV->setOrigin(I, Origin);
1302 typedef Combiner<true> ShadowAndOriginCombiner;
1303 typedef Combiner<false> OriginCombiner;
1305 /// \brief Propagate origin for arbitrary operation.
1306 void setOriginForNaryOp(Instruction &I) {
1307 if (!MS.TrackOrigins) return;
1308 IRBuilder<> IRB(&I);
1309 OriginCombiner OC(this, IRB);
1310 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1315 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1316 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1317 "Vector of pointers is not a valid shadow type");
1318 return Ty->isVectorTy() ?
1319 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1320 Ty->getPrimitiveSizeInBits();
1323 /// \brief Cast between two shadow types, extending or truncating as
1325 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1326 bool Signed = false) {
1327 Type *srcTy = V->getType();
1328 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1329 return IRB.CreateIntCast(V, dstTy, Signed);
1330 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1331 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1332 return IRB.CreateIntCast(V, dstTy, Signed);
1333 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1334 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1335 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1337 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1338 return IRB.CreateBitCast(V2, dstTy);
1339 // TODO: handle struct types.
1342 /// \brief Cast an application value to the type of its own shadow.
1343 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1344 Type *ShadowTy = getShadowTy(V);
1345 if (V->getType() == ShadowTy)
1347 if (V->getType()->isPtrOrPtrVectorTy())
1348 return IRB.CreatePtrToInt(V, ShadowTy);
1350 return IRB.CreateBitCast(V, ShadowTy);
1353 /// \brief Propagate shadow for arbitrary operation.
1354 void handleShadowOr(Instruction &I) {
1355 IRBuilder<> IRB(&I);
1356 ShadowAndOriginCombiner SC(this, IRB);
1357 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1362 // \brief Handle multiplication by constant.
1364 // Handle a special case of multiplication by constant that may have one or
1365 // more zeros in the lower bits. This makes corresponding number of lower bits
1366 // of the result zero as well. We model it by shifting the other operand
1367 // shadow left by the required number of bits. Effectively, we transform
1368 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1369 // We use multiplication by 2**N instead of shift to cover the case of
1370 // multiplication by 0, which may occur in some elements of a vector operand.
1371 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1373 Constant *ShadowMul;
1374 Type *Ty = ConstArg->getType();
1375 if (Ty->isVectorTy()) {
1376 unsigned NumElements = Ty->getVectorNumElements();
1377 Type *EltTy = Ty->getSequentialElementType();
1378 SmallVector<Constant *, 16> Elements;
1379 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1381 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1382 APInt V = Elt->getValue();
1383 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1384 Elements.push_back(ConstantInt::get(EltTy, V2));
1386 ShadowMul = ConstantVector::get(Elements);
1388 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1389 APInt V = Elt->getValue();
1390 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1391 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1394 IRBuilder<> IRB(&I);
1396 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1397 setOrigin(&I, getOrigin(OtherArg));
1400 void visitMul(BinaryOperator &I) {
1401 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1402 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1403 if (constOp0 && !constOp1)
1404 handleMulByConstant(I, constOp0, I.getOperand(1));
1405 else if (constOp1 && !constOp0)
1406 handleMulByConstant(I, constOp1, I.getOperand(0));
1411 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1412 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1413 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1414 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1415 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1416 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1418 void handleDiv(Instruction &I) {
1419 IRBuilder<> IRB(&I);
1420 // Strict on the second argument.
1421 insertShadowCheck(I.getOperand(1), &I);
1422 setShadow(&I, getShadow(&I, 0));
1423 setOrigin(&I, getOrigin(&I, 0));
1426 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1427 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1428 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1429 void visitURem(BinaryOperator &I) { handleDiv(I); }
1430 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1431 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1433 /// \brief Instrument == and != comparisons.
1435 /// Sometimes the comparison result is known even if some of the bits of the
1436 /// arguments are not.
1437 void handleEqualityComparison(ICmpInst &I) {
1438 IRBuilder<> IRB(&I);
1439 Value *A = I.getOperand(0);
1440 Value *B = I.getOperand(1);
1441 Value *Sa = getShadow(A);
1442 Value *Sb = getShadow(B);
1444 // Get rid of pointers and vectors of pointers.
1445 // For ints (and vectors of ints), types of A and Sa match,
1446 // and this is a no-op.
1447 A = IRB.CreatePointerCast(A, Sa->getType());
1448 B = IRB.CreatePointerCast(B, Sb->getType());
1450 // A == B <==> (C = A^B) == 0
1451 // A != B <==> (C = A^B) != 0
1453 Value *C = IRB.CreateXor(A, B);
1454 Value *Sc = IRB.CreateOr(Sa, Sb);
1455 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1456 // Result is defined if one of the following is true
1457 // * there is a defined 1 bit in C
1458 // * C is fully defined
1459 // Si = !(C & ~Sc) && Sc
1460 Value *Zero = Constant::getNullValue(Sc->getType());
1461 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1463 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1465 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1466 Si->setName("_msprop_icmp");
1468 setOriginForNaryOp(I);
1471 /// \brief Build the lowest possible value of V, taking into account V's
1472 /// uninitialized bits.
1473 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1476 // Split shadow into sign bit and other bits.
1477 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1478 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1479 // Maximise the undefined shadow bit, minimize other undefined bits.
1481 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1483 // Minimize undefined bits.
1484 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1488 /// \brief Build the highest possible value of V, taking into account V's
1489 /// uninitialized bits.
1490 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1493 // Split shadow into sign bit and other bits.
1494 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1495 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1496 // Minimise the undefined shadow bit, maximise other undefined bits.
1498 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1500 // Maximize undefined bits.
1501 return IRB.CreateOr(A, Sa);
1505 /// \brief Instrument relational comparisons.
1507 /// This function does exact shadow propagation for all relational
1508 /// comparisons of integers, pointers and vectors of those.
1509 /// FIXME: output seems suboptimal when one of the operands is a constant
1510 void handleRelationalComparisonExact(ICmpInst &I) {
1511 IRBuilder<> IRB(&I);
1512 Value *A = I.getOperand(0);
1513 Value *B = I.getOperand(1);
1514 Value *Sa = getShadow(A);
1515 Value *Sb = getShadow(B);
1517 // Get rid of pointers and vectors of pointers.
1518 // For ints (and vectors of ints), types of A and Sa match,
1519 // and this is a no-op.
1520 A = IRB.CreatePointerCast(A, Sa->getType());
1521 B = IRB.CreatePointerCast(B, Sb->getType());
1523 // Let [a0, a1] be the interval of possible values of A, taking into account
1524 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1525 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1526 bool IsSigned = I.isSigned();
1527 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1528 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1529 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1530 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1531 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1532 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1533 Value *Si = IRB.CreateXor(S1, S2);
1535 setOriginForNaryOp(I);
1538 /// \brief Instrument signed relational comparisons.
1540 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1541 /// propagating the highest bit of the shadow. Everything else is delegated
1542 /// to handleShadowOr().
1543 void handleSignedRelationalComparison(ICmpInst &I) {
1544 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1545 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1546 Value* op = nullptr;
1547 CmpInst::Predicate pre = I.getPredicate();
1548 if (constOp0 && constOp0->isNullValue() &&
1549 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1550 op = I.getOperand(1);
1551 } else if (constOp1 && constOp1->isNullValue() &&
1552 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1553 op = I.getOperand(0);
1556 IRBuilder<> IRB(&I);
1558 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1559 setShadow(&I, Shadow);
1560 setOrigin(&I, getOrigin(op));
1566 void visitICmpInst(ICmpInst &I) {
1567 if (!ClHandleICmp) {
1571 if (I.isEquality()) {
1572 handleEqualityComparison(I);
1576 assert(I.isRelational());
1577 if (ClHandleICmpExact) {
1578 handleRelationalComparisonExact(I);
1582 handleSignedRelationalComparison(I);
1586 assert(I.isUnsigned());
1587 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1588 handleRelationalComparisonExact(I);
1595 void visitFCmpInst(FCmpInst &I) {
1599 void handleShift(BinaryOperator &I) {
1600 IRBuilder<> IRB(&I);
1601 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1602 // Otherwise perform the same shift on S1.
1603 Value *S1 = getShadow(&I, 0);
1604 Value *S2 = getShadow(&I, 1);
1605 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1607 Value *V2 = I.getOperand(1);
1608 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1609 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1610 setOriginForNaryOp(I);
1613 void visitShl(BinaryOperator &I) { handleShift(I); }
1614 void visitAShr(BinaryOperator &I) { handleShift(I); }
1615 void visitLShr(BinaryOperator &I) { handleShift(I); }
1617 /// \brief Instrument llvm.memmove
1619 /// At this point we don't know if llvm.memmove will be inlined or not.
1620 /// If we don't instrument it and it gets inlined,
1621 /// our interceptor will not kick in and we will lose the memmove.
1622 /// If we instrument the call here, but it does not get inlined,
1623 /// we will memove the shadow twice: which is bad in case
1624 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1626 /// Similar situation exists for memcpy and memset.
1627 void visitMemMoveInst(MemMoveInst &I) {
1628 IRBuilder<> IRB(&I);
1631 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1632 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1633 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1634 I.eraseFromParent();
1637 // Similar to memmove: avoid copying shadow twice.
1638 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1639 // FIXME: consider doing manual inline for small constant sizes and proper
1641 void visitMemCpyInst(MemCpyInst &I) {
1642 IRBuilder<> IRB(&I);
1645 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1646 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1647 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1648 I.eraseFromParent();
1652 void visitMemSetInst(MemSetInst &I) {
1653 IRBuilder<> IRB(&I);
1656 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1657 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1658 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1659 I.eraseFromParent();
1662 void visitVAStartInst(VAStartInst &I) {
1663 VAHelper->visitVAStartInst(I);
1666 void visitVACopyInst(VACopyInst &I) {
1667 VAHelper->visitVACopyInst(I);
1670 enum IntrinsicKind {
1671 IK_DoesNotAccessMemory,
1676 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1677 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1678 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1679 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1680 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1681 const int UnknownModRefBehavior = IK_WritesMemory;
1682 #define GET_INTRINSIC_MODREF_BEHAVIOR
1683 #define ModRefBehavior IntrinsicKind
1684 #include "llvm/IR/Intrinsics.gen"
1685 #undef ModRefBehavior
1686 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1689 /// \brief Handle vector store-like intrinsics.
1691 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1692 /// has 1 pointer argument and 1 vector argument, returns void.
1693 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1694 IRBuilder<> IRB(&I);
1695 Value* Addr = I.getArgOperand(0);
1696 Value *Shadow = getShadow(&I, 1);
1697 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1699 // We don't know the pointer alignment (could be unaligned SSE store!).
1700 // Have to assume to worst case.
1701 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1703 if (ClCheckAccessAddress)
1704 insertShadowCheck(Addr, &I);
1706 // FIXME: use ClStoreCleanOrigin
1707 // FIXME: factor out common code from materializeStores
1708 if (MS.TrackOrigins)
1709 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1713 /// \brief Handle vector load-like intrinsics.
1715 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1716 /// has 1 pointer argument, returns a vector.
1717 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1718 IRBuilder<> IRB(&I);
1719 Value *Addr = I.getArgOperand(0);
1721 Type *ShadowTy = getShadowTy(&I);
1722 if (PropagateShadow) {
1723 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1724 // We don't know the pointer alignment (could be unaligned SSE load!).
1725 // Have to assume to worst case.
1726 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1728 setShadow(&I, getCleanShadow(&I));
1731 if (ClCheckAccessAddress)
1732 insertShadowCheck(Addr, &I);
1734 if (MS.TrackOrigins) {
1735 if (PropagateShadow)
1736 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1738 setOrigin(&I, getCleanOrigin());
1743 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1745 /// Instrument intrinsics with any number of arguments of the same type,
1746 /// equal to the return type. The type should be simple (no aggregates or
1747 /// pointers; vectors are fine).
1748 /// Caller guarantees that this intrinsic does not access memory.
1749 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1750 Type *RetTy = I.getType();
1751 if (!(RetTy->isIntOrIntVectorTy() ||
1752 RetTy->isFPOrFPVectorTy() ||
1753 RetTy->isX86_MMXTy()))
1756 unsigned NumArgOperands = I.getNumArgOperands();
1758 for (unsigned i = 0; i < NumArgOperands; ++i) {
1759 Type *Ty = I.getArgOperand(i)->getType();
1764 IRBuilder<> IRB(&I);
1765 ShadowAndOriginCombiner SC(this, IRB);
1766 for (unsigned i = 0; i < NumArgOperands; ++i)
1767 SC.Add(I.getArgOperand(i));
1773 /// \brief Heuristically instrument unknown intrinsics.
1775 /// The main purpose of this code is to do something reasonable with all
1776 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1777 /// We recognize several classes of intrinsics by their argument types and
1778 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1779 /// sure that we know what the intrinsic does.
1781 /// We special-case intrinsics where this approach fails. See llvm.bswap
1782 /// handling as an example of that.
1783 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1784 unsigned NumArgOperands = I.getNumArgOperands();
1785 if (NumArgOperands == 0)
1788 Intrinsic::ID iid = I.getIntrinsicID();
1789 IntrinsicKind IK = getIntrinsicKind(iid);
1790 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1791 bool WritesMemory = IK == IK_WritesMemory;
1792 assert(!(OnlyReadsMemory && WritesMemory));
1794 if (NumArgOperands == 2 &&
1795 I.getArgOperand(0)->getType()->isPointerTy() &&
1796 I.getArgOperand(1)->getType()->isVectorTy() &&
1797 I.getType()->isVoidTy() &&
1799 // This looks like a vector store.
1800 return handleVectorStoreIntrinsic(I);
1803 if (NumArgOperands == 1 &&
1804 I.getArgOperand(0)->getType()->isPointerTy() &&
1805 I.getType()->isVectorTy() &&
1807 // This looks like a vector load.
1808 return handleVectorLoadIntrinsic(I);
1811 if (!OnlyReadsMemory && !WritesMemory)
1812 if (maybeHandleSimpleNomemIntrinsic(I))
1815 // FIXME: detect and handle SSE maskstore/maskload
1819 void handleBswap(IntrinsicInst &I) {
1820 IRBuilder<> IRB(&I);
1821 Value *Op = I.getArgOperand(0);
1822 Type *OpType = Op->getType();
1823 Function *BswapFunc = Intrinsic::getDeclaration(
1824 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
1825 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1826 setOrigin(&I, getOrigin(Op));
1829 // \brief Instrument vector convert instrinsic.
1831 // This function instruments intrinsics like cvtsi2ss:
1832 // %Out = int_xxx_cvtyyy(%ConvertOp)
1834 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1835 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1836 // number \p Out elements, and (if has 2 arguments) copies the rest of the
1837 // elements from \p CopyOp.
1838 // In most cases conversion involves floating-point value which may trigger a
1839 // hardware exception when not fully initialized. For this reason we require
1840 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1841 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1842 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1843 // return a fully initialized value.
1844 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1845 IRBuilder<> IRB(&I);
1846 Value *CopyOp, *ConvertOp;
1848 switch (I.getNumArgOperands()) {
1850 CopyOp = I.getArgOperand(0);
1851 ConvertOp = I.getArgOperand(1);
1854 ConvertOp = I.getArgOperand(0);
1858 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1861 // The first *NumUsedElements* elements of ConvertOp are converted to the
1862 // same number of output elements. The rest of the output is copied from
1863 // CopyOp, or (if not available) filled with zeroes.
1864 // Combine shadow for elements of ConvertOp that are used in this operation,
1865 // and insert a check.
1866 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1867 // int->any conversion.
1868 Value *ConvertShadow = getShadow(ConvertOp);
1869 Value *AggShadow = nullptr;
1870 if (ConvertOp->getType()->isVectorTy()) {
1871 AggShadow = IRB.CreateExtractElement(
1872 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1873 for (int i = 1; i < NumUsedElements; ++i) {
1874 Value *MoreShadow = IRB.CreateExtractElement(
1875 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1876 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1879 AggShadow = ConvertShadow;
1881 assert(AggShadow->getType()->isIntegerTy());
1882 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1884 // Build result shadow by zero-filling parts of CopyOp shadow that come from
1887 assert(CopyOp->getType() == I.getType());
1888 assert(CopyOp->getType()->isVectorTy());
1889 Value *ResultShadow = getShadow(CopyOp);
1890 Type *EltTy = ResultShadow->getType()->getVectorElementType();
1891 for (int i = 0; i < NumUsedElements; ++i) {
1892 ResultShadow = IRB.CreateInsertElement(
1893 ResultShadow, ConstantInt::getNullValue(EltTy),
1894 ConstantInt::get(IRB.getInt32Ty(), i));
1896 setShadow(&I, ResultShadow);
1897 setOrigin(&I, getOrigin(CopyOp));
1899 setShadow(&I, getCleanShadow(&I));
1900 setOrigin(&I, getCleanOrigin());
1904 // Given a scalar or vector, extract lower 64 bits (or less), and return all
1905 // zeroes if it is zero, and all ones otherwise.
1906 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1907 if (S->getType()->isVectorTy())
1908 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1909 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1910 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1911 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1914 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1915 Type *T = S->getType();
1916 assert(T->isVectorTy());
1917 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1918 return IRB.CreateSExt(S2, T);
1921 // \brief Instrument vector shift instrinsic.
1923 // This function instruments intrinsics like int_x86_avx2_psll_w.
1924 // Intrinsic shifts %In by %ShiftSize bits.
1925 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
1926 // size, and the rest is ignored. Behavior is defined even if shift size is
1927 // greater than register (or field) width.
1928 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
1929 assert(I.getNumArgOperands() == 2);
1930 IRBuilder<> IRB(&I);
1931 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1932 // Otherwise perform the same shift on S1.
1933 Value *S1 = getShadow(&I, 0);
1934 Value *S2 = getShadow(&I, 1);
1935 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
1936 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
1937 Value *V1 = I.getOperand(0);
1938 Value *V2 = I.getOperand(1);
1939 Value *Shift = IRB.CreateCall2(I.getCalledValue(),
1940 IRB.CreateBitCast(S1, V1->getType()), V2);
1941 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
1942 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1943 setOriginForNaryOp(I);
1946 // \brief Get an X86_MMX-sized vector type.
1947 Type *getMMXVectorTy(unsigned EltSizeInBits) {
1948 const unsigned X86_MMXSizeInBits = 64;
1949 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
1950 X86_MMXSizeInBits / EltSizeInBits);
1953 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
1955 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
1957 case llvm::Intrinsic::x86_sse2_packsswb_128:
1958 case llvm::Intrinsic::x86_sse2_packuswb_128:
1959 return llvm::Intrinsic::x86_sse2_packsswb_128;
1961 case llvm::Intrinsic::x86_sse2_packssdw_128:
1962 case llvm::Intrinsic::x86_sse41_packusdw:
1963 return llvm::Intrinsic::x86_sse2_packssdw_128;
1965 case llvm::Intrinsic::x86_avx2_packsswb:
1966 case llvm::Intrinsic::x86_avx2_packuswb:
1967 return llvm::Intrinsic::x86_avx2_packsswb;
1969 case llvm::Intrinsic::x86_avx2_packssdw:
1970 case llvm::Intrinsic::x86_avx2_packusdw:
1971 return llvm::Intrinsic::x86_avx2_packssdw;
1973 case llvm::Intrinsic::x86_mmx_packsswb:
1974 case llvm::Intrinsic::x86_mmx_packuswb:
1975 return llvm::Intrinsic::x86_mmx_packsswb;
1977 case llvm::Intrinsic::x86_mmx_packssdw:
1978 return llvm::Intrinsic::x86_mmx_packssdw;
1980 llvm_unreachable("unexpected intrinsic id");
1984 // \brief Instrument vector pack instrinsic.
1986 // This function instruments intrinsics like x86_mmx_packsswb, that
1987 // packs elements of 2 input vectors into half as many bits with saturation.
1988 // Shadow is propagated with the signed variant of the same intrinsic applied
1989 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
1990 // EltSizeInBits is used only for x86mmx arguments.
1991 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
1992 assert(I.getNumArgOperands() == 2);
1993 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
1994 IRBuilder<> IRB(&I);
1995 Value *S1 = getShadow(&I, 0);
1996 Value *S2 = getShadow(&I, 1);
1997 assert(isX86_MMX || S1->getType()->isVectorTy());
1999 // SExt and ICmpNE below must apply to individual elements of input vectors.
2000 // In case of x86mmx arguments, cast them to appropriate vector types and
2002 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2004 S1 = IRB.CreateBitCast(S1, T);
2005 S2 = IRB.CreateBitCast(S2, T);
2007 Value *S1_ext = IRB.CreateSExt(
2008 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2009 Value *S2_ext = IRB.CreateSExt(
2010 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2012 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2013 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2014 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2017 Function *ShadowFn = Intrinsic::getDeclaration(
2018 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2020 Value *S = IRB.CreateCall2(ShadowFn, S1_ext, S2_ext, "_msprop_vector_pack");
2021 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2023 setOriginForNaryOp(I);
2026 // \brief Instrument sum-of-absolute-differencies intrinsic.
2027 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2028 const unsigned SignificantBitsPerResultElement = 16;
2029 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2030 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2031 unsigned ZeroBitsPerResultElement =
2032 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2034 IRBuilder<> IRB(&I);
2035 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2036 S = IRB.CreateBitCast(S, ResTy);
2037 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2039 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2040 S = IRB.CreateBitCast(S, getShadowTy(&I));
2042 setOriginForNaryOp(I);
2045 // \brief Instrument multiply-add intrinsic.
2046 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2047 unsigned EltSizeInBits = 0) {
2048 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2049 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2050 IRBuilder<> IRB(&I);
2051 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2052 S = IRB.CreateBitCast(S, ResTy);
2053 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2055 S = IRB.CreateBitCast(S, getShadowTy(&I));
2057 setOriginForNaryOp(I);
2060 void visitIntrinsicInst(IntrinsicInst &I) {
2061 switch (I.getIntrinsicID()) {
2062 case llvm::Intrinsic::bswap:
2065 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2066 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2067 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2068 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2069 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2070 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2071 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2072 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2073 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2074 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2075 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2076 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2077 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2078 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2079 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2080 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2081 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2082 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2083 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2084 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2085 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2086 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2087 case llvm::Intrinsic::x86_sse_cvtss2si64:
2088 case llvm::Intrinsic::x86_sse_cvtss2si:
2089 case llvm::Intrinsic::x86_sse_cvttss2si64:
2090 case llvm::Intrinsic::x86_sse_cvttss2si:
2091 handleVectorConvertIntrinsic(I, 1);
2093 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2094 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2095 case llvm::Intrinsic::x86_sse_cvtps2pi:
2096 case llvm::Intrinsic::x86_sse_cvttps2pi:
2097 handleVectorConvertIntrinsic(I, 2);
2099 case llvm::Intrinsic::x86_avx512_psll_dq:
2100 case llvm::Intrinsic::x86_avx512_psrl_dq:
2101 case llvm::Intrinsic::x86_avx2_psll_w:
2102 case llvm::Intrinsic::x86_avx2_psll_d:
2103 case llvm::Intrinsic::x86_avx2_psll_q:
2104 case llvm::Intrinsic::x86_avx2_pslli_w:
2105 case llvm::Intrinsic::x86_avx2_pslli_d:
2106 case llvm::Intrinsic::x86_avx2_pslli_q:
2107 case llvm::Intrinsic::x86_avx2_psll_dq:
2108 case llvm::Intrinsic::x86_avx2_psrl_w:
2109 case llvm::Intrinsic::x86_avx2_psrl_d:
2110 case llvm::Intrinsic::x86_avx2_psrl_q:
2111 case llvm::Intrinsic::x86_avx2_psra_w:
2112 case llvm::Intrinsic::x86_avx2_psra_d:
2113 case llvm::Intrinsic::x86_avx2_psrli_w:
2114 case llvm::Intrinsic::x86_avx2_psrli_d:
2115 case llvm::Intrinsic::x86_avx2_psrli_q:
2116 case llvm::Intrinsic::x86_avx2_psrai_w:
2117 case llvm::Intrinsic::x86_avx2_psrai_d:
2118 case llvm::Intrinsic::x86_avx2_psrl_dq:
2119 case llvm::Intrinsic::x86_sse2_psll_w:
2120 case llvm::Intrinsic::x86_sse2_psll_d:
2121 case llvm::Intrinsic::x86_sse2_psll_q:
2122 case llvm::Intrinsic::x86_sse2_pslli_w:
2123 case llvm::Intrinsic::x86_sse2_pslli_d:
2124 case llvm::Intrinsic::x86_sse2_pslli_q:
2125 case llvm::Intrinsic::x86_sse2_psll_dq:
2126 case llvm::Intrinsic::x86_sse2_psrl_w:
2127 case llvm::Intrinsic::x86_sse2_psrl_d:
2128 case llvm::Intrinsic::x86_sse2_psrl_q:
2129 case llvm::Intrinsic::x86_sse2_psra_w:
2130 case llvm::Intrinsic::x86_sse2_psra_d:
2131 case llvm::Intrinsic::x86_sse2_psrli_w:
2132 case llvm::Intrinsic::x86_sse2_psrli_d:
2133 case llvm::Intrinsic::x86_sse2_psrli_q:
2134 case llvm::Intrinsic::x86_sse2_psrai_w:
2135 case llvm::Intrinsic::x86_sse2_psrai_d:
2136 case llvm::Intrinsic::x86_sse2_psrl_dq:
2137 case llvm::Intrinsic::x86_mmx_psll_w:
2138 case llvm::Intrinsic::x86_mmx_psll_d:
2139 case llvm::Intrinsic::x86_mmx_psll_q:
2140 case llvm::Intrinsic::x86_mmx_pslli_w:
2141 case llvm::Intrinsic::x86_mmx_pslli_d:
2142 case llvm::Intrinsic::x86_mmx_pslli_q:
2143 case llvm::Intrinsic::x86_mmx_psrl_w:
2144 case llvm::Intrinsic::x86_mmx_psrl_d:
2145 case llvm::Intrinsic::x86_mmx_psrl_q:
2146 case llvm::Intrinsic::x86_mmx_psra_w:
2147 case llvm::Intrinsic::x86_mmx_psra_d:
2148 case llvm::Intrinsic::x86_mmx_psrli_w:
2149 case llvm::Intrinsic::x86_mmx_psrli_d:
2150 case llvm::Intrinsic::x86_mmx_psrli_q:
2151 case llvm::Intrinsic::x86_mmx_psrai_w:
2152 case llvm::Intrinsic::x86_mmx_psrai_d:
2153 handleVectorShiftIntrinsic(I, /* Variable */ false);
2155 case llvm::Intrinsic::x86_avx2_psllv_d:
2156 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2157 case llvm::Intrinsic::x86_avx2_psllv_q:
2158 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2159 case llvm::Intrinsic::x86_avx2_psrlv_d:
2160 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2161 case llvm::Intrinsic::x86_avx2_psrlv_q:
2162 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2163 case llvm::Intrinsic::x86_avx2_psrav_d:
2164 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2165 handleVectorShiftIntrinsic(I, /* Variable */ true);
2168 // Byte shifts are not implemented.
2169 // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
2170 // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
2171 // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
2172 // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
2173 // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
2174 // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
2176 case llvm::Intrinsic::x86_sse2_packsswb_128:
2177 case llvm::Intrinsic::x86_sse2_packssdw_128:
2178 case llvm::Intrinsic::x86_sse2_packuswb_128:
2179 case llvm::Intrinsic::x86_sse41_packusdw:
2180 case llvm::Intrinsic::x86_avx2_packsswb:
2181 case llvm::Intrinsic::x86_avx2_packssdw:
2182 case llvm::Intrinsic::x86_avx2_packuswb:
2183 case llvm::Intrinsic::x86_avx2_packusdw:
2184 handleVectorPackIntrinsic(I);
2187 case llvm::Intrinsic::x86_mmx_packsswb:
2188 case llvm::Intrinsic::x86_mmx_packuswb:
2189 handleVectorPackIntrinsic(I, 16);
2192 case llvm::Intrinsic::x86_mmx_packssdw:
2193 handleVectorPackIntrinsic(I, 32);
2196 case llvm::Intrinsic::x86_mmx_psad_bw:
2197 case llvm::Intrinsic::x86_sse2_psad_bw:
2198 case llvm::Intrinsic::x86_avx2_psad_bw:
2199 handleVectorSadIntrinsic(I);
2202 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2203 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2204 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2205 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2206 handleVectorPmaddIntrinsic(I);
2209 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2210 handleVectorPmaddIntrinsic(I, 8);
2213 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2214 handleVectorPmaddIntrinsic(I, 16);
2218 if (!handleUnknownIntrinsic(I))
2219 visitInstruction(I);
2224 void visitCallSite(CallSite CS) {
2225 Instruction &I = *CS.getInstruction();
2226 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2228 CallInst *Call = cast<CallInst>(&I);
2230 // For inline asm, do the usual thing: check argument shadow and mark all
2231 // outputs as clean. Note that any side effects of the inline asm that are
2232 // not immediately visible in its constraints are not handled.
2233 if (Call->isInlineAsm()) {
2234 visitInstruction(I);
2238 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2240 // We are going to insert code that relies on the fact that the callee
2241 // will become a non-readonly function after it is instrumented by us. To
2242 // prevent this code from being optimized out, mark that function
2243 // non-readonly in advance.
2244 if (Function *Func = Call->getCalledFunction()) {
2245 // Clear out readonly/readnone attributes.
2247 B.addAttribute(Attribute::ReadOnly)
2248 .addAttribute(Attribute::ReadNone);
2249 Func->removeAttributes(AttributeSet::FunctionIndex,
2250 AttributeSet::get(Func->getContext(),
2251 AttributeSet::FunctionIndex,
2255 IRBuilder<> IRB(&I);
2257 unsigned ArgOffset = 0;
2258 DEBUG(dbgs() << " CallSite: " << I << "\n");
2259 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2260 ArgIt != End; ++ArgIt) {
2262 unsigned i = ArgIt - CS.arg_begin();
2263 if (!A->getType()->isSized()) {
2264 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2268 Value *Store = nullptr;
2269 // Compute the Shadow for arg even if it is ByVal, because
2270 // in that case getShadow() will copy the actual arg shadow to
2271 // __msan_param_tls.
2272 Value *ArgShadow = getShadow(A);
2273 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2274 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2275 " Shadow: " << *ArgShadow << "\n");
2276 bool ArgIsInitialized = false;
2277 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2278 assert(A->getType()->isPointerTy() &&
2279 "ByVal argument is not a pointer!");
2280 Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
2281 if (ArgOffset + Size > kParamTLSSize) break;
2282 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2283 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2284 Store = IRB.CreateMemCpy(ArgShadowBase,
2285 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2288 Size = MS.DL->getTypeAllocSize(A->getType());
2289 if (ArgOffset + Size > kParamTLSSize) break;
2290 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2291 kShadowTLSAlignment);
2292 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2293 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2295 if (MS.TrackOrigins && !ArgIsInitialized)
2296 IRB.CreateStore(getOrigin(A),
2297 getOriginPtrForArgument(A, IRB, ArgOffset));
2299 assert(Size != 0 && Store != nullptr);
2300 DEBUG(dbgs() << " Param:" << *Store << "\n");
2301 ArgOffset += RoundUpToAlignment(Size, 8);
2303 DEBUG(dbgs() << " done with call args\n");
2306 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2307 if (FT->isVarArg()) {
2308 VAHelper->visitCallSite(CS, IRB);
2311 // Now, get the shadow for the RetVal.
2312 if (!I.getType()->isSized()) return;
2313 IRBuilder<> IRBBefore(&I);
2314 // Until we have full dynamic coverage, make sure the retval shadow is 0.
2315 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2316 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2317 Instruction *NextInsn = nullptr;
2319 NextInsn = I.getNextNode();
2321 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2322 if (!NormalDest->getSinglePredecessor()) {
2323 // FIXME: this case is tricky, so we are just conservative here.
2324 // Perhaps we need to split the edge between this BB and NormalDest,
2325 // but a naive attempt to use SplitEdge leads to a crash.
2326 setShadow(&I, getCleanShadow(&I));
2327 setOrigin(&I, getCleanOrigin());
2330 NextInsn = NormalDest->getFirstInsertionPt();
2332 "Could not find insertion point for retval shadow load");
2334 IRBuilder<> IRBAfter(NextInsn);
2335 Value *RetvalShadow =
2336 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2337 kShadowTLSAlignment, "_msret");
2338 setShadow(&I, RetvalShadow);
2339 if (MS.TrackOrigins)
2340 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2343 void visitReturnInst(ReturnInst &I) {
2344 IRBuilder<> IRB(&I);
2345 Value *RetVal = I.getReturnValue();
2346 if (!RetVal) return;
2347 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2348 if (CheckReturnValue) {
2349 insertShadowCheck(RetVal, &I);
2350 Value *Shadow = getCleanShadow(RetVal);
2351 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2353 Value *Shadow = getShadow(RetVal);
2354 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2355 // FIXME: make it conditional if ClStoreCleanOrigin==0
2356 if (MS.TrackOrigins)
2357 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2361 void visitPHINode(PHINode &I) {
2362 IRBuilder<> IRB(&I);
2363 if (!PropagateShadow) {
2364 setShadow(&I, getCleanShadow(&I));
2365 setOrigin(&I, getCleanOrigin());
2369 ShadowPHINodes.push_back(&I);
2370 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2372 if (MS.TrackOrigins)
2373 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2377 void visitAllocaInst(AllocaInst &I) {
2378 setShadow(&I, getCleanShadow(&I));
2379 setOrigin(&I, getCleanOrigin());
2380 IRBuilder<> IRB(I.getNextNode());
2381 uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
2382 if (PoisonStack && ClPoisonStackWithCall) {
2383 IRB.CreateCall2(MS.MsanPoisonStackFn,
2384 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2385 ConstantInt::get(MS.IntptrTy, Size));
2387 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2388 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2389 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2392 if (PoisonStack && MS.TrackOrigins) {
2393 SmallString<2048> StackDescriptionStorage;
2394 raw_svector_ostream StackDescription(StackDescriptionStorage);
2395 // We create a string with a description of the stack allocation and
2396 // pass it into __msan_set_alloca_origin.
2397 // It will be printed by the run-time if stack-originated UMR is found.
2398 // The first 4 bytes of the string are set to '----' and will be replaced
2399 // by __msan_va_arg_overflow_size_tls at the first call.
2400 StackDescription << "----" << I.getName() << "@" << F.getName();
2402 createPrivateNonConstGlobalForString(*F.getParent(),
2403 StackDescription.str());
2405 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
2406 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2407 ConstantInt::get(MS.IntptrTy, Size),
2408 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2409 IRB.CreatePointerCast(&F, MS.IntptrTy));
2413 void visitSelectInst(SelectInst& I) {
2414 IRBuilder<> IRB(&I);
2415 // a = select b, c, d
2416 Value *B = I.getCondition();
2417 Value *C = I.getTrueValue();
2418 Value *D = I.getFalseValue();
2419 Value *Sb = getShadow(B);
2420 Value *Sc = getShadow(C);
2421 Value *Sd = getShadow(D);
2423 // Result shadow if condition shadow is 0.
2424 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2426 if (I.getType()->isAggregateType()) {
2427 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2428 // an extra "select". This results in much more compact IR.
2429 // Sa = select Sb, poisoned, (select b, Sc, Sd)
2430 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2432 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2433 // If Sb (condition is poisoned), look for bits in c and d that are equal
2434 // and both unpoisoned.
2435 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2437 // Cast arguments to shadow-compatible type.
2438 C = CreateAppToShadowCast(IRB, C);
2439 D = CreateAppToShadowCast(IRB, D);
2441 // Result shadow if condition shadow is 1.
2442 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2444 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2446 if (MS.TrackOrigins) {
2447 // Origins are always i32, so any vector conditions must be flattened.
2448 // FIXME: consider tracking vector origins for app vectors?
2449 if (B->getType()->isVectorTy()) {
2450 Type *FlatTy = getShadowTyNoVec(B->getType());
2451 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2452 ConstantInt::getNullValue(FlatTy));
2453 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2454 ConstantInt::getNullValue(FlatTy));
2456 // a = select b, c, d
2457 // Oa = Sb ? Ob : (b ? Oc : Od)
2459 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2460 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2461 getOrigin(I.getFalseValue()))));
2465 void visitLandingPadInst(LandingPadInst &I) {
2467 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2468 setShadow(&I, getCleanShadow(&I));
2469 setOrigin(&I, getCleanOrigin());
2472 void visitGetElementPtrInst(GetElementPtrInst &I) {
2476 void visitExtractValueInst(ExtractValueInst &I) {
2477 IRBuilder<> IRB(&I);
2478 Value *Agg = I.getAggregateOperand();
2479 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2480 Value *AggShadow = getShadow(Agg);
2481 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2482 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2483 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2484 setShadow(&I, ResShadow);
2485 setOriginForNaryOp(I);
2488 void visitInsertValueInst(InsertValueInst &I) {
2489 IRBuilder<> IRB(&I);
2490 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2491 Value *AggShadow = getShadow(I.getAggregateOperand());
2492 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2493 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2494 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2495 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2496 DEBUG(dbgs() << " Res: " << *Res << "\n");
2498 setOriginForNaryOp(I);
2501 void dumpInst(Instruction &I) {
2502 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2503 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2505 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2507 errs() << "QQQ " << I << "\n";
2510 void visitResumeInst(ResumeInst &I) {
2511 DEBUG(dbgs() << "Resume: " << I << "\n");
2512 // Nothing to do here.
2515 void visitInstruction(Instruction &I) {
2516 // Everything else: stop propagating and check for poisoned shadow.
2517 if (ClDumpStrictInstructions)
2519 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2520 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2521 insertShadowCheck(I.getOperand(i), &I);
2522 setShadow(&I, getCleanShadow(&I));
2523 setOrigin(&I, getCleanOrigin());
2527 /// \brief AMD64-specific implementation of VarArgHelper.
2528 struct VarArgAMD64Helper : public VarArgHelper {
2529 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2530 // See a comment in visitCallSite for more details.
2531 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
2532 static const unsigned AMD64FpEndOffset = 176;
2535 MemorySanitizer &MS;
2536 MemorySanitizerVisitor &MSV;
2537 Value *VAArgTLSCopy;
2538 Value *VAArgOverflowSize;
2540 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2542 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2543 MemorySanitizerVisitor &MSV)
2544 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2545 VAArgOverflowSize(nullptr) {}
2547 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2549 ArgKind classifyArgument(Value* arg) {
2550 // A very rough approximation of X86_64 argument classification rules.
2551 Type *T = arg->getType();
2552 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2553 return AK_FloatingPoint;
2554 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2555 return AK_GeneralPurpose;
2556 if (T->isPointerTy())
2557 return AK_GeneralPurpose;
2561 // For VarArg functions, store the argument shadow in an ABI-specific format
2562 // that corresponds to va_list layout.
2563 // We do this because Clang lowers va_arg in the frontend, and this pass
2564 // only sees the low level code that deals with va_list internals.
2565 // A much easier alternative (provided that Clang emits va_arg instructions)
2566 // would have been to associate each live instance of va_list with a copy of
2567 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2569 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2570 unsigned GpOffset = 0;
2571 unsigned FpOffset = AMD64GpEndOffset;
2572 unsigned OverflowOffset = AMD64FpEndOffset;
2573 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2574 ArgIt != End; ++ArgIt) {
2576 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2577 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2579 // ByVal arguments always go to the overflow area.
2580 assert(A->getType()->isPointerTy());
2581 Type *RealTy = A->getType()->getPointerElementType();
2582 uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2583 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2584 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2585 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2586 ArgSize, kShadowTLSAlignment);
2588 ArgKind AK = classifyArgument(A);
2589 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2591 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2595 case AK_GeneralPurpose:
2596 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2599 case AK_FloatingPoint:
2600 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2604 uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2605 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2606 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2608 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2611 Constant *OverflowSize =
2612 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2613 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2616 /// \brief Compute the shadow address for a given va_arg.
2617 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2619 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2620 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2621 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2625 void visitVAStartInst(VAStartInst &I) override {
2626 IRBuilder<> IRB(&I);
2627 VAStartInstrumentationList.push_back(&I);
2628 Value *VAListTag = I.getArgOperand(0);
2629 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2631 // Unpoison the whole __va_list_tag.
2632 // FIXME: magic ABI constants.
2633 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2634 /* size */24, /* alignment */8, false);
2637 void visitVACopyInst(VACopyInst &I) override {
2638 IRBuilder<> IRB(&I);
2639 Value *VAListTag = I.getArgOperand(0);
2640 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2642 // Unpoison the whole __va_list_tag.
2643 // FIXME: magic ABI constants.
2644 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2645 /* size */24, /* alignment */8, false);
2648 void finalizeInstrumentation() override {
2649 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2650 "finalizeInstrumentation called twice");
2651 if (!VAStartInstrumentationList.empty()) {
2652 // If there is a va_start in this function, make a backup copy of
2653 // va_arg_tls somewhere in the function entry block.
2654 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2655 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2657 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2659 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2660 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2663 // Instrument va_start.
2664 // Copy va_list shadow from the backup copy of the TLS contents.
2665 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2666 CallInst *OrigInst = VAStartInstrumentationList[i];
2667 IRBuilder<> IRB(OrigInst->getNextNode());
2668 Value *VAListTag = OrigInst->getArgOperand(0);
2670 Value *RegSaveAreaPtrPtr =
2672 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2673 ConstantInt::get(MS.IntptrTy, 16)),
2674 Type::getInt64PtrTy(*MS.C));
2675 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2676 Value *RegSaveAreaShadowPtr =
2677 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2678 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2679 AMD64FpEndOffset, 16);
2681 Value *OverflowArgAreaPtrPtr =
2683 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2684 ConstantInt::get(MS.IntptrTy, 8)),
2685 Type::getInt64PtrTy(*MS.C));
2686 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2687 Value *OverflowArgAreaShadowPtr =
2688 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2689 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2690 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2695 /// \brief A no-op implementation of VarArgHelper.
2696 struct VarArgNoOpHelper : public VarArgHelper {
2697 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2698 MemorySanitizerVisitor &MSV) {}
2700 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
2702 void visitVAStartInst(VAStartInst &I) override {}
2704 void visitVACopyInst(VACopyInst &I) override {}
2706 void finalizeInstrumentation() override {}
2709 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2710 MemorySanitizerVisitor &Visitor) {
2711 // VarArg handling is only implemented on AMD64. False positives are possible
2712 // on other platforms.
2713 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2714 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2715 return new VarArgAMD64Helper(Func, Msan, Visitor);
2717 return new VarArgNoOpHelper(Func, Msan, Visitor);
2722 bool MemorySanitizer::runOnFunction(Function &F) {
2723 MemorySanitizerVisitor Visitor(F, *this);
2725 // Clear out readonly/readnone attributes.
2727 B.addAttribute(Attribute::ReadOnly)
2728 .addAttribute(Attribute::ReadNone);
2729 F.removeAttributes(AttributeSet::FunctionIndex,
2730 AttributeSet::get(F.getContext(),
2731 AttributeSet::FunctionIndex, B));
2733 return Visitor.runOnFunction();