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