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