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