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