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