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