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