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