[msan] Propagate origin for insertvalue, extractvalue.
[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 /// Status: early prototype.
14 ///
15 /// The algorithm of the tool is similar to Memcheck
16 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
17 /// byte of the application memory, poison the shadow of the malloc-ed
18 /// or alloca-ed memory, load the shadow bits on every memory read,
19 /// propagate the shadow bits through some of the arithmetic
20 /// instruction (including MOV), store the shadow bits on every memory
21 /// write, report a bug on some other instructions (e.g. JMP) if the
22 /// associated shadow is poisoned.
23 ///
24 /// But there are differences too. The first and the major one:
25 /// compiler instrumentation instead of binary instrumentation. This
26 /// gives us much better register allocation, possible compiler
27 /// optimizations and a fast start-up. But this brings the major issue
28 /// as well: msan needs to see all program events, including system
29 /// calls and reads/writes in system libraries, so we either need to
30 /// compile *everything* with msan or use a binary translation
31 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
32 /// Another difference from Memcheck is that we use 8 shadow bits per
33 /// byte of application memory and use a direct shadow mapping. This
34 /// greatly simplifies the instrumentation code and avoids races on
35 /// shadow updates (Memcheck is single-threaded so races are not a
36 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
37 /// path storage that uses 8 bits per byte).
38 ///
39 /// The default value of shadow is 0, which means "clean" (not poisoned).
40 ///
41 /// Every module initializer should call __msan_init to ensure that the
42 /// shadow memory is ready. On error, __msan_warning is called. Since
43 /// parameters and return values may be passed via registers, we have a
44 /// specialized thread-local shadow for return values
45 /// (__msan_retval_tls) and parameters (__msan_param_tls).
46 ///
47 ///                           Origin tracking.
48 ///
49 /// MemorySanitizer can track origins (allocation points) of all uninitialized
50 /// values. This behavior is controlled with a flag (msan-track-origins) and is
51 /// disabled by default.
52 ///
53 /// Origins are 4-byte values created and interpreted by the runtime library.
54 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
55 /// of application memory. Propagation of origins is basically a bunch of
56 /// "select" instructions that pick the origin of a dirty argument, if an
57 /// instruction has one.
58 ///
59 /// Every 4 aligned, consecutive bytes of application memory have one origin
60 /// value associated with them. If these bytes contain uninitialized data
61 /// coming from 2 different allocations, the last store wins. Because of this,
62 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
63 /// practice.
64 ///
65 /// Origins are meaningless for fully initialized values, so MemorySanitizer
66 /// avoids storing origin to memory when a fully initialized value is stored.
67 /// This way it avoids needless overwritting origin of the 4-byte region on
68 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
69 ///
70 ///                            Atomic handling.
71 ///
72 /// Ideally, every atomic store of application value should update the
73 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
74 /// of two disjoint locations can not be done without severe slowdown.
75 ///
76 /// Therefore, we implement an approximation that may err on the safe side.
77 /// In this implementation, every atomically accessed location in the program
78 /// may only change from (partially) uninitialized to fully initialized, but
79 /// not the other way around. We load the shadow _after_ the application load,
80 /// and we store the shadow _before_ the app store. Also, we always store clean
81 /// shadow (if the application store is atomic). This way, if the store-load
82 /// pair constitutes a happens-before arc, shadow store and load are correctly
83 /// ordered such that the load will get either the value that was stored, or
84 /// some later value (which is always clean).
85 ///
86 /// This does not work very well with Compare-And-Swap (CAS) and
87 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
88 /// must store the new shadow before the app operation, and load the shadow
89 /// after the app operation. Computers don't work this way. Current
90 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
91 /// value. It implements the store part as a simple atomic store by storing a
92 /// clean shadow.
93
94 //===----------------------------------------------------------------------===//
95
96 #define DEBUG_TYPE "msan"
97
98 #include "llvm/Transforms/Instrumentation.h"
99 #include "llvm/ADT/DepthFirstIterator.h"
100 #include "llvm/ADT/SmallString.h"
101 #include "llvm/ADT/SmallVector.h"
102 #include "llvm/ADT/Triple.h"
103 #include "llvm/ADT/ValueMap.h"
104 #include "llvm/IR/DataLayout.h"
105 #include "llvm/IR/Function.h"
106 #include "llvm/IR/IRBuilder.h"
107 #include "llvm/IR/InlineAsm.h"
108 #include "llvm/IR/IntrinsicInst.h"
109 #include "llvm/IR/LLVMContext.h"
110 #include "llvm/IR/MDBuilder.h"
111 #include "llvm/IR/Module.h"
112 #include "llvm/IR/Type.h"
113 #include "llvm/InstVisitor.h"
114 #include "llvm/Support/CommandLine.h"
115 #include "llvm/Support/Compiler.h"
116 #include "llvm/Support/Debug.h"
117 #include "llvm/Support/raw_ostream.h"
118 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
119 #include "llvm/Transforms/Utils/Local.h"
120 #include "llvm/Transforms/Utils/ModuleUtils.h"
121 #include "llvm/Transforms/Utils/SpecialCaseList.h"
122
123 using namespace llvm;
124
125 static const uint64_t kShadowMask32 = 1ULL << 31;
126 static const uint64_t kShadowMask64 = 1ULL << 46;
127 static const uint64_t kOriginOffset32 = 1ULL << 30;
128 static const uint64_t kOriginOffset64 = 1ULL << 45;
129 static const unsigned kMinOriginAlignment = 4;
130 static const unsigned kShadowTLSAlignment = 8;
131
132 /// \brief Track origins of uninitialized values.
133 ///
134 /// Adds a section to MemorySanitizer report that points to the allocation
135 /// (stack or heap) the uninitialized bits came from originally.
136 static cl::opt<bool> ClTrackOrigins("msan-track-origins",
137        cl::desc("Track origins (allocation sites) of poisoned memory"),
138        cl::Hidden, cl::init(false));
139 static cl::opt<bool> ClKeepGoing("msan-keep-going",
140        cl::desc("keep going after reporting a UMR"),
141        cl::Hidden, cl::init(false));
142 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
143        cl::desc("poison uninitialized stack variables"),
144        cl::Hidden, cl::init(true));
145 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
146        cl::desc("poison uninitialized stack variables with a call"),
147        cl::Hidden, cl::init(false));
148 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
149        cl::desc("poison uninitialized stack variables with the given patter"),
150        cl::Hidden, cl::init(0xff));
151 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
152        cl::desc("poison undef temps"),
153        cl::Hidden, cl::init(true));
154
155 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
156        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
157        cl::Hidden, cl::init(true));
158
159 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
160        cl::desc("exact handling of relational integer ICmp"),
161        cl::Hidden, cl::init(false));
162
163 static cl::opt<bool> ClStoreCleanOrigin("msan-store-clean-origin",
164        cl::desc("store origin for clean (fully initialized) values"),
165        cl::Hidden, cl::init(false));
166
167 // This flag controls whether we check the shadow of the address
168 // operand of load or store. Such bugs are very rare, since load from
169 // a garbage address typically results in SEGV, but still happen
170 // (e.g. only lower bits of address are garbage, or the access happens
171 // early at program startup where malloc-ed memory is more likely to
172 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
173 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
174        cl::desc("report accesses through a pointer which has poisoned shadow"),
175        cl::Hidden, cl::init(true));
176
177 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
178        cl::desc("print out instructions with default strict semantics"),
179        cl::Hidden, cl::init(false));
180
181 static cl::opt<std::string>  ClBlacklistFile("msan-blacklist",
182        cl::desc("File containing the list of functions where MemorySanitizer "
183                 "should not report bugs"), cl::Hidden);
184
185 // Experimental. Wraps all indirect calls in the instrumented code with
186 // a call to the given function. This is needed to assist the dynamic
187 // helper tool (MSanDR) to regain control on transition between instrumented and
188 // non-instrumented code.
189 static cl::opt<std::string> ClWrapIndirectCalls("msan-wrap-indirect-calls",
190        cl::desc("Wrap indirect calls with a given function"),
191        cl::Hidden);
192
193 namespace {
194
195 /// \brief An instrumentation pass implementing detection of uninitialized
196 /// reads.
197 ///
198 /// MemorySanitizer: instrument the code in module to find
199 /// uninitialized reads.
200 class MemorySanitizer : public FunctionPass {
201  public:
202   MemorySanitizer(bool TrackOrigins = false,
203                   StringRef BlacklistFile = StringRef())
204       : FunctionPass(ID),
205         TrackOrigins(TrackOrigins || ClTrackOrigins),
206         TD(0),
207         WarningFn(0),
208         BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile : BlacklistFile),
209         WrapIndirectCalls(!ClWrapIndirectCalls.empty()) {}
210   const char *getPassName() const { return "MemorySanitizer"; }
211   bool runOnFunction(Function &F);
212   bool doInitialization(Module &M);
213   static char ID;  // Pass identification, replacement for typeid.
214
215  private:
216   void initializeCallbacks(Module &M);
217
218   /// \brief Track origins (allocation points) of uninitialized values.
219   bool TrackOrigins;
220
221   DataLayout *TD;
222   LLVMContext *C;
223   Type *IntptrTy;
224   Type *OriginTy;
225   /// \brief Thread-local shadow storage for function parameters.
226   GlobalVariable *ParamTLS;
227   /// \brief Thread-local origin storage for function parameters.
228   GlobalVariable *ParamOriginTLS;
229   /// \brief Thread-local shadow storage for function return value.
230   GlobalVariable *RetvalTLS;
231   /// \brief Thread-local origin storage for function return value.
232   GlobalVariable *RetvalOriginTLS;
233   /// \brief Thread-local shadow storage for in-register va_arg function
234   /// parameters (x86_64-specific).
235   GlobalVariable *VAArgTLS;
236   /// \brief Thread-local shadow storage for va_arg overflow area
237   /// (x86_64-specific).
238   GlobalVariable *VAArgOverflowSizeTLS;
239   /// \brief Thread-local space used to pass origin value to the UMR reporting
240   /// function.
241   GlobalVariable *OriginTLS;
242
243   /// \brief The run-time callback to print a warning.
244   Value *WarningFn;
245   /// \brief Run-time helper that copies origin info for a memory range.
246   Value *MsanCopyOriginFn;
247   /// \brief Run-time helper that generates a new origin value for a stack
248   /// allocation.
249   Value *MsanSetAllocaOrigin4Fn;
250   /// \brief Run-time helper that poisons stack on function entry.
251   Value *MsanPoisonStackFn;
252   /// \brief MSan runtime replacements for memmove, memcpy and memset.
253   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
254
255   /// \brief Address mask used in application-to-shadow address calculation.
256   /// ShadowAddr is computed as ApplicationAddr & ~ShadowMask.
257   uint64_t ShadowMask;
258   /// \brief Offset of the origin shadow from the "normal" shadow.
259   /// OriginAddr is computed as (ShadowAddr + OriginOffset) & ~3ULL
260   uint64_t OriginOffset;
261   /// \brief Branch weights for error reporting.
262   MDNode *ColdCallWeights;
263   /// \brief Branch weights for origin store.
264   MDNode *OriginStoreWeights;
265   /// \brief Path to blacklist file.
266   SmallString<64> BlacklistFile;
267   /// \brief The blacklist.
268   OwningPtr<SpecialCaseList> BL;
269   /// \brief An empty volatile inline asm that prevents callback merge.
270   InlineAsm *EmptyAsm;
271
272   bool WrapIndirectCalls;
273   /// \brief Run-time wrapper for indirect calls.
274   Value *IndirectCallWrapperFn;
275   // Argument and return type of IndirectCallWrapperFn: void (*f)(void).
276   Type *AnyFunctionPtrTy;
277
278   friend struct MemorySanitizerVisitor;
279   friend struct VarArgAMD64Helper;
280 };
281 }  // namespace
282
283 char MemorySanitizer::ID = 0;
284 INITIALIZE_PASS(MemorySanitizer, "msan",
285                 "MemorySanitizer: detects uninitialized reads.",
286                 false, false)
287
288 FunctionPass *llvm::createMemorySanitizerPass(bool TrackOrigins,
289                                               StringRef BlacklistFile) {
290   return new MemorySanitizer(TrackOrigins, BlacklistFile);
291 }
292
293 /// \brief Create a non-const global initialized with the given string.
294 ///
295 /// Creates a writable global for Str so that we can pass it to the
296 /// run-time lib. Runtime uses first 4 bytes of the string to store the
297 /// frame ID, so the string needs to be mutable.
298 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
299                                                             StringRef Str) {
300   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
301   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
302                             GlobalValue::PrivateLinkage, StrConst, "");
303 }
304
305
306 /// \brief Insert extern declaration of runtime-provided functions and globals.
307 void MemorySanitizer::initializeCallbacks(Module &M) {
308   // Only do this once.
309   if (WarningFn)
310     return;
311
312   IRBuilder<> IRB(*C);
313   // Create the callback.
314   // FIXME: this function should have "Cold" calling conv,
315   // which is not yet implemented.
316   StringRef WarningFnName = ClKeepGoing ? "__msan_warning"
317                                         : "__msan_warning_noreturn";
318   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy(), NULL);
319
320   MsanCopyOriginFn = M.getOrInsertFunction(
321     "__msan_copy_origin", IRB.getVoidTy(), IRB.getInt8PtrTy(),
322     IRB.getInt8PtrTy(), IntptrTy, NULL);
323   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
324     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
325     IRB.getInt8PtrTy(), IntptrTy, NULL);
326   MsanPoisonStackFn = M.getOrInsertFunction(
327     "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, NULL);
328   MemmoveFn = M.getOrInsertFunction(
329     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
330     IRB.getInt8PtrTy(), IntptrTy, NULL);
331   MemcpyFn = M.getOrInsertFunction(
332     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
333     IntptrTy, NULL);
334   MemsetFn = M.getOrInsertFunction(
335     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
336     IntptrTy, NULL);
337
338   // Create globals.
339   RetvalTLS = new GlobalVariable(
340     M, ArrayType::get(IRB.getInt64Ty(), 8), false,
341     GlobalVariable::ExternalLinkage, 0, "__msan_retval_tls", 0,
342     GlobalVariable::InitialExecTLSModel);
343   RetvalOriginTLS = new GlobalVariable(
344     M, OriginTy, false, GlobalVariable::ExternalLinkage, 0,
345     "__msan_retval_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
346
347   ParamTLS = new GlobalVariable(
348     M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
349     GlobalVariable::ExternalLinkage, 0, "__msan_param_tls", 0,
350     GlobalVariable::InitialExecTLSModel);
351   ParamOriginTLS = new GlobalVariable(
352     M, ArrayType::get(OriginTy, 1000), false, GlobalVariable::ExternalLinkage,
353     0, "__msan_param_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
354
355   VAArgTLS = new GlobalVariable(
356     M, ArrayType::get(IRB.getInt64Ty(), 1000), false,
357     GlobalVariable::ExternalLinkage, 0, "__msan_va_arg_tls", 0,
358     GlobalVariable::InitialExecTLSModel);
359   VAArgOverflowSizeTLS = new GlobalVariable(
360     M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, 0,
361     "__msan_va_arg_overflow_size_tls", 0,
362     GlobalVariable::InitialExecTLSModel);
363   OriginTLS = new GlobalVariable(
364     M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, 0,
365     "__msan_origin_tls", 0, GlobalVariable::InitialExecTLSModel);
366
367   // We insert an empty inline asm after __msan_report* to avoid callback merge.
368   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
369                             StringRef(""), StringRef(""),
370                             /*hasSideEffects=*/true);
371
372   if (WrapIndirectCalls) {
373     AnyFunctionPtrTy =
374         PointerType::getUnqual(FunctionType::get(IRB.getVoidTy(), false));
375     IndirectCallWrapperFn = M.getOrInsertFunction(
376         ClWrapIndirectCalls, AnyFunctionPtrTy, AnyFunctionPtrTy, NULL);
377   }
378 }
379
380 /// \brief Module-level initialization.
381 ///
382 /// inserts a call to __msan_init to the module's constructor list.
383 bool MemorySanitizer::doInitialization(Module &M) {
384   TD = getAnalysisIfAvailable<DataLayout>();
385   if (!TD)
386     return false;
387   BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
388   C = &(M.getContext());
389   unsigned PtrSize = TD->getPointerSizeInBits(/* AddressSpace */0);
390   switch (PtrSize) {
391     case 64:
392       ShadowMask = kShadowMask64;
393       OriginOffset = kOriginOffset64;
394       break;
395     case 32:
396       ShadowMask = kShadowMask32;
397       OriginOffset = kOriginOffset32;
398       break;
399     default:
400       report_fatal_error("unsupported pointer size");
401       break;
402   }
403
404   IRBuilder<> IRB(*C);
405   IntptrTy = IRB.getIntPtrTy(TD);
406   OriginTy = IRB.getInt32Ty();
407
408   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
409   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
410
411   // Insert a call to __msan_init/__msan_track_origins into the module's CTORs.
412   appendToGlobalCtors(M, cast<Function>(M.getOrInsertFunction(
413                       "__msan_init", IRB.getVoidTy(), NULL)), 0);
414
415   if (TrackOrigins)
416     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
417                        IRB.getInt32(TrackOrigins), "__msan_track_origins");
418
419   if (ClKeepGoing)
420     new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
421                        IRB.getInt32(ClKeepGoing), "__msan_keep_going");
422
423   return true;
424 }
425
426 namespace {
427
428 /// \brief A helper class that handles instrumentation of VarArg
429 /// functions on a particular platform.
430 ///
431 /// Implementations are expected to insert the instrumentation
432 /// necessary to propagate argument shadow through VarArg function
433 /// calls. Visit* methods are called during an InstVisitor pass over
434 /// the function, and should avoid creating new basic blocks. A new
435 /// instance of this class is created for each instrumented function.
436 struct VarArgHelper {
437   /// \brief Visit a CallSite.
438   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
439
440   /// \brief Visit a va_start call.
441   virtual void visitVAStartInst(VAStartInst &I) = 0;
442
443   /// \brief Visit a va_copy call.
444   virtual void visitVACopyInst(VACopyInst &I) = 0;
445
446   /// \brief Finalize function instrumentation.
447   ///
448   /// This method is called after visiting all interesting (see above)
449   /// instructions in a function.
450   virtual void finalizeInstrumentation() = 0;
451
452   virtual ~VarArgHelper() {}
453 };
454
455 struct MemorySanitizerVisitor;
456
457 VarArgHelper*
458 CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
459                    MemorySanitizerVisitor &Visitor);
460
461 /// This class does all the work for a given function. Store and Load
462 /// instructions store and load corresponding shadow and origin
463 /// values. Most instructions propagate shadow from arguments to their
464 /// return values. Certain instructions (most importantly, BranchInst)
465 /// test their argument shadow and print reports (with a runtime call) if it's
466 /// non-zero.
467 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
468   Function &F;
469   MemorySanitizer &MS;
470   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
471   ValueMap<Value*, Value*> ShadowMap, OriginMap;
472   OwningPtr<VarArgHelper> VAHelper;
473
474   // The following flags disable parts of MSan instrumentation based on
475   // blacklist contents and command-line options.
476   bool InsertChecks;
477   bool LoadShadow;
478   bool PoisonStack;
479   bool PoisonUndef;
480   bool CheckReturnValue;
481
482   struct ShadowOriginAndInsertPoint {
483     Value *Shadow;
484     Value *Origin;
485     Instruction *OrigIns;
486     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
487       : Shadow(S), Origin(O), OrigIns(I) { }
488     ShadowOriginAndInsertPoint() : Shadow(0), Origin(0), OrigIns(0) { }
489   };
490   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
491   SmallVector<Instruction*, 16> StoreList;
492
493   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
494       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
495     bool SanitizeFunction = !MS.BL->isIn(F) && F.getAttributes().hasAttribute(
496                                                    AttributeSet::FunctionIndex,
497                                                    Attribute::SanitizeMemory);
498     InsertChecks = SanitizeFunction;
499     LoadShadow = SanitizeFunction;
500     PoisonStack = SanitizeFunction && ClPoisonStack;
501     PoisonUndef = SanitizeFunction && ClPoisonUndef;
502     // FIXME: Consider using SpecialCaseList to specify a list of functions that
503     // must always return fully initialized values. For now, we hardcode "main".
504     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
505
506     DEBUG(if (!InsertChecks)
507           dbgs() << "MemorySanitizer is not inserting checks into '"
508                  << F.getName() << "'\n");
509   }
510
511   void materializeStores() {
512     for (size_t i = 0, n = StoreList.size(); i < n; i++) {
513       StoreInst& I = *dyn_cast<StoreInst>(StoreList[i]);
514
515       IRBuilder<> IRB(&I);
516       Value *Val = I.getValueOperand();
517       Value *Addr = I.getPointerOperand();
518       Value *Shadow = I.isAtomic() ? getCleanShadow(Val) : getShadow(Val);
519       Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
520
521       StoreInst *NewSI =
522         IRB.CreateAlignedStore(Shadow, ShadowPtr, I.getAlignment());
523       DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
524       (void)NewSI;
525
526       if (ClCheckAccessAddress)
527         insertShadowCheck(Addr, &I);
528
529       if (I.isAtomic())
530         I.setOrdering(addReleaseOrdering(I.getOrdering()));
531
532       if (MS.TrackOrigins) {
533         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
534         if (ClStoreCleanOrigin || isa<StructType>(Shadow->getType())) {
535           IRB.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRB),
536                                  Alignment);
537         } else {
538           Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
539
540           // TODO(eugenis): handle non-zero constant shadow by inserting an
541           // unconditional check (can not simply fail compilation as this could
542           // be in the dead code).
543           if (isa<Constant>(ConvertedShadow))
544             continue;
545
546           Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
547               getCleanShadow(ConvertedShadow), "_mscmp");
548           Instruction *CheckTerm =
549             SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false,
550                                       MS.OriginStoreWeights);
551           IRBuilder<> IRBNew(CheckTerm);
552           IRBNew.CreateAlignedStore(getOrigin(Val), getOriginPtr(Addr, IRBNew),
553                                     Alignment);
554         }
555       }
556     }
557   }
558
559   void materializeChecks() {
560     for (size_t i = 0, n = InstrumentationList.size(); i < n; i++) {
561       Value *Shadow = InstrumentationList[i].Shadow;
562       Instruction *OrigIns = InstrumentationList[i].OrigIns;
563       IRBuilder<> IRB(OrigIns);
564       DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
565       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
566       DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
567       // See the comment in materializeStores().
568       if (isa<Constant>(ConvertedShadow))
569         continue;
570       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
571                                     getCleanShadow(ConvertedShadow), "_mscmp");
572       Instruction *CheckTerm =
573         SplitBlockAndInsertIfThen(cast<Instruction>(Cmp),
574                                   /* Unreachable */ !ClKeepGoing,
575                                   MS.ColdCallWeights);
576
577       IRB.SetInsertPoint(CheckTerm);
578       if (MS.TrackOrigins) {
579         Value *Origin = InstrumentationList[i].Origin;
580         IRB.CreateStore(Origin ? (Value*)Origin : (Value*)IRB.getInt32(0),
581                         MS.OriginTLS);
582       }
583       CallInst *Call = IRB.CreateCall(MS.WarningFn);
584       Call->setDebugLoc(OrigIns->getDebugLoc());
585       IRB.CreateCall(MS.EmptyAsm);
586       DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
587     }
588     DEBUG(dbgs() << "DONE:\n" << F);
589   }
590
591   /// \brief Add MemorySanitizer instrumentation to a function.
592   bool runOnFunction() {
593     MS.initializeCallbacks(*F.getParent());
594     if (!MS.TD) return false;
595
596     // In the presence of unreachable blocks, we may see Phi nodes with
597     // incoming nodes from such blocks. Since InstVisitor skips unreachable
598     // blocks, such nodes will not have any shadow value associated with them.
599     // It's easier to remove unreachable blocks than deal with missing shadow.
600     removeUnreachableBlocks(F);
601
602     // Iterate all BBs in depth-first order and create shadow instructions
603     // for all instructions (where applicable).
604     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
605     for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
606          DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
607       BasicBlock *BB = *DI;
608       visit(*BB);
609     }
610
611     // Finalize PHI nodes.
612     for (size_t i = 0, n = ShadowPHINodes.size(); i < n; i++) {
613       PHINode *PN = ShadowPHINodes[i];
614       PHINode *PNS = cast<PHINode>(getShadow(PN));
615       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : 0;
616       size_t NumValues = PN->getNumIncomingValues();
617       for (size_t v = 0; v < NumValues; v++) {
618         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
619         if (PNO)
620           PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
621       }
622     }
623
624     VAHelper->finalizeInstrumentation();
625
626     // Delayed instrumentation of StoreInst.
627     // This may add new checks to be inserted later.
628     materializeStores();
629
630     // Insert shadow value checks.
631     materializeChecks();
632
633     return true;
634   }
635
636   /// \brief Compute the shadow type that corresponds to a given Value.
637   Type *getShadowTy(Value *V) {
638     return getShadowTy(V->getType());
639   }
640
641   /// \brief Compute the shadow type that corresponds to a given Type.
642   Type *getShadowTy(Type *OrigTy) {
643     if (!OrigTy->isSized()) {
644       return 0;
645     }
646     // For integer type, shadow is the same as the original type.
647     // This may return weird-sized types like i1.
648     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
649       return IT;
650     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
651       uint32_t EltSize = MS.TD->getTypeSizeInBits(VT->getElementType());
652       return VectorType::get(IntegerType::get(*MS.C, EltSize),
653                              VT->getNumElements());
654     }
655     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
656       SmallVector<Type*, 4> Elements;
657       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
658         Elements.push_back(getShadowTy(ST->getElementType(i)));
659       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
660       DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
661       return Res;
662     }
663     uint32_t TypeSize = MS.TD->getTypeSizeInBits(OrigTy);
664     return IntegerType::get(*MS.C, TypeSize);
665   }
666
667   /// \brief Flatten a vector type.
668   Type *getShadowTyNoVec(Type *ty) {
669     if (VectorType *vt = dyn_cast<VectorType>(ty))
670       return IntegerType::get(*MS.C, vt->getBitWidth());
671     return ty;
672   }
673
674   /// \brief Convert a shadow value to it's flattened variant.
675   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
676     Type *Ty = V->getType();
677     Type *NoVecTy = getShadowTyNoVec(Ty);
678     if (Ty == NoVecTy) return V;
679     return IRB.CreateBitCast(V, NoVecTy);
680   }
681
682   /// \brief Compute the shadow address that corresponds to a given application
683   /// address.
684   ///
685   /// Shadow = Addr & ~ShadowMask.
686   Value *getShadowPtr(Value *Addr, Type *ShadowTy,
687                       IRBuilder<> &IRB) {
688     Value *ShadowLong =
689       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
690                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
691     return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
692   }
693
694   /// \brief Compute the origin address that corresponds to a given application
695   /// address.
696   ///
697   /// OriginAddr = (ShadowAddr + OriginOffset) & ~3ULL
698   Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB) {
699     Value *ShadowLong =
700       IRB.CreateAnd(IRB.CreatePointerCast(Addr, MS.IntptrTy),
701                     ConstantInt::get(MS.IntptrTy, ~MS.ShadowMask));
702     Value *Add =
703       IRB.CreateAdd(ShadowLong,
704                     ConstantInt::get(MS.IntptrTy, MS.OriginOffset));
705     Value *SecondAnd =
706       IRB.CreateAnd(Add, ConstantInt::get(MS.IntptrTy, ~3ULL));
707     return IRB.CreateIntToPtr(SecondAnd, PointerType::get(IRB.getInt32Ty(), 0));
708   }
709
710   /// \brief Compute the shadow address for a given function argument.
711   ///
712   /// Shadow = ParamTLS+ArgOffset.
713   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
714                                  int ArgOffset) {
715     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
716     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
717     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
718                               "_msarg");
719   }
720
721   /// \brief Compute the origin address for a given function argument.
722   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
723                                  int ArgOffset) {
724     if (!MS.TrackOrigins) return 0;
725     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
726     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
727     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
728                               "_msarg_o");
729   }
730
731   /// \brief Compute the shadow address for a retval.
732   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
733     Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
734     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
735                               "_msret");
736   }
737
738   /// \brief Compute the origin address for a retval.
739   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
740     // We keep a single origin for the entire retval. Might be too optimistic.
741     return MS.RetvalOriginTLS;
742   }
743
744   /// \brief Set SV to be the shadow value for V.
745   void setShadow(Value *V, Value *SV) {
746     assert(!ShadowMap.count(V) && "Values may only have one shadow");
747     ShadowMap[V] = SV;
748   }
749
750   /// \brief Set Origin to be the origin value for V.
751   void setOrigin(Value *V, Value *Origin) {
752     if (!MS.TrackOrigins) return;
753     assert(!OriginMap.count(V) && "Values may only have one origin");
754     DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
755     OriginMap[V] = Origin;
756   }
757
758   /// \brief Create a clean shadow value for a given value.
759   ///
760   /// Clean shadow (all zeroes) means all bits of the value are defined
761   /// (initialized).
762   Constant *getCleanShadow(Value *V) {
763     Type *ShadowTy = getShadowTy(V);
764     if (!ShadowTy)
765       return 0;
766     return Constant::getNullValue(ShadowTy);
767   }
768
769   /// \brief Create a dirty shadow of a given shadow type.
770   Constant *getPoisonedShadow(Type *ShadowTy) {
771     assert(ShadowTy);
772     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
773       return Constant::getAllOnesValue(ShadowTy);
774     StructType *ST = cast<StructType>(ShadowTy);
775     SmallVector<Constant *, 4> Vals;
776     for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
777       Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
778     return ConstantStruct::get(ST, Vals);
779   }
780
781   /// \brief Create a dirty shadow for a given value.
782   Constant *getPoisonedShadow(Value *V) {
783     Type *ShadowTy = getShadowTy(V);
784     if (!ShadowTy)
785       return 0;
786     return getPoisonedShadow(ShadowTy);
787   }
788
789   /// \brief Create a clean (zero) origin.
790   Value *getCleanOrigin() {
791     return Constant::getNullValue(MS.OriginTy);
792   }
793
794   /// \brief Get the shadow value for a given Value.
795   ///
796   /// This function either returns the value set earlier with setShadow,
797   /// or extracts if from ParamTLS (for function arguments).
798   Value *getShadow(Value *V) {
799     if (Instruction *I = dyn_cast<Instruction>(V)) {
800       // For instructions the shadow is already stored in the map.
801       Value *Shadow = ShadowMap[V];
802       if (!Shadow) {
803         DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
804         (void)I;
805         assert(Shadow && "No shadow for a value");
806       }
807       return Shadow;
808     }
809     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
810       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
811       DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
812       (void)U;
813       return AllOnes;
814     }
815     if (Argument *A = dyn_cast<Argument>(V)) {
816       // For arguments we compute the shadow on demand and store it in the map.
817       Value **ShadowPtr = &ShadowMap[V];
818       if (*ShadowPtr)
819         return *ShadowPtr;
820       Function *F = A->getParent();
821       IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
822       unsigned ArgOffset = 0;
823       for (Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
824            AI != AE; ++AI) {
825         if (!AI->getType()->isSized()) {
826           DEBUG(dbgs() << "Arg is not sized\n");
827           continue;
828         }
829         unsigned Size = AI->hasByValAttr()
830           ? MS.TD->getTypeAllocSize(AI->getType()->getPointerElementType())
831           : MS.TD->getTypeAllocSize(AI->getType());
832         if (A == AI) {
833           Value *Base = getShadowPtrForArgument(AI, EntryIRB, ArgOffset);
834           if (AI->hasByValAttr()) {
835             // ByVal pointer itself has clean shadow. We copy the actual
836             // argument shadow to the underlying memory.
837             // Figure out maximal valid memcpy alignment.
838             unsigned ArgAlign = AI->getParamAlignment();
839             if (ArgAlign == 0) {
840               Type *EltType = A->getType()->getPointerElementType();
841               ArgAlign = MS.TD->getABITypeAlignment(EltType);
842             }
843             unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
844             Value *Cpy = EntryIRB.CreateMemCpy(
845                 getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
846                 CopyAlign);
847             DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
848             (void)Cpy;
849             *ShadowPtr = getCleanShadow(V);
850           } else {
851             *ShadowPtr = EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
852           }
853           DEBUG(dbgs() << "  ARG:    "  << *AI << " ==> " <<
854                 **ShadowPtr << "\n");
855           if (MS.TrackOrigins) {
856             Value* OriginPtr = getOriginPtrForArgument(AI, EntryIRB, ArgOffset);
857             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
858           }
859         }
860         ArgOffset += DataLayout::RoundUpAlignment(Size, kShadowTLSAlignment);
861       }
862       assert(*ShadowPtr && "Could not find shadow for an argument");
863       return *ShadowPtr;
864     }
865     // For everything else the shadow is zero.
866     return getCleanShadow(V);
867   }
868
869   /// \brief Get the shadow for i-th argument of the instruction I.
870   Value *getShadow(Instruction *I, int i) {
871     return getShadow(I->getOperand(i));
872   }
873
874   /// \brief Get the origin for a value.
875   Value *getOrigin(Value *V) {
876     if (!MS.TrackOrigins) return 0;
877     if (isa<Instruction>(V) || isa<Argument>(V)) {
878       Value *Origin = OriginMap[V];
879       if (!Origin) {
880         DEBUG(dbgs() << "NO ORIGIN: " << *V << "\n");
881         Origin = getCleanOrigin();
882       }
883       return Origin;
884     }
885     return getCleanOrigin();
886   }
887
888   /// \brief Get the origin for i-th argument of the instruction I.
889   Value *getOrigin(Instruction *I, int i) {
890     return getOrigin(I->getOperand(i));
891   }
892
893   /// \brief Remember the place where a shadow check should be inserted.
894   ///
895   /// This location will be later instrumented with a check that will print a
896   /// UMR warning in runtime if the shadow value is not 0.
897   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
898     assert(Shadow);
899     if (!InsertChecks) return;
900 #ifndef NDEBUG
901     Type *ShadowTy = Shadow->getType();
902     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
903            "Can only insert checks for integer and vector shadow types");
904 #endif
905     InstrumentationList.push_back(
906         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
907   }
908
909   /// \brief Remember the place where a shadow check should be inserted.
910   ///
911   /// This location will be later instrumented with a check that will print a
912   /// UMR warning in runtime if the value is not fully defined.
913   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
914     assert(Val);
915     Instruction *Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
916     if (!Shadow) return;
917     Instruction *Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
918     insertShadowCheck(Shadow, Origin, OrigIns);
919   }
920
921   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
922     switch (a) {
923       case NotAtomic:
924         return NotAtomic;
925       case Unordered:
926       case Monotonic:
927       case Release:
928         return Release;
929       case Acquire:
930       case AcquireRelease:
931         return AcquireRelease;
932       case SequentiallyConsistent:
933         return SequentiallyConsistent;
934     }
935     llvm_unreachable("Unknown ordering");
936   }
937
938   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
939     switch (a) {
940       case NotAtomic:
941         return NotAtomic;
942       case Unordered:
943       case Monotonic:
944       case Acquire:
945         return Acquire;
946       case Release:
947       case AcquireRelease:
948         return AcquireRelease;
949       case SequentiallyConsistent:
950         return SequentiallyConsistent;
951     }
952     llvm_unreachable("Unknown ordering");
953   }
954
955   // ------------------- Visitors.
956
957   /// \brief Instrument LoadInst
958   ///
959   /// Loads the corresponding shadow and (optionally) origin.
960   /// Optionally, checks that the load address is fully defined.
961   void visitLoadInst(LoadInst &I) {
962     assert(I.getType()->isSized() && "Load type must have size");
963     IRBuilder<> IRB(I.getNextNode());
964     Type *ShadowTy = getShadowTy(&I);
965     Value *Addr = I.getPointerOperand();
966     if (LoadShadow) {
967       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
968       setShadow(&I,
969                 IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
970     } else {
971       setShadow(&I, getCleanShadow(&I));
972     }
973
974     if (ClCheckAccessAddress)
975       insertShadowCheck(I.getPointerOperand(), &I);
976
977     if (I.isAtomic())
978       I.setOrdering(addAcquireOrdering(I.getOrdering()));
979
980     if (MS.TrackOrigins) {
981       if (LoadShadow) {
982         unsigned Alignment = std::max(kMinOriginAlignment, I.getAlignment());
983         setOrigin(&I,
984                   IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB), Alignment));
985       } else {
986         setOrigin(&I, getCleanOrigin());
987       }
988     }
989   }
990
991   /// \brief Instrument StoreInst
992   ///
993   /// Stores the corresponding shadow and (optionally) origin.
994   /// Optionally, checks that the store address is fully defined.
995   void visitStoreInst(StoreInst &I) {
996     StoreList.push_back(&I);
997   }
998
999   void handleCASOrRMW(Instruction &I) {
1000     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1001
1002     IRBuilder<> IRB(&I);
1003     Value *Addr = I.getOperand(0);
1004     Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
1005
1006     if (ClCheckAccessAddress)
1007       insertShadowCheck(Addr, &I);
1008
1009     // Only test the conditional argument of cmpxchg instruction.
1010     // The other argument can potentially be uninitialized, but we can not
1011     // detect this situation reliably without possible false positives.
1012     if (isa<AtomicCmpXchgInst>(I))
1013       insertShadowCheck(I.getOperand(1), &I);
1014
1015     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1016
1017     setShadow(&I, getCleanShadow(&I));
1018   }
1019
1020   void visitAtomicRMWInst(AtomicRMWInst &I) {
1021     handleCASOrRMW(I);
1022     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1023   }
1024
1025   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1026     handleCASOrRMW(I);
1027     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1028   }
1029
1030   // Vector manipulation.
1031   void visitExtractElementInst(ExtractElementInst &I) {
1032     insertShadowCheck(I.getOperand(1), &I);
1033     IRBuilder<> IRB(&I);
1034     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1035               "_msprop"));
1036     setOrigin(&I, getOrigin(&I, 0));
1037   }
1038
1039   void visitInsertElementInst(InsertElementInst &I) {
1040     insertShadowCheck(I.getOperand(2), &I);
1041     IRBuilder<> IRB(&I);
1042     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1043               I.getOperand(2), "_msprop"));
1044     setOriginForNaryOp(I);
1045   }
1046
1047   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1048     insertShadowCheck(I.getOperand(2), &I);
1049     IRBuilder<> IRB(&I);
1050     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1051               I.getOperand(2), "_msprop"));
1052     setOriginForNaryOp(I);
1053   }
1054
1055   // Casts.
1056   void visitSExtInst(SExtInst &I) {
1057     IRBuilder<> IRB(&I);
1058     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1059     setOrigin(&I, getOrigin(&I, 0));
1060   }
1061
1062   void visitZExtInst(ZExtInst &I) {
1063     IRBuilder<> IRB(&I);
1064     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1065     setOrigin(&I, getOrigin(&I, 0));
1066   }
1067
1068   void visitTruncInst(TruncInst &I) {
1069     IRBuilder<> IRB(&I);
1070     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1071     setOrigin(&I, getOrigin(&I, 0));
1072   }
1073
1074   void visitBitCastInst(BitCastInst &I) {
1075     IRBuilder<> IRB(&I);
1076     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1077     setOrigin(&I, getOrigin(&I, 0));
1078   }
1079
1080   void visitPtrToIntInst(PtrToIntInst &I) {
1081     IRBuilder<> IRB(&I);
1082     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1083              "_msprop_ptrtoint"));
1084     setOrigin(&I, getOrigin(&I, 0));
1085   }
1086
1087   void visitIntToPtrInst(IntToPtrInst &I) {
1088     IRBuilder<> IRB(&I);
1089     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1090              "_msprop_inttoptr"));
1091     setOrigin(&I, getOrigin(&I, 0));
1092   }
1093
1094   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1095   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1096   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1097   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1098   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1099   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1100
1101   /// \brief Propagate shadow for bitwise AND.
1102   ///
1103   /// This code is exact, i.e. if, for example, a bit in the left argument
1104   /// is defined and 0, then neither the value not definedness of the
1105   /// corresponding bit in B don't affect the resulting shadow.
1106   void visitAnd(BinaryOperator &I) {
1107     IRBuilder<> IRB(&I);
1108     //  "And" of 0 and a poisoned value results in unpoisoned value.
1109     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1110     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1111     //  1&p => p;     0&p => 0;     p&p => p;
1112     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1113     Value *S1 = getShadow(&I, 0);
1114     Value *S2 = getShadow(&I, 1);
1115     Value *V1 = I.getOperand(0);
1116     Value *V2 = I.getOperand(1);
1117     if (V1->getType() != S1->getType()) {
1118       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1119       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1120     }
1121     Value *S1S2 = IRB.CreateAnd(S1, S2);
1122     Value *V1S2 = IRB.CreateAnd(V1, S2);
1123     Value *S1V2 = IRB.CreateAnd(S1, V2);
1124     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1125     setOriginForNaryOp(I);
1126   }
1127
1128   void visitOr(BinaryOperator &I) {
1129     IRBuilder<> IRB(&I);
1130     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1131     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1132     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1133     //  1|p => 1;     0|p => p;     p|p => p;
1134     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1135     Value *S1 = getShadow(&I, 0);
1136     Value *S2 = getShadow(&I, 1);
1137     Value *V1 = IRB.CreateNot(I.getOperand(0));
1138     Value *V2 = IRB.CreateNot(I.getOperand(1));
1139     if (V1->getType() != S1->getType()) {
1140       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1141       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1142     }
1143     Value *S1S2 = IRB.CreateAnd(S1, S2);
1144     Value *V1S2 = IRB.CreateAnd(V1, S2);
1145     Value *S1V2 = IRB.CreateAnd(S1, V2);
1146     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1147     setOriginForNaryOp(I);
1148   }
1149
1150   /// \brief Default propagation of shadow and/or origin.
1151   ///
1152   /// This class implements the general case of shadow propagation, used in all
1153   /// cases where we don't know and/or don't care about what the operation
1154   /// actually does. It converts all input shadow values to a common type
1155   /// (extending or truncating as necessary), and bitwise OR's them.
1156   ///
1157   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1158   /// fully initialized), and less prone to false positives.
1159   ///
1160   /// This class also implements the general case of origin propagation. For a
1161   /// Nary operation, result origin is set to the origin of an argument that is
1162   /// not entirely initialized. If there is more than one such arguments, the
1163   /// rightmost of them is picked. It does not matter which one is picked if all
1164   /// arguments are initialized.
1165   template <bool CombineShadow>
1166   class Combiner {
1167     Value *Shadow;
1168     Value *Origin;
1169     IRBuilder<> &IRB;
1170     MemorySanitizerVisitor *MSV;
1171
1172   public:
1173     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
1174       Shadow(0), Origin(0), IRB(IRB), MSV(MSV) {}
1175
1176     /// \brief Add a pair of shadow and origin values to the mix.
1177     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1178       if (CombineShadow) {
1179         assert(OpShadow);
1180         if (!Shadow)
1181           Shadow = OpShadow;
1182         else {
1183           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1184           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1185         }
1186       }
1187
1188       if (MSV->MS.TrackOrigins) {
1189         assert(OpOrigin);
1190         if (!Origin) {
1191           Origin = OpOrigin;
1192         } else {
1193           Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1194           Value *Cond = IRB.CreateICmpNE(FlatShadow,
1195                                          MSV->getCleanShadow(FlatShadow));
1196           Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1197         }
1198       }
1199       return *this;
1200     }
1201
1202     /// \brief Add an application value to the mix.
1203     Combiner &Add(Value *V) {
1204       Value *OpShadow = MSV->getShadow(V);
1205       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : 0;
1206       return Add(OpShadow, OpOrigin);
1207     }
1208
1209     /// \brief Set the current combined values as the given instruction's shadow
1210     /// and origin.
1211     void Done(Instruction *I) {
1212       if (CombineShadow) {
1213         assert(Shadow);
1214         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
1215         MSV->setShadow(I, Shadow);
1216       }
1217       if (MSV->MS.TrackOrigins) {
1218         assert(Origin);
1219         MSV->setOrigin(I, Origin);
1220       }
1221     }
1222   };
1223
1224   typedef Combiner<true> ShadowAndOriginCombiner;
1225   typedef Combiner<false> OriginCombiner;
1226
1227   /// \brief Propagate origin for arbitrary operation.
1228   void setOriginForNaryOp(Instruction &I) {
1229     if (!MS.TrackOrigins) return;
1230     IRBuilder<> IRB(&I);
1231     OriginCombiner OC(this, IRB);
1232     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1233       OC.Add(OI->get());
1234     OC.Done(&I);
1235   }
1236
1237   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
1238     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
1239            "Vector of pointers is not a valid shadow type");
1240     return Ty->isVectorTy() ?
1241       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
1242       Ty->getPrimitiveSizeInBits();
1243   }
1244
1245   /// \brief Cast between two shadow types, extending or truncating as
1246   /// necessary.
1247   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
1248                           bool Signed = false) {
1249     Type *srcTy = V->getType();
1250     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
1251       return IRB.CreateIntCast(V, dstTy, Signed);
1252     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
1253         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
1254       return IRB.CreateIntCast(V, dstTy, Signed);
1255     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
1256     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
1257     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
1258     Value *V2 =
1259       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
1260     return IRB.CreateBitCast(V2, dstTy);
1261     // TODO: handle struct types.
1262   }
1263
1264   /// \brief Propagate shadow for arbitrary operation.
1265   void handleShadowOr(Instruction &I) {
1266     IRBuilder<> IRB(&I);
1267     ShadowAndOriginCombiner SC(this, IRB);
1268     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
1269       SC.Add(OI->get());
1270     SC.Done(&I);
1271   }
1272
1273   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
1274   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
1275   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
1276   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
1277   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
1278   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
1279   void visitMul(BinaryOperator &I) { handleShadowOr(I); }
1280
1281   void handleDiv(Instruction &I) {
1282     IRBuilder<> IRB(&I);
1283     // Strict on the second argument.
1284     insertShadowCheck(I.getOperand(1), &I);
1285     setShadow(&I, getShadow(&I, 0));
1286     setOrigin(&I, getOrigin(&I, 0));
1287   }
1288
1289   void visitUDiv(BinaryOperator &I) { handleDiv(I); }
1290   void visitSDiv(BinaryOperator &I) { handleDiv(I); }
1291   void visitFDiv(BinaryOperator &I) { handleDiv(I); }
1292   void visitURem(BinaryOperator &I) { handleDiv(I); }
1293   void visitSRem(BinaryOperator &I) { handleDiv(I); }
1294   void visitFRem(BinaryOperator &I) { handleDiv(I); }
1295
1296   /// \brief Instrument == and != comparisons.
1297   ///
1298   /// Sometimes the comparison result is known even if some of the bits of the
1299   /// arguments are not.
1300   void handleEqualityComparison(ICmpInst &I) {
1301     IRBuilder<> IRB(&I);
1302     Value *A = I.getOperand(0);
1303     Value *B = I.getOperand(1);
1304     Value *Sa = getShadow(A);
1305     Value *Sb = getShadow(B);
1306
1307     // Get rid of pointers and vectors of pointers.
1308     // For ints (and vectors of ints), types of A and Sa match,
1309     // and this is a no-op.
1310     A = IRB.CreatePointerCast(A, Sa->getType());
1311     B = IRB.CreatePointerCast(B, Sb->getType());
1312
1313     // A == B  <==>  (C = A^B) == 0
1314     // A != B  <==>  (C = A^B) != 0
1315     // Sc = Sa | Sb
1316     Value *C = IRB.CreateXor(A, B);
1317     Value *Sc = IRB.CreateOr(Sa, Sb);
1318     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
1319     // Result is defined if one of the following is true
1320     // * there is a defined 1 bit in C
1321     // * C is fully defined
1322     // Si = !(C & ~Sc) && Sc
1323     Value *Zero = Constant::getNullValue(Sc->getType());
1324     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
1325     Value *Si =
1326       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
1327                     IRB.CreateICmpEQ(
1328                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
1329     Si->setName("_msprop_icmp");
1330     setShadow(&I, Si);
1331     setOriginForNaryOp(I);
1332   }
1333
1334   /// \brief Build the lowest possible value of V, taking into account V's
1335   ///        uninitialized bits.
1336   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1337                                 bool isSigned) {
1338     if (isSigned) {
1339       // Split shadow into sign bit and other bits.
1340       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1341       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1342       // Maximise the undefined shadow bit, minimize other undefined bits.
1343       return
1344         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
1345     } else {
1346       // Minimize undefined bits.
1347       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
1348     }
1349   }
1350
1351   /// \brief Build the highest possible value of V, taking into account V's
1352   ///        uninitialized bits.
1353   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
1354                                 bool isSigned) {
1355     if (isSigned) {
1356       // Split shadow into sign bit and other bits.
1357       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
1358       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
1359       // Minimise the undefined shadow bit, maximise other undefined bits.
1360       return
1361         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
1362     } else {
1363       // Maximize undefined bits.
1364       return IRB.CreateOr(A, Sa);
1365     }
1366   }
1367
1368   /// \brief Instrument relational comparisons.
1369   ///
1370   /// This function does exact shadow propagation for all relational
1371   /// comparisons of integers, pointers and vectors of those.
1372   /// FIXME: output seems suboptimal when one of the operands is a constant
1373   void handleRelationalComparisonExact(ICmpInst &I) {
1374     IRBuilder<> IRB(&I);
1375     Value *A = I.getOperand(0);
1376     Value *B = I.getOperand(1);
1377     Value *Sa = getShadow(A);
1378     Value *Sb = getShadow(B);
1379
1380     // Get rid of pointers and vectors of pointers.
1381     // For ints (and vectors of ints), types of A and Sa match,
1382     // and this is a no-op.
1383     A = IRB.CreatePointerCast(A, Sa->getType());
1384     B = IRB.CreatePointerCast(B, Sb->getType());
1385
1386     // Let [a0, a1] be the interval of possible values of A, taking into account
1387     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
1388     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
1389     bool IsSigned = I.isSigned();
1390     Value *S1 = IRB.CreateICmp(I.getPredicate(),
1391                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
1392                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
1393     Value *S2 = IRB.CreateICmp(I.getPredicate(),
1394                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
1395                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
1396     Value *Si = IRB.CreateXor(S1, S2);
1397     setShadow(&I, Si);
1398     setOriginForNaryOp(I);
1399   }
1400
1401   /// \brief Instrument signed relational comparisons.
1402   ///
1403   /// Handle (x<0) and (x>=0) comparisons (essentially, sign bit tests) by
1404   /// propagating the highest bit of the shadow. Everything else is delegated
1405   /// to handleShadowOr().
1406   void handleSignedRelationalComparison(ICmpInst &I) {
1407     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
1408     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
1409     Value* op = NULL;
1410     CmpInst::Predicate pre = I.getPredicate();
1411     if (constOp0 && constOp0->isNullValue() &&
1412         (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE)) {
1413       op = I.getOperand(1);
1414     } else if (constOp1 && constOp1->isNullValue() &&
1415                (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) {
1416       op = I.getOperand(0);
1417     }
1418     if (op) {
1419       IRBuilder<> IRB(&I);
1420       Value* Shadow =
1421         IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), "_msprop_icmpslt");
1422       setShadow(&I, Shadow);
1423       setOrigin(&I, getOrigin(op));
1424     } else {
1425       handleShadowOr(I);
1426     }
1427   }
1428
1429   void visitICmpInst(ICmpInst &I) {
1430     if (!ClHandleICmp) {
1431       handleShadowOr(I);
1432       return;
1433     }
1434     if (I.isEquality()) {
1435       handleEqualityComparison(I);
1436       return;
1437     }
1438
1439     assert(I.isRelational());
1440     if (ClHandleICmpExact) {
1441       handleRelationalComparisonExact(I);
1442       return;
1443     }
1444     if (I.isSigned()) {
1445       handleSignedRelationalComparison(I);
1446       return;
1447     }
1448
1449     assert(I.isUnsigned());
1450     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
1451       handleRelationalComparisonExact(I);
1452       return;
1453     }
1454
1455     handleShadowOr(I);
1456   }
1457
1458   void visitFCmpInst(FCmpInst &I) {
1459     handleShadowOr(I);
1460   }
1461
1462   void handleShift(BinaryOperator &I) {
1463     IRBuilder<> IRB(&I);
1464     // If any of the S2 bits are poisoned, the whole thing is poisoned.
1465     // Otherwise perform the same shift on S1.
1466     Value *S1 = getShadow(&I, 0);
1467     Value *S2 = getShadow(&I, 1);
1468     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
1469                                    S2->getType());
1470     Value *V2 = I.getOperand(1);
1471     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
1472     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
1473     setOriginForNaryOp(I);
1474   }
1475
1476   void visitShl(BinaryOperator &I) { handleShift(I); }
1477   void visitAShr(BinaryOperator &I) { handleShift(I); }
1478   void visitLShr(BinaryOperator &I) { handleShift(I); }
1479
1480   /// \brief Instrument llvm.memmove
1481   ///
1482   /// At this point we don't know if llvm.memmove will be inlined or not.
1483   /// If we don't instrument it and it gets inlined,
1484   /// our interceptor will not kick in and we will lose the memmove.
1485   /// If we instrument the call here, but it does not get inlined,
1486   /// we will memove the shadow twice: which is bad in case
1487   /// of overlapping regions. So, we simply lower the intrinsic to a call.
1488   ///
1489   /// Similar situation exists for memcpy and memset.
1490   void visitMemMoveInst(MemMoveInst &I) {
1491     IRBuilder<> IRB(&I);
1492     IRB.CreateCall3(
1493       MS.MemmoveFn,
1494       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1495       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1496       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1497     I.eraseFromParent();
1498   }
1499
1500   // Similar to memmove: avoid copying shadow twice.
1501   // This is somewhat unfortunate as it may slowdown small constant memcpys.
1502   // FIXME: consider doing manual inline for small constant sizes and proper
1503   // alignment.
1504   void visitMemCpyInst(MemCpyInst &I) {
1505     IRBuilder<> IRB(&I);
1506     IRB.CreateCall3(
1507       MS.MemcpyFn,
1508       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1509       IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
1510       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1511     I.eraseFromParent();
1512   }
1513
1514   // Same as memcpy.
1515   void visitMemSetInst(MemSetInst &I) {
1516     IRBuilder<> IRB(&I);
1517     IRB.CreateCall3(
1518       MS.MemsetFn,
1519       IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
1520       IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
1521       IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false));
1522     I.eraseFromParent();
1523   }
1524
1525   void visitVAStartInst(VAStartInst &I) {
1526     VAHelper->visitVAStartInst(I);
1527   }
1528
1529   void visitVACopyInst(VACopyInst &I) {
1530     VAHelper->visitVACopyInst(I);
1531   }
1532
1533   enum IntrinsicKind {
1534     IK_DoesNotAccessMemory,
1535     IK_OnlyReadsMemory,
1536     IK_WritesMemory
1537   };
1538
1539   static IntrinsicKind getIntrinsicKind(Intrinsic::ID iid) {
1540     const int DoesNotAccessMemory = IK_DoesNotAccessMemory;
1541     const int OnlyReadsArgumentPointees = IK_OnlyReadsMemory;
1542     const int OnlyReadsMemory = IK_OnlyReadsMemory;
1543     const int OnlyAccessesArgumentPointees = IK_WritesMemory;
1544     const int UnknownModRefBehavior = IK_WritesMemory;
1545 #define GET_INTRINSIC_MODREF_BEHAVIOR
1546 #define ModRefBehavior IntrinsicKind
1547 #include "llvm/IR/Intrinsics.gen"
1548 #undef ModRefBehavior
1549 #undef GET_INTRINSIC_MODREF_BEHAVIOR
1550   }
1551
1552   /// \brief Handle vector store-like intrinsics.
1553   ///
1554   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
1555   /// has 1 pointer argument and 1 vector argument, returns void.
1556   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
1557     IRBuilder<> IRB(&I);
1558     Value* Addr = I.getArgOperand(0);
1559     Value *Shadow = getShadow(&I, 1);
1560     Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
1561
1562     // We don't know the pointer alignment (could be unaligned SSE store!).
1563     // Have to assume to worst case.
1564     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
1565
1566     if (ClCheckAccessAddress)
1567       insertShadowCheck(Addr, &I);
1568
1569     // FIXME: use ClStoreCleanOrigin
1570     // FIXME: factor out common code from materializeStores
1571     if (MS.TrackOrigins)
1572       IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB));
1573     return true;
1574   }
1575
1576   /// \brief Handle vector load-like intrinsics.
1577   ///
1578   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
1579   /// has 1 pointer argument, returns a vector.
1580   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
1581     IRBuilder<> IRB(&I);
1582     Value *Addr = I.getArgOperand(0);
1583
1584     Type *ShadowTy = getShadowTy(&I);
1585     if (LoadShadow) {
1586       Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
1587       // We don't know the pointer alignment (could be unaligned SSE load!).
1588       // Have to assume to worst case.
1589       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
1590     } else {
1591       setShadow(&I, getCleanShadow(&I));
1592     }
1593
1594     if (ClCheckAccessAddress)
1595       insertShadowCheck(Addr, &I);
1596
1597     if (MS.TrackOrigins) {
1598       if (LoadShadow)
1599         setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB)));
1600       else
1601         setOrigin(&I, getCleanOrigin());
1602     }
1603     return true;
1604   }
1605
1606   /// \brief Handle (SIMD arithmetic)-like intrinsics.
1607   ///
1608   /// Instrument intrinsics with any number of arguments of the same type,
1609   /// equal to the return type. The type should be simple (no aggregates or
1610   /// pointers; vectors are fine).
1611   /// Caller guarantees that this intrinsic does not access memory.
1612   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
1613     Type *RetTy = I.getType();
1614     if (!(RetTy->isIntOrIntVectorTy() ||
1615           RetTy->isFPOrFPVectorTy() ||
1616           RetTy->isX86_MMXTy()))
1617       return false;
1618
1619     unsigned NumArgOperands = I.getNumArgOperands();
1620
1621     for (unsigned i = 0; i < NumArgOperands; ++i) {
1622       Type *Ty = I.getArgOperand(i)->getType();
1623       if (Ty != RetTy)
1624         return false;
1625     }
1626
1627     IRBuilder<> IRB(&I);
1628     ShadowAndOriginCombiner SC(this, IRB);
1629     for (unsigned i = 0; i < NumArgOperands; ++i)
1630       SC.Add(I.getArgOperand(i));
1631     SC.Done(&I);
1632
1633     return true;
1634   }
1635
1636   /// \brief Heuristically instrument unknown intrinsics.
1637   ///
1638   /// The main purpose of this code is to do something reasonable with all
1639   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
1640   /// We recognize several classes of intrinsics by their argument types and
1641   /// ModRefBehaviour and apply special intrumentation when we are reasonably
1642   /// sure that we know what the intrinsic does.
1643   ///
1644   /// We special-case intrinsics where this approach fails. See llvm.bswap
1645   /// handling as an example of that.
1646   bool handleUnknownIntrinsic(IntrinsicInst &I) {
1647     unsigned NumArgOperands = I.getNumArgOperands();
1648     if (NumArgOperands == 0)
1649       return false;
1650
1651     Intrinsic::ID iid = I.getIntrinsicID();
1652     IntrinsicKind IK = getIntrinsicKind(iid);
1653     bool OnlyReadsMemory = IK == IK_OnlyReadsMemory;
1654     bool WritesMemory = IK == IK_WritesMemory;
1655     assert(!(OnlyReadsMemory && WritesMemory));
1656
1657     if (NumArgOperands == 2 &&
1658         I.getArgOperand(0)->getType()->isPointerTy() &&
1659         I.getArgOperand(1)->getType()->isVectorTy() &&
1660         I.getType()->isVoidTy() &&
1661         WritesMemory) {
1662       // This looks like a vector store.
1663       return handleVectorStoreIntrinsic(I);
1664     }
1665
1666     if (NumArgOperands == 1 &&
1667         I.getArgOperand(0)->getType()->isPointerTy() &&
1668         I.getType()->isVectorTy() &&
1669         OnlyReadsMemory) {
1670       // This looks like a vector load.
1671       return handleVectorLoadIntrinsic(I);
1672     }
1673
1674     if (!OnlyReadsMemory && !WritesMemory)
1675       if (maybeHandleSimpleNomemIntrinsic(I))
1676         return true;
1677
1678     // FIXME: detect and handle SSE maskstore/maskload
1679     return false;
1680   }
1681
1682   void handleBswap(IntrinsicInst &I) {
1683     IRBuilder<> IRB(&I);
1684     Value *Op = I.getArgOperand(0);
1685     Type *OpType = Op->getType();
1686     Function *BswapFunc = Intrinsic::getDeclaration(
1687       F.getParent(), Intrinsic::bswap, ArrayRef<Type*>(&OpType, 1));
1688     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
1689     setOrigin(&I, getOrigin(Op));
1690   }
1691
1692   // \brief Instrument vector convert instrinsic.
1693   //
1694   // This function instruments intrinsics like cvtsi2ss:
1695   // %Out = int_xxx_cvtyyy(%ConvertOp)
1696   // or
1697   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
1698   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
1699   // number \p Out elements, and (if has 2 arguments) copies the rest of the
1700   // elements from \p CopyOp.
1701   // In most cases conversion involves floating-point value which may trigger a
1702   // hardware exception when not fully initialized. For this reason we require
1703   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
1704   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
1705   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
1706   // return a fully initialized value.
1707   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
1708     IRBuilder<> IRB(&I);
1709     Value *CopyOp, *ConvertOp;
1710
1711     switch (I.getNumArgOperands()) {
1712     case 2:
1713       CopyOp = I.getArgOperand(0);
1714       ConvertOp = I.getArgOperand(1);
1715       break;
1716     case 1:
1717       ConvertOp = I.getArgOperand(0);
1718       CopyOp = NULL;
1719       break;
1720     default:
1721       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
1722     }
1723
1724     // The first *NumUsedElements* elements of ConvertOp are converted to the
1725     // same number of output elements. The rest of the output is copied from
1726     // CopyOp, or (if not available) filled with zeroes.
1727     // Combine shadow for elements of ConvertOp that are used in this operation,
1728     // and insert a check.
1729     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
1730     // int->any conversion.
1731     Value *ConvertShadow = getShadow(ConvertOp);
1732     Value *AggShadow = 0;
1733     if (ConvertOp->getType()->isVectorTy()) {
1734       AggShadow = IRB.CreateExtractElement(
1735           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
1736       for (int i = 1; i < NumUsedElements; ++i) {
1737         Value *MoreShadow = IRB.CreateExtractElement(
1738             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
1739         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
1740       }
1741     } else {
1742       AggShadow = ConvertShadow;
1743     }
1744     assert(AggShadow->getType()->isIntegerTy());
1745     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
1746
1747     // Build result shadow by zero-filling parts of CopyOp shadow that come from
1748     // ConvertOp.
1749     if (CopyOp) {
1750       assert(CopyOp->getType() == I.getType());
1751       assert(CopyOp->getType()->isVectorTy());
1752       Value *ResultShadow = getShadow(CopyOp);
1753       Type *EltTy = ResultShadow->getType()->getVectorElementType();
1754       for (int i = 0; i < NumUsedElements; ++i) {
1755         ResultShadow = IRB.CreateInsertElement(
1756             ResultShadow, ConstantInt::getNullValue(EltTy),
1757             ConstantInt::get(IRB.getInt32Ty(), i));
1758       }
1759       setShadow(&I, ResultShadow);
1760       setOrigin(&I, getOrigin(CopyOp));
1761     } else {
1762       setShadow(&I, getCleanShadow(&I));
1763     }
1764   }
1765
1766   void visitIntrinsicInst(IntrinsicInst &I) {
1767     switch (I.getIntrinsicID()) {
1768     case llvm::Intrinsic::bswap:
1769       handleBswap(I);
1770       break;
1771     case llvm::Intrinsic::x86_avx512_cvtsd2usi64:
1772     case llvm::Intrinsic::x86_avx512_cvtsd2usi:
1773     case llvm::Intrinsic::x86_avx512_cvtss2usi64:
1774     case llvm::Intrinsic::x86_avx512_cvtss2usi:
1775     case llvm::Intrinsic::x86_avx512_cvttss2usi64:
1776     case llvm::Intrinsic::x86_avx512_cvttss2usi:
1777     case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
1778     case llvm::Intrinsic::x86_avx512_cvttsd2usi:
1779     case llvm::Intrinsic::x86_avx512_cvtusi2sd:
1780     case llvm::Intrinsic::x86_avx512_cvtusi2ss:
1781     case llvm::Intrinsic::x86_avx512_cvtusi642sd:
1782     case llvm::Intrinsic::x86_avx512_cvtusi642ss:
1783     case llvm::Intrinsic::x86_sse2_cvtsd2si64:
1784     case llvm::Intrinsic::x86_sse2_cvtsd2si:
1785     case llvm::Intrinsic::x86_sse2_cvtsd2ss:
1786     case llvm::Intrinsic::x86_sse2_cvtsi2sd:
1787     case llvm::Intrinsic::x86_sse2_cvtsi642sd:
1788     case llvm::Intrinsic::x86_sse2_cvtss2sd:
1789     case llvm::Intrinsic::x86_sse2_cvttsd2si64:
1790     case llvm::Intrinsic::x86_sse2_cvttsd2si:
1791     case llvm::Intrinsic::x86_sse_cvtsi2ss:
1792     case llvm::Intrinsic::x86_sse_cvtsi642ss:
1793     case llvm::Intrinsic::x86_sse_cvtss2si64:
1794     case llvm::Intrinsic::x86_sse_cvtss2si:
1795     case llvm::Intrinsic::x86_sse_cvttss2si64:
1796     case llvm::Intrinsic::x86_sse_cvttss2si:
1797       handleVectorConvertIntrinsic(I, 1);
1798       break;
1799     case llvm::Intrinsic::x86_sse2_cvtdq2pd:
1800     case llvm::Intrinsic::x86_sse2_cvtps2pd:
1801     case llvm::Intrinsic::x86_sse_cvtps2pi:
1802     case llvm::Intrinsic::x86_sse_cvttps2pi:
1803       handleVectorConvertIntrinsic(I, 2);
1804       break;
1805     default:
1806       if (!handleUnknownIntrinsic(I))
1807         visitInstruction(I);
1808       break;
1809     }
1810   }
1811
1812   // Replace call to (*Fn) with a call to (*IndirectCallWrapperFn(Fn)).
1813   void wrapIndirectCall(IRBuilder<> &IRB, CallSite CS) {
1814     Value *Fn = CS.getCalledValue();
1815     Value *NewFn = IRB.CreateBitCast(
1816         IRB.CreateCall(MS.IndirectCallWrapperFn,
1817                        IRB.CreateBitCast(Fn, MS.AnyFunctionPtrTy)),
1818         Fn->getType());
1819     setShadow(NewFn, getShadow(Fn));
1820     CS.setCalledFunction(NewFn);
1821   }
1822
1823   void visitCallSite(CallSite CS) {
1824     Instruction &I = *CS.getInstruction();
1825     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
1826     if (CS.isCall()) {
1827       CallInst *Call = cast<CallInst>(&I);
1828
1829       // For inline asm, do the usual thing: check argument shadow and mark all
1830       // outputs as clean. Note that any side effects of the inline asm that are
1831       // not immediately visible in its constraints are not handled.
1832       if (Call->isInlineAsm()) {
1833         visitInstruction(I);
1834         return;
1835       }
1836
1837       // Allow only tail calls with the same types, otherwise
1838       // we may have a false positive: shadow for a non-void RetVal
1839       // will get propagated to a void RetVal.
1840       if (Call->isTailCall() && Call->getType() != Call->getParent()->getType())
1841         Call->setTailCall(false);
1842
1843       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
1844
1845       // We are going to insert code that relies on the fact that the callee
1846       // will become a non-readonly function after it is instrumented by us. To
1847       // prevent this code from being optimized out, mark that function
1848       // non-readonly in advance.
1849       if (Function *Func = Call->getCalledFunction()) {
1850         // Clear out readonly/readnone attributes.
1851         AttrBuilder B;
1852         B.addAttribute(Attribute::ReadOnly)
1853           .addAttribute(Attribute::ReadNone);
1854         Func->removeAttributes(AttributeSet::FunctionIndex,
1855                                AttributeSet::get(Func->getContext(),
1856                                                  AttributeSet::FunctionIndex,
1857                                                  B));
1858       }
1859     }
1860     IRBuilder<> IRB(&I);
1861
1862     if (MS.WrapIndirectCalls && !CS.getCalledFunction())
1863       wrapIndirectCall(IRB, CS);
1864
1865     unsigned ArgOffset = 0;
1866     DEBUG(dbgs() << "  CallSite: " << I << "\n");
1867     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
1868          ArgIt != End; ++ArgIt) {
1869       Value *A = *ArgIt;
1870       unsigned i = ArgIt - CS.arg_begin();
1871       if (!A->getType()->isSized()) {
1872         DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
1873         continue;
1874       }
1875       unsigned Size = 0;
1876       Value *Store = 0;
1877       // Compute the Shadow for arg even if it is ByVal, because
1878       // in that case getShadow() will copy the actual arg shadow to
1879       // __msan_param_tls.
1880       Value *ArgShadow = getShadow(A);
1881       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
1882       DEBUG(dbgs() << "  Arg#" << i << ": " << *A <<
1883             " Shadow: " << *ArgShadow << "\n");
1884       if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
1885         assert(A->getType()->isPointerTy() &&
1886                "ByVal argument is not a pointer!");
1887         Size = MS.TD->getTypeAllocSize(A->getType()->getPointerElementType());
1888         unsigned Alignment = CS.getParamAlignment(i + 1);
1889         Store = IRB.CreateMemCpy(ArgShadowBase,
1890                                  getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
1891                                  Size, Alignment);
1892       } else {
1893         Size = MS.TD->getTypeAllocSize(A->getType());
1894         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
1895                                        kShadowTLSAlignment);
1896       }
1897       if (MS.TrackOrigins)
1898         IRB.CreateStore(getOrigin(A),
1899                         getOriginPtrForArgument(A, IRB, ArgOffset));
1900       (void)Store;
1901       assert(Size != 0 && Store != 0);
1902       DEBUG(dbgs() << "  Param:" << *Store << "\n");
1903       ArgOffset += DataLayout::RoundUpAlignment(Size, 8);
1904     }
1905     DEBUG(dbgs() << "  done with call args\n");
1906
1907     FunctionType *FT =
1908       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
1909     if (FT->isVarArg()) {
1910       VAHelper->visitCallSite(CS, IRB);
1911     }
1912
1913     // Now, get the shadow for the RetVal.
1914     if (!I.getType()->isSized()) return;
1915     IRBuilder<> IRBBefore(&I);
1916     // Untill we have full dynamic coverage, make sure the retval shadow is 0.
1917     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
1918     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
1919     Instruction *NextInsn = 0;
1920     if (CS.isCall()) {
1921       NextInsn = I.getNextNode();
1922     } else {
1923       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
1924       if (!NormalDest->getSinglePredecessor()) {
1925         // FIXME: this case is tricky, so we are just conservative here.
1926         // Perhaps we need to split the edge between this BB and NormalDest,
1927         // but a naive attempt to use SplitEdge leads to a crash.
1928         setShadow(&I, getCleanShadow(&I));
1929         setOrigin(&I, getCleanOrigin());
1930         return;
1931       }
1932       NextInsn = NormalDest->getFirstInsertionPt();
1933       assert(NextInsn &&
1934              "Could not find insertion point for retval shadow load");
1935     }
1936     IRBuilder<> IRBAfter(NextInsn);
1937     Value *RetvalShadow =
1938       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
1939                                  kShadowTLSAlignment, "_msret");
1940     setShadow(&I, RetvalShadow);
1941     if (MS.TrackOrigins)
1942       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
1943   }
1944
1945   void visitReturnInst(ReturnInst &I) {
1946     IRBuilder<> IRB(&I);
1947     Value *RetVal = I.getReturnValue();
1948     if (!RetVal) return;
1949     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
1950     if (CheckReturnValue) {
1951       insertShadowCheck(RetVal, &I);
1952       Value *Shadow = getCleanShadow(RetVal);
1953       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1954     } else {
1955       Value *Shadow = getShadow(RetVal);
1956       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
1957       // FIXME: make it conditional if ClStoreCleanOrigin==0
1958       if (MS.TrackOrigins)
1959         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
1960     }
1961   }
1962
1963   void visitPHINode(PHINode &I) {
1964     IRBuilder<> IRB(&I);
1965     ShadowPHINodes.push_back(&I);
1966     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
1967                                 "_msphi_s"));
1968     if (MS.TrackOrigins)
1969       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
1970                                   "_msphi_o"));
1971   }
1972
1973   void visitAllocaInst(AllocaInst &I) {
1974     setShadow(&I, getCleanShadow(&I));
1975     IRBuilder<> IRB(I.getNextNode());
1976     uint64_t Size = MS.TD->getTypeAllocSize(I.getAllocatedType());
1977     if (PoisonStack && ClPoisonStackWithCall) {
1978       IRB.CreateCall2(MS.MsanPoisonStackFn,
1979                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
1980                       ConstantInt::get(MS.IntptrTy, Size));
1981     } else {
1982       Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
1983       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
1984       IRB.CreateMemSet(ShadowBase, PoisonValue, Size, I.getAlignment());
1985     }
1986
1987     if (PoisonStack && MS.TrackOrigins) {
1988       setOrigin(&I, getCleanOrigin());
1989       SmallString<2048> StackDescriptionStorage;
1990       raw_svector_ostream StackDescription(StackDescriptionStorage);
1991       // We create a string with a description of the stack allocation and
1992       // pass it into __msan_set_alloca_origin.
1993       // It will be printed by the run-time if stack-originated UMR is found.
1994       // The first 4 bytes of the string are set to '----' and will be replaced
1995       // by __msan_va_arg_overflow_size_tls at the first call.
1996       StackDescription << "----" << I.getName() << "@" << F.getName();
1997       Value *Descr =
1998           createPrivateNonConstGlobalForString(*F.getParent(),
1999                                                StackDescription.str());
2000
2001       IRB.CreateCall4(MS.MsanSetAllocaOrigin4Fn,
2002                       IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()),
2003                       ConstantInt::get(MS.IntptrTy, Size),
2004                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
2005                       IRB.CreatePointerCast(&F, MS.IntptrTy));
2006     }
2007   }
2008
2009   void visitSelectInst(SelectInst& I) {
2010     IRBuilder<> IRB(&I);
2011     // a = select b, c, d
2012     Value *S = IRB.CreateSelect(I.getCondition(), getShadow(I.getTrueValue()),
2013                                 getShadow(I.getFalseValue()));
2014     if (I.getType()->isAggregateType()) {
2015       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
2016       // an extra "select". This results in much more compact IR.
2017       // Sa = select Sb, poisoned, (select b, Sc, Sd)
2018       S = IRB.CreateSelect(getShadow(I.getCondition()),
2019                            getPoisonedShadow(getShadowTy(I.getType())), S,
2020                            "_msprop_select_agg");
2021     } else {
2022       // Sa = (sext Sb) | (select b, Sc, Sd)
2023       S = IRB.CreateOr(S, CreateShadowCast(IRB, getShadow(I.getCondition()),
2024                                            S->getType(), true),
2025                        "_msprop_select");
2026     }
2027     setShadow(&I, S);
2028     if (MS.TrackOrigins) {
2029       // Origins are always i32, so any vector conditions must be flattened.
2030       // FIXME: consider tracking vector origins for app vectors?
2031       Value *Cond = I.getCondition();
2032       if (Cond->getType()->isVectorTy()) {
2033         Value *ConvertedShadow = convertToShadowTyNoVec(Cond, IRB);
2034         Cond = IRB.CreateICmpNE(ConvertedShadow,
2035                                 getCleanShadow(ConvertedShadow), "_mso_select");
2036       }
2037       setOrigin(&I, IRB.CreateSelect(Cond,
2038                 getOrigin(I.getTrueValue()), getOrigin(I.getFalseValue())));
2039     }
2040   }
2041
2042   void visitLandingPadInst(LandingPadInst &I) {
2043     // Do nothing.
2044     // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
2045     setShadow(&I, getCleanShadow(&I));
2046     setOrigin(&I, getCleanOrigin());
2047   }
2048
2049   void visitGetElementPtrInst(GetElementPtrInst &I) {
2050     handleShadowOr(I);
2051   }
2052
2053   void visitExtractValueInst(ExtractValueInst &I) {
2054     IRBuilder<> IRB(&I);
2055     Value *Agg = I.getAggregateOperand();
2056     DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
2057     Value *AggShadow = getShadow(Agg);
2058     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2059     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
2060     DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
2061     setShadow(&I, ResShadow);
2062     setOriginForNaryOp(I);
2063   }
2064
2065   void visitInsertValueInst(InsertValueInst &I) {
2066     IRBuilder<> IRB(&I);
2067     DEBUG(dbgs() << "InsertValue:  " << I << "\n");
2068     Value *AggShadow = getShadow(I.getAggregateOperand());
2069     Value *InsShadow = getShadow(I.getInsertedValueOperand());
2070     DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
2071     DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
2072     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
2073     DEBUG(dbgs() << "   Res:        " << *Res << "\n");
2074     setShadow(&I, Res);
2075     setOriginForNaryOp(I);
2076   }
2077
2078   void dumpInst(Instruction &I) {
2079     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2080       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
2081     } else {
2082       errs() << "ZZZ " << I.getOpcodeName() << "\n";
2083     }
2084     errs() << "QQQ " << I << "\n";
2085   }
2086
2087   void visitResumeInst(ResumeInst &I) {
2088     DEBUG(dbgs() << "Resume: " << I << "\n");
2089     // Nothing to do here.
2090   }
2091
2092   void visitInstruction(Instruction &I) {
2093     // Everything else: stop propagating and check for poisoned shadow.
2094     if (ClDumpStrictInstructions)
2095       dumpInst(I);
2096     DEBUG(dbgs() << "DEFAULT: " << I << "\n");
2097     for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
2098       insertShadowCheck(I.getOperand(i), &I);
2099     setShadow(&I, getCleanShadow(&I));
2100     setOrigin(&I, getCleanOrigin());
2101   }
2102 };
2103
2104 /// \brief AMD64-specific implementation of VarArgHelper.
2105 struct VarArgAMD64Helper : public VarArgHelper {
2106   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
2107   // See a comment in visitCallSite for more details.
2108   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
2109   static const unsigned AMD64FpEndOffset = 176;
2110
2111   Function &F;
2112   MemorySanitizer &MS;
2113   MemorySanitizerVisitor &MSV;
2114   Value *VAArgTLSCopy;
2115   Value *VAArgOverflowSize;
2116
2117   SmallVector<CallInst*, 16> VAStartInstrumentationList;
2118
2119   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
2120                     MemorySanitizerVisitor &MSV)
2121     : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(0), VAArgOverflowSize(0) { }
2122
2123   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
2124
2125   ArgKind classifyArgument(Value* arg) {
2126     // A very rough approximation of X86_64 argument classification rules.
2127     Type *T = arg->getType();
2128     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
2129       return AK_FloatingPoint;
2130     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
2131       return AK_GeneralPurpose;
2132     if (T->isPointerTy())
2133       return AK_GeneralPurpose;
2134     return AK_Memory;
2135   }
2136
2137   // For VarArg functions, store the argument shadow in an ABI-specific format
2138   // that corresponds to va_list layout.
2139   // We do this because Clang lowers va_arg in the frontend, and this pass
2140   // only sees the low level code that deals with va_list internals.
2141   // A much easier alternative (provided that Clang emits va_arg instructions)
2142   // would have been to associate each live instance of va_list with a copy of
2143   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
2144   // order.
2145   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {
2146     unsigned GpOffset = 0;
2147     unsigned FpOffset = AMD64GpEndOffset;
2148     unsigned OverflowOffset = AMD64FpEndOffset;
2149     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
2150          ArgIt != End; ++ArgIt) {
2151       Value *A = *ArgIt;
2152       ArgKind AK = classifyArgument(A);
2153       if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
2154         AK = AK_Memory;
2155       if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
2156         AK = AK_Memory;
2157       Value *Base;
2158       switch (AK) {
2159       case AK_GeneralPurpose:
2160         Base = getShadowPtrForVAArgument(A, IRB, GpOffset);
2161         GpOffset += 8;
2162         break;
2163       case AK_FloatingPoint:
2164         Base = getShadowPtrForVAArgument(A, IRB, FpOffset);
2165         FpOffset += 16;
2166         break;
2167       case AK_Memory:
2168         uint64_t ArgSize = MS.TD->getTypeAllocSize(A->getType());
2169         Base = getShadowPtrForVAArgument(A, IRB, OverflowOffset);
2170         OverflowOffset += DataLayout::RoundUpAlignment(ArgSize, 8);
2171       }
2172       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
2173     }
2174     Constant *OverflowSize =
2175       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
2176     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
2177   }
2178
2179   /// \brief Compute the shadow address for a given va_arg.
2180   Value *getShadowPtrForVAArgument(Value *A, IRBuilder<> &IRB,
2181                                    int ArgOffset) {
2182     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
2183     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
2184     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(A), 0),
2185                               "_msarg");
2186   }
2187
2188   void visitVAStartInst(VAStartInst &I) {
2189     IRBuilder<> IRB(&I);
2190     VAStartInstrumentationList.push_back(&I);
2191     Value *VAListTag = I.getArgOperand(0);
2192     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2193
2194     // Unpoison the whole __va_list_tag.
2195     // FIXME: magic ABI constants.
2196     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2197                      /* size */24, /* alignment */8, false);
2198   }
2199
2200   void visitVACopyInst(VACopyInst &I) {
2201     IRBuilder<> IRB(&I);
2202     Value *VAListTag = I.getArgOperand(0);
2203     Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
2204
2205     // Unpoison the whole __va_list_tag.
2206     // FIXME: magic ABI constants.
2207     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
2208                      /* size */24, /* alignment */8, false);
2209   }
2210
2211   void finalizeInstrumentation() {
2212     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
2213            "finalizeInstrumentation called twice");
2214     if (!VAStartInstrumentationList.empty()) {
2215       // If there is a va_start in this function, make a backup copy of
2216       // va_arg_tls somewhere in the function entry block.
2217       IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
2218       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
2219       Value *CopySize =
2220         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
2221                       VAArgOverflowSize);
2222       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
2223       IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
2224     }
2225
2226     // Instrument va_start.
2227     // Copy va_list shadow from the backup copy of the TLS contents.
2228     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
2229       CallInst *OrigInst = VAStartInstrumentationList[i];
2230       IRBuilder<> IRB(OrigInst->getNextNode());
2231       Value *VAListTag = OrigInst->getArgOperand(0);
2232
2233       Value *RegSaveAreaPtrPtr =
2234         IRB.CreateIntToPtr(
2235           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2236                         ConstantInt::get(MS.IntptrTy, 16)),
2237           Type::getInt64PtrTy(*MS.C));
2238       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
2239       Value *RegSaveAreaShadowPtr =
2240         MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
2241       IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
2242                        AMD64FpEndOffset, 16);
2243
2244       Value *OverflowArgAreaPtrPtr =
2245         IRB.CreateIntToPtr(
2246           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
2247                         ConstantInt::get(MS.IntptrTy, 8)),
2248           Type::getInt64PtrTy(*MS.C));
2249       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
2250       Value *OverflowArgAreaShadowPtr =
2251         MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
2252       Value *SrcPtr = IRB.CreateConstGEP1_32(VAArgTLSCopy, AMD64FpEndOffset);
2253       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
2254     }
2255   }
2256 };
2257
2258 /// \brief A no-op implementation of VarArgHelper.
2259 struct VarArgNoOpHelper : public VarArgHelper {
2260   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
2261                    MemorySanitizerVisitor &MSV) {}
2262
2263   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) {}
2264
2265   void visitVAStartInst(VAStartInst &I) {}
2266
2267   void visitVACopyInst(VACopyInst &I) {}
2268
2269   void finalizeInstrumentation() {}
2270 };
2271
2272 VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
2273                                  MemorySanitizerVisitor &Visitor) {
2274   // VarArg handling is only implemented on AMD64. False positives are possible
2275   // on other platforms.
2276   llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
2277   if (TargetTriple.getArch() == llvm::Triple::x86_64)
2278     return new VarArgAMD64Helper(Func, Msan, Visitor);
2279   else
2280     return new VarArgNoOpHelper(Func, Msan, Visitor);
2281 }
2282
2283 }  // namespace
2284
2285 bool MemorySanitizer::runOnFunction(Function &F) {
2286   MemorySanitizerVisitor Visitor(F, *this);
2287
2288   // Clear out readonly/readnone attributes.
2289   AttrBuilder B;
2290   B.addAttribute(Attribute::ReadOnly)
2291     .addAttribute(Attribute::ReadNone);
2292   F.removeAttributes(AttributeSet::FunctionIndex,
2293                      AttributeSet::get(F.getContext(),
2294                                        AttributeSet::FunctionIndex, B));
2295
2296   return Visitor.runOnFunction();
2297 }