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