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