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