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