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