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