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