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