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