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 unsigned kOriginSize = 4;
124 static const unsigned kMinOriginAlignment = 4;
125 static const unsigned kShadowTLSAlignment = 8;
127 // These constants must be kept in sync with the ones in msan.h.
128 static const unsigned kParamTLSSize = 800;
129 static const unsigned kRetvalTLSSize = 800;
131 // Accesses sizes are powers of two: 1, 2, 4, 8.
132 static const size_t kNumberOfAccessSizes = 4;
134 /// \brief Track origins of uninitialized values.
136 /// Adds a section to MemorySanitizer report that points to the allocation
137 /// (stack or heap) the uninitialized bits came from originally.
138 static cl::opt<int> ClTrackOrigins("msan-track-origins",
139 cl::desc("Track origins (allocation sites) of poisoned memory"),
140 cl::Hidden, cl::init(0));
141 static cl::opt<bool> ClKeepGoing("msan-keep-going",
142 cl::desc("keep going after reporting a UMR"),
143 cl::Hidden, cl::init(false));
144 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
145 cl::desc("poison uninitialized stack variables"),
146 cl::Hidden, cl::init(true));
147 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
148 cl::desc("poison uninitialized stack variables with a call"),
149 cl::Hidden, cl::init(false));
150 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
151 cl::desc("poison uninitialized stack variables with the given patter"),
152 cl::Hidden, cl::init(0xff));
153 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
154 cl::desc("poison undef temps"),
155 cl::Hidden, cl::init(true));
157 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
158 cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
159 cl::Hidden, cl::init(true));
161 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
162 cl::desc("exact handling of relational integer ICmp"),
163 cl::Hidden, cl::init(false));
165 // This flag controls whether we check the shadow of the address
166 // operand of load or store. Such bugs are very rare, since load from
167 // a garbage address typically results in SEGV, but still happen
168 // (e.g. only lower bits of address are garbage, or the access happens
169 // early at program startup where malloc-ed memory is more likely to
170 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
171 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
172 cl::desc("report accesses through a pointer which has poisoned shadow"),
173 cl::Hidden, cl::init(true));
175 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
176 cl::desc("print out instructions with default strict semantics"),
177 cl::Hidden, cl::init(false));
179 static cl::opt<int> ClInstrumentationWithCallThreshold(
180 "msan-instrumentation-with-call-threshold",
182 "If the function being instrumented requires more than "
183 "this number of checks and origin stores, use callbacks instead of "
184 "inline checks (-1 means never use callbacks)."),
185 cl::Hidden, cl::init(3500));
187 // This is an experiment to enable handling of cases where shadow is a non-zero
188 // compile-time constant. For some unexplainable reason they were silently
189 // ignored in the instrumentation.
190 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
191 cl::desc("Insert checks for constant shadow values"),
192 cl::Hidden, cl::init(false));
194 static const char *const kMsanModuleCtorName = "msan.module_ctor";
195 static const char *const kMsanInitName = "__msan_init";
199 // Memory map parameters used in application-to-shadow address calculation.
200 // Offset = (Addr & ~AndMask) ^ XorMask
201 // Shadow = ShadowBase + Offset
202 // Origin = OriginBase + Offset
203 struct MemoryMapParams {
210 struct PlatformMemoryMapParams {
211 const MemoryMapParams *bits32;
212 const MemoryMapParams *bits64;
216 static const MemoryMapParams Linux_I386_MemoryMapParams = {
217 0x000080000000, // AndMask
218 0, // XorMask (not used)
219 0, // ShadowBase (not used)
220 0x000040000000, // OriginBase
224 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
225 0x400000000000, // AndMask
226 0, // XorMask (not used)
227 0, // ShadowBase (not used)
228 0x200000000000, // OriginBase
232 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
233 0x004000000000, // AndMask
234 0, // XorMask (not used)
235 0, // ShadowBase (not used)
236 0x002000000000, // OriginBase
240 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
241 0x200000000000, // AndMask
242 0x100000000000, // XorMask
243 0x080000000000, // ShadowBase
244 0x1C0000000000, // OriginBase
248 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
249 0x000180000000, // AndMask
250 0x000040000000, // XorMask
251 0x000020000000, // ShadowBase
252 0x000700000000, // OriginBase
256 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
257 0xc00000000000, // AndMask
258 0x200000000000, // XorMask
259 0x100000000000, // ShadowBase
260 0x380000000000, // OriginBase
263 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
264 &Linux_I386_MemoryMapParams,
265 &Linux_X86_64_MemoryMapParams,
268 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
270 &Linux_MIPS64_MemoryMapParams,
273 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
275 &Linux_PowerPC64_MemoryMapParams,
278 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
279 &FreeBSD_I386_MemoryMapParams,
280 &FreeBSD_X86_64_MemoryMapParams,
283 /// \brief An instrumentation pass implementing detection of uninitialized
286 /// MemorySanitizer: instrument the code in module to find
287 /// uninitialized reads.
288 class MemorySanitizer : public FunctionPass {
290 MemorySanitizer(int TrackOrigins = 0)
292 TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
293 WarningFn(nullptr) {}
294 const char *getPassName() const override { return "MemorySanitizer"; }
295 bool runOnFunction(Function &F) override;
296 bool doInitialization(Module &M) override;
297 static char ID; // Pass identification, replacement for typeid.
300 void initializeCallbacks(Module &M);
302 /// \brief Track origins (allocation points) of uninitialized values.
308 /// \brief Thread-local shadow storage for function parameters.
309 GlobalVariable *ParamTLS;
310 /// \brief Thread-local origin storage for function parameters.
311 GlobalVariable *ParamOriginTLS;
312 /// \brief Thread-local shadow storage for function return value.
313 GlobalVariable *RetvalTLS;
314 /// \brief Thread-local origin storage for function return value.
315 GlobalVariable *RetvalOriginTLS;
316 /// \brief Thread-local shadow storage for in-register va_arg function
317 /// parameters (x86_64-specific).
318 GlobalVariable *VAArgTLS;
319 /// \brief Thread-local shadow storage for va_arg overflow area
320 /// (x86_64-specific).
321 GlobalVariable *VAArgOverflowSizeTLS;
322 /// \brief Thread-local space used to pass origin value to the UMR reporting
324 GlobalVariable *OriginTLS;
326 /// \brief The run-time callback to print a warning.
328 // These arrays are indexed by log2(AccessSize).
329 Value *MaybeWarningFn[kNumberOfAccessSizes];
330 Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
332 /// \brief Run-time helper that generates a new origin value for a stack
334 Value *MsanSetAllocaOrigin4Fn;
335 /// \brief Run-time helper that poisons stack on function entry.
336 Value *MsanPoisonStackFn;
337 /// \brief Run-time helper that records a store (or any event) of an
338 /// uninitialized value and returns an updated origin id encoding this info.
339 Value *MsanChainOriginFn;
340 /// \brief MSan runtime replacements for memmove, memcpy and memset.
341 Value *MemmoveFn, *MemcpyFn, *MemsetFn;
343 /// \brief Memory map parameters used in application-to-shadow calculation.
344 const MemoryMapParams *MapParams;
346 MDNode *ColdCallWeights;
347 /// \brief Branch weights for origin store.
348 MDNode *OriginStoreWeights;
349 /// \brief An empty volatile inline asm that prevents callback merge.
351 Function *MsanCtorFunction;
353 friend struct MemorySanitizerVisitor;
354 friend struct VarArgAMD64Helper;
355 friend struct VarArgMIPS64Helper;
359 char MemorySanitizer::ID = 0;
360 INITIALIZE_PASS(MemorySanitizer, "msan",
361 "MemorySanitizer: detects uninitialized reads.",
364 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
365 return new MemorySanitizer(TrackOrigins);
368 /// \brief Create a non-const global initialized with the given string.
370 /// Creates a writable global for Str so that we can pass it to the
371 /// run-time lib. Runtime uses first 4 bytes of the string to store the
372 /// frame ID, so the string needs to be mutable.
373 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
375 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
376 return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
377 GlobalValue::PrivateLinkage, StrConst, "");
381 /// \brief Insert extern declaration of runtime-provided functions and globals.
382 void MemorySanitizer::initializeCallbacks(Module &M) {
383 // Only do this once.
388 // Create the callback.
389 // FIXME: this function should have "Cold" calling conv,
390 // which is not yet implemented.
391 StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
392 : "__msan_warning_noreturn";
393 WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), nullptr);
395 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
397 unsigned AccessSize = 1 << AccessSizeIndex;
398 std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
399 MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
400 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
401 IRB.getInt32Ty(), nullptr);
403 FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
404 MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
405 FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
406 IRB.getInt8PtrTy(), IRB.getInt32Ty(), nullptr);
409 MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
410 "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
411 IRB.getInt8PtrTy(), IntptrTy, nullptr);
413 M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
414 IRB.getInt8PtrTy(), IntptrTy, nullptr);
415 MsanChainOriginFn = M.getOrInsertFunction(
416 "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), nullptr);
417 MemmoveFn = M.getOrInsertFunction(
418 "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
419 IRB.getInt8PtrTy(), IntptrTy, nullptr);
420 MemcpyFn = M.getOrInsertFunction(
421 "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
423 MemsetFn = M.getOrInsertFunction(
424 "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
428 RetvalTLS = new GlobalVariable(
429 M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
430 GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
431 GlobalVariable::InitialExecTLSModel);
432 RetvalOriginTLS = new GlobalVariable(
433 M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
434 "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
436 ParamTLS = new GlobalVariable(
437 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
438 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
439 GlobalVariable::InitialExecTLSModel);
440 ParamOriginTLS = new GlobalVariable(
441 M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
442 GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
443 nullptr, GlobalVariable::InitialExecTLSModel);
445 VAArgTLS = new GlobalVariable(
446 M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
447 GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
448 GlobalVariable::InitialExecTLSModel);
449 VAArgOverflowSizeTLS = new GlobalVariable(
450 M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
451 "__msan_va_arg_overflow_size_tls", nullptr,
452 GlobalVariable::InitialExecTLSModel);
453 OriginTLS = new GlobalVariable(
454 M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
455 "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
457 // We insert an empty inline asm after __msan_report* to avoid callback merge.
458 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
459 StringRef(""), StringRef(""),
460 /*hasSideEffects=*/true);
463 /// \brief Module-level initialization.
465 /// inserts a call to __msan_init to the module's constructor list.
466 bool MemorySanitizer::doInitialization(Module &M) {
467 auto &DL = M.getDataLayout();
469 Triple TargetTriple(M.getTargetTriple());
470 switch (TargetTriple.getOS()) {
471 case Triple::FreeBSD:
472 switch (TargetTriple.getArch()) {
474 MapParams = FreeBSD_X86_MemoryMapParams.bits64;
477 MapParams = FreeBSD_X86_MemoryMapParams.bits32;
480 report_fatal_error("unsupported architecture");
484 switch (TargetTriple.getArch()) {
486 MapParams = Linux_X86_MemoryMapParams.bits64;
489 MapParams = Linux_X86_MemoryMapParams.bits32;
492 case Triple::mips64el:
493 MapParams = Linux_MIPS_MemoryMapParams.bits64;
496 case Triple::ppc64le:
497 MapParams = Linux_PowerPC_MemoryMapParams.bits64;
500 report_fatal_error("unsupported architecture");
504 report_fatal_error("unsupported operating system");
507 C = &(M.getContext());
509 IntptrTy = IRB.getIntPtrTy(DL);
510 OriginTy = IRB.getInt32Ty();
512 ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
513 OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
515 std::tie(MsanCtorFunction, std::ignore) =
516 createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
520 appendToGlobalCtors(M, MsanCtorFunction, 0);
523 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
524 IRB.getInt32(TrackOrigins), "__msan_track_origins");
527 new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
528 IRB.getInt32(ClKeepGoing), "__msan_keep_going");
535 /// \brief A helper class that handles instrumentation of VarArg
536 /// functions on a particular platform.
538 /// Implementations are expected to insert the instrumentation
539 /// necessary to propagate argument shadow through VarArg function
540 /// calls. Visit* methods are called during an InstVisitor pass over
541 /// the function, and should avoid creating new basic blocks. A new
542 /// instance of this class is created for each instrumented function.
543 struct VarArgHelper {
544 /// \brief Visit a CallSite.
545 virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
547 /// \brief Visit a va_start call.
548 virtual void visitVAStartInst(VAStartInst &I) = 0;
550 /// \brief Visit a va_copy call.
551 virtual void visitVACopyInst(VACopyInst &I) = 0;
553 /// \brief Finalize function instrumentation.
555 /// This method is called after visiting all interesting (see above)
556 /// instructions in a function.
557 virtual void finalizeInstrumentation() = 0;
559 virtual ~VarArgHelper() {}
562 struct MemorySanitizerVisitor;
565 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
566 MemorySanitizerVisitor &Visitor);
568 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
569 if (TypeSize <= 8) return 0;
570 return Log2_32_Ceil(TypeSize / 8);
573 /// This class does all the work for a given function. Store and Load
574 /// instructions store and load corresponding shadow and origin
575 /// values. Most instructions propagate shadow from arguments to their
576 /// return values. Certain instructions (most importantly, BranchInst)
577 /// test their argument shadow and print reports (with a runtime call) if it's
579 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
582 SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
583 ValueMap<Value*, Value*> ShadowMap, OriginMap;
584 std::unique_ptr<VarArgHelper> VAHelper;
586 // The following flags disable parts of MSan instrumentation based on
587 // blacklist contents and command-line options.
589 bool PropagateShadow;
592 bool CheckReturnValue;
594 struct ShadowOriginAndInsertPoint {
597 Instruction *OrigIns;
598 ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
599 : Shadow(S), Origin(O), OrigIns(I) { }
601 SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
602 SmallVector<Instruction*, 16> StoreList;
604 MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
605 : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
606 bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
607 InsertChecks = SanitizeFunction;
608 PropagateShadow = SanitizeFunction;
609 PoisonStack = SanitizeFunction && ClPoisonStack;
610 PoisonUndef = SanitizeFunction && ClPoisonUndef;
611 // FIXME: Consider using SpecialCaseList to specify a list of functions that
612 // must always return fully initialized values. For now, we hardcode "main".
613 CheckReturnValue = SanitizeFunction && (F.getName() == "main");
615 DEBUG(if (!InsertChecks)
616 dbgs() << "MemorySanitizer is not inserting checks into '"
617 << F.getName() << "'\n");
620 Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
621 if (MS.TrackOrigins <= 1) return V;
622 return IRB.CreateCall(MS.MsanChainOriginFn, V);
625 Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
626 const DataLayout &DL = F.getParent()->getDataLayout();
627 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
628 if (IntptrSize == kOriginSize) return Origin;
629 assert(IntptrSize == kOriginSize * 2);
630 Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
631 return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
634 /// \brief Fill memory range with the given origin value.
635 void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
636 unsigned Size, unsigned Alignment) {
637 const DataLayout &DL = F.getParent()->getDataLayout();
638 unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
639 unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
640 assert(IntptrAlignment >= kMinOriginAlignment);
641 assert(IntptrSize >= kOriginSize);
644 unsigned CurrentAlignment = Alignment;
645 if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
646 Value *IntptrOrigin = originToIntptr(IRB, Origin);
647 Value *IntptrOriginPtr =
648 IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
649 for (unsigned i = 0; i < Size / IntptrSize; ++i) {
650 Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
652 IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
653 Ofs += IntptrSize / kOriginSize;
654 CurrentAlignment = IntptrAlignment;
658 for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
660 i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
661 IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
662 CurrentAlignment = kMinOriginAlignment;
666 void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
667 unsigned Alignment, bool AsCall) {
668 const DataLayout &DL = F.getParent()->getDataLayout();
669 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
670 unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
671 if (isa<StructType>(Shadow->getType())) {
672 paintOrigin(IRB, updateOrigin(Origin, IRB),
673 getOriginPtr(Addr, IRB, Alignment), StoreSize,
676 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
677 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
678 if (ConstantShadow) {
679 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
680 paintOrigin(IRB, updateOrigin(Origin, IRB),
681 getOriginPtr(Addr, IRB, Alignment), StoreSize,
686 unsigned TypeSizeInBits =
687 DL.getTypeSizeInBits(ConvertedShadow->getType());
688 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
689 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
690 Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
691 Value *ConvertedShadow2 = IRB.CreateZExt(
692 ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
693 IRB.CreateCall(Fn, {ConvertedShadow2,
694 IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
697 Value *Cmp = IRB.CreateICmpNE(
698 ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
699 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
700 Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
701 IRBuilder<> IRBNew(CheckTerm);
702 paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
703 getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
709 void materializeStores(bool InstrumentWithCalls) {
710 for (auto Inst : StoreList) {
711 StoreInst &SI = *dyn_cast<StoreInst>(Inst);
713 IRBuilder<> IRB(&SI);
714 Value *Val = SI.getValueOperand();
715 Value *Addr = SI.getPointerOperand();
716 Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
717 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
720 IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
721 DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
724 if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
726 if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
728 if (MS.TrackOrigins && !SI.isAtomic())
729 storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI.getAlignment(),
730 InstrumentWithCalls);
734 void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
736 IRBuilder<> IRB(OrigIns);
737 DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
738 Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
739 DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
741 Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
742 if (ConstantShadow) {
743 if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
744 if (MS.TrackOrigins) {
745 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
748 IRB.CreateCall(MS.WarningFn, {});
749 IRB.CreateCall(MS.EmptyAsm, {});
750 // FIXME: Insert UnreachableInst if !ClKeepGoing?
751 // This may invalidate some of the following checks and needs to be done
757 const DataLayout &DL = OrigIns->getModule()->getDataLayout();
759 unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
760 unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
761 if (AsCall && SizeIndex < kNumberOfAccessSizes) {
762 Value *Fn = MS.MaybeWarningFn[SizeIndex];
763 Value *ConvertedShadow2 =
764 IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
765 IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
767 : (Value *)IRB.getInt32(0)});
769 Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
770 getCleanShadow(ConvertedShadow), "_mscmp");
771 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
773 /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
775 IRB.SetInsertPoint(CheckTerm);
776 if (MS.TrackOrigins) {
777 IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
780 IRB.CreateCall(MS.WarningFn, {});
781 IRB.CreateCall(MS.EmptyAsm, {});
782 DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
786 void materializeChecks(bool InstrumentWithCalls) {
787 for (const auto &ShadowData : InstrumentationList) {
788 Instruction *OrigIns = ShadowData.OrigIns;
789 Value *Shadow = ShadowData.Shadow;
790 Value *Origin = ShadowData.Origin;
791 materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
793 DEBUG(dbgs() << "DONE:\n" << F);
796 /// \brief Add MemorySanitizer instrumentation to a function.
797 bool runOnFunction() {
798 MS.initializeCallbacks(*F.getParent());
800 // In the presence of unreachable blocks, we may see Phi nodes with
801 // incoming nodes from such blocks. Since InstVisitor skips unreachable
802 // blocks, such nodes will not have any shadow value associated with them.
803 // It's easier to remove unreachable blocks than deal with missing shadow.
804 removeUnreachableBlocks(F);
806 // Iterate all BBs in depth-first order and create shadow instructions
807 // for all instructions (where applicable).
808 // For PHI nodes we create dummy shadow PHIs which will be finalized later.
809 for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
813 // Finalize PHI nodes.
814 for (PHINode *PN : ShadowPHINodes) {
815 PHINode *PNS = cast<PHINode>(getShadow(PN));
816 PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
817 size_t NumValues = PN->getNumIncomingValues();
818 for (size_t v = 0; v < NumValues; v++) {
819 PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
820 if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
824 VAHelper->finalizeInstrumentation();
826 bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
827 InstrumentationList.size() + StoreList.size() >
828 (unsigned)ClInstrumentationWithCallThreshold;
830 // Delayed instrumentation of StoreInst.
831 // This may add new checks to be inserted later.
832 materializeStores(InstrumentWithCalls);
834 // Insert shadow value checks.
835 materializeChecks(InstrumentWithCalls);
840 /// \brief Compute the shadow type that corresponds to a given Value.
841 Type *getShadowTy(Value *V) {
842 return getShadowTy(V->getType());
845 /// \brief Compute the shadow type that corresponds to a given Type.
846 Type *getShadowTy(Type *OrigTy) {
847 if (!OrigTy->isSized()) {
850 // For integer type, shadow is the same as the original type.
851 // This may return weird-sized types like i1.
852 if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
854 const DataLayout &DL = F.getParent()->getDataLayout();
855 if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
856 uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
857 return VectorType::get(IntegerType::get(*MS.C, EltSize),
858 VT->getNumElements());
860 if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
861 return ArrayType::get(getShadowTy(AT->getElementType()),
862 AT->getNumElements());
864 if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
865 SmallVector<Type*, 4> Elements;
866 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
867 Elements.push_back(getShadowTy(ST->getElementType(i)));
868 StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
869 DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
872 uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
873 return IntegerType::get(*MS.C, TypeSize);
876 /// \brief Flatten a vector type.
877 Type *getShadowTyNoVec(Type *ty) {
878 if (VectorType *vt = dyn_cast<VectorType>(ty))
879 return IntegerType::get(*MS.C, vt->getBitWidth());
883 /// \brief Convert a shadow value to it's flattened variant.
884 Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
885 Type *Ty = V->getType();
886 Type *NoVecTy = getShadowTyNoVec(Ty);
887 if (Ty == NoVecTy) return V;
888 return IRB.CreateBitCast(V, NoVecTy);
891 /// \brief Compute the integer shadow offset that corresponds to a given
892 /// application address.
894 /// Offset = (Addr & ~AndMask) ^ XorMask
895 Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
896 uint64_t AndMask = MS.MapParams->AndMask;
897 assert(AndMask != 0 && "AndMask shall be specified");
899 IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
900 ConstantInt::get(MS.IntptrTy, ~AndMask));
902 uint64_t XorMask = MS.MapParams->XorMask;
904 OffsetLong = IRB.CreateXor(OffsetLong,
905 ConstantInt::get(MS.IntptrTy, XorMask));
909 /// \brief Compute the shadow address that corresponds to a given application
912 /// Shadow = ShadowBase + Offset
913 Value *getShadowPtr(Value *Addr, Type *ShadowTy,
915 Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
916 uint64_t ShadowBase = MS.MapParams->ShadowBase;
919 IRB.CreateAdd(ShadowLong,
920 ConstantInt::get(MS.IntptrTy, ShadowBase));
921 return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
924 /// \brief Compute the origin address that corresponds to a given application
927 /// OriginAddr = (OriginBase + Offset) & ~3ULL
928 Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
929 Value *OriginLong = getShadowPtrOffset(Addr, IRB);
930 uint64_t OriginBase = MS.MapParams->OriginBase;
933 IRB.CreateAdd(OriginLong,
934 ConstantInt::get(MS.IntptrTy, OriginBase));
935 if (Alignment < kMinOriginAlignment) {
936 uint64_t Mask = kMinOriginAlignment - 1;
937 OriginLong = IRB.CreateAnd(OriginLong,
938 ConstantInt::get(MS.IntptrTy, ~Mask));
940 return IRB.CreateIntToPtr(OriginLong,
941 PointerType::get(IRB.getInt32Ty(), 0));
944 /// \brief Compute the shadow address for a given function argument.
946 /// Shadow = ParamTLS+ArgOffset.
947 Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
949 Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
950 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
951 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
955 /// \brief Compute the origin address for a given function argument.
956 Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
958 if (!MS.TrackOrigins) return nullptr;
959 Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
960 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
961 return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
965 /// \brief Compute the shadow address for a retval.
966 Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
967 Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
968 return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
972 /// \brief Compute the origin address for a retval.
973 Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
974 // We keep a single origin for the entire retval. Might be too optimistic.
975 return MS.RetvalOriginTLS;
978 /// \brief Set SV to be the shadow value for V.
979 void setShadow(Value *V, Value *SV) {
980 assert(!ShadowMap.count(V) && "Values may only have one shadow");
981 ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
984 /// \brief Set Origin to be the origin value for V.
985 void setOrigin(Value *V, Value *Origin) {
986 if (!MS.TrackOrigins) return;
987 assert(!OriginMap.count(V) && "Values may only have one origin");
988 DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
989 OriginMap[V] = Origin;
992 /// \brief Create a clean shadow value for a given value.
994 /// Clean shadow (all zeroes) means all bits of the value are defined
996 Constant *getCleanShadow(Value *V) {
997 Type *ShadowTy = getShadowTy(V);
1000 return Constant::getNullValue(ShadowTy);
1003 /// \brief Create a dirty shadow of a given shadow type.
1004 Constant *getPoisonedShadow(Type *ShadowTy) {
1006 if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1007 return Constant::getAllOnesValue(ShadowTy);
1008 if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1009 SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1010 getPoisonedShadow(AT->getElementType()));
1011 return ConstantArray::get(AT, Vals);
1013 if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1014 SmallVector<Constant *, 4> Vals;
1015 for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1016 Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1017 return ConstantStruct::get(ST, Vals);
1019 llvm_unreachable("Unexpected shadow type");
1022 /// \brief Create a dirty shadow for a given value.
1023 Constant *getPoisonedShadow(Value *V) {
1024 Type *ShadowTy = getShadowTy(V);
1027 return getPoisonedShadow(ShadowTy);
1030 /// \brief Create a clean (zero) origin.
1031 Value *getCleanOrigin() {
1032 return Constant::getNullValue(MS.OriginTy);
1035 /// \brief Get the shadow value for a given Value.
1037 /// This function either returns the value set earlier with setShadow,
1038 /// or extracts if from ParamTLS (for function arguments).
1039 Value *getShadow(Value *V) {
1040 if (!PropagateShadow) return getCleanShadow(V);
1041 if (Instruction *I = dyn_cast<Instruction>(V)) {
1042 // For instructions the shadow is already stored in the map.
1043 Value *Shadow = ShadowMap[V];
1045 DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1047 assert(Shadow && "No shadow for a value");
1051 if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1052 Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1053 DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1057 if (Argument *A = dyn_cast<Argument>(V)) {
1058 // For arguments we compute the shadow on demand and store it in the map.
1059 Value **ShadowPtr = &ShadowMap[V];
1062 Function *F = A->getParent();
1063 IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
1064 unsigned ArgOffset = 0;
1065 const DataLayout &DL = F->getParent()->getDataLayout();
1066 for (auto &FArg : F->args()) {
1067 if (!FArg.getType()->isSized()) {
1068 DEBUG(dbgs() << "Arg is not sized\n");
1073 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1074 : DL.getTypeAllocSize(FArg.getType());
1076 bool Overflow = ArgOffset + Size > kParamTLSSize;
1077 Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1078 if (FArg.hasByValAttr()) {
1079 // ByVal pointer itself has clean shadow. We copy the actual
1080 // argument shadow to the underlying memory.
1081 // Figure out maximal valid memcpy alignment.
1082 unsigned ArgAlign = FArg.getParamAlignment();
1083 if (ArgAlign == 0) {
1084 Type *EltType = A->getType()->getPointerElementType();
1085 ArgAlign = DL.getABITypeAlignment(EltType);
1088 // ParamTLS overflow.
1089 EntryIRB.CreateMemSet(
1090 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
1091 Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
1093 unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1094 Value *Cpy = EntryIRB.CreateMemCpy(
1095 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
1097 DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
1100 *ShadowPtr = getCleanShadow(V);
1103 // ParamTLS overflow.
1104 *ShadowPtr = getCleanShadow(V);
1107 EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1110 DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
1111 **ShadowPtr << "\n");
1112 if (MS.TrackOrigins && !Overflow) {
1114 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1115 setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1117 setOrigin(A, getCleanOrigin());
1120 ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
1122 assert(*ShadowPtr && "Could not find shadow for an argument");
1125 // For everything else the shadow is zero.
1126 return getCleanShadow(V);
1129 /// \brief Get the shadow for i-th argument of the instruction I.
1130 Value *getShadow(Instruction *I, int i) {
1131 return getShadow(I->getOperand(i));
1134 /// \brief Get the origin for a value.
1135 Value *getOrigin(Value *V) {
1136 if (!MS.TrackOrigins) return nullptr;
1137 if (!PropagateShadow) return getCleanOrigin();
1138 if (isa<Constant>(V)) return getCleanOrigin();
1139 assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1140 "Unexpected value type in getOrigin()");
1141 Value *Origin = OriginMap[V];
1142 assert(Origin && "Missing origin");
1146 /// \brief Get the origin for i-th argument of the instruction I.
1147 Value *getOrigin(Instruction *I, int i) {
1148 return getOrigin(I->getOperand(i));
1151 /// \brief Remember the place where a shadow check should be inserted.
1153 /// This location will be later instrumented with a check that will print a
1154 /// UMR warning in runtime if the shadow value is not 0.
1155 void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1157 if (!InsertChecks) return;
1159 Type *ShadowTy = Shadow->getType();
1160 assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1161 "Can only insert checks for integer and vector shadow types");
1163 InstrumentationList.push_back(
1164 ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1167 /// \brief Remember the place where a shadow check should be inserted.
1169 /// This location will be later instrumented with a check that will print a
1170 /// UMR warning in runtime if the value is not fully defined.
1171 void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1173 Value *Shadow, *Origin;
1174 if (ClCheckConstantShadow) {
1175 Shadow = getShadow(Val);
1176 if (!Shadow) return;
1177 Origin = getOrigin(Val);
1179 Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1180 if (!Shadow) return;
1181 Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1183 insertShadowCheck(Shadow, Origin, OrigIns);
1186 AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1195 case AcquireRelease:
1196 return AcquireRelease;
1197 case SequentiallyConsistent:
1198 return SequentiallyConsistent;
1200 llvm_unreachable("Unknown ordering");
1203 AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1212 case AcquireRelease:
1213 return AcquireRelease;
1214 case SequentiallyConsistent:
1215 return SequentiallyConsistent;
1217 llvm_unreachable("Unknown ordering");
1220 // ------------------- Visitors.
1222 /// \brief Instrument LoadInst
1224 /// Loads the corresponding shadow and (optionally) origin.
1225 /// Optionally, checks that the load address is fully defined.
1226 void visitLoadInst(LoadInst &I) {
1227 assert(I.getType()->isSized() && "Load type must have size");
1228 IRBuilder<> IRB(I.getNextNode());
1229 Type *ShadowTy = getShadowTy(&I);
1230 Value *Addr = I.getPointerOperand();
1231 if (PropagateShadow && !I.getMetadata("nosanitize")) {
1232 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1234 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1236 setShadow(&I, getCleanShadow(&I));
1239 if (ClCheckAccessAddress)
1240 insertShadowCheck(I.getPointerOperand(), &I);
1243 I.setOrdering(addAcquireOrdering(I.getOrdering()));
1245 if (MS.TrackOrigins) {
1246 if (PropagateShadow) {
1247 unsigned Alignment = I.getAlignment();
1248 unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1249 setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
1252 setOrigin(&I, getCleanOrigin());
1257 /// \brief Instrument StoreInst
1259 /// Stores the corresponding shadow and (optionally) origin.
1260 /// Optionally, checks that the store address is fully defined.
1261 void visitStoreInst(StoreInst &I) {
1262 StoreList.push_back(&I);
1265 void handleCASOrRMW(Instruction &I) {
1266 assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1268 IRBuilder<> IRB(&I);
1269 Value *Addr = I.getOperand(0);
1270 Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1272 if (ClCheckAccessAddress)
1273 insertShadowCheck(Addr, &I);
1275 // Only test the conditional argument of cmpxchg instruction.
1276 // The other argument can potentially be uninitialized, but we can not
1277 // detect this situation reliably without possible false positives.
1278 if (isa<AtomicCmpXchgInst>(I))
1279 insertShadowCheck(I.getOperand(1), &I);
1281 IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1283 setShadow(&I, getCleanShadow(&I));
1284 setOrigin(&I, getCleanOrigin());
1287 void visitAtomicRMWInst(AtomicRMWInst &I) {
1289 I.setOrdering(addReleaseOrdering(I.getOrdering()));
1292 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1294 I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1297 // Vector manipulation.
1298 void visitExtractElementInst(ExtractElementInst &I) {
1299 insertShadowCheck(I.getOperand(1), &I);
1300 IRBuilder<> IRB(&I);
1301 setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1303 setOrigin(&I, getOrigin(&I, 0));
1306 void visitInsertElementInst(InsertElementInst &I) {
1307 insertShadowCheck(I.getOperand(2), &I);
1308 IRBuilder<> IRB(&I);
1309 setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1310 I.getOperand(2), "_msprop"));
1311 setOriginForNaryOp(I);
1314 void visitShuffleVectorInst(ShuffleVectorInst &I) {
1315 insertShadowCheck(I.getOperand(2), &I);
1316 IRBuilder<> IRB(&I);
1317 setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1318 I.getOperand(2), "_msprop"));
1319 setOriginForNaryOp(I);
1323 void visitSExtInst(SExtInst &I) {
1324 IRBuilder<> IRB(&I);
1325 setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1326 setOrigin(&I, getOrigin(&I, 0));
1329 void visitZExtInst(ZExtInst &I) {
1330 IRBuilder<> IRB(&I);
1331 setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1332 setOrigin(&I, getOrigin(&I, 0));
1335 void visitTruncInst(TruncInst &I) {
1336 IRBuilder<> IRB(&I);
1337 setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1338 setOrigin(&I, getOrigin(&I, 0));
1341 void visitBitCastInst(BitCastInst &I) {
1342 // Special case: if this is the bitcast (there is exactly 1 allowed) between
1343 // a musttail call and a ret, don't instrument. New instructions are not
1344 // allowed after a musttail call.
1345 if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1346 if (CI->isMustTailCall())
1348 IRBuilder<> IRB(&I);
1349 setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1350 setOrigin(&I, getOrigin(&I, 0));
1353 void visitPtrToIntInst(PtrToIntInst &I) {
1354 IRBuilder<> IRB(&I);
1355 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1356 "_msprop_ptrtoint"));
1357 setOrigin(&I, getOrigin(&I, 0));
1360 void visitIntToPtrInst(IntToPtrInst &I) {
1361 IRBuilder<> IRB(&I);
1362 setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1363 "_msprop_inttoptr"));
1364 setOrigin(&I, getOrigin(&I, 0));
1367 void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1368 void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1369 void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1370 void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1371 void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1372 void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1374 /// \brief Propagate shadow for bitwise AND.
1376 /// This code is exact, i.e. if, for example, a bit in the left argument
1377 /// is defined and 0, then neither the value not definedness of the
1378 /// corresponding bit in B don't affect the resulting shadow.
1379 void visitAnd(BinaryOperator &I) {
1380 IRBuilder<> IRB(&I);
1381 // "And" of 0 and a poisoned value results in unpoisoned value.
1382 // 1&1 => 1; 0&1 => 0; p&1 => p;
1383 // 1&0 => 0; 0&0 => 0; p&0 => 0;
1384 // 1&p => p; 0&p => 0; p&p => p;
1385 // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1386 Value *S1 = getShadow(&I, 0);
1387 Value *S2 = getShadow(&I, 1);
1388 Value *V1 = I.getOperand(0);
1389 Value *V2 = I.getOperand(1);
1390 if (V1->getType() != S1->getType()) {
1391 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1392 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1394 Value *S1S2 = IRB.CreateAnd(S1, S2);
1395 Value *V1S2 = IRB.CreateAnd(V1, S2);
1396 Value *S1V2 = IRB.CreateAnd(S1, V2);
1397 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1398 setOriginForNaryOp(I);
1401 void visitOr(BinaryOperator &I) {
1402 IRBuilder<> IRB(&I);
1403 // "Or" of 1 and a poisoned value results in unpoisoned value.
1404 // 1|1 => 1; 0|1 => 1; p|1 => 1;
1405 // 1|0 => 1; 0|0 => 0; p|0 => p;
1406 // 1|p => 1; 0|p => p; p|p => p;
1407 // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1408 Value *S1 = getShadow(&I, 0);
1409 Value *S2 = getShadow(&I, 1);
1410 Value *V1 = IRB.CreateNot(I.getOperand(0));
1411 Value *V2 = IRB.CreateNot(I.getOperand(1));
1412 if (V1->getType() != S1->getType()) {
1413 V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1414 V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1416 Value *S1S2 = IRB.CreateAnd(S1, S2);
1417 Value *V1S2 = IRB.CreateAnd(V1, S2);
1418 Value *S1V2 = IRB.CreateAnd(S1, V2);
1419 setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1420 setOriginForNaryOp(I);
1423 /// \brief Default propagation of shadow and/or origin.
1425 /// This class implements the general case of shadow propagation, used in all
1426 /// cases where we don't know and/or don't care about what the operation
1427 /// actually does. It converts all input shadow values to a common type
1428 /// (extending or truncating as necessary), and bitwise OR's them.
1430 /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1431 /// fully initialized), and less prone to false positives.
1433 /// This class also implements the general case of origin propagation. For a
1434 /// Nary operation, result origin is set to the origin of an argument that is
1435 /// not entirely initialized. If there is more than one such arguments, the
1436 /// rightmost of them is picked. It does not matter which one is picked if all
1437 /// arguments are initialized.
1438 template <bool CombineShadow>
1443 MemorySanitizerVisitor *MSV;
1446 Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1447 Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1449 /// \brief Add a pair of shadow and origin values to the mix.
1450 Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1451 if (CombineShadow) {
1456 OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1457 Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1461 if (MSV->MS.TrackOrigins) {
1466 Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1467 // No point in adding something that might result in 0 origin value.
1468 if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1469 Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1471 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1472 Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1479 /// \brief Add an application value to the mix.
1480 Combiner &Add(Value *V) {
1481 Value *OpShadow = MSV->getShadow(V);
1482 Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1483 return Add(OpShadow, OpOrigin);
1486 /// \brief Set the current combined values as the given instruction's shadow
1488 void Done(Instruction *I) {
1489 if (CombineShadow) {
1491 Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1492 MSV->setShadow(I, Shadow);
1494 if (MSV->MS.TrackOrigins) {
1496 MSV->setOrigin(I, Origin);
1501 typedef Combiner<true> ShadowAndOriginCombiner;
1502 typedef Combiner<false> OriginCombiner;
1504 /// \brief Propagate origin for arbitrary operation.
1505 void setOriginForNaryOp(Instruction &I) {
1506 if (!MS.TrackOrigins) return;
1507 IRBuilder<> IRB(&I);
1508 OriginCombiner OC(this, IRB);
1509 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1514 size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1515 assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1516 "Vector of pointers is not a valid shadow type");
1517 return Ty->isVectorTy() ?
1518 Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1519 Ty->getPrimitiveSizeInBits();
1522 /// \brief Cast between two shadow types, extending or truncating as
1524 Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1525 bool Signed = false) {
1526 Type *srcTy = V->getType();
1527 if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1528 return IRB.CreateIntCast(V, dstTy, Signed);
1529 if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1530 dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1531 return IRB.CreateIntCast(V, dstTy, Signed);
1532 size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1533 size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1534 Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1536 IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1537 return IRB.CreateBitCast(V2, dstTy);
1538 // TODO: handle struct types.
1541 /// \brief Cast an application value to the type of its own shadow.
1542 Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1543 Type *ShadowTy = getShadowTy(V);
1544 if (V->getType() == ShadowTy)
1546 if (V->getType()->isPtrOrPtrVectorTy())
1547 return IRB.CreatePtrToInt(V, ShadowTy);
1549 return IRB.CreateBitCast(V, ShadowTy);
1552 /// \brief Propagate shadow for arbitrary operation.
1553 void handleShadowOr(Instruction &I) {
1554 IRBuilder<> IRB(&I);
1555 ShadowAndOriginCombiner SC(this, IRB);
1556 for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1561 // \brief Handle multiplication by constant.
1563 // Handle a special case of multiplication by constant that may have one or
1564 // more zeros in the lower bits. This makes corresponding number of lower bits
1565 // of the result zero as well. We model it by shifting the other operand
1566 // shadow left by the required number of bits. Effectively, we transform
1567 // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1568 // We use multiplication by 2**N instead of shift to cover the case of
1569 // multiplication by 0, which may occur in some elements of a vector operand.
1570 void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1572 Constant *ShadowMul;
1573 Type *Ty = ConstArg->getType();
1574 if (Ty->isVectorTy()) {
1575 unsigned NumElements = Ty->getVectorNumElements();
1576 Type *EltTy = Ty->getSequentialElementType();
1577 SmallVector<Constant *, 16> Elements;
1578 for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1580 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1581 APInt V = Elt->getValue();
1582 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1583 Elements.push_back(ConstantInt::get(EltTy, V2));
1585 ShadowMul = ConstantVector::get(Elements);
1587 ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1588 APInt V = Elt->getValue();
1589 APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1590 ShadowMul = ConstantInt::get(Elt->getType(), V2);
1593 IRBuilder<> IRB(&I);
1595 IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1596 setOrigin(&I, getOrigin(OtherArg));
1599 void visitMul(BinaryOperator &I) {
1600 Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1601 Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1602 if (constOp0 && !constOp1)
1603 handleMulByConstant(I, constOp0, I.getOperand(1));
1604 else if (constOp1 && !constOp0)
1605 handleMulByConstant(I, constOp1, I.getOperand(0));
1610 void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1611 void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1612 void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1613 void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1614 void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1615 void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1617 void handleDiv(Instruction &I) {
1618 IRBuilder<> IRB(&I);
1619 // Strict on the second argument.
1620 insertShadowCheck(I.getOperand(1), &I);
1621 setShadow(&I, getShadow(&I, 0));
1622 setOrigin(&I, getOrigin(&I, 0));
1625 void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1626 void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1627 void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1628 void visitURem(BinaryOperator &I) { handleDiv(I); }
1629 void visitSRem(BinaryOperator &I) { handleDiv(I); }
1630 void visitFRem(BinaryOperator &I) { handleDiv(I); }
1632 /// \brief Instrument == and != comparisons.
1634 /// Sometimes the comparison result is known even if some of the bits of the
1635 /// arguments are not.
1636 void handleEqualityComparison(ICmpInst &I) {
1637 IRBuilder<> IRB(&I);
1638 Value *A = I.getOperand(0);
1639 Value *B = I.getOperand(1);
1640 Value *Sa = getShadow(A);
1641 Value *Sb = getShadow(B);
1643 // Get rid of pointers and vectors of pointers.
1644 // For ints (and vectors of ints), types of A and Sa match,
1645 // and this is a no-op.
1646 A = IRB.CreatePointerCast(A, Sa->getType());
1647 B = IRB.CreatePointerCast(B, Sb->getType());
1649 // A == B <==> (C = A^B) == 0
1650 // A != B <==> (C = A^B) != 0
1652 Value *C = IRB.CreateXor(A, B);
1653 Value *Sc = IRB.CreateOr(Sa, Sb);
1654 // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1655 // Result is defined if one of the following is true
1656 // * there is a defined 1 bit in C
1657 // * C is fully defined
1658 // Si = !(C & ~Sc) && Sc
1659 Value *Zero = Constant::getNullValue(Sc->getType());
1660 Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1662 IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1664 IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1665 Si->setName("_msprop_icmp");
1667 setOriginForNaryOp(I);
1670 /// \brief Build the lowest possible value of V, taking into account V's
1671 /// uninitialized bits.
1672 Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1675 // Split shadow into sign bit and other bits.
1676 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1677 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1678 // Maximise the undefined shadow bit, minimize other undefined bits.
1680 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1682 // Minimize undefined bits.
1683 return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1687 /// \brief Build the highest possible value of V, taking into account V's
1688 /// uninitialized bits.
1689 Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1692 // Split shadow into sign bit and other bits.
1693 Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1694 Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1695 // Minimise the undefined shadow bit, maximise other undefined bits.
1697 IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1699 // Maximize undefined bits.
1700 return IRB.CreateOr(A, Sa);
1704 /// \brief Instrument relational comparisons.
1706 /// This function does exact shadow propagation for all relational
1707 /// comparisons of integers, pointers and vectors of those.
1708 /// FIXME: output seems suboptimal when one of the operands is a constant
1709 void handleRelationalComparisonExact(ICmpInst &I) {
1710 IRBuilder<> IRB(&I);
1711 Value *A = I.getOperand(0);
1712 Value *B = I.getOperand(1);
1713 Value *Sa = getShadow(A);
1714 Value *Sb = getShadow(B);
1716 // Get rid of pointers and vectors of pointers.
1717 // For ints (and vectors of ints), types of A and Sa match,
1718 // and this is a no-op.
1719 A = IRB.CreatePointerCast(A, Sa->getType());
1720 B = IRB.CreatePointerCast(B, Sb->getType());
1722 // Let [a0, a1] be the interval of possible values of A, taking into account
1723 // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1724 // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1725 bool IsSigned = I.isSigned();
1726 Value *S1 = IRB.CreateICmp(I.getPredicate(),
1727 getLowestPossibleValue(IRB, A, Sa, IsSigned),
1728 getHighestPossibleValue(IRB, B, Sb, IsSigned));
1729 Value *S2 = IRB.CreateICmp(I.getPredicate(),
1730 getHighestPossibleValue(IRB, A, Sa, IsSigned),
1731 getLowestPossibleValue(IRB, B, Sb, IsSigned));
1732 Value *Si = IRB.CreateXor(S1, S2);
1734 setOriginForNaryOp(I);
1737 /// \brief Instrument signed relational comparisons.
1739 /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
1740 /// bit of the shadow. Everything else is delegated to handleShadowOr().
1741 void handleSignedRelationalComparison(ICmpInst &I) {
1743 Value *op = nullptr;
1744 CmpInst::Predicate pre;
1745 if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
1746 op = I.getOperand(0);
1747 pre = I.getPredicate();
1748 } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
1749 op = I.getOperand(1);
1750 pre = I.getSwappedPredicate();
1756 if ((constOp->isNullValue() &&
1757 (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
1758 (constOp->isAllOnesValue() &&
1759 (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
1760 IRBuilder<> IRB(&I);
1761 Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
1763 setShadow(&I, Shadow);
1764 setOrigin(&I, getOrigin(op));
1770 void visitICmpInst(ICmpInst &I) {
1771 if (!ClHandleICmp) {
1775 if (I.isEquality()) {
1776 handleEqualityComparison(I);
1780 assert(I.isRelational());
1781 if (ClHandleICmpExact) {
1782 handleRelationalComparisonExact(I);
1786 handleSignedRelationalComparison(I);
1790 assert(I.isUnsigned());
1791 if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1792 handleRelationalComparisonExact(I);
1799 void visitFCmpInst(FCmpInst &I) {
1803 void handleShift(BinaryOperator &I) {
1804 IRBuilder<> IRB(&I);
1805 // If any of the S2 bits are poisoned, the whole thing is poisoned.
1806 // Otherwise perform the same shift on S1.
1807 Value *S1 = getShadow(&I, 0);
1808 Value *S2 = getShadow(&I, 1);
1809 Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1811 Value *V2 = I.getOperand(1);
1812 Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1813 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1814 setOriginForNaryOp(I);
1817 void visitShl(BinaryOperator &I) { handleShift(I); }
1818 void visitAShr(BinaryOperator &I) { handleShift(I); }
1819 void visitLShr(BinaryOperator &I) { handleShift(I); }
1821 /// \brief Instrument llvm.memmove
1823 /// At this point we don't know if llvm.memmove will be inlined or not.
1824 /// If we don't instrument it and it gets inlined,
1825 /// our interceptor will not kick in and we will lose the memmove.
1826 /// If we instrument the call here, but it does not get inlined,
1827 /// we will memove the shadow twice: which is bad in case
1828 /// of overlapping regions. So, we simply lower the intrinsic to a call.
1830 /// Similar situation exists for memcpy and memset.
1831 void visitMemMoveInst(MemMoveInst &I) {
1832 IRBuilder<> IRB(&I);
1835 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1836 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1837 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1838 I.eraseFromParent();
1841 // Similar to memmove: avoid copying shadow twice.
1842 // This is somewhat unfortunate as it may slowdown small constant memcpys.
1843 // FIXME: consider doing manual inline for small constant sizes and proper
1845 void visitMemCpyInst(MemCpyInst &I) {
1846 IRBuilder<> IRB(&I);
1849 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1850 IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1851 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1852 I.eraseFromParent();
1856 void visitMemSetInst(MemSetInst &I) {
1857 IRBuilder<> IRB(&I);
1860 {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1861 IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1862 IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
1863 I.eraseFromParent();
1866 void visitVAStartInst(VAStartInst &I) {
1867 VAHelper->visitVAStartInst(I);
1870 void visitVACopyInst(VACopyInst &I) {
1871 VAHelper->visitVACopyInst(I);
1874 enum IntrinsicKind {
1875 IK_DoesNotAccessMemory,
1880 static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1881 const int FMRB_DoesNotAccessMemory = IK_DoesNotAccessMemory;
1882 const int FMRB_OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1883 const int FMRB_OnlyReadsMemory = IK_OnlyReadsMemory;
1884 const int FMRB_OnlyAccessesArgumentPointees = IK_WritesMemory;
1885 const int FMRB_UnknownModRefBehavior = IK_WritesMemory;
1886 #define GET_INTRINSIC_MODREF_BEHAVIOR
1887 #define FunctionModRefBehavior IntrinsicKind
1888 #include "llvm/IR/Intrinsics.gen"
1889 #undef FunctionModRefBehavior
1890 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1893 /// \brief Handle vector store-like intrinsics.
1895 /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1896 /// has 1 pointer argument and 1 vector argument, returns void.
1897 bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1898 IRBuilder<> IRB(&I);
1899 Value* Addr = I.getArgOperand(0);
1900 Value *Shadow = getShadow(&I, 1);
1901 Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1903 // We don't know the pointer alignment (could be unaligned SSE store!).
1904 // Have to assume to worst case.
1905 IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1907 if (ClCheckAccessAddress)
1908 insertShadowCheck(Addr, &I);
1910 // FIXME: use ClStoreCleanOrigin
1911 // FIXME: factor out common code from materializeStores
1912 if (MS.TrackOrigins)
1913 IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
1917 /// \brief Handle vector load-like intrinsics.
1919 /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1920 /// has 1 pointer argument, returns a vector.
1921 bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1922 IRBuilder<> IRB(&I);
1923 Value *Addr = I.getArgOperand(0);
1925 Type *ShadowTy = getShadowTy(&I);
1926 if (PropagateShadow) {
1927 Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1928 // We don't know the pointer alignment (could be unaligned SSE load!).
1929 // Have to assume to worst case.
1930 setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1932 setShadow(&I, getCleanShadow(&I));
1935 if (ClCheckAccessAddress)
1936 insertShadowCheck(Addr, &I);
1938 if (MS.TrackOrigins) {
1939 if (PropagateShadow)
1940 setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
1942 setOrigin(&I, getCleanOrigin());
1947 /// \brief Handle (SIMD arithmetic)-like intrinsics.
1949 /// Instrument intrinsics with any number of arguments of the same type,
1950 /// equal to the return type. The type should be simple (no aggregates or
1951 /// pointers; vectors are fine).
1952 /// Caller guarantees that this intrinsic does not access memory.
1953 bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1954 Type *RetTy = I.getType();
1955 if (!(RetTy->isIntOrIntVectorTy() ||
1956 RetTy->isFPOrFPVectorTy() ||
1957 RetTy->isX86_MMXTy()))
1960 unsigned NumArgOperands = I.getNumArgOperands();
1962 for (unsigned i = 0; i < NumArgOperands; ++i) {
1963 Type *Ty = I.getArgOperand(i)->getType();
1968 IRBuilder<> IRB(&I);
1969 ShadowAndOriginCombiner SC(this, IRB);
1970 for (unsigned i = 0; i < NumArgOperands; ++i)
1971 SC.Add(I.getArgOperand(i));
1977 /// \brief Heuristically instrument unknown intrinsics.
1979 /// The main purpose of this code is to do something reasonable with all
1980 /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1981 /// We recognize several classes of intrinsics by their argument types and
1982 /// ModRefBehaviour and apply special intrumentation when we are reasonably
1983 /// sure that we know what the intrinsic does.
1985 /// We special-case intrinsics where this approach fails. See llvm.bswap
1986 /// handling as an example of that.
1987 bool handleUnknownIntrinsic(IntrinsicInst &I) {
1988 unsigned NumArgOperands = I.getNumArgOperands();
1989 if (NumArgOperands == 0)
1992 Intrinsic::ID iid = I.getIntrinsicID();
1993 IntrinsicKind IK = getIntrinsicKind(iid);
1994 bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1995 bool WritesMemory = IK == IK_WritesMemory;
1996 assert(!(OnlyReadsMemory && WritesMemory));
1998 if (NumArgOperands == 2 &&
1999 I.getArgOperand(0)->getType()->isPointerTy() &&
2000 I.getArgOperand(1)->getType()->isVectorTy() &&
2001 I.getType()->isVoidTy() &&
2003 // This looks like a vector store.
2004 return handleVectorStoreIntrinsic(I);
2007 if (NumArgOperands == 1 &&
2008 I.getArgOperand(0)->getType()->isPointerTy() &&
2009 I.getType()->isVectorTy() &&
2011 // This looks like a vector load.
2012 return handleVectorLoadIntrinsic(I);
2015 if (!OnlyReadsMemory && !WritesMemory)
2016 if (maybeHandleSimpleNomemIntrinsic(I))
2019 // FIXME: detect and handle SSE maskstore/maskload
2023 void handleBswap(IntrinsicInst &I) {
2024 IRBuilder<> IRB(&I);
2025 Value *Op = I.getArgOperand(0);
2026 Type *OpType = Op->getType();
2027 Function *BswapFunc = Intrinsic::getDeclaration(
2028 F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2029 setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2030 setOrigin(&I, getOrigin(Op));
2033 // \brief Instrument vector convert instrinsic.
2035 // This function instruments intrinsics like cvtsi2ss:
2036 // %Out = int_xxx_cvtyyy(%ConvertOp)
2038 // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2039 // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2040 // number \p Out elements, and (if has 2 arguments) copies the rest of the
2041 // elements from \p CopyOp.
2042 // In most cases conversion involves floating-point value which may trigger a
2043 // hardware exception when not fully initialized. For this reason we require
2044 // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2045 // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2046 // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2047 // return a fully initialized value.
2048 void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2049 IRBuilder<> IRB(&I);
2050 Value *CopyOp, *ConvertOp;
2052 switch (I.getNumArgOperands()) {
2054 assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2056 CopyOp = I.getArgOperand(0);
2057 ConvertOp = I.getArgOperand(1);
2060 ConvertOp = I.getArgOperand(0);
2064 llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2067 // The first *NumUsedElements* elements of ConvertOp are converted to the
2068 // same number of output elements. The rest of the output is copied from
2069 // CopyOp, or (if not available) filled with zeroes.
2070 // Combine shadow for elements of ConvertOp that are used in this operation,
2071 // and insert a check.
2072 // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2073 // int->any conversion.
2074 Value *ConvertShadow = getShadow(ConvertOp);
2075 Value *AggShadow = nullptr;
2076 if (ConvertOp->getType()->isVectorTy()) {
2077 AggShadow = IRB.CreateExtractElement(
2078 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2079 for (int i = 1; i < NumUsedElements; ++i) {
2080 Value *MoreShadow = IRB.CreateExtractElement(
2081 ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2082 AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2085 AggShadow = ConvertShadow;
2087 assert(AggShadow->getType()->isIntegerTy());
2088 insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2090 // Build result shadow by zero-filling parts of CopyOp shadow that come from
2093 assert(CopyOp->getType() == I.getType());
2094 assert(CopyOp->getType()->isVectorTy());
2095 Value *ResultShadow = getShadow(CopyOp);
2096 Type *EltTy = ResultShadow->getType()->getVectorElementType();
2097 for (int i = 0; i < NumUsedElements; ++i) {
2098 ResultShadow = IRB.CreateInsertElement(
2099 ResultShadow, ConstantInt::getNullValue(EltTy),
2100 ConstantInt::get(IRB.getInt32Ty(), i));
2102 setShadow(&I, ResultShadow);
2103 setOrigin(&I, getOrigin(CopyOp));
2105 setShadow(&I, getCleanShadow(&I));
2106 setOrigin(&I, getCleanOrigin());
2110 // Given a scalar or vector, extract lower 64 bits (or less), and return all
2111 // zeroes if it is zero, and all ones otherwise.
2112 Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2113 if (S->getType()->isVectorTy())
2114 S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2115 assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2116 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2117 return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2120 Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2121 Type *T = S->getType();
2122 assert(T->isVectorTy());
2123 Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2124 return IRB.CreateSExt(S2, T);
2127 // \brief Instrument vector shift instrinsic.
2129 // This function instruments intrinsics like int_x86_avx2_psll_w.
2130 // Intrinsic shifts %In by %ShiftSize bits.
2131 // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2132 // size, and the rest is ignored. Behavior is defined even if shift size is
2133 // greater than register (or field) width.
2134 void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2135 assert(I.getNumArgOperands() == 2);
2136 IRBuilder<> IRB(&I);
2137 // If any of the S2 bits are poisoned, the whole thing is poisoned.
2138 // Otherwise perform the same shift on S1.
2139 Value *S1 = getShadow(&I, 0);
2140 Value *S2 = getShadow(&I, 1);
2141 Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2142 : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2143 Value *V1 = I.getOperand(0);
2144 Value *V2 = I.getOperand(1);
2145 Value *Shift = IRB.CreateCall(I.getCalledValue(),
2146 {IRB.CreateBitCast(S1, V1->getType()), V2});
2147 Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2148 setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2149 setOriginForNaryOp(I);
2152 // \brief Get an X86_MMX-sized vector type.
2153 Type *getMMXVectorTy(unsigned EltSizeInBits) {
2154 const unsigned X86_MMXSizeInBits = 64;
2155 return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2156 X86_MMXSizeInBits / EltSizeInBits);
2159 // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2161 Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2163 case llvm::Intrinsic::x86_sse2_packsswb_128:
2164 case llvm::Intrinsic::x86_sse2_packuswb_128:
2165 return llvm::Intrinsic::x86_sse2_packsswb_128;
2167 case llvm::Intrinsic::x86_sse2_packssdw_128:
2168 case llvm::Intrinsic::x86_sse41_packusdw:
2169 return llvm::Intrinsic::x86_sse2_packssdw_128;
2171 case llvm::Intrinsic::x86_avx2_packsswb:
2172 case llvm::Intrinsic::x86_avx2_packuswb:
2173 return llvm::Intrinsic::x86_avx2_packsswb;
2175 case llvm::Intrinsic::x86_avx2_packssdw:
2176 case llvm::Intrinsic::x86_avx2_packusdw:
2177 return llvm::Intrinsic::x86_avx2_packssdw;
2179 case llvm::Intrinsic::x86_mmx_packsswb:
2180 case llvm::Intrinsic::x86_mmx_packuswb:
2181 return llvm::Intrinsic::x86_mmx_packsswb;
2183 case llvm::Intrinsic::x86_mmx_packssdw:
2184 return llvm::Intrinsic::x86_mmx_packssdw;
2186 llvm_unreachable("unexpected intrinsic id");
2190 // \brief Instrument vector pack instrinsic.
2192 // This function instruments intrinsics like x86_mmx_packsswb, that
2193 // packs elements of 2 input vectors into half as many bits with saturation.
2194 // Shadow is propagated with the signed variant of the same intrinsic applied
2195 // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2196 // EltSizeInBits is used only for x86mmx arguments.
2197 void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2198 assert(I.getNumArgOperands() == 2);
2199 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2200 IRBuilder<> IRB(&I);
2201 Value *S1 = getShadow(&I, 0);
2202 Value *S2 = getShadow(&I, 1);
2203 assert(isX86_MMX || S1->getType()->isVectorTy());
2205 // SExt and ICmpNE below must apply to individual elements of input vectors.
2206 // In case of x86mmx arguments, cast them to appropriate vector types and
2208 Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2210 S1 = IRB.CreateBitCast(S1, T);
2211 S2 = IRB.CreateBitCast(S2, T);
2213 Value *S1_ext = IRB.CreateSExt(
2214 IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2215 Value *S2_ext = IRB.CreateSExt(
2216 IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2218 Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2219 S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2220 S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2223 Function *ShadowFn = Intrinsic::getDeclaration(
2224 F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2227 IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2228 if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2230 setOriginForNaryOp(I);
2233 // \brief Instrument sum-of-absolute-differencies intrinsic.
2234 void handleVectorSadIntrinsic(IntrinsicInst &I) {
2235 const unsigned SignificantBitsPerResultElement = 16;
2236 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2237 Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2238 unsigned ZeroBitsPerResultElement =
2239 ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2241 IRBuilder<> IRB(&I);
2242 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2243 S = IRB.CreateBitCast(S, ResTy);
2244 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2246 S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2247 S = IRB.CreateBitCast(S, getShadowTy(&I));
2249 setOriginForNaryOp(I);
2252 // \brief Instrument multiply-add intrinsic.
2253 void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2254 unsigned EltSizeInBits = 0) {
2255 bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2256 Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2257 IRBuilder<> IRB(&I);
2258 Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2259 S = IRB.CreateBitCast(S, ResTy);
2260 S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2262 S = IRB.CreateBitCast(S, getShadowTy(&I));
2264 setOriginForNaryOp(I);
2267 void visitIntrinsicInst(IntrinsicInst &I) {
2268 switch (I.getIntrinsicID()) {
2269 case llvm::Intrinsic::bswap:
2272 case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2273 case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2274 case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2275 case llvm::Intrinsic::x86_avx512_cvtss2usi:
2276 case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2277 case llvm::Intrinsic::x86_avx512_cvttss2usi:
2278 case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2279 case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2280 case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2281 case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2282 case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2283 case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2284 case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2285 case llvm::Intrinsic::x86_sse2_cvtsd2si:
2286 case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2287 case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2288 case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2289 case llvm::Intrinsic::x86_sse2_cvtss2sd:
2290 case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2291 case llvm::Intrinsic::x86_sse2_cvttsd2si:
2292 case llvm::Intrinsic::x86_sse_cvtsi2ss:
2293 case llvm::Intrinsic::x86_sse_cvtsi642ss:
2294 case llvm::Intrinsic::x86_sse_cvtss2si64:
2295 case llvm::Intrinsic::x86_sse_cvtss2si:
2296 case llvm::Intrinsic::x86_sse_cvttss2si64:
2297 case llvm::Intrinsic::x86_sse_cvttss2si:
2298 handleVectorConvertIntrinsic(I, 1);
2300 case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2301 case llvm::Intrinsic::x86_sse2_cvtps2pd:
2302 case llvm::Intrinsic::x86_sse_cvtps2pi:
2303 case llvm::Intrinsic::x86_sse_cvttps2pi:
2304 handleVectorConvertIntrinsic(I, 2);
2306 case llvm::Intrinsic::x86_avx2_psll_w:
2307 case llvm::Intrinsic::x86_avx2_psll_d:
2308 case llvm::Intrinsic::x86_avx2_psll_q:
2309 case llvm::Intrinsic::x86_avx2_pslli_w:
2310 case llvm::Intrinsic::x86_avx2_pslli_d:
2311 case llvm::Intrinsic::x86_avx2_pslli_q:
2312 case llvm::Intrinsic::x86_avx2_psrl_w:
2313 case llvm::Intrinsic::x86_avx2_psrl_d:
2314 case llvm::Intrinsic::x86_avx2_psrl_q:
2315 case llvm::Intrinsic::x86_avx2_psra_w:
2316 case llvm::Intrinsic::x86_avx2_psra_d:
2317 case llvm::Intrinsic::x86_avx2_psrli_w:
2318 case llvm::Intrinsic::x86_avx2_psrli_d:
2319 case llvm::Intrinsic::x86_avx2_psrli_q:
2320 case llvm::Intrinsic::x86_avx2_psrai_w:
2321 case llvm::Intrinsic::x86_avx2_psrai_d:
2322 case llvm::Intrinsic::x86_sse2_psll_w:
2323 case llvm::Intrinsic::x86_sse2_psll_d:
2324 case llvm::Intrinsic::x86_sse2_psll_q:
2325 case llvm::Intrinsic::x86_sse2_pslli_w:
2326 case llvm::Intrinsic::x86_sse2_pslli_d:
2327 case llvm::Intrinsic::x86_sse2_pslli_q:
2328 case llvm::Intrinsic::x86_sse2_psrl_w:
2329 case llvm::Intrinsic::x86_sse2_psrl_d:
2330 case llvm::Intrinsic::x86_sse2_psrl_q:
2331 case llvm::Intrinsic::x86_sse2_psra_w:
2332 case llvm::Intrinsic::x86_sse2_psra_d:
2333 case llvm::Intrinsic::x86_sse2_psrli_w:
2334 case llvm::Intrinsic::x86_sse2_psrli_d:
2335 case llvm::Intrinsic::x86_sse2_psrli_q:
2336 case llvm::Intrinsic::x86_sse2_psrai_w:
2337 case llvm::Intrinsic::x86_sse2_psrai_d:
2338 case llvm::Intrinsic::x86_mmx_psll_w:
2339 case llvm::Intrinsic::x86_mmx_psll_d:
2340 case llvm::Intrinsic::x86_mmx_psll_q:
2341 case llvm::Intrinsic::x86_mmx_pslli_w:
2342 case llvm::Intrinsic::x86_mmx_pslli_d:
2343 case llvm::Intrinsic::x86_mmx_pslli_q:
2344 case llvm::Intrinsic::x86_mmx_psrl_w:
2345 case llvm::Intrinsic::x86_mmx_psrl_d:
2346 case llvm::Intrinsic::x86_mmx_psrl_q:
2347 case llvm::Intrinsic::x86_mmx_psra_w:
2348 case llvm::Intrinsic::x86_mmx_psra_d:
2349 case llvm::Intrinsic::x86_mmx_psrli_w:
2350 case llvm::Intrinsic::x86_mmx_psrli_d:
2351 case llvm::Intrinsic::x86_mmx_psrli_q:
2352 case llvm::Intrinsic::x86_mmx_psrai_w:
2353 case llvm::Intrinsic::x86_mmx_psrai_d:
2354 handleVectorShiftIntrinsic(I, /* Variable */ false);
2356 case llvm::Intrinsic::x86_avx2_psllv_d:
2357 case llvm::Intrinsic::x86_avx2_psllv_d_256:
2358 case llvm::Intrinsic::x86_avx2_psllv_q:
2359 case llvm::Intrinsic::x86_avx2_psllv_q_256:
2360 case llvm::Intrinsic::x86_avx2_psrlv_d:
2361 case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2362 case llvm::Intrinsic::x86_avx2_psrlv_q:
2363 case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2364 case llvm::Intrinsic::x86_avx2_psrav_d:
2365 case llvm::Intrinsic::x86_avx2_psrav_d_256:
2366 handleVectorShiftIntrinsic(I, /* Variable */ true);
2369 case llvm::Intrinsic::x86_sse2_packsswb_128:
2370 case llvm::Intrinsic::x86_sse2_packssdw_128:
2371 case llvm::Intrinsic::x86_sse2_packuswb_128:
2372 case llvm::Intrinsic::x86_sse41_packusdw:
2373 case llvm::Intrinsic::x86_avx2_packsswb:
2374 case llvm::Intrinsic::x86_avx2_packssdw:
2375 case llvm::Intrinsic::x86_avx2_packuswb:
2376 case llvm::Intrinsic::x86_avx2_packusdw:
2377 handleVectorPackIntrinsic(I);
2380 case llvm::Intrinsic::x86_mmx_packsswb:
2381 case llvm::Intrinsic::x86_mmx_packuswb:
2382 handleVectorPackIntrinsic(I, 16);
2385 case llvm::Intrinsic::x86_mmx_packssdw:
2386 handleVectorPackIntrinsic(I, 32);
2389 case llvm::Intrinsic::x86_mmx_psad_bw:
2390 case llvm::Intrinsic::x86_sse2_psad_bw:
2391 case llvm::Intrinsic::x86_avx2_psad_bw:
2392 handleVectorSadIntrinsic(I);
2395 case llvm::Intrinsic::x86_sse2_pmadd_wd:
2396 case llvm::Intrinsic::x86_avx2_pmadd_wd:
2397 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2398 case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2399 handleVectorPmaddIntrinsic(I);
2402 case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2403 handleVectorPmaddIntrinsic(I, 8);
2406 case llvm::Intrinsic::x86_mmx_pmadd_wd:
2407 handleVectorPmaddIntrinsic(I, 16);
2411 if (!handleUnknownIntrinsic(I))
2412 visitInstruction(I);
2417 void visitCallSite(CallSite CS) {
2418 Instruction &I = *CS.getInstruction();
2419 assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2421 CallInst *Call = cast<CallInst>(&I);
2423 // For inline asm, do the usual thing: check argument shadow and mark all
2424 // outputs as clean. Note that any side effects of the inline asm that are
2425 // not immediately visible in its constraints are not handled.
2426 if (Call->isInlineAsm()) {
2427 visitInstruction(I);
2431 assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2433 // We are going to insert code that relies on the fact that the callee
2434 // will become a non-readonly function after it is instrumented by us. To
2435 // prevent this code from being optimized out, mark that function
2436 // non-readonly in advance.
2437 if (Function *Func = Call->getCalledFunction()) {
2438 // Clear out readonly/readnone attributes.
2440 B.addAttribute(Attribute::ReadOnly)
2441 .addAttribute(Attribute::ReadNone);
2442 Func->removeAttributes(AttributeSet::FunctionIndex,
2443 AttributeSet::get(Func->getContext(),
2444 AttributeSet::FunctionIndex,
2448 IRBuilder<> IRB(&I);
2450 unsigned ArgOffset = 0;
2451 DEBUG(dbgs() << " CallSite: " << I << "\n");
2452 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2453 ArgIt != End; ++ArgIt) {
2455 unsigned i = ArgIt - CS.arg_begin();
2456 if (!A->getType()->isSized()) {
2457 DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2461 Value *Store = nullptr;
2462 // Compute the Shadow for arg even if it is ByVal, because
2463 // in that case getShadow() will copy the actual arg shadow to
2464 // __msan_param_tls.
2465 Value *ArgShadow = getShadow(A);
2466 Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2467 DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
2468 " Shadow: " << *ArgShadow << "\n");
2469 bool ArgIsInitialized = false;
2470 const DataLayout &DL = F.getParent()->getDataLayout();
2471 if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2472 assert(A->getType()->isPointerTy() &&
2473 "ByVal argument is not a pointer!");
2474 Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
2475 if (ArgOffset + Size > kParamTLSSize) break;
2476 unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2477 unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2478 Store = IRB.CreateMemCpy(ArgShadowBase,
2479 getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2482 Size = DL.getTypeAllocSize(A->getType());
2483 if (ArgOffset + Size > kParamTLSSize) break;
2484 Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2485 kShadowTLSAlignment);
2486 Constant *Cst = dyn_cast<Constant>(ArgShadow);
2487 if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2489 if (MS.TrackOrigins && !ArgIsInitialized)
2490 IRB.CreateStore(getOrigin(A),
2491 getOriginPtrForArgument(A, IRB, ArgOffset));
2493 assert(Size != 0 && Store != nullptr);
2494 DEBUG(dbgs() << " Param:" << *Store << "\n");
2495 ArgOffset += RoundUpToAlignment(Size, 8);
2497 DEBUG(dbgs() << " done with call args\n");
2500 cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2501 if (FT->isVarArg()) {
2502 VAHelper->visitCallSite(CS, IRB);
2505 // Now, get the shadow for the RetVal.
2506 if (!I.getType()->isSized()) return;
2507 // Don't emit the epilogue for musttail call returns.
2508 if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
2509 IRBuilder<> IRBBefore(&I);
2510 // Until we have full dynamic coverage, make sure the retval shadow is 0.
2511 Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2512 IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2513 Instruction *NextInsn = nullptr;
2515 NextInsn = I.getNextNode();
2517 BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2518 if (!NormalDest->getSinglePredecessor()) {
2519 // FIXME: this case is tricky, so we are just conservative here.
2520 // Perhaps we need to split the edge between this BB and NormalDest,
2521 // but a naive attempt to use SplitEdge leads to a crash.
2522 setShadow(&I, getCleanShadow(&I));
2523 setOrigin(&I, getCleanOrigin());
2526 NextInsn = NormalDest->getFirstInsertionPt();
2528 "Could not find insertion point for retval shadow load");
2530 IRBuilder<> IRBAfter(NextInsn);
2531 Value *RetvalShadow =
2532 IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2533 kShadowTLSAlignment, "_msret");
2534 setShadow(&I, RetvalShadow);
2535 if (MS.TrackOrigins)
2536 setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2539 bool isAMustTailRetVal(Value *RetVal) {
2540 if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
2541 RetVal = I->getOperand(0);
2543 if (auto *I = dyn_cast<CallInst>(RetVal)) {
2544 return I->isMustTailCall();
2549 void visitReturnInst(ReturnInst &I) {
2550 IRBuilder<> IRB(&I);
2551 Value *RetVal = I.getReturnValue();
2552 if (!RetVal) return;
2553 // Don't emit the epilogue for musttail call returns.
2554 if (isAMustTailRetVal(RetVal)) return;
2555 Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2556 if (CheckReturnValue) {
2557 insertShadowCheck(RetVal, &I);
2558 Value *Shadow = getCleanShadow(RetVal);
2559 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2561 Value *Shadow = getShadow(RetVal);
2562 IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2563 // FIXME: make it conditional if ClStoreCleanOrigin==0
2564 if (MS.TrackOrigins)
2565 IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2569 void visitPHINode(PHINode &I) {
2570 IRBuilder<> IRB(&I);
2571 if (!PropagateShadow) {
2572 setShadow(&I, getCleanShadow(&I));
2573 setOrigin(&I, getCleanOrigin());
2577 ShadowPHINodes.push_back(&I);
2578 setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2580 if (MS.TrackOrigins)
2581 setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2585 void visitAllocaInst(AllocaInst &I) {
2586 setShadow(&I, getCleanShadow(&I));
2587 setOrigin(&I, getCleanOrigin());
2588 IRBuilder<> IRB(I.getNextNode());
2589 const DataLayout &DL = F.getParent()->getDataLayout();
2590 uint64_t Size = DL.getTypeAllocSize(I.getAllocatedType());
2591 if (PoisonStack && ClPoisonStackWithCall) {
2592 IRB.CreateCall(MS.MsanPoisonStackFn,
2593 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2594 ConstantInt::get(MS.IntptrTy, Size)});
2596 Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2597 Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2598 IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2601 if (PoisonStack && MS.TrackOrigins) {
2602 SmallString<2048> StackDescriptionStorage;
2603 raw_svector_ostream StackDescription(StackDescriptionStorage);
2604 // We create a string with a description of the stack allocation and
2605 // pass it into __msan_set_alloca_origin.
2606 // It will be printed by the run-time if stack-originated UMR is found.
2607 // The first 4 bytes of the string are set to '----' and will be replaced
2608 // by __msan_va_arg_overflow_size_tls at the first call.
2609 StackDescription << "----" << I.getName() << "@" << F.getName();
2611 createPrivateNonConstGlobalForString(*F.getParent(),
2612 StackDescription.str());
2614 IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
2615 {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2616 ConstantInt::get(MS.IntptrTy, Size),
2617 IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2618 IRB.CreatePointerCast(&F, MS.IntptrTy)});
2622 void visitSelectInst(SelectInst& I) {
2623 IRBuilder<> IRB(&I);
2624 // a = select b, c, d
2625 Value *B = I.getCondition();
2626 Value *C = I.getTrueValue();
2627 Value *D = I.getFalseValue();
2628 Value *Sb = getShadow(B);
2629 Value *Sc = getShadow(C);
2630 Value *Sd = getShadow(D);
2632 // Result shadow if condition shadow is 0.
2633 Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2635 if (I.getType()->isAggregateType()) {
2636 // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2637 // an extra "select". This results in much more compact IR.
2638 // Sa = select Sb, poisoned, (select b, Sc, Sd)
2639 Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2641 // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2642 // If Sb (condition is poisoned), look for bits in c and d that are equal
2643 // and both unpoisoned.
2644 // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2646 // Cast arguments to shadow-compatible type.
2647 C = CreateAppToShadowCast(IRB, C);
2648 D = CreateAppToShadowCast(IRB, D);
2650 // Result shadow if condition shadow is 1.
2651 Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2653 Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2655 if (MS.TrackOrigins) {
2656 // Origins are always i32, so any vector conditions must be flattened.
2657 // FIXME: consider tracking vector origins for app vectors?
2658 if (B->getType()->isVectorTy()) {
2659 Type *FlatTy = getShadowTyNoVec(B->getType());
2660 B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2661 ConstantInt::getNullValue(FlatTy));
2662 Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2663 ConstantInt::getNullValue(FlatTy));
2665 // a = select b, c, d
2666 // Oa = Sb ? Ob : (b ? Oc : Od)
2668 &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
2669 IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
2670 getOrigin(I.getFalseValue()))));
2674 void visitLandingPadInst(LandingPadInst &I) {
2676 // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2677 setShadow(&I, getCleanShadow(&I));
2678 setOrigin(&I, getCleanOrigin());
2681 void visitCleanupPadInst(CleanupPadInst &I) {
2682 setShadow(&I, getCleanShadow(&I));
2683 setOrigin(&I, getCleanOrigin());
2686 void visitCatchPad(CatchPadInst &I) {
2687 setShadow(&I, getCleanShadow(&I));
2688 setOrigin(&I, getCleanOrigin());
2691 void visitTerminatePad(TerminatePadInst &I) {
2692 DEBUG(dbgs() << "TerminatePad: " << I << "\n");
2693 // Nothing to do here.
2696 void visitCatchEndPadInst(CatchEndPadInst &I) {
2697 DEBUG(dbgs() << "CatchEndPad: " << I << "\n");
2698 // Nothing to do here.
2701 void visitCleanupEndPadInst(CleanupEndPadInst &I) {
2702 DEBUG(dbgs() << "CleanupEndPad: " << I << "\n");
2703 // Nothing to do here.
2706 void visitGetElementPtrInst(GetElementPtrInst &I) {
2710 void visitExtractValueInst(ExtractValueInst &I) {
2711 IRBuilder<> IRB(&I);
2712 Value *Agg = I.getAggregateOperand();
2713 DEBUG(dbgs() << "ExtractValue: " << I << "\n");
2714 Value *AggShadow = getShadow(Agg);
2715 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2716 Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2717 DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
2718 setShadow(&I, ResShadow);
2719 setOriginForNaryOp(I);
2722 void visitInsertValueInst(InsertValueInst &I) {
2723 IRBuilder<> IRB(&I);
2724 DEBUG(dbgs() << "InsertValue: " << I << "\n");
2725 Value *AggShadow = getShadow(I.getAggregateOperand());
2726 Value *InsShadow = getShadow(I.getInsertedValueOperand());
2727 DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
2728 DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
2729 Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2730 DEBUG(dbgs() << " Res: " << *Res << "\n");
2732 setOriginForNaryOp(I);
2735 void dumpInst(Instruction &I) {
2736 if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2737 errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2739 errs() << "ZZZ " << I.getOpcodeName() << "\n";
2741 errs() << "QQQ " << I << "\n";
2744 void visitResumeInst(ResumeInst &I) {
2745 DEBUG(dbgs() << "Resume: " << I << "\n");
2746 // Nothing to do here.
2749 void visitCleanupReturnInst(CleanupReturnInst &CRI) {
2750 DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
2751 // Nothing to do here.
2754 void visitCatchReturnInst(CatchReturnInst &CRI) {
2755 DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
2756 // Nothing to do here.
2759 void visitInstruction(Instruction &I) {
2760 // Everything else: stop propagating and check for poisoned shadow.
2761 if (ClDumpStrictInstructions)
2763 DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2764 for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2765 insertShadowCheck(I.getOperand(i), &I);
2766 setShadow(&I, getCleanShadow(&I));
2767 setOrigin(&I, getCleanOrigin());
2771 /// \brief AMD64-specific implementation of VarArgHelper.
2772 struct VarArgAMD64Helper : public VarArgHelper {
2773 // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2774 // See a comment in visitCallSite for more details.
2775 static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
2776 static const unsigned AMD64FpEndOffset = 176;
2779 MemorySanitizer &MS;
2780 MemorySanitizerVisitor &MSV;
2781 Value *VAArgTLSCopy;
2782 Value *VAArgOverflowSize;
2784 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2786 VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2787 MemorySanitizerVisitor &MSV)
2788 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2789 VAArgOverflowSize(nullptr) {}
2791 enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2793 ArgKind classifyArgument(Value* arg) {
2794 // A very rough approximation of X86_64 argument classification rules.
2795 Type *T = arg->getType();
2796 if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2797 return AK_FloatingPoint;
2798 if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2799 return AK_GeneralPurpose;
2800 if (T->isPointerTy())
2801 return AK_GeneralPurpose;
2805 // For VarArg functions, store the argument shadow in an ABI-specific format
2806 // that corresponds to va_list layout.
2807 // We do this because Clang lowers va_arg in the frontend, and this pass
2808 // only sees the low level code that deals with va_list internals.
2809 // A much easier alternative (provided that Clang emits va_arg instructions)
2810 // would have been to associate each live instance of va_list with a copy of
2811 // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2813 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2814 unsigned GpOffset = 0;
2815 unsigned FpOffset = AMD64GpEndOffset;
2816 unsigned OverflowOffset = AMD64FpEndOffset;
2817 const DataLayout &DL = F.getParent()->getDataLayout();
2818 for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2819 ArgIt != End; ++ArgIt) {
2821 unsigned ArgNo = CS.getArgumentNo(ArgIt);
2822 bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2824 // ByVal arguments always go to the overflow area.
2825 assert(A->getType()->isPointerTy());
2826 Type *RealTy = A->getType()->getPointerElementType();
2827 uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
2828 Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2829 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2830 IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2831 ArgSize, kShadowTLSAlignment);
2833 ArgKind AK = classifyArgument(A);
2834 if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2836 if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2840 case AK_GeneralPurpose:
2841 Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2844 case AK_FloatingPoint:
2845 Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2849 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2850 Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2851 OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2853 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2856 Constant *OverflowSize =
2857 ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2858 IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2861 /// \brief Compute the shadow address for a given va_arg.
2862 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2864 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2865 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2866 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2870 void visitVAStartInst(VAStartInst &I) override {
2871 if (F.getCallingConv() == CallingConv::X86_64_Win64)
2873 IRBuilder<> IRB(&I);
2874 VAStartInstrumentationList.push_back(&I);
2875 Value *VAListTag = I.getArgOperand(0);
2876 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2878 // Unpoison the whole __va_list_tag.
2879 // FIXME: magic ABI constants.
2880 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2881 /* size */24, /* alignment */8, false);
2884 void visitVACopyInst(VACopyInst &I) override {
2885 if (F.getCallingConv() == CallingConv::X86_64_Win64)
2887 IRBuilder<> IRB(&I);
2888 Value *VAListTag = I.getArgOperand(0);
2889 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2891 // Unpoison the whole __va_list_tag.
2892 // FIXME: magic ABI constants.
2893 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2894 /* size */24, /* alignment */8, false);
2897 void finalizeInstrumentation() override {
2898 assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2899 "finalizeInstrumentation called twice");
2900 if (!VAStartInstrumentationList.empty()) {
2901 // If there is a va_start in this function, make a backup copy of
2902 // va_arg_tls somewhere in the function entry block.
2903 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2904 VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2906 IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2908 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2909 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2912 // Instrument va_start.
2913 // Copy va_list shadow from the backup copy of the TLS contents.
2914 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2915 CallInst *OrigInst = VAStartInstrumentationList[i];
2916 IRBuilder<> IRB(OrigInst->getNextNode());
2917 Value *VAListTag = OrigInst->getArgOperand(0);
2919 Value *RegSaveAreaPtrPtr =
2921 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2922 ConstantInt::get(MS.IntptrTy, 16)),
2923 Type::getInt64PtrTy(*MS.C));
2924 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2925 Value *RegSaveAreaShadowPtr =
2926 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2927 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2928 AMD64FpEndOffset, 16);
2930 Value *OverflowArgAreaPtrPtr =
2932 IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2933 ConstantInt::get(MS.IntptrTy, 8)),
2934 Type::getInt64PtrTy(*MS.C));
2935 Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2936 Value *OverflowArgAreaShadowPtr =
2937 MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2938 Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
2940 IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2945 /// \brief MIPS64-specific implementation of VarArgHelper.
2946 struct VarArgMIPS64Helper : public VarArgHelper {
2948 MemorySanitizer &MS;
2949 MemorySanitizerVisitor &MSV;
2950 Value *VAArgTLSCopy;
2953 SmallVector<CallInst*, 16> VAStartInstrumentationList;
2955 VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
2956 MemorySanitizerVisitor &MSV)
2957 : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2958 VAArgSize(nullptr) {}
2960 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2961 unsigned VAArgOffset = 0;
2962 const DataLayout &DL = F.getParent()->getDataLayout();
2963 for (CallSite::arg_iterator ArgIt = CS.arg_begin() + 1, End = CS.arg_end();
2964 ArgIt != End; ++ArgIt) {
2967 uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
2968 #if defined(__MIPSEB__) || defined(MIPSEB)
2969 // Adjusting the shadow for argument with size < 8 to match the placement
2970 // of bits in big endian system
2972 VAArgOffset += (8 - ArgSize);
2974 Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
2975 VAArgOffset += ArgSize;
2976 VAArgOffset = RoundUpToAlignment(VAArgOffset, 8);
2977 IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2980 Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
2981 // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
2982 // a new class member i.e. it is the total size of all VarArgs.
2983 IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
2986 /// \brief Compute the shadow address for a given va_arg.
2987 Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2989 Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2990 Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2991 return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2995 void visitVAStartInst(VAStartInst &I) override {
2996 IRBuilder<> IRB(&I);
2997 VAStartInstrumentationList.push_back(&I);
2998 Value *VAListTag = I.getArgOperand(0);
2999 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3000 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3001 /* size */8, /* alignment */8, false);
3004 void visitVACopyInst(VACopyInst &I) override {
3005 IRBuilder<> IRB(&I);
3006 Value *VAListTag = I.getArgOperand(0);
3007 Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
3008 // Unpoison the whole __va_list_tag.
3009 // FIXME: magic ABI constants.
3010 IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3011 /* size */8, /* alignment */8, false);
3014 void finalizeInstrumentation() override {
3015 assert(!VAArgSize && !VAArgTLSCopy &&
3016 "finalizeInstrumentation called twice");
3017 IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
3018 VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3019 Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3022 if (!VAStartInstrumentationList.empty()) {
3023 // If there is a va_start in this function, make a backup copy of
3024 // va_arg_tls somewhere in the function entry block.
3025 VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3026 IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
3029 // Instrument va_start.
3030 // Copy va_list shadow from the backup copy of the TLS contents.
3031 for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3032 CallInst *OrigInst = VAStartInstrumentationList[i];
3033 IRBuilder<> IRB(OrigInst->getNextNode());
3034 Value *VAListTag = OrigInst->getArgOperand(0);
3035 Value *RegSaveAreaPtrPtr =
3036 IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3037 Type::getInt64PtrTy(*MS.C));
3038 Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3039 Value *RegSaveAreaShadowPtr =
3040 MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
3041 IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
3046 /// \brief A no-op implementation of VarArgHelper.
3047 struct VarArgNoOpHelper : public VarArgHelper {
3048 VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
3049 MemorySanitizerVisitor &MSV) {}
3051 void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
3053 void visitVAStartInst(VAStartInst &I) override {}
3055 void visitVACopyInst(VACopyInst &I) override {}
3057 void finalizeInstrumentation() override {}
3060 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
3061 MemorySanitizerVisitor &Visitor) {
3062 // VarArg handling is only implemented on AMD64. False positives are possible
3063 // on other platforms.
3064 llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
3065 if (TargetTriple.getArch() == llvm::Triple::x86_64)
3066 return new VarArgAMD64Helper(Func, Msan, Visitor);
3067 else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
3068 TargetTriple.getArch() == llvm::Triple::mips64el)
3069 return new VarArgMIPS64Helper(Func, Msan, Visitor);
3071 return new VarArgNoOpHelper(Func, Msan, Visitor);
3076 bool MemorySanitizer::runOnFunction(Function &F) {
3077 if (&F == MsanCtorFunction)
3079 MemorySanitizerVisitor Visitor(F, *this);
3081 // Clear out readonly/readnone attributes.
3083 B.addAttribute(Attribute::ReadOnly)
3084 .addAttribute(Attribute::ReadNone);
3085 F.removeAttributes(AttributeSet::FunctionIndex,
3086 AttributeSet::get(F.getContext(),
3087 AttributeSet::FunctionIndex, B));
3089 return Visitor.runOnFunction();