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));
926 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
928 assert(*ShadowPtr && "Could not find shadow for an argument");
931 // For everything else the shadow is zero.
932 return getCleanShadow(V);
935 /// \brief Get the shadow for i-th argument of the instruction I.
936 Value *getShadow(Instruction *I, int i) {
937 return getShadow(I->getOperand(i));
940 /// \brief Get the origin for a value.
941 Value *getOrigin(Value *V) {
942 if (!MS.TrackOrigins) return nullptr;
943 if (isa<Instruction>(V) || isa<Argument>(V)) {
944 Value *Origin = OriginMap[V];
946 DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
947 Origin = getCleanOrigin();
951 return getCleanOrigin();
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) {
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));
1093 void visitAtomicRMWInst(AtomicRMWInst &I) {
1095 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1098 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1100 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1103 // Vector manipulation.
1104 void visitExtractElementInst(ExtractElementInst &I) {
1105 insertShadowCheck(I.getOperand(1), &I);
1106 IRBuilder<> IRB(&I);
1107 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1109 setOrigin(&I, getOrigin(&I, 0));
1112 void visitInsertElementInst(InsertElementInst &I) {
1113 insertShadowCheck(I.getOperand(2), &I);
1114 IRBuilder<> IRB(&I);
1115 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1116 I.getOperand(2), "_msprop"));
1117 setOriginForNaryOp(I);
1120 void visitShuffleVectorInst(ShuffleVectorInst &I) {
1121 insertShadowCheck(I.getOperand(2), &I);
1122 IRBuilder<> IRB(&I);
1123 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1124 I.getOperand(2), "_msprop"));
1125 setOriginForNaryOp(I);
1129 void visitSExtInst(SExtInst &I) {
1130 IRBuilder<> IRB(&I);
1131 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1132 setOrigin(&I, getOrigin(&I, 0));
1135 void visitZExtInst(ZExtInst &I) {
1136 IRBuilder<> IRB(&I);
1137 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1138 setOrigin(&I, getOrigin(&I, 0));
1141 void visitTruncInst(TruncInst &I) {
1142 IRBuilder<> IRB(&I);
1143 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1144 setOrigin(&I, getOrigin(&I, 0));
1147 void visitBitCastInst(BitCastInst &I) {
1148 IRBuilder<> IRB(&I);
1149 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1150 setOrigin(&I, getOrigin(&I, 0));
1153 void visitPtrToIntInst(PtrToIntInst &I) {
1154 IRBuilder<> IRB(&I);
1155 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1156 "_msprop_ptrtoint"));
1157 setOrigin(&I, getOrigin(&I, 0));
1160 void visitIntToPtrInst(IntToPtrInst &I) {
1161 IRBuilder<> IRB(&I);
1162 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1163 "_msprop_inttoptr"));
1164 setOrigin(&I, getOrigin(&I, 0));
1167 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1168 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1169 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1170 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1171 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1172 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1174 /// \brief Propagate shadow for bitwise AND.
1176 /// This code is exact, i.e. if, for example, a bit in the left argument
1177 /// is defined and 0, then neither the value not definedness of the
1178 /// corresponding bit in B don't affect the resulting shadow.
1179 void visitAnd(BinaryOperator &I) {
1180 IRBuilder<> IRB(&I);
1181 // "And" of 0 and a poisoned value results in unpoisoned value.
1182 // 1&1 => 1; 0&1 => 0; p&1 => p;
1183 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1184 // 1&p => p; 0&p => 0; p&p => p;
1185 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1186 Value *S1 = getShadow(&I, 0);
1187 Value *S2 = getShadow(&I, 1);
1188 Value *V1 = I.getOperand(0);
1189 Value *V2 = I.getOperand(1);
1190 if (V1->getType() != S1->getType()) {
1191 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1192 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1194 Value *S1S2 = IRB.CreateAnd(S1, S2);
1195 Value *V1S2 = IRB.CreateAnd(V1, S2);
1196 Value *S1V2 = IRB.CreateAnd(S1, V2);
1197 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1198 setOriginForNaryOp(I);
1201 void visitOr(BinaryOperator &I) {
1202 IRBuilder<> IRB(&I);
1203 // "Or" of 1 and a poisoned value results in unpoisoned value.
1204 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1205 // 1|0 => 1; 0|0 => 0; p|0 => p;
1206 // 1|p => 1; 0|p => p; p|p => p;
1207 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1208 Value *S1 = getShadow(&I, 0);
1209 Value *S2 = getShadow(&I, 1);
1210 Value *V1 = IRB.CreateNot(I.getOperand(0));
1211 Value *V2 = IRB.CreateNot(I.getOperand(1));
1212 if (V1->getType() != S1->getType()) {
1213 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1214 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1216 Value *S1S2 = IRB.CreateAnd(S1, S2);
1217 Value *V1S2 = IRB.CreateAnd(V1, S2);
1218 Value *S1V2 = IRB.CreateAnd(S1, V2);
1219 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1220 setOriginForNaryOp(I);
1223 /// \brief Default propagation of shadow and/or origin.
1225 /// This class implements the general case of shadow propagation, used in all
1226 /// cases where we don't know and/or don't care about what the operation
1227 /// actually does. It converts all input shadow values to a common type
1228 /// (extending or truncating as necessary), and bitwise OR's them.
1230 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1231 /// fully initialized), and less prone to false positives.
1233 /// This class also implements the general case of origin propagation. For a
1234 /// Nary operation, result origin is set to the origin of an argument that is
1235 /// not entirely initialized. If there is more than one such arguments, the
1236 /// rightmost of them is picked. It does not matter which one is picked if all
1237 /// arguments are initialized.
1238 template <bool CombineShadow>
1243 MemorySanitizerVisitor *MSV;
1246 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1247 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1249 /// \brief Add a pair of shadow and origin values to the mix.
1250 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1251 if (CombineShadow) {
1256 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1257 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1261 if (MSV->MS.TrackOrigins) {
1266 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1267 // No point in adding something that might result in 0 origin value.
1268 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1269 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1271 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1272 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1279 /// \brief Add an application value to the mix.
1280 Combiner &Add(Value *V) {
1281 Value *OpShadow = MSV->getShadow(V);
1282 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1283 return Add(OpShadow, OpOrigin);
1286 /// \brief Set the current combined values as the given instruction's shadow
1288 void Done(Instruction *I) {
1289 if (CombineShadow) {
1291 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1292 MSV->setShadow(I, Shadow);
1294 if (MSV->MS.TrackOrigins) {
1296 MSV->setOrigin(I, Origin);
1301 typedef Combiner<true> ShadowAndOriginCombiner;
1302 typedef Combiner<false> OriginCombiner;
1304 /// \brief Propagate origin for arbitrary operation.
1305 void setOriginForNaryOp(Instruction &I) {
1306 if (!MS.TrackOrigins) return;
1307 IRBuilder<> IRB(&I);
1308 OriginCombiner OC(this, IRB);
1309 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1314 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1315 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1316 "Vector of pointers is not a valid shadow type");
1317 return Ty->isVectorTy() ?
1318 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1319 Ty->getPrimitiveSizeInBits();
1322 /// \brief Cast between two shadow types, extending or truncating as
1324 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1325 bool Signed = false) {
1326 Type *srcTy = V->getType();
1327 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1328 return IRB.CreateIntCast(V, dstTy, Signed);
1329 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1330 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1331 return IRB.CreateIntCast(V, dstTy, Signed);
1332 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1333 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1334 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1336 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1337 return IRB.CreateBitCast(V2, dstTy);
1338 // TODO: handle struct types.
1341 /// \brief Cast an application value to the type of its own shadow.
1342 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1343 Type *ShadowTy = getShadowTy(V);
1344 if (V->getType() == ShadowTy)
1346 if (V->getType()->isPtrOrPtrVectorTy())
1347 return IRB.CreatePtrToInt(V, ShadowTy);
1349 return IRB.CreateBitCast(V, ShadowTy);
1352 /// \brief Propagate shadow for arbitrary operation.
1353 void handleShadowOr(Instruction &I) {
1354 IRBuilder<> IRB(&I);
1355 ShadowAndOriginCombiner SC(this, IRB);
1356 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1361 // \brief Handle multiplication by constant.
1363 // Handle a special case of multiplication by constant that may have one or
1364 // more zeros in the lower bits. This makes corresponding number of lower bits
1365 // of the result zero as well. We model it by shifting the other operand
1366 // shadow left by the required number of bits. Effectively, we transform
1367 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1368 // We use multiplication by 2**N instead of shift to cover the case of
1369 // multiplication by 0, which may occur in some elements of a vector operand.
1370 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1372 Constant *ShadowMul;
1373 Type *Ty = ConstArg->getType();
1374 if (Ty->isVectorTy()) {
1375 unsigned NumElements = Ty->getVectorNumElements();
1376 Type *EltTy = Ty->getSequentialElementType();
1377 SmallVector<Constant *, 16> Elements;
1378 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1380 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1381 APInt V = Elt->getValue();
1382 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1383 Elements.push_back(ConstantInt::get(EltTy, V2));
1385 ShadowMul = ConstantVector::get(Elements);
1387 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1388 APInt V = Elt->getValue();
1389 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1390 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1393 IRBuilder<> IRB(&I);
1395 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1396 setOrigin(&I, getOrigin(OtherArg));
1399 void visitMul(BinaryOperator &I) {
1400 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1401 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1402 if (constOp0 && !constOp1)
1403 handleMulByConstant(I, constOp0, I.getOperand(1));
1404 else if (constOp1 && !constOp0)
1405 handleMulByConstant(I, constOp1, I.getOperand(0));
1410 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1411 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1412 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1413 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1414 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1415 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1417 void handleDiv(Instruction &I) {
1418 IRBuilder<> IRB(&I);
1419 // Strict on the second argument.
1420 insertShadowCheck(I.getOperand(1), &I);
1421 setShadow(&I, getShadow(&I, 0));
1422 setOrigin(&I, getOrigin(&I, 0));
1425 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1426 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1427 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1428 void visitURem(BinaryOperator &I) { handleDiv(I); }
1429 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1430 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1432 /// \brief Instrument == and != comparisons.
1434 /// Sometimes the comparison result is known even if some of the bits of the
1435 /// arguments are not.
1436 void handleEqualityComparison(ICmpInst &I) {
1437 IRBuilder<> IRB(&I);
1438 Value *A = I.getOperand(0);
1439 Value *B = I.getOperand(1);
1440 Value *Sa = getShadow(A);
1441 Value *Sb = getShadow(B);
1443 // Get rid of pointers and vectors of pointers.
1444 // For ints (and vectors of ints), types of A and Sa match,
1445 // and this is a no-op.
1446 A = IRB.CreatePointerCast(A, Sa->getType());
1447 B = IRB.CreatePointerCast(B, Sb->getType());
1449 // A == B <==> (C = A^B) == 0
1450 // A != B <==> (C = A^B) != 0
1452 Value *C = IRB.CreateXor(A, B);
1453 Value *Sc = IRB.CreateOr(Sa, Sb);
1454 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1455 // Result is defined if one of the following is true
1456 // * there is a defined 1 bit in C
1457 // * C is fully defined
1458 // Si = !(C & ~Sc) && Sc
1459 Value *Zero = Constant::getNullValue(Sc->getType());
1460 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1462 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1464 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1465 Si->setName("_msprop_icmp");
1467 setOriginForNaryOp(I);
1470 /// \brief Build the lowest possible value of V, taking into account V's
1471 /// uninitialized bits.
1472 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1475 // Split shadow into sign bit and other bits.
1476 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1477 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1478 // Maximise the undefined shadow bit, minimize other undefined bits.
1480 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1482 // Minimize undefined bits.
1483 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1487 /// \brief Build the highest possible value of V, taking into account V's
1488 /// uninitialized bits.
1489 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1492 // Split shadow into sign bit and other bits.
1493 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1494 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1495 // Minimise the undefined shadow bit, maximise other undefined bits.
1497 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1499 // Maximize undefined bits.
1500 return IRB.CreateOr(A, Sa);
1504 /// \brief Instrument relational comparisons.
1506 /// This function does exact shadow propagation for all relational
1507 /// comparisons of integers, pointers and vectors of those.
1508 /// FIXME: output seems suboptimal when one of the operands is a constant
1509 void handleRelationalComparisonExact(ICmpInst &I) {
1510 IRBuilder<> IRB(&I);
1511 Value *A = I.getOperand(0);
1512 Value *B = I.getOperand(1);
1513 Value *Sa = getShadow(A);
1514 Value *Sb = getShadow(B);
1516 // Get rid of pointers and vectors of pointers.
1517 // For ints (and vectors of ints), types of A and Sa match,
1518 // and this is a no-op.
1519 A = IRB.CreatePointerCast(A, Sa->getType());
1520 B = IRB.CreatePointerCast(B, Sb->getType());
1522 // Let [a0, a1] be the interval of possible values of A, taking into account
1523 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1524 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1525 bool IsSigned = I.isSigned();
1526 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1527 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1528 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1529 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1530 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1531 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1532 Value *Si = IRB.CreateXor(S1, S2);
1534 setOriginForNaryOp(I);
1537 /// \brief Instrument signed relational comparisons.
1539 /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1540 /// propagating the highest bit of the shadow. Everything else is delegated
1541 /// to handleShadowOr().
1542 void handleSignedRelationalComparison(ICmpInst &I) {
1543 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1544 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1545 Value* op = nullptr;
1546 CmpInst::Predicate pre = I.getPredicate();
1547 if (constOp0 && constOp0->isNullValue() &&
1548 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1549 op = I.getOperand(1);
1550 } else if (constOp1 && constOp1->isNullValue() &&
1551 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1552 op = I.getOperand(0);
1555 IRBuilder<> IRB(&I);
1557 IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1558 setShadow(&I, Shadow);
1559 setOrigin(&I, getOrigin(op));
1565 void visitICmpInst(ICmpInst &I) {
1566 if (!ClHandleICmp) {
1570 if (I.isEquality()) {
1571 handleEqualityComparison(I);
1575 assert(I.isRelational());
1576 if (ClHandleICmpExact) {
1577 handleRelationalComparisonExact(I);
1581 handleSignedRelationalComparison(I);
1585 assert(I.isUnsigned());
1586 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1587 handleRelationalComparisonExact(I);
1594 void visitFCmpInst(FCmpInst &I) {
1598 void handleShift(BinaryOperator &I) {
1599 IRBuilder<> IRB(&I);
1600 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1601 // Otherwise perform the same shift on S1.
1602 Value *S1 = getShadow(&I, 0);
1603 Value *S2 = getShadow(&I, 1);
1604 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1606 Value *V2 = I.getOperand(1);
1607 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1608 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1609 setOriginForNaryOp(I);
1612 void visitShl(BinaryOperator &I) { handleShift(I); }
1613 void visitAShr(BinaryOperator &I) { handleShift(I); }
1614 void visitLShr(BinaryOperator &I) { handleShift(I); }
1616 /// \brief Instrument llvm.memmove
1618 /// At this point we don't know if llvm.memmove will be inlined or not.
1619 /// If we don't instrument it and it gets inlined,
1620 /// our interceptor will not kick in and we will lose the memmove.
1621 /// If we instrument the call here, but it does not get inlined,
1622 /// we will memove the shadow twice: which is bad in case
1623 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1625 /// Similar situation exists for memcpy and memset.
1626 void visitMemMoveInst(MemMoveInst &I) {
1627 IRBuilder<> IRB(&I);
1630 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1631 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1632 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1633 I.eraseFromParent();
1636 // Similar to memmove: avoid copying shadow twice.
1637 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1638 // FIXME: consider doing manual inline for small constant sizes and proper
1640 void visitMemCpyInst(MemCpyInst &I) {
1641 IRBuilder<> IRB(&I);
1644 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1645 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1646 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1647 I.eraseFromParent();
1651 void visitMemSetInst(MemSetInst &I) {
1652 IRBuilder<> IRB(&I);
1655 IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1656 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1657 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1658 I.eraseFromParent();
1661 void visitVAStartInst(VAStartInst &I) {
1662 VAHelper->visitVAStartInst(I);
1665 void visitVACopyInst(VACopyInst &I) {
1666 VAHelper->visitVACopyInst(I);
1669 enum IntrinsicKind {
1670 IK_DoesNotAccessMemory,
1675 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1676 const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1677 const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1678 const int OnlyReadsMemory = IK_OnlyReadsMemory;
1679 const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1680 const int UnknownModRefBehavior = IK_WritesMemory;
1681 #define GET_INTRINSIC_MODREF_BEHAVIOR
1682 #define ModRefBehavior IntrinsicKind
1683 #include "llvm/IR/Intrinsics.gen"
1684 #undef ModRefBehavior
1685 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1688 /// \brief Handle vector store-like intrinsics.
1690 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1691 /// has 1 pointer argument and 1 vector argument, returns void.
1692 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1693 IRBuilder<> IRB(&I);
1694 Value* Addr = I.getArgOperand(0);
1695 Value *Shadow = getShadow(&I, 1);
1696 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1698 // We don't know the pointer alignment (could be unaligned SSE store!).
1699 // Have to assume to worst case.
1700 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1702 if (ClCheckAccessAddress)
1703 insertShadowCheck(Addr, &I);
1705 // FIXME: use ClStoreCleanOrigin
1706 // FIXME: factor out common code from materializeStores
1707 if (MS.TrackOrigins)
1708 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1712 /// \brief Handle vector load-like intrinsics.
1714 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1715 /// has 1 pointer argument, returns a vector.
1716 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1717 IRBuilder<> IRB(&I);
1718 Value *Addr = I.getArgOperand(0);
1720 Type *ShadowTy = getShadowTy(&I);
1721 if (PropagateShadow) {
1722 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1723 // We don't know the pointer alignment (could be unaligned SSE load!).
1724 // Have to assume to worst case.
1725 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1727 setShadow(&I, getCleanShadow(&I));
1730 if (ClCheckAccessAddress)
1731 insertShadowCheck(Addr, &I);
1733 if (MS.TrackOrigins) {
1734 if (PropagateShadow)
1735 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1737 setOrigin(&I, getCleanOrigin());
1742 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1744 /// Instrument intrinsics with any number of arguments of the same type,
1745 /// equal to the return type. The type should be simple (no aggregates or
1746 /// pointers; vectors are fine).
1747 /// Caller guarantees that this intrinsic does not access memory.
1748 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1749 Type *RetTy = I.getType();
1750 if (!(RetTy->isIntOrIntVectorTy() ||
1751 RetTy->isFPOrFPVectorTy() ||
1752 RetTy->isX86_MMXTy()))
1755 unsigned NumArgOperands = I.getNumArgOperands();
1757 for (unsigned i = 0; i < NumArgOperands; ++i) {
1758 Type *Ty = I.getArgOperand(i)->getType();
1763 IRBuilder<> IRB(&I);
1764 ShadowAndOriginCombiner SC(this, IRB);
1765 for (unsigned i = 0; i < NumArgOperands; ++i)
1766 SC.Add(I.getArgOperand(i));
1772 /// \brief Heuristically instrument unknown intrinsics.
1774 /// The main purpose of this code is to do something reasonable with all
1775 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1776 /// We recognize several classes of intrinsics by their argument types and
1777 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1778 /// sure that we know what the intrinsic does.
1780 /// We special-case intrinsics where this approach fails. See llvm.bswap
1781 /// handling as an example of that.
1782 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1783 unsigned NumArgOperands = I.getNumArgOperands();
1784 if (NumArgOperands == 0)
1787 Intrinsic::ID iid = I.getIntrinsicID();
1788 IntrinsicKind IK = getIntrinsicKind(iid);
1789 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1790 bool WritesMemory = IK == IK_WritesMemory;
1791 assert(!(OnlyReadsMemory && WritesMemory));
1793 if (NumArgOperands == 2 &&
1794 I.getArgOperand(0)->getType()->isPointerTy() &&
1795 I.getArgOperand(1)->getType()->isVectorTy() &&
1796 I.getType()->isVoidTy() &&
1798 // This looks like a vector store.
1799 return handleVectorStoreIntrinsic(I);
1802 if (NumArgOperands == 1 &&
1803 I.getArgOperand(0)->getType()->isPointerTy() &&
1804 I.getType()->isVectorTy() &&
1806 // This looks like a vector load.
1807 return handleVectorLoadIntrinsic(I);
1810 if (!OnlyReadsMemory && !WritesMemory)
1811 if (maybeHandleSimpleNomemIntrinsic(I))
1814 // FIXME: detect and handle SSE maskstore/maskload
1818 void handleBswap(IntrinsicInst &I) {
1819 IRBuilder<> IRB(&I);
1820 Value *Op = I.getArgOperand(0);
1821 Type *OpType = Op->getType();
1822 Function *BswapFunc = Intrinsic::getDeclaration(
1823 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
1824 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1825 setOrigin(&I, getOrigin(Op));
1828 // \brief Instrument vector convert instrinsic.
1830 // This function instruments intrinsics like cvtsi2ss:
1831 // %Out = int_xxx_cvtyyy(%ConvertOp)
1833 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1834 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1835 // number \p Out elements, and (if has 2 arguments) copies the rest of the
1836 // elements from \p CopyOp.
1837 // In most cases conversion involves floating-point value which may trigger a
1838 // hardware exception when not fully initialized. For this reason we require
1839 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1840 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1841 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1842 // return a fully initialized value.
1843 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1844 IRBuilder<> IRB(&I);
1845 Value *CopyOp, *ConvertOp;
1847 switch (I.getNumArgOperands()) {
1849 CopyOp = I.getArgOperand(0);
1850 ConvertOp = I.getArgOperand(1);
1853 ConvertOp = I.getArgOperand(0);
1857 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1860 // The first *NumUsedElements* elements of ConvertOp are converted to the
1861 // same number of output elements. The rest of the output is copied from
1862 // CopyOp, or (if not available) filled with zeroes.
1863 // Combine shadow for elements of ConvertOp that are used in this operation,
1864 // and insert a check.
1865 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1866 // int->any conversion.
1867 Value *ConvertShadow = getShadow(ConvertOp);
1868 Value *AggShadow = nullptr;
1869 if (ConvertOp->getType()->isVectorTy()) {
1870 AggShadow = IRB.CreateExtractElement(
1871 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1872 for (int i = 1; i < NumUsedElements; ++i) {
1873 Value *MoreShadow = IRB.CreateExtractElement(
1874 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1875 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1878 AggShadow = ConvertShadow;
1880 assert(AggShadow->getType()->isIntegerTy());
1881 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1883 // Build result shadow by zero-filling parts of CopyOp shadow that come from
1886 assert(CopyOp->getType() == I.getType());
1887 assert(CopyOp->getType()->isVectorTy());
1888 Value *ResultShadow = getShadow(CopyOp);
1889 Type *EltTy = ResultShadow->getType()->getVectorElementType();
1890 for (int i = 0; i < NumUsedElements; ++i) {
1891 ResultShadow = IRB.CreateInsertElement(
1892 ResultShadow, ConstantInt::getNullValue(EltTy),
1893 ConstantInt::get(IRB.getInt32Ty(), i));
1895 setShadow(&I, ResultShadow);
1896 setOrigin(&I, getOrigin(CopyOp));
1898 setShadow(&I, getCleanShadow(&I));
1902 // Given a scalar or vector, extract lower 64 bits (or less), and return all
1903 // zeroes if it is zero, and all ones otherwise.
1904 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1905 if (S->getType()->isVectorTy())
1906 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1907 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1908 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1909 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1912 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1913 Type *T = S->getType();
1914 assert(T->isVectorTy());
1915 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1916 return IRB.CreateSExt(S2, T);
1919 // \brief Instrument vector shift instrinsic.
1921 // This function instruments intrinsics like int_x86_avx2_psll_w.
1922 // Intrinsic shifts %In by %ShiftSize bits.
1923 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
1924 // size, and the rest is ignored. Behavior is defined even if shift size is
1925 // greater than register (or field) width.
1926 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
1927 assert(I.getNumArgOperands() == 2);
1928 IRBuilder<> IRB(&I);
1929 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1930 // Otherwise perform the same shift on S1.
1931 Value *S1 = getShadow(&I, 0);
1932 Value *S2 = getShadow(&I, 1);
1933 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
1934 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
1935 Value *V1 = I.getOperand(0);
1936 Value *V2 = I.getOperand(1);
1937 Value *Shift = IRB.CreateCall2(I.getCalledValue(),
1938 IRB.CreateBitCast(S1, V1->getType()), V2);
1939 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
1940 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1941 setOriginForNaryOp(I);
1944 // \brief Get an X86_MMX-sized vector type.
1945 Type *getMMXVectorTy(unsigned EltSizeInBits) {
1946 const unsigned X86_MMXSizeInBits = 64;
1947 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
1948 X86_MMXSizeInBits / EltSizeInBits);
1951 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
1953 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
1955 case llvm::Intrinsic::x86_sse2_packsswb_128:
1956 case llvm::Intrinsic::x86_sse2_packuswb_128:
1957 return llvm::Intrinsic::x86_sse2_packsswb_128;
1959 case llvm::Intrinsic::x86_sse2_packssdw_128:
1960 case llvm::Intrinsic::x86_sse41_packusdw:
1961 return llvm::Intrinsic::x86_sse2_packssdw_128;
1963 case llvm::Intrinsic::x86_avx2_packsswb:
1964 case llvm::Intrinsic::x86_avx2_packuswb:
1965 return llvm::Intrinsic::x86_avx2_packsswb;
1967 case llvm::Intrinsic::x86_avx2_packssdw:
1968 case llvm::Intrinsic::x86_avx2_packusdw:
1969 return llvm::Intrinsic::x86_avx2_packssdw;
1971 case llvm::Intrinsic::x86_mmx_packsswb:
1972 case llvm::Intrinsic::x86_mmx_packuswb:
1973 return llvm::Intrinsic::x86_mmx_packsswb;
1975 case llvm::Intrinsic::x86_mmx_packssdw:
1976 return llvm::Intrinsic::x86_mmx_packssdw;
1978 llvm_unreachable("unexpected intrinsic id");
1982 // \brief Instrument vector pack instrinsic.
1984 // This function instruments intrinsics like x86_mmx_packsswb, that
1985 // packs elements of 2 input vectors into half as many bits with saturation.
1986 // Shadow is propagated with the signed variant of the same intrinsic applied
1987 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
1988 // EltSizeInBits is used only for x86mmx arguments.
1989 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
1990 assert(I.getNumArgOperands() == 2);
1991 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
1992 IRBuilder<> IRB(&I);
1993 Value *S1 = getShadow(&I, 0);
1994 Value *S2 = getShadow(&I, 1);
1995 assert(isX86_MMX || S1->getType()->isVectorTy());
1997 // SExt and ICmpNE below must apply to individual elements of input vectors.
1998 // In case of x86mmx arguments, cast them to appropriate vector types and
2000 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2002 S1 = IRB.CreateBitCast(S1, T);
2003 S2 = IRB.CreateBitCast(S2, T);
2005 Value *S1_ext = IRB.CreateSExt(
2006 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2007 Value *S2_ext = IRB.CreateSExt(
2008 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2010 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2011 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2012 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2015 Function *ShadowFn = Intrinsic::getDeclaration(
2016 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2018 Value *S = IRB.CreateCall2(ShadowFn, S1_ext, S2_ext, "_msprop_vector_pack");
2019 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2021 setOriginForNaryOp(I);
2024 // \brief Instrument sum-of-absolute-differencies intrinsic.
2025 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2026 const unsigned SignificantBitsPerResultElement = 16;
2027 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2028 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2029 unsigned ZeroBitsPerResultElement =
2030 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2032 IRBuilder<> IRB(&I);
2033 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2034 S = IRB.CreateBitCast(S, ResTy);
2035 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2037 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2038 S = IRB.CreateBitCast(S, getShadowTy(&I));
2040 setOriginForNaryOp(I);
2043 // \brief Instrument multiply-add intrinsic.
2044 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2045 unsigned EltSizeInBits = 0) {
2046 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2047 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2048 IRBuilder<> IRB(&I);
2049 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2050 S = IRB.CreateBitCast(S, ResTy);
2051 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2053 S = IRB.CreateBitCast(S, getShadowTy(&I));
2055 setOriginForNaryOp(I);
2058 void visitIntrinsicInst(IntrinsicInst &I) {
2059 switch (I.getIntrinsicID()) {
2060 case llvm::Intrinsic::bswap:
2063 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2064 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2065 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2066 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2067 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2068 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2069 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2070 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2071 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2072 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2073 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2074 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2075 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2076 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2077 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2078 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2079 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2080 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2081 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2082 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2083 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2084 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2085 case llvm::Intrinsic::x86_sse_cvtss2si64:
2086 case llvm::Intrinsic::x86_sse_cvtss2si:
2087 case llvm::Intrinsic::x86_sse_cvttss2si64:
2088 case llvm::Intrinsic::x86_sse_cvttss2si:
2089 handleVectorConvertIntrinsic(I, 1);
2091 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2092 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2093 case llvm::Intrinsic::x86_sse_cvtps2pi:
2094 case llvm::Intrinsic::x86_sse_cvttps2pi:
2095 handleVectorConvertIntrinsic(I, 2);
2097 case llvm::Intrinsic::x86_avx512_psll_dq:
2098 case llvm::Intrinsic::x86_avx512_psrl_dq:
2099 case llvm::Intrinsic::x86_avx2_psll_w:
2100 case llvm::Intrinsic::x86_avx2_psll_d:
2101 case llvm::Intrinsic::x86_avx2_psll_q:
2102 case llvm::Intrinsic::x86_avx2_pslli_w:
2103 case llvm::Intrinsic::x86_avx2_pslli_d:
2104 case llvm::Intrinsic::x86_avx2_pslli_q:
2105 case llvm::Intrinsic::x86_avx2_psll_dq:
2106 case llvm::Intrinsic::x86_avx2_psrl_w:
2107 case llvm::Intrinsic::x86_avx2_psrl_d:
2108 case llvm::Intrinsic::x86_avx2_psrl_q:
2109 case llvm::Intrinsic::x86_avx2_psra_w:
2110 case llvm::Intrinsic::x86_avx2_psra_d:
2111 case llvm::Intrinsic::x86_avx2_psrli_w:
2112 case llvm::Intrinsic::x86_avx2_psrli_d:
2113 case llvm::Intrinsic::x86_avx2_psrli_q:
2114 case llvm::Intrinsic::x86_avx2_psrai_w:
2115 case llvm::Intrinsic::x86_avx2_psrai_d:
2116 case llvm::Intrinsic::x86_avx2_psrl_dq:
2117 case llvm::Intrinsic::x86_sse2_psll_w:
2118 case llvm::Intrinsic::x86_sse2_psll_d:
2119 case llvm::Intrinsic::x86_sse2_psll_q:
2120 case llvm::Intrinsic::x86_sse2_pslli_w:
2121 case llvm::Intrinsic::x86_sse2_pslli_d:
2122 case llvm::Intrinsic::x86_sse2_pslli_q:
2123 case llvm::Intrinsic::x86_sse2_psll_dq:
2124 case llvm::Intrinsic::x86_sse2_psrl_w:
2125 case llvm::Intrinsic::x86_sse2_psrl_d:
2126 case llvm::Intrinsic::x86_sse2_psrl_q:
2127 case llvm::Intrinsic::x86_sse2_psra_w:
2128 case llvm::Intrinsic::x86_sse2_psra_d:
2129 case llvm::Intrinsic::x86_sse2_psrli_w:
2130 case llvm::Intrinsic::x86_sse2_psrli_d:
2131 case llvm::Intrinsic::x86_sse2_psrli_q:
2132 case llvm::Intrinsic::x86_sse2_psrai_w:
2133 case llvm::Intrinsic::x86_sse2_psrai_d:
2134 case llvm::Intrinsic::x86_sse2_psrl_dq:
2135 case llvm::Intrinsic::x86_mmx_psll_w:
2136 case llvm::Intrinsic::x86_mmx_psll_d:
2137 case llvm::Intrinsic::x86_mmx_psll_q:
2138 case llvm::Intrinsic::x86_mmx_pslli_w:
2139 case llvm::Intrinsic::x86_mmx_pslli_d:
2140 case llvm::Intrinsic::x86_mmx_pslli_q:
2141 case llvm::Intrinsic::x86_mmx_psrl_w:
2142 case llvm::Intrinsic::x86_mmx_psrl_d:
2143 case llvm::Intrinsic::x86_mmx_psrl_q:
2144 case llvm::Intrinsic::x86_mmx_psra_w:
2145 case llvm::Intrinsic::x86_mmx_psra_d:
2146 case llvm::Intrinsic::x86_mmx_psrli_w:
2147 case llvm::Intrinsic::x86_mmx_psrli_d:
2148 case llvm::Intrinsic::x86_mmx_psrli_q:
2149 case llvm::Intrinsic::x86_mmx_psrai_w:
2150 case llvm::Intrinsic::x86_mmx_psrai_d:
2151 handleVectorShiftIntrinsic(I, /* Variable */ false);
2153 case llvm::Intrinsic::x86_avx2_psllv_d:
2154 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2155 case llvm::Intrinsic::x86_avx2_psllv_q:
2156 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2157 case llvm::Intrinsic::x86_avx2_psrlv_d:
2158 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2159 case llvm::Intrinsic::x86_avx2_psrlv_q:
2160 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2161 case llvm::Intrinsic::x86_avx2_psrav_d:
2162 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2163 handleVectorShiftIntrinsic(I, /* Variable */ true);
2166 // Byte shifts are not implemented.
2167 // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
2168 // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
2169 // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
2170 // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
2171 // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
2172 // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
2174 case llvm::Intrinsic::x86_sse2_packsswb_128:
2175 case llvm::Intrinsic::x86_sse2_packssdw_128:
2176 case llvm::Intrinsic::x86_sse2_packuswb_128:
2177 case llvm::Intrinsic::x86_sse41_packusdw:
2178 case llvm::Intrinsic::x86_avx2_packsswb:
2179 case llvm::Intrinsic::x86_avx2_packssdw:
2180 case llvm::Intrinsic::x86_avx2_packuswb:
2181 case llvm::Intrinsic::x86_avx2_packusdw:
2182 handleVectorPackIntrinsic(I);
2185 case llvm::Intrinsic::x86_mmx_packsswb:
2186 case llvm::Intrinsic::x86_mmx_packuswb:
2187 handleVectorPackIntrinsic(I, 16);
2190 case llvm::Intrinsic::x86_mmx_packssdw:
2191 handleVectorPackIntrinsic(I, 32);
2194 case llvm::Intrinsic::x86_mmx_psad_bw:
2195 case llvm::Intrinsic::x86_sse2_psad_bw:
2196 case llvm::Intrinsic::x86_avx2_psad_bw:
2197 handleVectorSadIntrinsic(I);
2200 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2201 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2202 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2203 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2204 handleVectorPmaddIntrinsic(I);
2207 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2208 handleVectorPmaddIntrinsic(I, 8);
2211 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2212 handleVectorPmaddIntrinsic(I, 16);
2216 if (!handleUnknownIntrinsic(I))
2217 visitInstruction(I);
2222 void visitCallSite(CallSite CS) {
2223 Instruction &I = *CS.getInstruction();
2224 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2226 CallInst *Call = cast<CallInst>(&I);
2228 // For inline asm, do the usual thing: check argument shadow and mark all
2229 // outputs as clean. Note that any side effects of the inline asm that are
2230 // not immediately visible in its constraints are not handled.
2231 if (Call->isInlineAsm()) {
2232 visitInstruction(I);
2236 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2238 // We are going to insert code that relies on the fact that the callee
2239 // will become a non-readonly function after it is instrumented by us. To
2240 // prevent this code from being optimized out, mark that function
2241 // non-readonly in advance.
2242 if (Function *Func = Call->getCalledFunction()) {
2243 // Clear out readonly/readnone attributes.
2245 B.addAttribute(Attribute::ReadOnly)
2246 .addAttribute(Attribute::ReadNone);
2247 Func->removeAttributes(AttributeSet::FunctionIndex,
2248 AttributeSet::get(Func->getContext(),
2249 AttributeSet::FunctionIndex,
2253 IRBuilder<> IRB(&I);
2255 unsigned ArgOffset = 0;
2256 DEBUG(dbgs() << " CallSite: " << I << "\n");
2257 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2258 ArgIt != End; ++ArgIt) {
2260 unsigned i = ArgIt - CS.arg_begin();
2261 if (!A->getType()->isSized()) {
2262 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2266 Value *Store = nullptr;
2267 // Compute the Shadow for arg even if it is ByVal, because
2268 // in that case getShadow() will copy the actual arg shadow to
2269 // __msan_param_tls.
2270 Value *ArgShadow = getShadow(A);
2271 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2272 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2273 " Shadow: " << *ArgShadow << "\n");
2274 bool ArgIsInitialized = false;
2275 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2276 assert(A->getType()->isPointerTy() &&
2277 "ByVal argument is not a pointer!");
2278 Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
2279 if (ArgOffset + Size > kParamTLSSize) break;
2280 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2281 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2282 Store = IRB.CreateMemCpy(ArgShadowBase,
2283 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2286 Size = MS.DL->getTypeAllocSize(A->getType());
2287 if (ArgOffset + Size > kParamTLSSize) break;
2288 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2289 kShadowTLSAlignment);
2290 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2291 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2293 if (MS.TrackOrigins && !ArgIsInitialized)
2294 IRB.CreateStore(getOrigin(A),
2295 getOriginPtrForArgument(A, IRB, ArgOffset));
2297 assert(Size != 0 && Store != nullptr);
2298 DEBUG(dbgs() << " Param:" << *Store << "\n");
2299 ArgOffset += RoundUpToAlignment(Size, 8);
2301 DEBUG(dbgs() << " done with call args\n");
2304 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2305 if (FT->isVarArg()) {
2306 VAHelper->visitCallSite(CS, IRB);
2309 // Now, get the shadow for the RetVal.
2310 if (!I.getType()->isSized()) return;
2311 IRBuilder<> IRBBefore(&I);
2312 // Until we have full dynamic coverage, make sure the retval shadow is 0.
2313 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2314 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2315 Instruction *NextInsn = nullptr;
2317 NextInsn = I.getNextNode();
2319 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2320 if (!NormalDest->getSinglePredecessor()) {
2321 // FIXME: this case is tricky, so we are just conservative here.
2322 // Perhaps we need to split the edge between this BB and NormalDest,
2323 // but a naive attempt to use SplitEdge leads to a crash.
2324 setShadow(&I, getCleanShadow(&I));
2325 setOrigin(&I, getCleanOrigin());
2328 NextInsn = NormalDest->getFirstInsertionPt();
2330 "Could not find insertion point for retval shadow load");
2332 IRBuilder<> IRBAfter(NextInsn);
2333 Value *RetvalShadow =
2334 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2335 kShadowTLSAlignment, "_msret");
2336 setShadow(&I, RetvalShadow);
2337 if (MS.TrackOrigins)
2338 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2341 void visitReturnInst(ReturnInst &I) {
2342 IRBuilder<> IRB(&I);
2343 Value *RetVal = I.getReturnValue();
2344 if (!RetVal) return;
2345 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2346 if (CheckReturnValue) {
2347 insertShadowCheck(RetVal, &I);
2348 Value *Shadow = getCleanShadow(RetVal);
2349 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2351 Value *Shadow = getShadow(RetVal);
2352 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2353 // FIXME: make it conditional if ClStoreCleanOrigin==0
2354 if (MS.TrackOrigins)
2355 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2359 void visitPHINode(PHINode &I) {
2360 IRBuilder<> IRB(&I);
2361 if (!PropagateShadow) {
2362 setShadow(&I, getCleanShadow(&I));
2366 ShadowPHINodes.push_back(&I);
2367 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2369 if (MS.TrackOrigins)
2370 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2374 void visitAllocaInst(AllocaInst &I) {
2375 setShadow(&I, getCleanShadow(&I));
2376 IRBuilder<> IRB(I.getNextNode());
2377 uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
2378 if (PoisonStack && ClPoisonStackWithCall) {
2379 IRB.CreateCall2(MS.MsanPoisonStackFn,
2380 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2381 ConstantInt::get(MS.IntptrTy, Size));
2383 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2384 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2385 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2388 if (PoisonStack && MS.TrackOrigins) {
2389 setOrigin(&I, getCleanOrigin());
2390 SmallString<2048> StackDescriptionStorage;
2391 raw_svector_ostream StackDescription(StackDescriptionStorage);
2392 // We create a string with a description of the stack allocation and
2393 // pass it into __msan_set_alloca_origin.
2394 // It will be printed by the run-time if stack-originated UMR is found.
2395 // The first 4 bytes of the string are set to '----' and will be replaced
2396 // by __msan_va_arg_overflow_size_tls at the first call.
2397 StackDescription << "----" << I.getName() << "@" << F.getName();
2399 createPrivateNonConstGlobalForString(*F.getParent(),
2400 StackDescription.str());
2402 IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
2403 IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2404 ConstantInt::get(MS.IntptrTy, Size),
2405 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2406 IRB.CreatePointerCast(&F, MS.IntptrTy));
2410 void visitSelectInst(SelectInst& I) {
2411 IRBuilder<> IRB(&I);
2412 // a = select b, c, d
2413 Value *B = I.getCondition();
2414 Value *C = I.getTrueValue();
2415 Value *D = I.getFalseValue();
2416 Value *Sb = getShadow(B);
2417 Value *Sc = getShadow(C);
2418 Value *Sd = getShadow(D);
2420 // Result shadow if condition shadow is 0.
2421 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2423 if (I.getType()->isAggregateType()) {
2424 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2425 // an extra "select". This results in much more compact IR.
2426 // Sa = select Sb, poisoned, (select b, Sc, Sd)
2427 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2429 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2430 // If Sb (condition is poisoned), look for bits in c and d that are equal
2431 // and both unpoisoned.
2432 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2434 // Cast arguments to shadow-compatible type.
2435 C = CreateAppToShadowCast(IRB, C);
2436 D = CreateAppToShadowCast(IRB, D);
2438 // Result shadow if condition shadow is 1.
2439 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2441 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2443 if (MS.TrackOrigins) {
2444 // Origins are always i32, so any vector conditions must be flattened.
2445 // FIXME: consider tracking vector origins for app vectors?
2446 if (B->getType()->isVectorTy()) {
2447 Type *FlatTy = getShadowTyNoVec(B->getType());
2448 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2449 ConstantInt::getNullValue(FlatTy));
2450 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2451 ConstantInt::getNullValue(FlatTy));
2453 // a = select b, c, d
2454 // Oa = Sb ? Ob : (b ? Oc : Od)
2456 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2457 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2458 getOrigin(I.getFalseValue()))));
2462 void visitLandingPadInst(LandingPadInst &I) {
2464 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2465 setShadow(&I, getCleanShadow(&I));
2466 setOrigin(&I, getCleanOrigin());
2469 void visitGetElementPtrInst(GetElementPtrInst &I) {
2473 void visitExtractValueInst(ExtractValueInst &I) {
2474 IRBuilder<> IRB(&I);
2475 Value *Agg = I.getAggregateOperand();
2476 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2477 Value *AggShadow = getShadow(Agg);
2478 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2479 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2480 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2481 setShadow(&I, ResShadow);
2482 setOriginForNaryOp(I);
2485 void visitInsertValueInst(InsertValueInst &I) {
2486 IRBuilder<> IRB(&I);
2487 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2488 Value *AggShadow = getShadow(I.getAggregateOperand());
2489 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2490 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2491 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2492 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2493 DEBUG(dbgs() << " Res: " << *Res << "\n");
2495 setOriginForNaryOp(I);
2498 void dumpInst(Instruction &I) {
2499 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2500 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2502 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2504 errs() << "QQQ " << I << "\n";
2507 void visitResumeInst(ResumeInst &I) {
2508 DEBUG(dbgs() << "Resume: " << I << "\n");
2509 // Nothing to do here.
2512 void visitInstruction(Instruction &I) {
2513 // Everything else: stop propagating and check for poisoned shadow.
2514 if (ClDumpStrictInstructions)
2516 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2517 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2518 insertShadowCheck(I.getOperand(i), &I);
2519 setShadow(&I, getCleanShadow(&I));
2520 setOrigin(&I, getCleanOrigin());
2524 /// \brief AMD64-specific implementation of VarArgHelper.
2525 struct VarArgAMD64Helper : public VarArgHelper {
2526 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2527 // See a comment in visitCallSite for more details.
2528 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
2529 static const unsigned AMD64FpEndOffset = 176;
2532 MemorySanitizer &MS;
2533 MemorySanitizerVisitor &MSV;
2534 Value *VAArgTLSCopy;
2535 Value *VAArgOverflowSize;
2537 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2539 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2540 MemorySanitizerVisitor &MSV)
2541 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2542 VAArgOverflowSize(nullptr) {}
2544 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2546 ArgKind classifyArgument(Value* arg) {
2547 // A very rough approximation of X86_64 argument classification rules.
2548 Type *T = arg->getType();
2549 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2550 return AK_FloatingPoint;
2551 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2552 return AK_GeneralPurpose;
2553 if (T->isPointerTy())
2554 return AK_GeneralPurpose;
2558 // For VarArg functions, store the argument shadow in an ABI-specific format
2559 // that corresponds to va_list layout.
2560 // We do this because Clang lowers va_arg in the frontend, and this pass
2561 // only sees the low level code that deals with va_list internals.
2562 // A much easier alternative (provided that Clang emits va_arg instructions)
2563 // would have been to associate each live instance of va_list with a copy of
2564 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2566 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2567 unsigned GpOffset = 0;
2568 unsigned FpOffset = AMD64GpEndOffset;
2569 unsigned OverflowOffset = AMD64FpEndOffset;
2570 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2571 ArgIt != End; ++ArgIt) {
2573 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2574 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2576 // ByVal arguments always go to the overflow area.
2577 assert(A->getType()->isPointerTy());
2578 Type *RealTy = A->getType()->getPointerElementType();
2579 uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2580 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2581 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2582 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2583 ArgSize, kShadowTLSAlignment);
2585 ArgKind AK = classifyArgument(A);
2586 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2588 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2592 case AK_GeneralPurpose:
2593 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2596 case AK_FloatingPoint:
2597 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2601 uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2602 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2603 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2605 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2608 Constant *OverflowSize =
2609 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2610 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2613 /// \brief Compute the shadow address for a given va_arg.
2614 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2616 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2617 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2618 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2622 void visitVAStartInst(VAStartInst &I) override {
2623 IRBuilder<> IRB(&I);
2624 VAStartInstrumentationList.push_back(&I);
2625 Value *VAListTag = I.getArgOperand(0);
2626 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2628 // Unpoison the whole __va_list_tag.
2629 // FIXME: magic ABI constants.
2630 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2631 /* size */24, /* alignment */8, false);
2634 void visitVACopyInst(VACopyInst &I) override {
2635 IRBuilder<> IRB(&I);
2636 Value *VAListTag = I.getArgOperand(0);
2637 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2639 // Unpoison the whole __va_list_tag.
2640 // FIXME: magic ABI constants.
2641 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2642 /* size */24, /* alignment */8, false);
2645 void finalizeInstrumentation() override {
2646 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2647 "finalizeInstrumentation called twice");
2648 if (!VAStartInstrumentationList.empty()) {
2649 // If there is a va_start in this function, make a backup copy of
2650 // va_arg_tls somewhere in the function entry block.
2651 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2652 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2654 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2656 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2657 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2660 // Instrument va_start.
2661 // Copy va_list shadow from the backup copy of the TLS contents.
2662 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2663 CallInst *OrigInst = VAStartInstrumentationList[i];
2664 IRBuilder<> IRB(OrigInst->getNextNode());
2665 Value *VAListTag = OrigInst->getArgOperand(0);
2667 Value *RegSaveAreaPtrPtr =
2669 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2670 ConstantInt::get(MS.IntptrTy, 16)),
2671 Type::getInt64PtrTy(*MS.C));
2672 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2673 Value *RegSaveAreaShadowPtr =
2674 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2675 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2676 AMD64FpEndOffset, 16);
2678 Value *OverflowArgAreaPtrPtr =
2680 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2681 ConstantInt::get(MS.IntptrTy, 8)),
2682 Type::getInt64PtrTy(*MS.C));
2683 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2684 Value *OverflowArgAreaShadowPtr =
2685 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2686 Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2687 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2692 /// \brief A no-op implementation of VarArgHelper.
2693 struct VarArgNoOpHelper : public VarArgHelper {
2694 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2695 MemorySanitizerVisitor &MSV) {}
2697 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
2699 void visitVAStartInst(VAStartInst &I) override {}
2701 void visitVACopyInst(VACopyInst &I) override {}
2703 void finalizeInstrumentation() override {}
2706 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2707 MemorySanitizerVisitor &Visitor) {
2708 // VarArg handling is only implemented on AMD64. False positives are possible
2709 // on other platforms.
2710 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2711 if (TargetTriple.getArch() == llvm::Triple::x86_64)
2712 return new VarArgAMD64Helper(Func, Msan, Visitor);
2714 return new VarArgNoOpHelper(Func, Msan, Visitor);
2719 bool MemorySanitizer::runOnFunction(Function &F) {
2720 MemorySanitizerVisitor Visitor(F, *this);
2722 // Clear out readonly/readnone attributes.
2724 B.addAttribute(Attribute::ReadOnly)
2725 .addAttribute(Attribute::ReadNone);
2726 F.removeAttributes(AttributeSet::FunctionIndex,
2727 AttributeSet::get(F.getContext(),
2728 AttributeSet::FunctionIndex, B));
2730 return Visitor.runOnFunction();