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