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