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