9f20b66f7bb1814f3483e99ef3e807ade7657819
[oota-llvm.git] / lib / Transforms / Instrumentation / MemorySanitizer.cpp
1 //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file is a part of MemorySanitizer, a detector of uninitialized
11 /// reads.
12 ///
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.
21 ///
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).
36 ///
37 /// The default value of shadow is 0, which means "clean" (not poisoned).
38 ///
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).
44 ///
45 ///                           Origin tracking.
46 ///
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.
50 ///
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.
56 ///
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
61 /// practice.
62 ///
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.
67 ///
68 ///                            Atomic handling.
69 ///
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.
73 ///
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).
83 ///
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
90 /// clean shadow.
91
92 //===----------------------------------------------------------------------===//
93
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"
118
119 using namespace llvm;
120
121 #define DEBUG_TYPE "msan"
122
123 static const uint64_t kShadowMask32 = 1ULL << 31;
124 static const uint64_t kShadowMask64 = 1ULL << 46;
125 static const uint64_t kOriginOffset32 = 1ULL << 30;
126 static const uint64_t kOriginOffset64 = 1ULL << 45;
127 static const unsigned kMinOriginAlignment = 4;
128 static const unsigned kShadowTLSAlignment = 8;
129
130 // These constants must be kept in sync with the ones in msan.h.
131 static const unsigned kParamTLSSize = 800;
132 static const unsigned kRetvalTLSSize = 800;
133
134 // Accesses sizes are powers of two: 1, 2, 4, 8.
135 static const size_t kNumberOfAccessSizes = 4;
136
137 /// \brief Track origins of uninitialized values.
138 ///
139 /// Adds a section to MemorySanitizer report that points to the allocation
140 /// (stack or heap) the uninitialized bits came from originally.
141 static cl::opt<int> ClTrackOrigins("msan-track-origins",
142        cl::desc("Track origins (allocation sites) of poisoned memory"),
143        cl::Hidden, cl::init(0));
144 static cl::opt<bool> ClKeepGoing("msan-keep-going",
145        cl::desc("keep going after reporting a UMR"),
146        cl::Hidden, cl::init(false));
147 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
148        cl::desc("poison uninitialized stack variables"),
149        cl::Hidden, cl::init(true));
150 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
151        cl::desc("poison uninitialized stack variables with a call"),
152        cl::Hidden, cl::init(false));
153 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
154        cl::desc("poison uninitialized stack variables with the given patter"),
155        cl::Hidden, cl::init(0xff));
156 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
157        cl::desc("poison undef temps"),
158        cl::Hidden, cl::init(true));
159
160 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
161        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
162        cl::Hidden, cl::init(true));
163
164 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
165        cl::desc("exact handling of relational integer ICmp"),
166        cl::Hidden, cl::init(false));
167
168 // This flag controls whether we check the shadow of the address
169 // operand of load or store. Such bugs are very rare, since load from
170 // a garbage address typically results in SEGV, but still happen
171 // (e.g. only lower bits of address are garbage, or the access happens
172 // early at program startup where malloc-ed memory is more likely to
173 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
174 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
175        cl::desc("report accesses through a pointer which has poisoned shadow"),
176        cl::Hidden, cl::init(true));
177
178 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
179        cl::desc("print out instructions with default strict semantics"),
180        cl::Hidden, cl::init(false));
181
182 static cl::opt<int> ClInstrumentationWithCallThreshold(
183     "msan-instrumentation-with-call-threshold",
184     cl::desc(
185         "If the function being instrumented requires more than "
186         "this number of checks and origin stores, use callbacks instead of "
187         "inline checks (-1 means never use callbacks)."),
188     cl::Hidden, cl::init(3500));
189
190 // Experimental. Wraps all indirect calls in the instrumented code with
191 // a call to the given function. This is needed to assist the dynamic
192 // helper tool (MSanDR) to regain control on transition between instrumented and
193 // non-instrumented code.
194 static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
195        cl::desc("Wrap indirect calls with a given function"),
196        cl::Hidden);
197
198 static cl::opt<bool> ClWrapIndirectCallsFast("msan-wrap-indirect-calls-fast",
199        cl::desc("Do not wrap indirect calls with target in the same module"),
200        cl::Hidden, cl::init(true));
201
202 // This is an experiment to enable handling of cases where shadow is a non-zero
203 // compile-time constant. For some unexplainable reason they were silently
204 // ignored in the instrumentation.
205 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
206        cl::desc("Insert checks for constant shadow values"),
207        cl::Hidden, cl::init(false));
208
209 namespace {
210
211 /// \brief An instrumentation pass implementing detection of uninitialized
212 /// reads.
213 ///
214 /// MemorySanitizer: instrument the code in module to find
215 /// uninitialized reads.
216 class MemorySanitizer : public FunctionPass {
217  public:
218   MemorySanitizer(int TrackOrigins = 0)
219       : FunctionPass(ID),
220         TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
221         DL(nullptr),
222         WarningFn(nullptr),
223         WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
224   const char *getPassName() const override { return "MemorySanitizer"; }
225   bool runOnFunction(Function &F) override;
226   bool doInitialization(Module &M) override;
227   static char ID;  // Pass identification, replacement for typeid.
228
229  private:
230   void initializeCallbacks(Module &M);
231
232   /// \brief Track origins (allocation points) of uninitialized values.
233   int TrackOrigins;
234
235   const DataLayout *DL;
236   LLVMContext *C;
237   Type *IntptrTy;
238   Type *OriginTy;
239   /// \brief Thread-local shadow storage for function parameters.
240   GlobalVariable *ParamTLS;
241   /// \brief Thread-local origin storage for function parameters.
242   GlobalVariable *ParamOriginTLS;
243   /// \brief Thread-local shadow storage for function return value.
244   GlobalVariable *RetvalTLS;
245   /// \brief Thread-local origin storage for function return value.
246   GlobalVariable *RetvalOriginTLS;
247   /// \brief Thread-local shadow storage for in-register va_arg function
248   /// parameters (x86_64-specific).
249   GlobalVariable *VAArgTLS;
250   /// \brief Thread-local shadow storage for va_arg overflow area
251   /// (x86_64-specific).
252   GlobalVariable *VAArgOverflowSizeTLS;
253   /// \brief Thread-local space used to pass origin value to the UMR reporting
254   /// function.
255   GlobalVariable *OriginTLS;
256
257   GlobalVariable *MsandrModuleStart;
258   GlobalVariable *MsandrModuleEnd;
259
260   /// \brief The run-time callback to print a warning.
261   Value *WarningFn;
262   // These arrays are indexed by log2(AccessSize).
263   Value *MaybeWarningFn[kNumberOfAccessSizes];
264   Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
265
266   /// \brief Run-time helper that generates a new origin value for a stack
267   /// allocation.
268   Value *MsanSetAllocaOrigin4Fn;
269   /// \brief Run-time helper that poisons stack on function entry.
270   Value *MsanPoisonStackFn;
271   /// \brief Run-time helper that records a store (or any event) of an
272   /// uninitialized value and returns an updated origin id encoding this info.
273   Value *MsanChainOriginFn;
274   /// \brief MSan runtime replacements for memmove, memcpy and memset.
275   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
276
277   /// \brief Address mask used in application-to-shadow address calculation.
278   /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
279   uint64_t ShadowMask;
280   /// \brief Offset of the origin shadow from the "normal" shadow.
281   /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
282   uint64_t OriginOffset;
283   /// \brief Branch weights for error reporting.
284   MDNode *ColdCallWeights;
285   /// \brief Branch weights for origin store.
286   MDNode *OriginStoreWeights;
287   /// \brief An empty volatile inline asm that prevents callback merge.
288   InlineAsm *EmptyAsm;
289
290   bool WrapIndirectCalls;
291   /// \brief Run-time wrapper for indirect calls.
292   Value *IndirectCallWrapperFn;
293   // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
294   Type *AnyFunctionPtrTy;
295
296   friend struct MemorySanitizerVisitor;
297   friend struct VarArgAMD64Helper;
298 };
299 }  // namespace
300
301 char MemorySanitizer::ID = 0;
302 INITIALIZE_PASS(MemorySanitizer, "msan",
303                 "MemorySanitizer: detects uninitialized reads.",
304                 false, false)
305
306 FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins) {
307   return new MemorySanitizer(TrackOrigins);
308 }
309
310 /// \brief Create a non-const global initialized with the given string.
311 ///
312 /// Creates a writable global for Str so that we can pass it to the
313 /// run-time lib. Runtime uses first 4 bytes of the string to store the
314 /// frame ID, so the string needs to be mutable.
315 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
316                                                             StringRef Str) {
317   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
318   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
319                             GlobalValue::PrivateLinkage, StrConst, "");
320 }
321
322
323 /// \brief Insert extern declaration of runtime-provided functions and globals.
324 void MemorySanitizer::initializeCallbacks(Module &M) {
325   // Only do this once.
326   if (WarningFn)
327     return;
328
329   IRBuilder<> IRB(*C);
330   // Create the callback.
331   // FIXME: this function should have "Cold" calling conv,
332   // which is not yet implemented.
333   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
334                                         : "__msan_warning_noreturn";
335   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
336
337   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
338        AccessSizeIndex++) {
339     unsigned AccessSize = 1 << AccessSizeIndex;
340     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
341     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
342         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
343         IRB.getInt32Ty(), NULL);
344
345     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
346     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
347         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
348         IRB.getInt8PtrTy(), IRB.getInt32Ty(), NULL);
349   }
350
351   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
352     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
353     IRB.getInt8PtrTy(), IntptrTy, NULL);
354   MsanPoisonStackFn = M.getOrInsertFunction(
355     "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
356   MsanChainOriginFn = M.getOrInsertFunction(
357     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty(), NULL);
358   MemmoveFn = M.getOrInsertFunction(
359     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
360     IRB.getInt8PtrTy(), IntptrTy, NULL);
361   MemcpyFn = M.getOrInsertFunction(
362     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
363     IntptrTy, NULL);
364   MemsetFn = M.getOrInsertFunction(
365     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
366     IntptrTy, NULL);
367
368   // Create globals.
369   RetvalTLS = new GlobalVariable(
370     M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
371     GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
372     GlobalVariable::InitialExecTLSModel);
373   RetvalOriginTLS = new GlobalVariable(
374     M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
375     "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
376
377   ParamTLS = new GlobalVariable(
378     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
379     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
380     GlobalVariable::InitialExecTLSModel);
381   ParamOriginTLS = new GlobalVariable(
382     M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
383     GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
384     nullptr, GlobalVariable::InitialExecTLSModel);
385
386   VAArgTLS = new GlobalVariable(
387     M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
388     GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
389     GlobalVariable::InitialExecTLSModel);
390   VAArgOverflowSizeTLS = new GlobalVariable(
391     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
392     "__msan_va_arg_overflow_size_tls", nullptr,
393     GlobalVariable::InitialExecTLSModel);
394   OriginTLS = new GlobalVariable(
395     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
396     "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
397
398   // We insert an empty inline asm after __msan_report* to avoid callback merge.
399   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
400                             StringRef(""), StringRef(""),
401                             /*hasSideEffects=*/true);
402
403   if (WrapIndirectCalls) {
404     AnyFunctionPtrTy =
405         PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
406     IndirectCallWrapperFn = M.getOrInsertFunction(
407         ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, NULL);
408   }
409
410   if (WrapIndirectCalls && ClWrapIndirectCallsFast) {
411     MsandrModuleStart = new GlobalVariable(
412         M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
413         nullptr, "__executable_start");
414     MsandrModuleStart->setVisibility(GlobalVariable::HiddenVisibility);
415     MsandrModuleEnd = new GlobalVariable(
416         M, IRB.getInt32Ty(), false, GlobalValue::ExternalLinkage,
417         nullptr, "_end");
418     MsandrModuleEnd->setVisibility(GlobalVariable::HiddenVisibility);
419   }
420 }
421
422 /// \brief Module-level initialization.
423 ///
424 /// inserts a call to __msan_init to the module's constructor list.
425 bool MemorySanitizer::doInitialization(Module &M) {
426   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
427   if (!DLP)
428     report_fatal_error("data layout missing");
429   DL = &DLP->getDataLayout();
430
431   C = &(M.getContext());
432   unsigned PtrSize = DL->getPointerSizeInBits(/* AddressSpace */0);
433   switch (PtrSize) {
434     case 64:
435       ShadowMask = kShadowMask64;
436       OriginOffset = kOriginOffset64;
437       break;
438     case 32:
439       ShadowMask = kShadowMask32;
440       OriginOffset = kOriginOffset32;
441       break;
442     default:
443       report_fatal_error("unsupported pointer size");
444       break;
445   }
446
447   IRBuilder<> IRB(*C);
448   IntptrTy = IRB.getIntPtrTy(DL);
449   OriginTy = IRB.getInt32Ty();
450
451   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
452   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
453
454   // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
455   appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
456                       "__msan_init", IRB.getVoidTy(), NULL)), 0);
457
458   if (TrackOrigins)
459     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
460                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
461
462   if (ClKeepGoing)
463     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
464                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
465
466   return true;
467 }
468
469 namespace {
470
471 /// \brief A helper class that handles instrumentation of VarArg
472 /// functions on a particular platform.
473 ///
474 /// Implementations are expected to insert the instrumentation
475 /// necessary to propagate argument shadow through VarArg function
476 /// calls. Visit* methods are called during an InstVisitor pass over
477 /// the function, and should avoid creating new basic blocks. A new
478 /// instance of this class is created for each instrumented function.
479 struct VarArgHelper {
480   /// \brief Visit a CallSite.
481   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
482
483   /// \brief Visit a va_start call.
484   virtual void visitVAStartInst(VAStartInst &I) = 0;
485
486   /// \brief Visit a va_copy call.
487   virtual void visitVACopyInst(VACopyInst &I) = 0;
488
489   /// \brief Finalize function instrumentation.
490   ///
491   /// This method is called after visiting all interesting (see above)
492   /// instructions in a function.
493   virtual void finalizeInstrumentation() = 0;
494
495   virtual ~VarArgHelper() {}
496 };
497
498 struct MemorySanitizerVisitor;
499
500 VarArgHelper*
501 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
502                    MemorySanitizerVisitor &Visitor);
503
504 unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
505   if (TypeSize <= 8) return 0;
506   return Log2_32_Ceil(TypeSize / 8);
507 }
508
509 /// This class does all the work for a given function. Store and Load
510 /// instructions store and load corresponding shadow and origin
511 /// values. Most instructions propagate shadow from arguments to their
512 /// return values. Certain instructions (most importantly, BranchInst)
513 /// test their argument shadow and print reports (with a runtime call) if it's
514 /// non-zero.
515 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
516   Function &F;
517   MemorySanitizer &MS;
518   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
519   ValueMap<Value*, Value*> ShadowMap, OriginMap;
520   std::unique_ptr<VarArgHelper> VAHelper;
521
522   // The following flags disable parts of MSan instrumentation based on
523   // blacklist contents and command-line options.
524   bool InsertChecks;
525   bool PropagateShadow;
526   bool PoisonStack;
527   bool PoisonUndef;
528   bool CheckReturnValue;
529
530   struct ShadowOriginAndInsertPoint {
531     Value *Shadow;
532     Value *Origin;
533     Instruction *OrigIns;
534     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
535       : Shadow(S), Origin(O), OrigIns(I) { }
536   };
537   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
538   SmallVector<Instruction*, 16> StoreList;
539   SmallVector<CallSite, 16> IndirectCallList;
540
541   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
542       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
543     bool SanitizeFunction = F.getAttributes().hasAttribute(
544         AttributeSet::FunctionIndex, Attribute::SanitizeMemory);
545     InsertChecks = SanitizeFunction;
546     PropagateShadow = SanitizeFunction;
547     PoisonStack = SanitizeFunction && ClPoisonStack;
548     PoisonUndef = SanitizeFunction && ClPoisonUndef;
549     // FIXME: Consider using SpecialCaseList to specify a list of functions that
550     // must always return fully initialized values. For now, we hardcode "main".
551     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
552
553     DEBUG(if (!InsertChecks)
554           dbgs() << "MemorySanitizer is not inserting checks into '"
555                  << F.getName() << "'\n");
556   }
557
558   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
559     if (MS.TrackOrigins <= 1) return V;
560     return IRB.CreateCall(MS.MsanChainOriginFn, V);
561   }
562
563   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
564                    unsigned Alignment, bool AsCall) {
565     if (isa<StructType>(Shadow->getType())) {
566       IRB.CreateAlignedStore(updateOrigin(Origin, IRB), getOriginPtr(Addr, IRB),
567                              Alignment);
568     } else {
569       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
570       // TODO(eugenis): handle non-zero constant shadow by inserting an
571       // unconditional check (can not simply fail compilation as this could
572       // be in the dead code).
573       if (!ClCheckConstantShadow)
574         if (isa<Constant>(ConvertedShadow)) return;
575       unsigned TypeSizeInBits =
576           MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
577       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
578       if (AsCall && SizeIndex < kNumberOfAccessSizes) {
579         Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
580         Value *ConvertedShadow2 = IRB.CreateZExt(
581             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
582         IRB.CreateCall3(Fn, ConvertedShadow2,
583                         IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
584                         Origin);
585       } else {
586         Value *Cmp = IRB.CreateICmpNE(
587             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
588         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
589             Cmp, IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
590         IRBuilder<> IRBNew(CheckTerm);
591         IRBNew.CreateAlignedStore(updateOrigin(Origin, IRBNew),
592                                   getOriginPtr(Addr, IRBNew), Alignment);
593       }
594     }
595   }
596
597   void materializeStores(bool InstrumentWithCalls) {
598     for (auto Inst : StoreList) {
599       StoreInst &SI = *dyn_cast<StoreInst>(Inst);
600
601       IRBuilder<> IRB(&SI);
602       Value *Val = SI.getValueOperand();
603       Value *Addr = SI.getPointerOperand();
604       Value *Shadow = SI.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
605       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
606
607       StoreInst *NewSI =
608           IRB.CreateAlignedStore(Shadow, ShadowPtr, SI.getAlignment());
609       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
610       (void)NewSI;
611
612       if (ClCheckAccessAddress) insertShadowCheck(Addr, &SI);
613
614       if (SI.isAtomic()) SI.setOrdering(addReleaseOrdering(SI.getOrdering()));
615
616       if (MS.TrackOrigins) {
617         unsigned Alignment = std::max(kMinOriginAlignment, SI.getAlignment());
618         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), Alignment,
619                     InstrumentWithCalls);
620       }
621     }
622   }
623
624   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
625                            bool AsCall) {
626     IRBuilder<> IRB(OrigIns);
627     DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
628     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
629     DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
630     // See the comment in storeOrigin().
631     if (!ClCheckConstantShadow)
632       if (isa<Constant>(ConvertedShadow)) return;
633     unsigned TypeSizeInBits =
634         MS.DL->getTypeSizeInBits(ConvertedShadow->getType());
635     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
636     if (AsCall && SizeIndex < kNumberOfAccessSizes) {
637       Value *Fn = MS.MaybeWarningFn[SizeIndex];
638       Value *ConvertedShadow2 =
639           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
640       IRB.CreateCall2(Fn, ConvertedShadow2, MS.TrackOrigins && Origin
641                                                 ? Origin
642                                                 : (Value *)IRB.getInt32(0));
643     } else {
644       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
645                                     getCleanShadow(ConvertedShadow), "_mscmp");
646       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
647           Cmp, OrigIns,
648           /* Unreachable */ !ClKeepGoing, MS.ColdCallWeights);
649
650       IRB.SetInsertPoint(CheckTerm);
651       if (MS.TrackOrigins) {
652         IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
653                         MS.OriginTLS);
654       }
655       IRB.CreateCall(MS.WarningFn);
656       IRB.CreateCall(MS.EmptyAsm);
657       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
658     }
659   }
660
661   void materializeChecks(bool InstrumentWithCalls) {
662     for (const auto &ShadowData : InstrumentationList) {
663       Instruction *OrigIns = ShadowData.OrigIns;
664       Value *Shadow = ShadowData.Shadow;
665       Value *Origin = ShadowData.Origin;
666       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
667     }
668     DEBUG(dbgs() << "DONE:\n" << F);
669   }
670
671   void materializeIndirectCalls() {
672     for (auto &CS : IndirectCallList) {
673       Instruction *I = CS.getInstruction();
674       BasicBlock *B = I->getParent();
675       IRBuilder<> IRB(I);
676       Value *Fn0 = CS.getCalledValue();
677       Value *Fn = IRB.CreateBitCast(Fn0, MS.AnyFunctionPtrTy);
678
679       if (ClWrapIndirectCallsFast) {
680         // Check that call target is inside this module limits.
681         Value *Start =
682             IRB.CreateBitCast(MS.MsandrModuleStart, MS.AnyFunctionPtrTy);
683         Value *End = IRB.CreateBitCast(MS.MsandrModuleEnd, MS.AnyFunctionPtrTy);
684
685         Value *NotInThisModule = IRB.CreateOr(IRB.CreateICmpULT(Fn, Start),
686                                               IRB.CreateICmpUGE(Fn, End));
687
688         PHINode *NewFnPhi =
689             IRB.CreatePHI(Fn0->getType(), 2, "msandr.indirect_target");
690
691         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
692             NotInThisModule, NewFnPhi,
693             /* Unreachable */ false, MS.ColdCallWeights);
694
695         IRB.SetInsertPoint(CheckTerm);
696         // Slow path: call wrapper function to possibly transform the call
697         // target.
698         Value *NewFn = IRB.CreateBitCast(
699             IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
700
701         NewFnPhi->addIncoming(Fn0, B);
702         NewFnPhi->addIncoming(NewFn, dyn_cast<Instruction>(NewFn)->getParent());
703         CS.setCalledFunction(NewFnPhi);
704       } else {
705         Value *NewFn = IRB.CreateBitCast(
706             IRB.CreateCall(MS.IndirectCallWrapperFn, Fn), Fn0->getType());
707         CS.setCalledFunction(NewFn);
708       }
709     }
710   }
711
712   /// \brief Add MemorySanitizer instrumentation to a function.
713   bool runOnFunction() {
714     MS.initializeCallbacks(*F.getParent());
715     if (!MS.DL) return false;
716
717     // In the presence of unreachable blocks, we may see Phi nodes with
718     // incoming nodes from such blocks. Since InstVisitor skips unreachable
719     // blocks, such nodes will not have any shadow value associated with them.
720     // It's easier to remove unreachable blocks than deal with missing shadow.
721     removeUnreachableBlocks(F);
722
723     // Iterate all BBs in depth-first order and create shadow instructions
724     // for all instructions (where applicable).
725     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
726     for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
727       visit(*BB);
728
729
730     // Finalize PHI nodes.
731     for (PHINode *PN : ShadowPHINodes) {
732       PHINode *PNS = cast<PHINode>(getShadow(PN));
733       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
734       size_t NumValues = PN->getNumIncomingValues();
735       for (size_t v = 0; v < NumValues; v++) {
736         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
737         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
738       }
739     }
740
741     VAHelper->finalizeInstrumentation();
742
743     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
744                                InstrumentationList.size() + StoreList.size() >
745                                    (unsigned)ClInstrumentationWithCallThreshold;
746
747     // Delayed instrumentation of StoreInst.
748     // This may add new checks to be inserted later.
749     materializeStores(InstrumentWithCalls);
750
751     // Insert shadow value checks.
752     materializeChecks(InstrumentWithCalls);
753
754     // Wrap indirect calls.
755     materializeIndirectCalls();
756
757     return true;
758   }
759
760   /// \brief Compute the shadow type that corresponds to a given Value.
761   Type *getShadowTy(Value *V) {
762     return getShadowTy(V->getType());
763   }
764
765   /// \brief Compute the shadow type that corresponds to a given Type.
766   Type *getShadowTy(Type *OrigTy) {
767     if (!OrigTy->isSized()) {
768       return nullptr;
769     }
770     // For integer type, shadow is the same as the original type.
771     // This may return weird-sized types like i1.
772     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
773       return IT;
774     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
775       uint32_t EltSize = MS.DL->getTypeSizeInBits(VT->getElementType());
776       return VectorType::get(IntegerType::get(*MS.C, EltSize),
777                              VT->getNumElements());
778     }
779     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
780       return ArrayType::get(getShadowTy(AT->getElementType()),
781                             AT->getNumElements());
782     }
783     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
784       SmallVector<Type*, 4> Elements;
785       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
786         Elements.push_back(getShadowTy(ST->getElementType(i)));
787       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
788       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
789       return Res;
790     }
791     uint32_t TypeSize = MS.DL->getTypeSizeInBits(OrigTy);
792     return IntegerType::get(*MS.C, TypeSize);
793   }
794
795   /// \brief Flatten a vector type.
796   Type *getShadowTyNoVec(Type *ty) {
797     if (VectorType *vt = dyn_cast<VectorType>(ty))
798       return IntegerType::get(*MS.C, vt->getBitWidth());
799     return ty;
800   }
801
802   /// \brief Convert a shadow value to it's flattened variant.
803   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
804     Type *Ty = V->getType();
805     Type *NoVecTy = getShadowTyNoVec(Ty);
806     if (Ty == NoVecTy) return V;
807     return IRB.CreateBitCast(V, NoVecTy);
808   }
809
810   /// \brief Compute the shadow address that corresponds to a given application
811   /// address.
812   ///
813   /// Shadow = Addr & ~ShadowMask.
814   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
815                       IRBuilder<> &IRB) {
816     Value *ShadowLong =
817       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
818                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
819     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
820   }
821
822   /// \brief Compute the origin address that corresponds to a given application
823   /// address.
824   ///
825   /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
826   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
827     Value *ShadowLong =
828       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
829                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
830     Value *Add =
831       IRB.CreateAdd(ShadowLong,
832                     ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
833     Value *SecondAnd =
834       IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
835     return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
836   }
837
838   /// \brief Compute the shadow address for a given function argument.
839   ///
840   /// Shadow = ParamTLS+ArgOffset.
841   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
842                                  int ArgOffset) {
843     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
844     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
845     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
846                               "_msarg");
847   }
848
849   /// \brief Compute the origin address for a given function argument.
850   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
851                                  int ArgOffset) {
852     if (!MS.TrackOrigins) return nullptr;
853     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
854     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
855     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
856                               "_msarg_o");
857   }
858
859   /// \brief Compute the shadow address for a retval.
860   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
861     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
862     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
863                               "_msret");
864   }
865
866   /// \brief Compute the origin address for a retval.
867   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
868     // We keep a single origin for the entire retval. Might be too optimistic.
869     return MS.RetvalOriginTLS;
870   }
871
872   /// \brief Set SV to be the shadow value for V.
873   void setShadow(Value *V, Value *SV) {
874     assert(!ShadowMap.count(V) && "Values may only have one shadow");
875     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
876   }
877
878   /// \brief Set Origin to be the origin value for V.
879   void setOrigin(Value *V, Value *Origin) {
880     if (!MS.TrackOrigins) return;
881     assert(!OriginMap.count(V) && "Values may only have one origin");
882     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
883     OriginMap[V] = Origin;
884   }
885
886   /// \brief Create a clean shadow value for a given value.
887   ///
888   /// Clean shadow (all zeroes) means all bits of the value are defined
889   /// (initialized).
890   Constant *getCleanShadow(Value *V) {
891     Type *ShadowTy = getShadowTy(V);
892     if (!ShadowTy)
893       return nullptr;
894     return Constant::getNullValue(ShadowTy);
895   }
896
897   /// \brief Create a dirty shadow of a given shadow type.
898   Constant *getPoisonedShadow(Type *ShadowTy) {
899     assert(ShadowTy);
900     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
901       return Constant::getAllOnesValue(ShadowTy);
902     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
903       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
904                                       getPoisonedShadow(AT->getElementType()));
905       return ConstantArray::get(AT, Vals);
906     }
907     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
908       SmallVector<Constant *, 4> Vals;
909       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
910         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
911       return ConstantStruct::get(ST, Vals);
912     }
913     llvm_unreachable("Unexpected shadow type");
914   }
915
916   /// \brief Create a dirty shadow for a given value.
917   Constant *getPoisonedShadow(Value *V) {
918     Type *ShadowTy = getShadowTy(V);
919     if (!ShadowTy)
920       return nullptr;
921     return getPoisonedShadow(ShadowTy);
922   }
923
924   /// \brief Create a clean (zero) origin.
925   Value *getCleanOrigin() {
926     return Constant::getNullValue(MS.OriginTy);
927   }
928
929   /// \brief Get the shadow value for a given Value.
930   ///
931   /// This function either returns the value set earlier with setShadow,
932   /// or extracts if from ParamTLS (for function arguments).
933   Value *getShadow(Value *V) {
934     if (!PropagateShadow) return getCleanShadow(V);
935     if (Instruction *I = dyn_cast<Instruction>(V)) {
936       // For instructions the shadow is already stored in the map.
937       Value *Shadow = ShadowMap[V];
938       if (!Shadow) {
939         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
940         (void)I;
941         assert(Shadow && "No shadow for a value");
942       }
943       return Shadow;
944     }
945     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
946       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
947       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
948       (void)U;
949       return AllOnes;
950     }
951     if (Argument *A = dyn_cast<Argument>(V)) {
952       // For arguments we compute the shadow on demand and store it in the map.
953       Value **ShadowPtr = &ShadowMap[V];
954       if (*ShadowPtr)
955         return *ShadowPtr;
956       Function *F = A->getParent();
957       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
958       unsigned ArgOffset = 0;
959       for (auto &FArg : F->args()) {
960         if (!FArg.getType()->isSized()) {
961           DEBUG(dbgs() << "Arg is not sized\n");
962           continue;
963         }
964         unsigned Size = FArg.hasByValAttr()
965           ? MS.DL->getTypeAllocSize(FArg.getType()->getPointerElementType())
966           : MS.DL->getTypeAllocSize(FArg.getType());
967         if (A == &FArg) {
968           bool Overflow = ArgOffset + Size > kParamTLSSize;
969           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
970           if (FArg.hasByValAttr()) {
971             // ByVal pointer itself has clean shadow. We copy the actual
972             // argument shadow to the underlying memory.
973             // Figure out maximal valid memcpy alignment.
974             unsigned ArgAlign = FArg.getParamAlignment();
975             if (ArgAlign == 0) {
976               Type *EltType = A->getType()->getPointerElementType();
977               ArgAlign = MS.DL->getABITypeAlignment(EltType);
978             }
979             if (Overflow) {
980               // ParamTLS overflow.
981               EntryIRB.CreateMemSet(
982                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
983                   Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
984             } else {
985               unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
986               Value *Cpy = EntryIRB.CreateMemCpy(
987                   getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
988                   CopyAlign);
989               DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
990               (void)Cpy;
991             }
992             *ShadowPtr = getCleanShadow(V);
993           } else {
994             if (Overflow) {
995               // ParamTLS overflow.
996               *ShadowPtr = getCleanShadow(V);
997             } else {
998               *ShadowPtr =
999                   EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1000             }
1001           }
1002           DEBUG(dbgs() << "  ARG:    "  << FArg << " ==> " <<
1003                 **ShadowPtr << "\n");
1004           if (MS.TrackOrigins && !Overflow) {
1005             Value *OriginPtr =
1006                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1007             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1008           }
1009         }
1010         ArgOffset += RoundUpToAlignment(Size, kShadowTLSAlignment);
1011       }
1012       assert(*ShadowPtr && "Could not find shadow for an argument");
1013       return *ShadowPtr;
1014     }
1015     // For everything else the shadow is zero.
1016     return getCleanShadow(V);
1017   }
1018
1019   /// \brief Get the shadow for i-th argument of the instruction I.
1020   Value *getShadow(Instruction *I, int i) {
1021     return getShadow(I->getOperand(i));
1022   }
1023
1024   /// \brief Get the origin for a value.
1025   Value *getOrigin(Value *V) {
1026     if (!MS.TrackOrigins) return nullptr;
1027     if (isa<Instruction>(V) || isa<Argument>(V)) {
1028       Value *Origin = OriginMap[V];
1029       if (!Origin) {
1030         DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
1031         Origin = getCleanOrigin();
1032       }
1033       return Origin;
1034     }
1035     return getCleanOrigin();
1036   }
1037
1038   /// \brief Get the origin for i-th argument of the instruction I.
1039   Value *getOrigin(Instruction *I, int i) {
1040     return getOrigin(I->getOperand(i));
1041   }
1042
1043   /// \brief Remember the place where a shadow check should be inserted.
1044   ///
1045   /// This location will be later instrumented with a check that will print a
1046   /// UMR warning in runtime if the shadow value is not 0.
1047   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1048     assert(Shadow);
1049     if (!InsertChecks) return;
1050 #ifndef NDEBUG
1051     Type *ShadowTy = Shadow->getType();
1052     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1053            "Can only insert checks for integer and vector shadow types");
1054 #endif
1055     InstrumentationList.push_back(
1056         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1057   }
1058
1059   /// \brief Remember the place where a shadow check should be inserted.
1060   ///
1061   /// This location will be later instrumented with a check that will print a
1062   /// UMR warning in runtime if the value is not fully defined.
1063   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1064     assert(Val);
1065     Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1066     if (!Shadow) return;
1067     Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1068     insertShadowCheck(Shadow, Origin, OrigIns);
1069   }
1070
1071   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1072     switch (a) {
1073       case NotAtomic:
1074         return NotAtomic;
1075       case Unordered:
1076       case Monotonic:
1077       case Release:
1078         return Release;
1079       case Acquire:
1080       case AcquireRelease:
1081         return AcquireRelease;
1082       case SequentiallyConsistent:
1083         return SequentiallyConsistent;
1084     }
1085     llvm_unreachable("Unknown ordering");
1086   }
1087
1088   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1089     switch (a) {
1090       case NotAtomic:
1091         return NotAtomic;
1092       case Unordered:
1093       case Monotonic:
1094       case Acquire:
1095         return Acquire;
1096       case Release:
1097       case AcquireRelease:
1098         return AcquireRelease;
1099       case SequentiallyConsistent:
1100         return SequentiallyConsistent;
1101     }
1102     llvm_unreachable("Unknown ordering");
1103   }
1104
1105   // ------------------- Visitors.
1106
1107   /// \brief Instrument LoadInst
1108   ///
1109   /// Loads the corresponding shadow and (optionally) origin.
1110   /// Optionally, checks that the load address is fully defined.
1111   void visitLoadInst(LoadInst &I) {
1112     assert(I.getType()->isSized() && "Load type must have size");
1113     IRBuilder<> IRB(I.getNextNode());
1114     Type *ShadowTy = getShadowTy(&I);
1115     Value *Addr = I.getPointerOperand();
1116     if (PropagateShadow) {
1117       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1118       setShadow(&I,
1119                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
1120     } else {
1121       setShadow(&I, getCleanShadow(&I));
1122     }
1123
1124     if (ClCheckAccessAddress)
1125       insertShadowCheck(I.getPointerOperand(), &I);
1126
1127     if (I.isAtomic())
1128       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1129
1130     if (MS.TrackOrigins) {
1131       if (PropagateShadow) {
1132         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
1133         setOrigin(&I,
1134                   IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
1135       } else {
1136         setOrigin(&I, getCleanOrigin());
1137       }
1138     }
1139   }
1140
1141   /// \brief Instrument StoreInst
1142   ///
1143   /// Stores the corresponding shadow and (optionally) origin.
1144   /// Optionally, checks that the store address is fully defined.
1145   void visitStoreInst(StoreInst &I) {
1146     StoreList.push_back(&I);
1147   }
1148
1149   void handleCASOrRMW(Instruction &I) {
1150     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1151
1152     IRBuilder<> IRB(&I);
1153     Value *Addr = I.getOperand(0);
1154     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1155
1156     if (ClCheckAccessAddress)
1157       insertShadowCheck(Addr, &I);
1158
1159     // Only test the conditional argument of cmpxchg instruction.
1160     // The other argument can potentially be uninitialized, but we can not
1161     // detect this situation reliably without possible false positives.
1162     if (isa<AtomicCmpXchgInst>(I))
1163       insertShadowCheck(I.getOperand(1), &I);
1164
1165     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1166
1167     setShadow(&I, getCleanShadow(&I));
1168   }
1169
1170   void visitAtomicRMWInst(AtomicRMWInst &I) {
1171     handleCASOrRMW(I);
1172     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1173   }
1174
1175   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1176     handleCASOrRMW(I);
1177     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1178   }
1179
1180   // Vector manipulation.
1181   void visitExtractElementInst(ExtractElementInst &I) {
1182     insertShadowCheck(I.getOperand(1), &I);
1183     IRBuilder<> IRB(&I);
1184     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1185               "_msprop"));
1186     setOrigin(&I, getOrigin(&I, 0));
1187   }
1188
1189   void visitInsertElementInst(InsertElementInst &I) {
1190     insertShadowCheck(I.getOperand(2), &I);
1191     IRBuilder<> IRB(&I);
1192     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1193               I.getOperand(2), "_msprop"));
1194     setOriginForNaryOp(I);
1195   }
1196
1197   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1198     insertShadowCheck(I.getOperand(2), &I);
1199     IRBuilder<> IRB(&I);
1200     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1201               I.getOperand(2), "_msprop"));
1202     setOriginForNaryOp(I);
1203   }
1204
1205   // Casts.
1206   void visitSExtInst(SExtInst &I) {
1207     IRBuilder<> IRB(&I);
1208     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1209     setOrigin(&I, getOrigin(&I, 0));
1210   }
1211
1212   void visitZExtInst(ZExtInst &I) {
1213     IRBuilder<> IRB(&I);
1214     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1215     setOrigin(&I, getOrigin(&I, 0));
1216   }
1217
1218   void visitTruncInst(TruncInst &I) {
1219     IRBuilder<> IRB(&I);
1220     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1221     setOrigin(&I, getOrigin(&I, 0));
1222   }
1223
1224   void visitBitCastInst(BitCastInst &I) {
1225     IRBuilder<> IRB(&I);
1226     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1227     setOrigin(&I, getOrigin(&I, 0));
1228   }
1229
1230   void visitPtrToIntInst(PtrToIntInst &I) {
1231     IRBuilder<> IRB(&I);
1232     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1233              "_msprop_ptrtoint"));
1234     setOrigin(&I, getOrigin(&I, 0));
1235   }
1236
1237   void visitIntToPtrInst(IntToPtrInst &I) {
1238     IRBuilder<> IRB(&I);
1239     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1240              "_msprop_inttoptr"));
1241     setOrigin(&I, getOrigin(&I, 0));
1242   }
1243
1244   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1245   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1246   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1247   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1248   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1249   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1250
1251   /// \brief Propagate shadow for bitwise AND.
1252   ///
1253   /// This code is exact, i.e. if, for example, a bit in the left argument
1254   /// is defined and 0, then neither the value not definedness of the
1255   /// corresponding bit in B don't affect the resulting shadow.
1256   void visitAnd(BinaryOperator &I) {
1257     IRBuilder<> IRB(&I);
1258     //  "And" of 0 and a poisoned value results in unpoisoned value.
1259     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1260     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1261     //  1&p => p;     0&p => 0;     p&p => p;
1262     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1263     Value *S1 = getShadow(&I, 0);
1264     Value *S2 = getShadow(&I, 1);
1265     Value *V1 = I.getOperand(0);
1266     Value *V2 = I.getOperand(1);
1267     if (V1->getType() != S1->getType()) {
1268       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1269       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1270     }
1271     Value *S1S2 = IRB.CreateAnd(S1, S2);
1272     Value *V1S2 = IRB.CreateAnd(V1, S2);
1273     Value *S1V2 = IRB.CreateAnd(S1, V2);
1274     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1275     setOriginForNaryOp(I);
1276   }
1277
1278   void visitOr(BinaryOperator &I) {
1279     IRBuilder<> IRB(&I);
1280     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1281     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1282     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1283     //  1|p => 1;     0|p => p;     p|p => p;
1284     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1285     Value *S1 = getShadow(&I, 0);
1286     Value *S2 = getShadow(&I, 1);
1287     Value *V1 = IRB.CreateNot(I.getOperand(0));
1288     Value *V2 = IRB.CreateNot(I.getOperand(1));
1289     if (V1->getType() != S1->getType()) {
1290       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1291       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1292     }
1293     Value *S1S2 = IRB.CreateAnd(S1, S2);
1294     Value *V1S2 = IRB.CreateAnd(V1, S2);
1295     Value *S1V2 = IRB.CreateAnd(S1, V2);
1296     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1297     setOriginForNaryOp(I);
1298   }
1299
1300   /// \brief Default propagation of shadow and/or origin.
1301   ///
1302   /// This class implements the general case of shadow propagation, used in all
1303   /// cases where we don't know and/or don't care about what the operation
1304   /// actually does. It converts all input shadow values to a common type
1305   /// (extending or truncating as necessary), and bitwise OR's them.
1306   ///
1307   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1308   /// fully initialized), and less prone to false positives.
1309   ///
1310   /// This class also implements the general case of origin propagation. For a
1311   /// Nary operation, result origin is set to the origin of an argument that is
1312   /// not entirely initialized. If there is more than one such arguments, the
1313   /// rightmost of them is picked. It does not matter which one is picked if all
1314   /// arguments are initialized.
1315   template <bool CombineShadow>
1316   class Combiner {
1317     Value *Shadow;
1318     Value *Origin;
1319     IRBuilder<> &IRB;
1320     MemorySanitizerVisitor *MSV;
1321
1322   public:
1323     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1324       Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
1325
1326     /// \brief Add a pair of shadow and origin values to the mix.
1327     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1328       if (CombineShadow) {
1329         assert(OpShadow);
1330         if (!Shadow)
1331           Shadow = OpShadow;
1332         else {
1333           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1334           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1335         }
1336       }
1337
1338       if (MSV->MS.TrackOrigins) {
1339         assert(OpOrigin);
1340         if (!Origin) {
1341           Origin = OpOrigin;
1342         } else {
1343           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1344           // No point in adding something that might result in 0 origin value.
1345           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1346             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1347             Value *Cond =
1348                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1349             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1350           }
1351         }
1352       }
1353       return *this;
1354     }
1355
1356     /// \brief Add an application value to the mix.
1357     Combiner &Add(Value *V) {
1358       Value *OpShadow = MSV->getShadow(V);
1359       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1360       return Add(OpShadow, OpOrigin);
1361     }
1362
1363     /// \brief Set the current combined values as the given instruction's shadow
1364     /// and origin.
1365     void Done(Instruction *I) {
1366       if (CombineShadow) {
1367         assert(Shadow);
1368         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1369         MSV->setShadow(I, Shadow);
1370       }
1371       if (MSV->MS.TrackOrigins) {
1372         assert(Origin);
1373         MSV->setOrigin(I, Origin);
1374       }
1375     }
1376   };
1377
1378   typedef Combiner<true> ShadowAndOriginCombiner;
1379   typedef Combiner<false> OriginCombiner;
1380
1381   /// \brief Propagate origin for arbitrary operation.
1382   void setOriginForNaryOp(Instruction &I) {
1383     if (!MS.TrackOrigins) return;
1384     IRBuilder<> IRB(&I);
1385     OriginCombiner OC(this, IRB);
1386     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1387       OC.Add(OI->get());
1388     OC.Done(&I);
1389   }
1390
1391   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1392     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1393            "Vector of pointers is not a valid shadow type");
1394     return Ty->isVectorTy() ?
1395       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1396       Ty->getPrimitiveSizeInBits();
1397   }
1398
1399   /// \brief Cast between two shadow types, extending or truncating as
1400   /// necessary.
1401   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1402                           bool Signed = false) {
1403     Type *srcTy = V->getType();
1404     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1405       return IRB.CreateIntCast(V, dstTy, Signed);
1406     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1407         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1408       return IRB.CreateIntCast(V, dstTy, Signed);
1409     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1410     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1411     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1412     Value *V2 =
1413       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1414     return IRB.CreateBitCast(V2, dstTy);
1415     // TODO: handle struct types.
1416   }
1417
1418   /// \brief Cast an application value to the type of its own shadow.
1419   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
1420     Type *ShadowTy = getShadowTy(V);
1421     if (V->getType() == ShadowTy)
1422       return V;
1423     if (V->getType()->isPtrOrPtrVectorTy())
1424       return IRB.CreatePtrToInt(V, ShadowTy);
1425     else
1426       return IRB.CreateBitCast(V, ShadowTy);
1427   }
1428
1429   /// \brief Propagate shadow for arbitrary operation.
1430   void handleShadowOr(Instruction &I) {
1431     IRBuilder<> IRB(&I);
1432     ShadowAndOriginCombiner SC(this, IRB);
1433     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1434       SC.Add(OI->get());
1435     SC.Done(&I);
1436   }
1437
1438   // \brief Handle multiplication by constant.
1439   //
1440   // Handle a special case of multiplication by constant that may have one or
1441   // more zeros in the lower bits. This makes corresponding number of lower bits
1442   // of the result zero as well. We model it by shifting the other operand
1443   // shadow left by the required number of bits. Effectively, we transform
1444   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
1445   // We use multiplication by 2**N instead of shift to cover the case of
1446   // multiplication by 0, which may occur in some elements of a vector operand.
1447   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
1448                            Value *OtherArg) {
1449     Constant *ShadowMul;
1450     Type *Ty = ConstArg->getType();
1451     if (Ty->isVectorTy()) {
1452       unsigned NumElements = Ty->getVectorNumElements();
1453       Type *EltTy = Ty->getSequentialElementType();
1454       SmallVector<Constant *, 16> Elements;
1455       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
1456         ConstantInt *Elt =
1457             dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx));
1458         APInt V = Elt->getValue();
1459         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1460         Elements.push_back(ConstantInt::get(EltTy, V2));
1461       }
1462       ShadowMul = ConstantVector::get(Elements);
1463     } else {
1464       ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg);
1465       APInt V = Elt->getValue();
1466       APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
1467       ShadowMul = ConstantInt::get(Elt->getType(), V2);
1468     }
1469
1470     IRBuilder<> IRB(&I);
1471     setShadow(&I,
1472               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
1473     setOrigin(&I, getOrigin(OtherArg));
1474   }
1475
1476   void visitMul(BinaryOperator &I) {
1477     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1478     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1479     if (constOp0 && !constOp1)
1480       handleMulByConstant(I, constOp0, I.getOperand(1));
1481     else if (constOp1 && !constOp0)
1482       handleMulByConstant(I, constOp1, I.getOperand(0));
1483     else
1484       handleShadowOr(I);
1485   }
1486
1487   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1488   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1489   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1490   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1491   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1492   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1493
1494   void handleDiv(Instruction &I) {
1495     IRBuilder<> IRB(&I);
1496     // Strict on the second argument.
1497     insertShadowCheck(I.getOperand(1), &I);
1498     setShadow(&I, getShadow(&I, 0));
1499     setOrigin(&I, getOrigin(&I, 0));
1500   }
1501
1502   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1503   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1504   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1505   void visitURem(BinaryOperator &I) { handleDiv(I); }
1506   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1507   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1508
1509   /// \brief Instrument == and != comparisons.
1510   ///
1511   /// Sometimes the comparison result is known even if some of the bits of the
1512   /// arguments are not.
1513   void handleEqualityComparison(ICmpInst &I) {
1514     IRBuilder<> IRB(&I);
1515     Value *A = I.getOperand(0);
1516     Value *B = I.getOperand(1);
1517     Value *Sa = getShadow(A);
1518     Value *Sb = getShadow(B);
1519
1520     // Get rid of pointers and vectors of pointers.
1521     // For ints (and vectors of ints), types of A and Sa match,
1522     // and this is a no-op.
1523     A = IRB.CreatePointerCast(A, Sa->getType());
1524     B = IRB.CreatePointerCast(B, Sb->getType());
1525
1526     // A == B  <==>  (C = A^B) == 0
1527     // A != B  <==>  (C = A^B) != 0
1528     // Sc = Sa | Sb
1529     Value *C = IRB.CreateXor(A, B);
1530     Value *Sc = IRB.CreateOr(Sa, Sb);
1531     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1532     // Result is defined if one of the following is true
1533     // * there is a defined 1 bit in C
1534     // * C is fully defined
1535     // Si = !(C & ~Sc) && Sc
1536     Value *Zero = Constant::getNullValue(Sc->getType());
1537     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1538     Value *Si =
1539       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1540                     IRB.CreateICmpEQ(
1541                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1542     Si->setName("_msprop_icmp");
1543     setShadow(&I, Si);
1544     setOriginForNaryOp(I);
1545   }
1546
1547   /// \brief Build the lowest possible value of V, taking into account V's
1548   ///        uninitialized bits.
1549   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1550                                 bool isSigned) {
1551     if (isSigned) {
1552       // Split shadow into sign bit and other bits.
1553       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1554       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1555       // Maximise the undefined shadow bit, minimize other undefined bits.
1556       return
1557         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1558     } else {
1559       // Minimize undefined bits.
1560       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1561     }
1562   }
1563
1564   /// \brief Build the highest possible value of V, taking into account V's
1565   ///        uninitialized bits.
1566   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1567                                 bool isSigned) {
1568     if (isSigned) {
1569       // Split shadow into sign bit and other bits.
1570       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1571       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1572       // Minimise the undefined shadow bit, maximise other undefined bits.
1573       return
1574         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1575     } else {
1576       // Maximize undefined bits.
1577       return IRB.CreateOr(A, Sa);
1578     }
1579   }
1580
1581   /// \brief Instrument relational comparisons.
1582   ///
1583   /// This function does exact shadow propagation for all relational
1584   /// comparisons of integers, pointers and vectors of those.
1585   /// FIXME: output seems suboptimal when one of the operands is a constant
1586   void handleRelationalComparisonExact(ICmpInst &I) {
1587     IRBuilder<> IRB(&I);
1588     Value *A = I.getOperand(0);
1589     Value *B = I.getOperand(1);
1590     Value *Sa = getShadow(A);
1591     Value *Sb = getShadow(B);
1592
1593     // Get rid of pointers and vectors of pointers.
1594     // For ints (and vectors of ints), types of A and Sa match,
1595     // and this is a no-op.
1596     A = IRB.CreatePointerCast(A, Sa->getType());
1597     B = IRB.CreatePointerCast(B, Sb->getType());
1598
1599     // Let [a0, a1] be the interval of possible values of A, taking into account
1600     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1601     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1602     bool IsSigned = I.isSigned();
1603     Value *S1 = IRB.CreateICmp(I.getPredicate(),
1604                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
1605                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
1606     Value *S2 = IRB.CreateICmp(I.getPredicate(),
1607                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
1608                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
1609     Value *Si = IRB.CreateXor(S1, S2);
1610     setShadow(&I, Si);
1611     setOriginForNaryOp(I);
1612   }
1613
1614   /// \brief Instrument signed relational comparisons.
1615   ///
1616   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1617   /// propagating the highest bit of the shadow. Everything else is delegated
1618   /// to handleShadowOr().
1619   void handleSignedRelationalComparison(ICmpInst &I) {
1620     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1621     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1622     Value* op = nullptr;
1623     CmpInst::Predicate pre = I.getPredicate();
1624     if (constOp0 && constOp0->isNullValue() &&
1625         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1626       op = I.getOperand(1);
1627     } else if (constOp1 && constOp1->isNullValue() &&
1628                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1629       op = I.getOperand(0);
1630     }
1631     if (op) {
1632       IRBuilder<> IRB(&I);
1633       Value* Shadow =
1634         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1635       setShadow(&I, Shadow);
1636       setOrigin(&I, getOrigin(op));
1637     } else {
1638       handleShadowOr(I);
1639     }
1640   }
1641
1642   void visitICmpInst(ICmpInst &I) {
1643     if (!ClHandleICmp) {
1644       handleShadowOr(I);
1645       return;
1646     }
1647     if (I.isEquality()) {
1648       handleEqualityComparison(I);
1649       return;
1650     }
1651
1652     assert(I.isRelational());
1653     if (ClHandleICmpExact) {
1654       handleRelationalComparisonExact(I);
1655       return;
1656     }
1657     if (I.isSigned()) {
1658       handleSignedRelationalComparison(I);
1659       return;
1660     }
1661
1662     assert(I.isUnsigned());
1663     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1664       handleRelationalComparisonExact(I);
1665       return;
1666     }
1667
1668     handleShadowOr(I);
1669   }
1670
1671   void visitFCmpInst(FCmpInst &I) {
1672     handleShadowOr(I);
1673   }
1674
1675   void handleShift(BinaryOperator &I) {
1676     IRBuilder<> IRB(&I);
1677     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1678     // Otherwise perform the same shift on S1.
1679     Value *S1 = getShadow(&I, 0);
1680     Value *S2 = getShadow(&I, 1);
1681     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1682                                    S2->getType());
1683     Value *V2 = I.getOperand(1);
1684     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1685     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1686     setOriginForNaryOp(I);
1687   }
1688
1689   void visitShl(BinaryOperator &I) { handleShift(I); }
1690   void visitAShr(BinaryOperator &I) { handleShift(I); }
1691   void visitLShr(BinaryOperator &I) { handleShift(I); }
1692
1693   /// \brief Instrument llvm.memmove
1694   ///
1695   /// At this point we don't know if llvm.memmove will be inlined or not.
1696   /// If we don't instrument it and it gets inlined,
1697   /// our interceptor will not kick in and we will lose the memmove.
1698   /// If we instrument the call here, but it does not get inlined,
1699   /// we will memove the shadow twice: which is bad in case
1700   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1701   ///
1702   /// Similar situation exists for memcpy and memset.
1703   void visitMemMoveInst(MemMoveInst &I) {
1704     IRBuilder<> IRB(&I);
1705     IRB.CreateCall3(
1706       MS.MemmoveFn,
1707       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1708       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1709       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1710     I.eraseFromParent();
1711   }
1712
1713   // Similar to memmove: avoid copying shadow twice.
1714   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1715   // FIXME: consider doing manual inline for small constant sizes and proper
1716   // alignment.
1717   void visitMemCpyInst(MemCpyInst &I) {
1718     IRBuilder<> IRB(&I);
1719     IRB.CreateCall3(
1720       MS.MemcpyFn,
1721       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1722       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1723       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1724     I.eraseFromParent();
1725   }
1726
1727   // Same as memcpy.
1728   void visitMemSetInst(MemSetInst &I) {
1729     IRBuilder<> IRB(&I);
1730     IRB.CreateCall3(
1731       MS.MemsetFn,
1732       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1733       IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1734       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1735     I.eraseFromParent();
1736   }
1737
1738   void visitVAStartInst(VAStartInst &I) {
1739     VAHelper->visitVAStartInst(I);
1740   }
1741
1742   void visitVACopyInst(VACopyInst &I) {
1743     VAHelper->visitVACopyInst(I);
1744   }
1745
1746   enum IntrinsicKind {
1747     IK_DoesNotAccessMemory,
1748     IK_OnlyReadsMemory,
1749     IK_WritesMemory
1750   };
1751
1752   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1753     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1754     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1755     const int OnlyReadsMemory = IK_OnlyReadsMemory;
1756     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1757     const int UnknownModRefBehavior = IK_WritesMemory;
1758 #define GET_INTRINSIC_MODREF_BEHAVIOR
1759 #define ModRefBehavior IntrinsicKind
1760 #include "llvm/IR/Intrinsics.gen"
1761 #undef ModRefBehavior
1762 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1763   }
1764
1765   /// \brief Handle vector store-like intrinsics.
1766   ///
1767   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1768   /// has 1 pointer argument and 1 vector argument, returns void.
1769   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1770     IRBuilder<> IRB(&I);
1771     Value* Addr = I.getArgOperand(0);
1772     Value *Shadow = getShadow(&I, 1);
1773     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1774
1775     // We don't know the pointer alignment (could be unaligned SSE store!).
1776     // Have to assume to worst case.
1777     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1778
1779     if (ClCheckAccessAddress)
1780       insertShadowCheck(Addr, &I);
1781
1782     // FIXME: use ClStoreCleanOrigin
1783     // FIXME: factor out common code from materializeStores
1784     if (MS.TrackOrigins)
1785       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1786     return true;
1787   }
1788
1789   /// \brief Handle vector load-like intrinsics.
1790   ///
1791   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1792   /// has 1 pointer argument, returns a vector.
1793   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1794     IRBuilder<> IRB(&I);
1795     Value *Addr = I.getArgOperand(0);
1796
1797     Type *ShadowTy = getShadowTy(&I);
1798     if (PropagateShadow) {
1799       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1800       // We don't know the pointer alignment (could be unaligned SSE load!).
1801       // Have to assume to worst case.
1802       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1803     } else {
1804       setShadow(&I, getCleanShadow(&I));
1805     }
1806
1807     if (ClCheckAccessAddress)
1808       insertShadowCheck(Addr, &I);
1809
1810     if (MS.TrackOrigins) {
1811       if (PropagateShadow)
1812         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1813       else
1814         setOrigin(&I, getCleanOrigin());
1815     }
1816     return true;
1817   }
1818
1819   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1820   ///
1821   /// Instrument intrinsics with any number of arguments of the same type,
1822   /// equal to the return type. The type should be simple (no aggregates or
1823   /// pointers; vectors are fine).
1824   /// Caller guarantees that this intrinsic does not access memory.
1825   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1826     Type *RetTy = I.getType();
1827     if (!(RetTy->isIntOrIntVectorTy() ||
1828           RetTy->isFPOrFPVectorTy() ||
1829           RetTy->isX86_MMXTy()))
1830       return false;
1831
1832     unsigned NumArgOperands = I.getNumArgOperands();
1833
1834     for (unsigned i = 0; i < NumArgOperands; ++i) {
1835       Type *Ty = I.getArgOperand(i)->getType();
1836       if (Ty != RetTy)
1837         return false;
1838     }
1839
1840     IRBuilder<> IRB(&I);
1841     ShadowAndOriginCombiner SC(this, IRB);
1842     for (unsigned i = 0; i < NumArgOperands; ++i)
1843       SC.Add(I.getArgOperand(i));
1844     SC.Done(&I);
1845
1846     return true;
1847   }
1848
1849   /// \brief Heuristically instrument unknown intrinsics.
1850   ///
1851   /// The main purpose of this code is to do something reasonable with all
1852   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1853   /// We recognize several classes of intrinsics by their argument types and
1854   /// ModRefBehaviour and apply special intrumentation when we are reasonably
1855   /// sure that we know what the intrinsic does.
1856   ///
1857   /// We special-case intrinsics where this approach fails. See llvm.bswap
1858   /// handling as an example of that.
1859   bool handleUnknownIntrinsic(IntrinsicInst &I) {
1860     unsigned NumArgOperands = I.getNumArgOperands();
1861     if (NumArgOperands == 0)
1862       return false;
1863
1864     Intrinsic::ID iid = I.getIntrinsicID();
1865     IntrinsicKind IK = getIntrinsicKind(iid);
1866     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1867     bool WritesMemory = IK == IK_WritesMemory;
1868     assert(!(OnlyReadsMemory && WritesMemory));
1869
1870     if (NumArgOperands == 2 &&
1871         I.getArgOperand(0)->getType()->isPointerTy() &&
1872         I.getArgOperand(1)->getType()->isVectorTy() &&
1873         I.getType()->isVoidTy() &&
1874         WritesMemory) {
1875       // This looks like a vector store.
1876       return handleVectorStoreIntrinsic(I);
1877     }
1878
1879     if (NumArgOperands == 1 &&
1880         I.getArgOperand(0)->getType()->isPointerTy() &&
1881         I.getType()->isVectorTy() &&
1882         OnlyReadsMemory) {
1883       // This looks like a vector load.
1884       return handleVectorLoadIntrinsic(I);
1885     }
1886
1887     if (!OnlyReadsMemory && !WritesMemory)
1888       if (maybeHandleSimpleNomemIntrinsic(I))
1889         return true;
1890
1891     // FIXME: detect and handle SSE maskstore/maskload
1892     return false;
1893   }
1894
1895   void handleBswap(IntrinsicInst &I) {
1896     IRBuilder<> IRB(&I);
1897     Value *Op = I.getArgOperand(0);
1898     Type *OpType = Op->getType();
1899     Function *BswapFunc = Intrinsic::getDeclaration(
1900       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
1901     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1902     setOrigin(&I, getOrigin(Op));
1903   }
1904
1905   // \brief Instrument vector convert instrinsic.
1906   //
1907   // This function instruments intrinsics like cvtsi2ss:
1908   // %Out = int_xxx_cvtyyy(%ConvertOp)
1909   // or
1910   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1911   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1912   // number \p Out elements, and (if has 2 arguments) copies the rest of the
1913   // elements from \p CopyOp.
1914   // In most cases conversion involves floating-point value which may trigger a
1915   // hardware exception when not fully initialized. For this reason we require
1916   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1917   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1918   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1919   // return a fully initialized value.
1920   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1921     IRBuilder<> IRB(&I);
1922     Value *CopyOp, *ConvertOp;
1923
1924     switch (I.getNumArgOperands()) {
1925     case 2:
1926       CopyOp = I.getArgOperand(0);
1927       ConvertOp = I.getArgOperand(1);
1928       break;
1929     case 1:
1930       ConvertOp = I.getArgOperand(0);
1931       CopyOp = nullptr;
1932       break;
1933     default:
1934       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1935     }
1936
1937     // The first *NumUsedElements* elements of ConvertOp are converted to the
1938     // same number of output elements. The rest of the output is copied from
1939     // CopyOp, or (if not available) filled with zeroes.
1940     // Combine shadow for elements of ConvertOp that are used in this operation,
1941     // and insert a check.
1942     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1943     // int->any conversion.
1944     Value *ConvertShadow = getShadow(ConvertOp);
1945     Value *AggShadow = nullptr;
1946     if (ConvertOp->getType()->isVectorTy()) {
1947       AggShadow = IRB.CreateExtractElement(
1948           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1949       for (int i = 1; i < NumUsedElements; ++i) {
1950         Value *MoreShadow = IRB.CreateExtractElement(
1951             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1952         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1953       }
1954     } else {
1955       AggShadow = ConvertShadow;
1956     }
1957     assert(AggShadow->getType()->isIntegerTy());
1958     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1959
1960     // Build result shadow by zero-filling parts of CopyOp shadow that come from
1961     // ConvertOp.
1962     if (CopyOp) {
1963       assert(CopyOp->getType() == I.getType());
1964       assert(CopyOp->getType()->isVectorTy());
1965       Value *ResultShadow = getShadow(CopyOp);
1966       Type *EltTy = ResultShadow->getType()->getVectorElementType();
1967       for (int i = 0; i < NumUsedElements; ++i) {
1968         ResultShadow = IRB.CreateInsertElement(
1969             ResultShadow, ConstantInt::getNullValue(EltTy),
1970             ConstantInt::get(IRB.getInt32Ty(), i));
1971       }
1972       setShadow(&I, ResultShadow);
1973       setOrigin(&I, getOrigin(CopyOp));
1974     } else {
1975       setShadow(&I, getCleanShadow(&I));
1976     }
1977   }
1978
1979   // Given a scalar or vector, extract lower 64 bits (or less), and return all
1980   // zeroes if it is zero, and all ones otherwise.
1981   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
1982     if (S->getType()->isVectorTy())
1983       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
1984     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
1985     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1986     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
1987   }
1988
1989   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
1990     Type *T = S->getType();
1991     assert(T->isVectorTy());
1992     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
1993     return IRB.CreateSExt(S2, T);
1994   }
1995
1996   // \brief Instrument vector shift instrinsic.
1997   //
1998   // This function instruments intrinsics like int_x86_avx2_psll_w.
1999   // Intrinsic shifts %In by %ShiftSize bits.
2000   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2001   // size, and the rest is ignored. Behavior is defined even if shift size is
2002   // greater than register (or field) width.
2003   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2004     assert(I.getNumArgOperands() == 2);
2005     IRBuilder<> IRB(&I);
2006     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2007     // Otherwise perform the same shift on S1.
2008     Value *S1 = getShadow(&I, 0);
2009     Value *S2 = getShadow(&I, 1);
2010     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2011                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2012     Value *V1 = I.getOperand(0);
2013     Value *V2 = I.getOperand(1);
2014     Value *Shift = IRB.CreateCall2(I.getCalledValue(),
2015                                    IRB.CreateBitCast(S1, V1->getType()), V2);
2016     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2017     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2018     setOriginForNaryOp(I);
2019   }
2020
2021   // \brief Get an X86_MMX-sized vector type.
2022   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2023     const unsigned X86_MMXSizeInBits = 64;
2024     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2025                            X86_MMXSizeInBits / EltSizeInBits);
2026   }
2027
2028   // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
2029   // intrinsic.
2030   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2031     switch (id) {
2032       case llvm::Intrinsic::x86_sse2_packsswb_128:
2033       case llvm::Intrinsic::x86_sse2_packuswb_128:
2034         return llvm::Intrinsic::x86_sse2_packsswb_128;
2035
2036       case llvm::Intrinsic::x86_sse2_packssdw_128:
2037       case llvm::Intrinsic::x86_sse41_packusdw:
2038         return llvm::Intrinsic::x86_sse2_packssdw_128;
2039
2040       case llvm::Intrinsic::x86_avx2_packsswb:
2041       case llvm::Intrinsic::x86_avx2_packuswb:
2042         return llvm::Intrinsic::x86_avx2_packsswb;
2043
2044       case llvm::Intrinsic::x86_avx2_packssdw:
2045       case llvm::Intrinsic::x86_avx2_packusdw:
2046         return llvm::Intrinsic::x86_avx2_packssdw;
2047
2048       case llvm::Intrinsic::x86_mmx_packsswb:
2049       case llvm::Intrinsic::x86_mmx_packuswb:
2050         return llvm::Intrinsic::x86_mmx_packsswb;
2051
2052       case llvm::Intrinsic::x86_mmx_packssdw:
2053         return llvm::Intrinsic::x86_mmx_packssdw;
2054       default:
2055         llvm_unreachable("unexpected intrinsic id");
2056     }
2057   }
2058
2059   // \brief Instrument vector pack instrinsic.
2060   //
2061   // This function instruments intrinsics like x86_mmx_packsswb, that
2062   // packs elements of 2 input vectors into half as many bits with saturation.
2063   // Shadow is propagated with the signed variant of the same intrinsic applied
2064   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2065   // EltSizeInBits is used only for x86mmx arguments.
2066   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2067     assert(I.getNumArgOperands() == 2);
2068     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2069     IRBuilder<> IRB(&I);
2070     Value *S1 = getShadow(&I, 0);
2071     Value *S2 = getShadow(&I, 1);
2072     assert(isX86_MMX || S1->getType()->isVectorTy());
2073
2074     // SExt and ICmpNE below must apply to individual elements of input vectors.
2075     // In case of x86mmx arguments, cast them to appropriate vector types and
2076     // back.
2077     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2078     if (isX86_MMX) {
2079       S1 = IRB.CreateBitCast(S1, T);
2080       S2 = IRB.CreateBitCast(S2, T);
2081     }
2082     Value *S1_ext = IRB.CreateSExt(
2083         IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
2084     Value *S2_ext = IRB.CreateSExt(
2085         IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
2086     if (isX86_MMX) {
2087       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2088       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2089       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2090     }
2091
2092     Function *ShadowFn = Intrinsic::getDeclaration(
2093         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2094
2095     Value *S = IRB.CreateCall2(ShadowFn, S1_ext, S2_ext, "_msprop_vector_pack");
2096     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2097     setShadow(&I, S);
2098     setOriginForNaryOp(I);
2099   }
2100
2101   // \brief Instrument sum-of-absolute-differencies intrinsic.
2102   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2103     const unsigned SignificantBitsPerResultElement = 16;
2104     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2105     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2106     unsigned ZeroBitsPerResultElement =
2107         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2108
2109     IRBuilder<> IRB(&I);
2110     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2111     S = IRB.CreateBitCast(S, ResTy);
2112     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2113                        ResTy);
2114     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2115     S = IRB.CreateBitCast(S, getShadowTy(&I));
2116     setShadow(&I, S);
2117     setOriginForNaryOp(I);
2118   }
2119
2120   // \brief Instrument multiply-add intrinsic.
2121   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2122                                   unsigned EltSizeInBits = 0) {
2123     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2124     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2125     IRBuilder<> IRB(&I);
2126     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2127     S = IRB.CreateBitCast(S, ResTy);
2128     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2129                        ResTy);
2130     S = IRB.CreateBitCast(S, getShadowTy(&I));
2131     setShadow(&I, S);
2132     setOriginForNaryOp(I);
2133   }
2134
2135   void visitIntrinsicInst(IntrinsicInst &I) {
2136     switch (I.getIntrinsicID()) {
2137     case llvm::Intrinsic::bswap:
2138       handleBswap(I);
2139       break;
2140     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
2141     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
2142     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
2143     case llvm::Intrinsic::x86_avx512_cvtss2usi:
2144     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
2145     case llvm::Intrinsic::x86_avx512_cvttss2usi:
2146     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
2147     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
2148     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
2149     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
2150     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
2151     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
2152     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
2153     case llvm::Intrinsic::x86_sse2_cvtsd2si:
2154     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
2155     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
2156     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
2157     case llvm::Intrinsic::x86_sse2_cvtss2sd:
2158     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
2159     case llvm::Intrinsic::x86_sse2_cvttsd2si:
2160     case llvm::Intrinsic::x86_sse_cvtsi2ss:
2161     case llvm::Intrinsic::x86_sse_cvtsi642ss:
2162     case llvm::Intrinsic::x86_sse_cvtss2si64:
2163     case llvm::Intrinsic::x86_sse_cvtss2si:
2164     case llvm::Intrinsic::x86_sse_cvttss2si64:
2165     case llvm::Intrinsic::x86_sse_cvttss2si:
2166       handleVectorConvertIntrinsic(I, 1);
2167       break;
2168     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
2169     case llvm::Intrinsic::x86_sse2_cvtps2pd:
2170     case llvm::Intrinsic::x86_sse_cvtps2pi:
2171     case llvm::Intrinsic::x86_sse_cvttps2pi:
2172       handleVectorConvertIntrinsic(I, 2);
2173       break;
2174     case llvm::Intrinsic::x86_avx512_psll_dq:
2175     case llvm::Intrinsic::x86_avx512_psrl_dq:
2176     case llvm::Intrinsic::x86_avx2_psll_w:
2177     case llvm::Intrinsic::x86_avx2_psll_d:
2178     case llvm::Intrinsic::x86_avx2_psll_q:
2179     case llvm::Intrinsic::x86_avx2_pslli_w:
2180     case llvm::Intrinsic::x86_avx2_pslli_d:
2181     case llvm::Intrinsic::x86_avx2_pslli_q:
2182     case llvm::Intrinsic::x86_avx2_psll_dq:
2183     case llvm::Intrinsic::x86_avx2_psrl_w:
2184     case llvm::Intrinsic::x86_avx2_psrl_d:
2185     case llvm::Intrinsic::x86_avx2_psrl_q:
2186     case llvm::Intrinsic::x86_avx2_psra_w:
2187     case llvm::Intrinsic::x86_avx2_psra_d:
2188     case llvm::Intrinsic::x86_avx2_psrli_w:
2189     case llvm::Intrinsic::x86_avx2_psrli_d:
2190     case llvm::Intrinsic::x86_avx2_psrli_q:
2191     case llvm::Intrinsic::x86_avx2_psrai_w:
2192     case llvm::Intrinsic::x86_avx2_psrai_d:
2193     case llvm::Intrinsic::x86_avx2_psrl_dq:
2194     case llvm::Intrinsic::x86_sse2_psll_w:
2195     case llvm::Intrinsic::x86_sse2_psll_d:
2196     case llvm::Intrinsic::x86_sse2_psll_q:
2197     case llvm::Intrinsic::x86_sse2_pslli_w:
2198     case llvm::Intrinsic::x86_sse2_pslli_d:
2199     case llvm::Intrinsic::x86_sse2_pslli_q:
2200     case llvm::Intrinsic::x86_sse2_psll_dq:
2201     case llvm::Intrinsic::x86_sse2_psrl_w:
2202     case llvm::Intrinsic::x86_sse2_psrl_d:
2203     case llvm::Intrinsic::x86_sse2_psrl_q:
2204     case llvm::Intrinsic::x86_sse2_psra_w:
2205     case llvm::Intrinsic::x86_sse2_psra_d:
2206     case llvm::Intrinsic::x86_sse2_psrli_w:
2207     case llvm::Intrinsic::x86_sse2_psrli_d:
2208     case llvm::Intrinsic::x86_sse2_psrli_q:
2209     case llvm::Intrinsic::x86_sse2_psrai_w:
2210     case llvm::Intrinsic::x86_sse2_psrai_d:
2211     case llvm::Intrinsic::x86_sse2_psrl_dq:
2212     case llvm::Intrinsic::x86_mmx_psll_w:
2213     case llvm::Intrinsic::x86_mmx_psll_d:
2214     case llvm::Intrinsic::x86_mmx_psll_q:
2215     case llvm::Intrinsic::x86_mmx_pslli_w:
2216     case llvm::Intrinsic::x86_mmx_pslli_d:
2217     case llvm::Intrinsic::x86_mmx_pslli_q:
2218     case llvm::Intrinsic::x86_mmx_psrl_w:
2219     case llvm::Intrinsic::x86_mmx_psrl_d:
2220     case llvm::Intrinsic::x86_mmx_psrl_q:
2221     case llvm::Intrinsic::x86_mmx_psra_w:
2222     case llvm::Intrinsic::x86_mmx_psra_d:
2223     case llvm::Intrinsic::x86_mmx_psrli_w:
2224     case llvm::Intrinsic::x86_mmx_psrli_d:
2225     case llvm::Intrinsic::x86_mmx_psrli_q:
2226     case llvm::Intrinsic::x86_mmx_psrai_w:
2227     case llvm::Intrinsic::x86_mmx_psrai_d:
2228       handleVectorShiftIntrinsic(I, /* Variable */ false);
2229       break;
2230     case llvm::Intrinsic::x86_avx2_psllv_d:
2231     case llvm::Intrinsic::x86_avx2_psllv_d_256:
2232     case llvm::Intrinsic::x86_avx2_psllv_q:
2233     case llvm::Intrinsic::x86_avx2_psllv_q_256:
2234     case llvm::Intrinsic::x86_avx2_psrlv_d:
2235     case llvm::Intrinsic::x86_avx2_psrlv_d_256:
2236     case llvm::Intrinsic::x86_avx2_psrlv_q:
2237     case llvm::Intrinsic::x86_avx2_psrlv_q_256:
2238     case llvm::Intrinsic::x86_avx2_psrav_d:
2239     case llvm::Intrinsic::x86_avx2_psrav_d_256:
2240       handleVectorShiftIntrinsic(I, /* Variable */ true);
2241       break;
2242
2243     // Byte shifts are not implemented.
2244     // case llvm::Intrinsic::x86_avx512_psll_dq_bs:
2245     // case llvm::Intrinsic::x86_avx512_psrl_dq_bs:
2246     // case llvm::Intrinsic::x86_avx2_psll_dq_bs:
2247     // case llvm::Intrinsic::x86_avx2_psrl_dq_bs:
2248     // case llvm::Intrinsic::x86_sse2_psll_dq_bs:
2249     // case llvm::Intrinsic::x86_sse2_psrl_dq_bs:
2250
2251     case llvm::Intrinsic::x86_sse2_packsswb_128:
2252     case llvm::Intrinsic::x86_sse2_packssdw_128:
2253     case llvm::Intrinsic::x86_sse2_packuswb_128:
2254     case llvm::Intrinsic::x86_sse41_packusdw:
2255     case llvm::Intrinsic::x86_avx2_packsswb:
2256     case llvm::Intrinsic::x86_avx2_packssdw:
2257     case llvm::Intrinsic::x86_avx2_packuswb:
2258     case llvm::Intrinsic::x86_avx2_packusdw:
2259       handleVectorPackIntrinsic(I);
2260       break;
2261
2262     case llvm::Intrinsic::x86_mmx_packsswb:
2263     case llvm::Intrinsic::x86_mmx_packuswb:
2264       handleVectorPackIntrinsic(I, 16);
2265       break;
2266
2267     case llvm::Intrinsic::x86_mmx_packssdw:
2268       handleVectorPackIntrinsic(I, 32);
2269       break;
2270
2271     case llvm::Intrinsic::x86_mmx_psad_bw:
2272     case llvm::Intrinsic::x86_sse2_psad_bw:
2273     case llvm::Intrinsic::x86_avx2_psad_bw:
2274       handleVectorSadIntrinsic(I);
2275       break;
2276
2277     case llvm::Intrinsic::x86_sse2_pmadd_wd:
2278     case llvm::Intrinsic::x86_avx2_pmadd_wd:
2279     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
2280     case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
2281       handleVectorPmaddIntrinsic(I);
2282       break;
2283
2284     case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
2285       handleVectorPmaddIntrinsic(I, 8);
2286       break;
2287
2288     case llvm::Intrinsic::x86_mmx_pmadd_wd:
2289       handleVectorPmaddIntrinsic(I, 16);
2290       break;
2291
2292     default:
2293       if (!handleUnknownIntrinsic(I))
2294         visitInstruction(I);
2295       break;
2296     }
2297   }
2298
2299   void visitCallSite(CallSite CS) {
2300     Instruction &I = *CS.getInstruction();
2301     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
2302     if (CS.isCall()) {
2303       CallInst *Call = cast<CallInst>(&I);
2304
2305       // For inline asm, do the usual thing: check argument shadow and mark all
2306       // outputs as clean. Note that any side effects of the inline asm that are
2307       // not immediately visible in its constraints are not handled.
2308       if (Call->isInlineAsm()) {
2309         visitInstruction(I);
2310         return;
2311       }
2312
2313       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
2314
2315       // We are going to insert code that relies on the fact that the callee
2316       // will become a non-readonly function after it is instrumented by us. To
2317       // prevent this code from being optimized out, mark that function
2318       // non-readonly in advance.
2319       if (Function *Func = Call->getCalledFunction()) {
2320         // Clear out readonly/readnone attributes.
2321         AttrBuilder B;
2322         B.addAttribute(Attribute::ReadOnly)
2323           .addAttribute(Attribute::ReadNone);
2324         Func->removeAttributes(AttributeSet::FunctionIndex,
2325                                AttributeSet::get(Func->getContext(),
2326                                                  AttributeSet::FunctionIndex,
2327                                                  B));
2328       }
2329     }
2330     IRBuilder<> IRB(&I);
2331
2332     if (MS.WrapIndirectCalls && !CS.getCalledFunction())
2333       IndirectCallList.push_back(CS);
2334
2335     unsigned ArgOffset = 0;
2336     DEBUG(dbgs() << "  CallSite: " << I << "\n");
2337     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2338          ArgIt != End; ++ArgIt) {
2339       Value *A = *ArgIt;
2340       unsigned i = ArgIt - CS.arg_begin();
2341       if (!A->getType()->isSized()) {
2342         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
2343         continue;
2344       }
2345       unsigned Size = 0;
2346       Value *Store = nullptr;
2347       // Compute the Shadow for arg even if it is ByVal, because
2348       // in that case getShadow() will copy the actual arg shadow to
2349       // __msan_param_tls.
2350       Value *ArgShadow = getShadow(A);
2351       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
2352       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
2353             " Shadow: " << *ArgShadow << "\n");
2354       bool ArgIsInitialized = false;
2355       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
2356         assert(A->getType()->isPointerTy() &&
2357                "ByVal argument is not a pointer!");
2358         Size = MS.DL->getTypeAllocSize(A->getType()->getPointerElementType());
2359         if (ArgOffset + Size > kParamTLSSize) break;
2360         unsigned ParamAlignment = CS.getParamAlignment(i + 1);
2361         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
2362         Store = IRB.CreateMemCpy(ArgShadowBase,
2363                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
2364                                  Size, Alignment);
2365       } else {
2366         Size = MS.DL->getTypeAllocSize(A->getType());
2367         if (ArgOffset + Size > kParamTLSSize) break;
2368         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
2369                                        kShadowTLSAlignment);
2370         Constant *Cst = dyn_cast<Constant>(ArgShadow);
2371         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
2372       }
2373       if (MS.TrackOrigins && !ArgIsInitialized)
2374         IRB.CreateStore(getOrigin(A),
2375                         getOriginPtrForArgument(A, IRB, ArgOffset));
2376       (void)Store;
2377       assert(Size != 0 && Store != nullptr);
2378       DEBUG(dbgs() << "  Param:" << *Store << "\n");
2379       ArgOffset += RoundUpToAlignment(Size, 8);
2380     }
2381     DEBUG(dbgs() << "  done with call args\n");
2382
2383     FunctionType *FT =
2384       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
2385     if (FT->isVarArg()) {
2386       VAHelper->visitCallSite(CS, IRB);
2387     }
2388
2389     // Now, get the shadow for the RetVal.
2390     if (!I.getType()->isSized()) return;
2391     IRBuilder<> IRBBefore(&I);
2392     // Until we have full dynamic coverage, make sure the retval shadow is 0.
2393     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
2394     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
2395     Instruction *NextInsn = nullptr;
2396     if (CS.isCall()) {
2397       NextInsn = I.getNextNode();
2398     } else {
2399       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
2400       if (!NormalDest->getSinglePredecessor()) {
2401         // FIXME: this case is tricky, so we are just conservative here.
2402         // Perhaps we need to split the edge between this BB and NormalDest,
2403         // but a naive attempt to use SplitEdge leads to a crash.
2404         setShadow(&I, getCleanShadow(&I));
2405         setOrigin(&I, getCleanOrigin());
2406         return;
2407       }
2408       NextInsn = NormalDest->getFirstInsertionPt();
2409       assert(NextInsn &&
2410              "Could not find insertion point for retval shadow load");
2411     }
2412     IRBuilder<> IRBAfter(NextInsn);
2413     Value *RetvalShadow =
2414       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
2415                                  kShadowTLSAlignment, "_msret");
2416     setShadow(&I, RetvalShadow);
2417     if (MS.TrackOrigins)
2418       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
2419   }
2420
2421   void visitReturnInst(ReturnInst &I) {
2422     IRBuilder<> IRB(&I);
2423     Value *RetVal = I.getReturnValue();
2424     if (!RetVal) return;
2425     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
2426     if (CheckReturnValue) {
2427       insertShadowCheck(RetVal, &I);
2428       Value *Shadow = getCleanShadow(RetVal);
2429       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2430     } else {
2431       Value *Shadow = getShadow(RetVal);
2432       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
2433       // FIXME: make it conditional if ClStoreCleanOrigin==0
2434       if (MS.TrackOrigins)
2435         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
2436     }
2437   }
2438
2439   void visitPHINode(PHINode &I) {
2440     IRBuilder<> IRB(&I);
2441     if (!PropagateShadow) {
2442       setShadow(&I, getCleanShadow(&I));
2443       return;
2444     }
2445
2446     ShadowPHINodes.push_back(&I);
2447     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
2448                                 "_msphi_s"));
2449     if (MS.TrackOrigins)
2450       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
2451                                   "_msphi_o"));
2452   }
2453
2454   void visitAllocaInst(AllocaInst &I) {
2455     setShadow(&I, getCleanShadow(&I));
2456     IRBuilder<> IRB(I.getNextNode());
2457     uint64_t Size = MS.DL->getTypeAllocSize(I.getAllocatedType());
2458     if (PoisonStack && ClPoisonStackWithCall) {
2459       IRB.CreateCall2(MS.MsanPoisonStackFn,
2460                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2461                       ConstantInt::get(MS.IntptrTy, Size));
2462     } else {
2463       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
2464       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
2465       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
2466     }
2467
2468     if (PoisonStack && MS.TrackOrigins) {
2469       setOrigin(&I, getCleanOrigin());
2470       SmallString<2048> StackDescriptionStorage;
2471       raw_svector_ostream StackDescription(StackDescriptionStorage);
2472       // We create a string with a description of the stack allocation and
2473       // pass it into __msan_set_alloca_origin.
2474       // It will be printed by the run-time if stack-originated UMR is found.
2475       // The first 4 bytes of the string are set to '----' and will be replaced
2476       // by __msan_va_arg_overflow_size_tls at the first call.
2477       StackDescription << "----" << I.getName() << "@" << F.getName();
2478       Value *Descr =
2479           createPrivateNonConstGlobalForString(*F.getParent(),
2480                                                StackDescription.str());
2481
2482       IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
2483                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2484                       ConstantInt::get(MS.IntptrTy, Size),
2485                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2486                       IRB.CreatePointerCast(&F, MS.IntptrTy));
2487     }
2488   }
2489
2490   void visitSelectInst(SelectInst& I) {
2491     IRBuilder<> IRB(&I);
2492     // a = select b, c, d
2493     Value *B = I.getCondition();
2494     Value *C = I.getTrueValue();
2495     Value *D = I.getFalseValue();
2496     Value *Sb = getShadow(B);
2497     Value *Sc = getShadow(C);
2498     Value *Sd = getShadow(D);
2499
2500     // Result shadow if condition shadow is 0.
2501     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
2502     Value *Sa1;
2503     if (I.getType()->isAggregateType()) {
2504       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2505       // an extra "select". This results in much more compact IR.
2506       // Sa = select Sb, poisoned, (select b, Sc, Sd)
2507       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
2508     } else {
2509       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
2510       // If Sb (condition is poisoned), look for bits in c and d that are equal
2511       // and both unpoisoned.
2512       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
2513
2514       // Cast arguments to shadow-compatible type.
2515       C = CreateAppToShadowCast(IRB, C);
2516       D = CreateAppToShadowCast(IRB, D);
2517
2518       // Result shadow if condition shadow is 1.
2519       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
2520     }
2521     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
2522     setShadow(&I, Sa);
2523     if (MS.TrackOrigins) {
2524       // Origins are always i32, so any vector conditions must be flattened.
2525       // FIXME: consider tracking vector origins for app vectors?
2526       if (B->getType()->isVectorTy()) {
2527         Type *FlatTy = getShadowTyNoVec(B->getType());
2528         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
2529                                 ConstantInt::getNullValue(FlatTy));
2530         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
2531                                       ConstantInt::getNullValue(FlatTy));
2532       }
2533       // a = select b, c, d
2534       // Oa = Sb ? Ob : (b ? Oc : Od)
2535       setOrigin(&I, IRB.CreateSelect(
2536                         Sb, getOrigin(I.getCondition()),
2537                         IRB.CreateSelect(B, getOrigin(C), getOrigin(D))));
2538     }
2539   }
2540
2541   void visitLandingPadInst(LandingPadInst &I) {
2542     // Do nothing.
2543     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2544     setShadow(&I, getCleanShadow(&I));
2545     setOrigin(&I, getCleanOrigin());
2546   }
2547
2548   void visitGetElementPtrInst(GetElementPtrInst &I) {
2549     handleShadowOr(I);
2550   }
2551
2552   void visitExtractValueInst(ExtractValueInst &I) {
2553     IRBuilder<> IRB(&I);
2554     Value *Agg = I.getAggregateOperand();
2555     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
2556     Value *AggShadow = getShadow(Agg);
2557     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2558     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2559     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
2560     setShadow(&I, ResShadow);
2561     setOriginForNaryOp(I);
2562   }
2563
2564   void visitInsertValueInst(InsertValueInst &I) {
2565     IRBuilder<> IRB(&I);
2566     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
2567     Value *AggShadow = getShadow(I.getAggregateOperand());
2568     Value *InsShadow = getShadow(I.getInsertedValueOperand());
2569     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2570     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
2571     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2572     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
2573     setShadow(&I, Res);
2574     setOriginForNaryOp(I);
2575   }
2576
2577   void dumpInst(Instruction &I) {
2578     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2579       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2580     } else {
2581       errs() << "ZZZ " << I.getOpcodeName() << "\n";
2582     }
2583     errs() << "QQQ " << I << "\n";
2584   }
2585
2586   void visitResumeInst(ResumeInst &I) {
2587     DEBUG(dbgs() << "Resume: " << I << "\n");
2588     // Nothing to do here.
2589   }
2590
2591   void visitInstruction(Instruction &I) {
2592     // Everything else: stop propagating and check for poisoned shadow.
2593     if (ClDumpStrictInstructions)
2594       dumpInst(I);
2595     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2596     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2597       insertShadowCheck(I.getOperand(i), &I);
2598     setShadow(&I, getCleanShadow(&I));
2599     setOrigin(&I, getCleanOrigin());
2600   }
2601 };
2602
2603 /// \brief AMD64-specific implementation of VarArgHelper.
2604 struct VarArgAMD64Helper : public VarArgHelper {
2605   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2606   // See a comment in visitCallSite for more details.
2607   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
2608   static const unsigned AMD64FpEndOffset = 176;
2609
2610   Function &F;
2611   MemorySanitizer &MS;
2612   MemorySanitizerVisitor &MSV;
2613   Value *VAArgTLSCopy;
2614   Value *VAArgOverflowSize;
2615
2616   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2617
2618   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2619                     MemorySanitizerVisitor &MSV)
2620     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
2621       VAArgOverflowSize(nullptr) {}
2622
2623   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2624
2625   ArgKind classifyArgument(Value* arg) {
2626     // A very rough approximation of X86_64 argument classification rules.
2627     Type *T = arg->getType();
2628     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2629       return AK_FloatingPoint;
2630     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2631       return AK_GeneralPurpose;
2632     if (T->isPointerTy())
2633       return AK_GeneralPurpose;
2634     return AK_Memory;
2635   }
2636
2637   // For VarArg functions, store the argument shadow in an ABI-specific format
2638   // that corresponds to va_list layout.
2639   // We do this because Clang lowers va_arg in the frontend, and this pass
2640   // only sees the low level code that deals with va_list internals.
2641   // A much easier alternative (provided that Clang emits va_arg instructions)
2642   // would have been to associate each live instance of va_list with a copy of
2643   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2644   // order.
2645   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
2646     unsigned GpOffset = 0;
2647     unsigned FpOffset = AMD64GpEndOffset;
2648     unsigned OverflowOffset = AMD64FpEndOffset;
2649     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2650          ArgIt != End; ++ArgIt) {
2651       Value *A = *ArgIt;
2652       unsigned ArgNo = CS.getArgumentNo(ArgIt);
2653       bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
2654       if (IsByVal) {
2655         // ByVal arguments always go to the overflow area.
2656         assert(A->getType()->isPointerTy());
2657         Type *RealTy = A->getType()->getPointerElementType();
2658         uint64_t ArgSize = MS.DL->getTypeAllocSize(RealTy);
2659         Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
2660         OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2661         IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
2662                          ArgSize, kShadowTLSAlignment);
2663       } else {
2664         ArgKind AK = classifyArgument(A);
2665         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2666           AK = AK_Memory;
2667         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2668           AK = AK_Memory;
2669         Value *Base;
2670         switch (AK) {
2671           case AK_GeneralPurpose:
2672             Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
2673             GpOffset += 8;
2674             break;
2675           case AK_FloatingPoint:
2676             Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
2677             FpOffset += 16;
2678             break;
2679           case AK_Memory:
2680             uint64_t ArgSize = MS.DL->getTypeAllocSize(A->getType());
2681             Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
2682             OverflowOffset += RoundUpToAlignment(ArgSize, 8);
2683         }
2684         IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2685       }
2686     }
2687     Constant *OverflowSize =
2688       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2689     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2690   }
2691
2692   /// \brief Compute the shadow address for a given va_arg.
2693   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
2694                                    int ArgOffset) {
2695     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2696     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2697     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
2698                               "_msarg");
2699   }
2700
2701   void visitVAStartInst(VAStartInst &I) override {
2702     IRBuilder<> IRB(&I);
2703     VAStartInstrumentationList.push_back(&I);
2704     Value *VAListTag = I.getArgOperand(0);
2705     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2706
2707     // Unpoison the whole __va_list_tag.
2708     // FIXME: magic ABI constants.
2709     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2710                      /* size */24, /* alignment */8, false);
2711   }
2712
2713   void visitVACopyInst(VACopyInst &I) override {
2714     IRBuilder<> IRB(&I);
2715     Value *VAListTag = I.getArgOperand(0);
2716     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2717
2718     // Unpoison the whole __va_list_tag.
2719     // FIXME: magic ABI constants.
2720     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2721                      /* size */24, /* alignment */8, false);
2722   }
2723
2724   void finalizeInstrumentation() override {
2725     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2726            "finalizeInstrumentation called twice");
2727     if (!VAStartInstrumentationList.empty()) {
2728       // If there is a va_start in this function, make a backup copy of
2729       // va_arg_tls somewhere in the function entry block.
2730       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2731       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2732       Value *CopySize =
2733         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2734                       VAArgOverflowSize);
2735       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2736       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2737     }
2738
2739     // Instrument va_start.
2740     // Copy va_list shadow from the backup copy of the TLS contents.
2741     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2742       CallInst *OrigInst = VAStartInstrumentationList[i];
2743       IRBuilder<> IRB(OrigInst->getNextNode());
2744       Value *VAListTag = OrigInst->getArgOperand(0);
2745
2746       Value *RegSaveAreaPtrPtr =
2747         IRB.CreateIntToPtr(
2748           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2749                         ConstantInt::get(MS.IntptrTy, 16)),
2750           Type::getInt64PtrTy(*MS.C));
2751       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2752       Value *RegSaveAreaShadowPtr =
2753         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2754       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2755                        AMD64FpEndOffset, 16);
2756
2757       Value *OverflowArgAreaPtrPtr =
2758         IRB.CreateIntToPtr(
2759           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2760                         ConstantInt::get(MS.IntptrTy, 8)),
2761           Type::getInt64PtrTy(*MS.C));
2762       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2763       Value *OverflowArgAreaShadowPtr =
2764         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2765       Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2766       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2767     }
2768   }
2769 };
2770
2771 /// \brief A no-op implementation of VarArgHelper.
2772 struct VarArgNoOpHelper : public VarArgHelper {
2773   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2774                    MemorySanitizerVisitor &MSV) {}
2775
2776   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
2777
2778   void visitVAStartInst(VAStartInst &I) override {}
2779
2780   void visitVACopyInst(VACopyInst &I) override {}
2781
2782   void finalizeInstrumentation() override {}
2783 };
2784
2785 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2786                                  MemorySanitizerVisitor &Visitor) {
2787   // VarArg handling is only implemented on AMD64. False positives are possible
2788   // on other platforms.
2789   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2790   if (TargetTriple.getArch() == llvm::Triple::x86_64)
2791     return new VarArgAMD64Helper(Func, Msan, Visitor);
2792   else
2793     return new VarArgNoOpHelper(Func, Msan, Visitor);
2794 }
2795
2796 }  // namespace
2797
2798 bool MemorySanitizer::runOnFunction(Function &F) {
2799   MemorySanitizerVisitor Visitor(F, *this);
2800
2801   // Clear out readonly/readnone attributes.
2802   AttrBuilder B;
2803   B.addAttribute(Attribute::ReadOnly)
2804     .addAttribute(Attribute::ReadNone);
2805   F.removeAttributes(AttributeSet::FunctionIndex,
2806                      AttributeSet::get(F.getContext(),
2807                                        AttributeSet::FunctionIndex, B));
2808
2809   return Visitor.runOnFunction();
2810 }