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