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 //
10 /// \file
11 /// This file is a part of MemorySanitizer, a detector of uninitialized
12 /// reads.
13 ///
14 /// The algorithm of the tool is similar to Memcheck
15 /// (http://goo.gl/QKbem). We associate a few shadow bits with every
16 /// byte of the application memory, poison the shadow of the malloc-ed
17 /// or alloca-ed memory, load the shadow bits on every memory read,
18 /// propagate the shadow bits through some of the arithmetic
19 /// instruction (including MOV), store the shadow bits on every memory
20 /// write, report a bug on some other instructions (e.g. JMP) if the
21 /// associated shadow is poisoned.
22 ///
23 /// But there are differences too. The first and the major one:
24 /// compiler instrumentation instead of binary instrumentation. This
25 /// gives us much better register allocation, possible compiler
26 /// optimizations and a fast start-up. But this brings the major issue
27 /// as well: msan needs to see all program events, including system
28 /// calls and reads/writes in system libraries, so we either need to
29 /// compile *everything* with msan or use a binary translation
30 /// component (e.g. DynamoRIO) to instrument pre-built libraries.
31 /// Another difference from Memcheck is that we use 8 shadow bits per
32 /// byte of application memory and use a direct shadow mapping. This
33 /// greatly simplifies the instrumentation code and avoids races on
34 /// shadow updates (Memcheck is single-threaded so races are not a
35 /// concern there. Memcheck uses 2 shadow bits per byte with a slow
36 /// path storage that uses 8 bits per byte).
37 ///
38 /// The default value of shadow is 0, which means "clean" (not poisoned).
39 ///
40 /// Every module initializer should call __msan_init to ensure that the
41 /// shadow memory is ready. On error, __msan_warning is called. Since
42 /// parameters and return values may be passed via registers, we have a
43 /// specialized thread-local shadow for return values
44 /// (__msan_retval_tls) and parameters (__msan_param_tls).
45 ///
46 ///                           Origin tracking.
47 ///
48 /// MemorySanitizer can track origins (allocation points) of all uninitialized
49 /// values. This behavior is controlled with a flag (msan-track-origins) and is
50 /// disabled by default.
51 ///
52 /// Origins are 4-byte values created and interpreted by the runtime library.
53 /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
54 /// of application memory. Propagation of origins is basically a bunch of
55 /// "select" instructions that pick the origin of a dirty argument, if an
56 /// instruction has one.
57 ///
58 /// Every 4 aligned, consecutive bytes of application memory have one origin
59 /// value associated with them. If these bytes contain uninitialized data
60 /// coming from 2 different allocations, the last store wins. Because of this,
61 /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
62 /// practice.
63 ///
64 /// Origins are meaningless for fully initialized values, so MemorySanitizer
65 /// avoids storing origin to memory when a fully initialized value is stored.
66 /// This way it avoids needless overwritting origin of the 4-byte region on
67 /// a short (i.e. 1 byte) clean store, and it is also good for performance.
68 ///
69 ///                            Atomic handling.
70 ///
71 /// Ideally, every atomic store of application value should update the
72 /// corresponding shadow location in an atomic way. Unfortunately, atomic store
73 /// of two disjoint locations can not be done without severe slowdown.
74 ///
75 /// Therefore, we implement an approximation that may err on the safe side.
76 /// In this implementation, every atomically accessed location in the program
77 /// may only change from (partially) uninitialized to fully initialized, but
78 /// not the other way around. We load the shadow _after_ the application load,
79 /// and we store the shadow _before_ the app store. Also, we always store clean
80 /// shadow (if the application store is atomic). This way, if the store-load
81 /// pair constitutes a happens-before arc, shadow store and load are correctly
82 /// ordered such that the load will get either the value that was stored, or
83 /// some later value (which is always clean).
84 ///
85 /// This does not work very well with Compare-And-Swap (CAS) and
86 /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
87 /// must store the new shadow before the app operation, and load the shadow
88 /// after the app operation. Computers don't work this way. Current
89 /// implementation ignores the load aspect of CAS/RMW, always returning a clean
90 /// value. It implements the store part as a simple atomic store by storing a
91 /// clean shadow.
92 ///
93 ///                      Instrumenting inline assembly.
94 ///
95 /// For inline assembly code LLVM has little idea about which memory locations
96 /// become initialized depending on the arguments. It can be possible to figure
97 /// out which arguments are meant to point to inputs and outputs, but the
98 /// actual semantics can be only visible at runtime. In the Linux kernel it's
99 /// also possible that the arguments only indicate the offset for a base taken
100 /// from a segment register, so it's dangerous to treat any asm() arguments as
101 /// pointers. We take a conservative approach generating calls to
102 ///   __msan_instrument_asm_store(ptr, size)
103 /// , which defer the memory unpoisoning to the runtime library.
104 /// The latter can perform more complex address checks to figure out whether
105 /// it's safe to touch the shadow memory.
106 /// Like with atomic operations, we call __msan_instrument_asm_store() before
107 /// the assembly call, so that changes to the shadow memory will be seen by
108 /// other threads together with main memory initialization.
109 ///
110 ///                  KernelMemorySanitizer (KMSAN) implementation.
111 ///
112 /// The major differences between KMSAN and MSan instrumentation are:
113 ///  - KMSAN always tracks the origins and implies msan-keep-going=true;
114 ///  - KMSAN allocates shadow and origin memory for each page separately, so
115 ///    there are no explicit accesses to shadow and origin in the
116 ///    instrumentation.
117 ///    Shadow and origin values for a particular X-byte memory location
118 ///    (X=1,2,4,8) are accessed through pointers obtained via the
119 ///      __msan_metadata_ptr_for_load_X(ptr)
120 ///      __msan_metadata_ptr_for_store_X(ptr)
121 ///    functions. The corresponding functions check that the X-byte accesses
122 ///    are possible and returns the pointers to shadow and origin memory.
123 ///    Arbitrary sized accesses are handled with:
124 ///      __msan_metadata_ptr_for_load_n(ptr, size)
125 ///      __msan_metadata_ptr_for_store_n(ptr, size);
126 ///  - TLS variables are stored in a single per-task struct. A call to a
127 ///    function __msan_get_context_state() returning a pointer to that struct
128 ///    is inserted into every instrumented function before the entry block;
129 ///  - __msan_warning() takes a 32-bit origin parameter;
130 ///  - local variables are poisoned with __msan_poison_alloca() upon function
131 ///    entry and unpoisoned with __msan_unpoison_alloca() before leaving the
132 ///    function;
133 ///  - the pass doesn't declare any global variables or add global constructors
134 ///    to the translation unit.
135 ///
136 /// Also, KMSAN currently ignores uninitialized memory passed into inline asm
137 /// calls, making sure we're on the safe side wrt. possible false positives.
138 ///
139 ///  KernelMemorySanitizer only supports X86_64 at the moment.
140 ///
141 //===----------------------------------------------------------------------===//
142 
143 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
144 #include "llvm/ADT/APInt.h"
145 #include "llvm/ADT/ArrayRef.h"
146 #include "llvm/ADT/DepthFirstIterator.h"
147 #include "llvm/ADT/SmallString.h"
148 #include "llvm/ADT/SmallVector.h"
149 #include "llvm/ADT/StringExtras.h"
150 #include "llvm/ADT/StringRef.h"
151 #include "llvm/ADT/Triple.h"
152 #include "llvm/Analysis/TargetLibraryInfo.h"
153 #include "llvm/IR/Argument.h"
154 #include "llvm/IR/Attributes.h"
155 #include "llvm/IR/BasicBlock.h"
156 #include "llvm/IR/CallSite.h"
157 #include "llvm/IR/CallingConv.h"
158 #include "llvm/IR/Constant.h"
159 #include "llvm/IR/Constants.h"
160 #include "llvm/IR/DataLayout.h"
161 #include "llvm/IR/DerivedTypes.h"
162 #include "llvm/IR/Function.h"
163 #include "llvm/IR/GlobalValue.h"
164 #include "llvm/IR/GlobalVariable.h"
165 #include "llvm/IR/IRBuilder.h"
166 #include "llvm/IR/InlineAsm.h"
167 #include "llvm/IR/InstVisitor.h"
168 #include "llvm/IR/InstrTypes.h"
169 #include "llvm/IR/Instruction.h"
170 #include "llvm/IR/Instructions.h"
171 #include "llvm/IR/IntrinsicInst.h"
172 #include "llvm/IR/Intrinsics.h"
173 #include "llvm/IR/LLVMContext.h"
174 #include "llvm/IR/MDBuilder.h"
175 #include "llvm/IR/Module.h"
176 #include "llvm/IR/Type.h"
177 #include "llvm/IR/Value.h"
178 #include "llvm/IR/ValueMap.h"
179 #include "llvm/Pass.h"
180 #include "llvm/Support/AtomicOrdering.h"
181 #include "llvm/Support/Casting.h"
182 #include "llvm/Support/CommandLine.h"
183 #include "llvm/Support/Compiler.h"
184 #include "llvm/Support/Debug.h"
185 #include "llvm/Support/ErrorHandling.h"
186 #include "llvm/Support/MathExtras.h"
187 #include "llvm/Support/raw_ostream.h"
188 #include "llvm/Transforms/Instrumentation.h"
189 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
190 #include "llvm/Transforms/Utils/Local.h"
191 #include "llvm/Transforms/Utils/ModuleUtils.h"
192 #include <algorithm>
193 #include <cassert>
194 #include <cstddef>
195 #include <cstdint>
196 #include <memory>
197 #include <string>
198 #include <tuple>
199 
200 using namespace llvm;
201 
202 #define DEBUG_TYPE "msan"
203 
204 static const unsigned kOriginSize = 4;
205 static const unsigned kMinOriginAlignment = 4;
206 static const unsigned kShadowTLSAlignment = 8;
207 
208 // These constants must be kept in sync with the ones in msan.h.
209 static const unsigned kParamTLSSize = 800;
210 static const unsigned kRetvalTLSSize = 800;
211 
212 // Accesses sizes are powers of two: 1, 2, 4, 8.
213 static const size_t kNumberOfAccessSizes = 4;
214 
215 /// Track origins of uninitialized values.
216 ///
217 /// Adds a section to MemorySanitizer report that points to the allocation
218 /// (stack or heap) the uninitialized bits came from originally.
219 static cl::opt<int> ClTrackOrigins("msan-track-origins",
220        cl::desc("Track origins (allocation sites) of poisoned memory"),
221        cl::Hidden, cl::init(0));
222 
223 static cl::opt<bool> ClKeepGoing("msan-keep-going",
224        cl::desc("keep going after reporting a UMR"),
225        cl::Hidden, cl::init(false));
226 
227 static cl::opt<bool> ClPoisonStack("msan-poison-stack",
228        cl::desc("poison uninitialized stack variables"),
229        cl::Hidden, cl::init(true));
230 
231 static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
232        cl::desc("poison uninitialized stack variables with a call"),
233        cl::Hidden, cl::init(false));
234 
235 static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
236        cl::desc("poison uninitialized stack variables with the given pattern"),
237        cl::Hidden, cl::init(0xff));
238 
239 static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
240        cl::desc("poison undef temps"),
241        cl::Hidden, cl::init(true));
242 
243 static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
244        cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
245        cl::Hidden, cl::init(true));
246 
247 static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
248        cl::desc("exact handling of relational integer ICmp"),
249        cl::Hidden, cl::init(false));
250 
251 // When compiling the Linux kernel, we sometimes see false positives related to
252 // MSan being unable to understand that inline assembly calls may initialize
253 // local variables.
254 // This flag makes the compiler conservatively unpoison every memory location
255 // passed into an assembly call. Note that this may cause false positives.
256 // Because it's impossible to figure out the array sizes, we can only unpoison
257 // the first sizeof(type) bytes for each type* pointer.
258 // The instrumentation is only enabled in KMSAN builds, and only if
259 // -msan-handle-asm-conservative is on. This is done because we may want to
260 // quickly disable assembly instrumentation when it breaks.
261 static cl::opt<bool> ClHandleAsmConservative(
262     "msan-handle-asm-conservative",
263     cl::desc("conservative handling of inline assembly"), cl::Hidden,
264     cl::init(true));
265 
266 // This flag controls whether we check the shadow of the address
267 // operand of load or store. Such bugs are very rare, since load from
268 // a garbage address typically results in SEGV, but still happen
269 // (e.g. only lower bits of address are garbage, or the access happens
270 // early at program startup where malloc-ed memory is more likely to
271 // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
272 static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
273        cl::desc("report accesses through a pointer which has poisoned shadow"),
274        cl::Hidden, cl::init(true));
275 
276 static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
277        cl::desc("print out instructions with default strict semantics"),
278        cl::Hidden, cl::init(false));
279 
280 static cl::opt<int> ClInstrumentationWithCallThreshold(
281     "msan-instrumentation-with-call-threshold",
282     cl::desc(
283         "If the function being instrumented requires more than "
284         "this number of checks and origin stores, use callbacks instead of "
285         "inline checks (-1 means never use callbacks)."),
286     cl::Hidden, cl::init(3500));
287 
288 static cl::opt<bool>
289     ClEnableKmsan("msan-kernel",
290                   cl::desc("Enable KernelMemorySanitizer instrumentation"),
291                   cl::Hidden, cl::init(false));
292 
293 // This is an experiment to enable handling of cases where shadow is a non-zero
294 // compile-time constant. For some unexplainable reason they were silently
295 // ignored in the instrumentation.
296 static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
297        cl::desc("Insert checks for constant shadow values"),
298        cl::Hidden, cl::init(false));
299 
300 // This is off by default because of a bug in gold:
301 // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
302 static cl::opt<bool> ClWithComdat("msan-with-comdat",
303        cl::desc("Place MSan constructors in comdat sections"),
304        cl::Hidden, cl::init(false));
305 
306 // These options allow to specify custom memory map parameters
307 // See MemoryMapParams for details.
308 static cl::opt<unsigned long long> ClAndMask("msan-and-mask",
309        cl::desc("Define custom MSan AndMask"),
310        cl::Hidden, cl::init(0));
311 
312 static cl::opt<unsigned long long> ClXorMask("msan-xor-mask",
313        cl::desc("Define custom MSan XorMask"),
314        cl::Hidden, cl::init(0));
315 
316 static cl::opt<unsigned long long> ClShadowBase("msan-shadow-base",
317        cl::desc("Define custom MSan ShadowBase"),
318        cl::Hidden, cl::init(0));
319 
320 static cl::opt<unsigned long long> ClOriginBase("msan-origin-base",
321        cl::desc("Define custom MSan OriginBase"),
322        cl::Hidden, cl::init(0));
323 
324 static const char *const kMsanInitName = "__msan_init";
325 
326 namespace {
327 
328 // Memory map parameters used in application-to-shadow address calculation.
329 // Offset = (Addr & ~AndMask) ^ XorMask
330 // Shadow = ShadowBase + Offset
331 // Origin = OriginBase + Offset
332 struct MemoryMapParams {
333   uint64_t AndMask;
334   uint64_t XorMask;
335   uint64_t ShadowBase;
336   uint64_t OriginBase;
337 };
338 
339 struct PlatformMemoryMapParams {
340   const MemoryMapParams *bits32;
341   const MemoryMapParams *bits64;
342 };
343 
344 } // end anonymous namespace
345 
346 // i386 Linux
347 static const MemoryMapParams Linux_I386_MemoryMapParams = {
348   0x000080000000,  // AndMask
349   0,               // XorMask (not used)
350   0,               // ShadowBase (not used)
351   0x000040000000,  // OriginBase
352 };
353 
354 // x86_64 Linux
355 static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
356 #ifdef MSAN_LINUX_X86_64_OLD_MAPPING
357   0x400000000000,  // AndMask
358   0,               // XorMask (not used)
359   0,               // ShadowBase (not used)
360   0x200000000000,  // OriginBase
361 #else
362   0,               // AndMask (not used)
363   0x500000000000,  // XorMask
364   0,               // ShadowBase (not used)
365   0x100000000000,  // OriginBase
366 #endif
367 };
368 
369 // mips64 Linux
370 static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
371   0,               // AndMask (not used)
372   0x008000000000,  // XorMask
373   0,               // ShadowBase (not used)
374   0x002000000000,  // OriginBase
375 };
376 
377 // ppc64 Linux
378 static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
379   0xE00000000000,  // AndMask
380   0x100000000000,  // XorMask
381   0x080000000000,  // ShadowBase
382   0x1C0000000000,  // OriginBase
383 };
384 
385 // aarch64 Linux
386 static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
387   0,               // AndMask (not used)
388   0x06000000000,   // XorMask
389   0,               // ShadowBase (not used)
390   0x01000000000,   // OriginBase
391 };
392 
393 // i386 FreeBSD
394 static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
395   0x000180000000,  // AndMask
396   0x000040000000,  // XorMask
397   0x000020000000,  // ShadowBase
398   0x000700000000,  // OriginBase
399 };
400 
401 // x86_64 FreeBSD
402 static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
403   0xc00000000000,  // AndMask
404   0x200000000000,  // XorMask
405   0x100000000000,  // ShadowBase
406   0x380000000000,  // OriginBase
407 };
408 
409 // x86_64 NetBSD
410 static const MemoryMapParams NetBSD_X86_64_MemoryMapParams = {
411   0,               // AndMask
412   0x500000000000,  // XorMask
413   0,               // ShadowBase
414   0x100000000000,  // OriginBase
415 };
416 
417 static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
418   &Linux_I386_MemoryMapParams,
419   &Linux_X86_64_MemoryMapParams,
420 };
421 
422 static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
423   nullptr,
424   &Linux_MIPS64_MemoryMapParams,
425 };
426 
427 static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
428   nullptr,
429   &Linux_PowerPC64_MemoryMapParams,
430 };
431 
432 static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
433   nullptr,
434   &Linux_AArch64_MemoryMapParams,
435 };
436 
437 static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
438   &FreeBSD_I386_MemoryMapParams,
439   &FreeBSD_X86_64_MemoryMapParams,
440 };
441 
442 static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams = {
443   nullptr,
444   &NetBSD_X86_64_MemoryMapParams,
445 };
446 
447 namespace {
448 
449 /// Instrument functions of a module to detect uninitialized reads.
450 ///
451 /// Instantiating MemorySanitizer inserts the msan runtime library API function
452 /// declarations into the module if they don't exist already. Instantiating
453 /// ensures the __msan_init function is in the list of global constructors for
454 /// the module.
455 class MemorySanitizer {
456 public:
457   MemorySanitizer(Module &M, int TrackOrigins = 0, bool Recover = false,
458                   bool EnableKmsan = false) {
459     this->CompileKernel =
460         ClEnableKmsan.getNumOccurrences() > 0 ? ClEnableKmsan : EnableKmsan;
461     if (ClTrackOrigins.getNumOccurrences() > 0)
462       this->TrackOrigins = ClTrackOrigins;
463     else
464       this->TrackOrigins = this->CompileKernel ? 2 : TrackOrigins;
465     this->Recover = ClKeepGoing.getNumOccurrences() > 0
466                         ? ClKeepGoing
467                         : (this->CompileKernel | Recover);
468     initializeModule(M);
469   }
470 
471   // MSan cannot be moved or copied because of MapParams.
472   MemorySanitizer(MemorySanitizer &&) = delete;
473   MemorySanitizer &operator=(MemorySanitizer &&) = delete;
474   MemorySanitizer(const MemorySanitizer &) = delete;
475   MemorySanitizer &operator=(const MemorySanitizer &) = delete;
476 
477   bool sanitizeFunction(Function &F, TargetLibraryInfo &TLI);
478 
479 private:
480   friend struct MemorySanitizerVisitor;
481   friend struct VarArgAMD64Helper;
482   friend struct VarArgMIPS64Helper;
483   friend struct VarArgAArch64Helper;
484   friend struct VarArgPowerPC64Helper;
485 
486   void initializeModule(Module &M);
487   void initializeCallbacks(Module &M);
488   void createKernelApi(Module &M);
489   void createUserspaceApi(Module &M);
490 
491   /// True if we're compiling the Linux kernel.
492   bool CompileKernel;
493   /// Track origins (allocation points) of uninitialized values.
494   int TrackOrigins;
495   bool Recover;
496 
497   LLVMContext *C;
498   Type *IntptrTy;
499   Type *OriginTy;
500 
501   // XxxTLS variables represent the per-thread state in MSan and per-task state
502   // in KMSAN.
503   // For the userspace these point to thread-local globals. In the kernel land
504   // they point to the members of a per-task struct obtained via a call to
505   // __msan_get_context_state().
506 
507   /// Thread-local shadow storage for function parameters.
508   Value *ParamTLS;
509 
510   /// Thread-local origin storage for function parameters.
511   Value *ParamOriginTLS;
512 
513   /// Thread-local shadow storage for function return value.
514   Value *RetvalTLS;
515 
516   /// Thread-local origin storage for function return value.
517   Value *RetvalOriginTLS;
518 
519   /// Thread-local shadow storage for in-register va_arg function
520   /// parameters (x86_64-specific).
521   Value *VAArgTLS;
522 
523   /// Thread-local shadow storage for in-register va_arg function
524   /// parameters (x86_64-specific).
525   Value *VAArgOriginTLS;
526 
527   /// Thread-local shadow storage for va_arg overflow area
528   /// (x86_64-specific).
529   Value *VAArgOverflowSizeTLS;
530 
531   /// Thread-local space used to pass origin value to the UMR reporting
532   /// function.
533   Value *OriginTLS;
534 
535   /// Are the instrumentation callbacks set up?
536   bool CallbacksInitialized = false;
537 
538   /// The run-time callback to print a warning.
539   Value *WarningFn;
540 
541   // These arrays are indexed by log2(AccessSize).
542   Value *MaybeWarningFn[kNumberOfAccessSizes];
543   Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
544 
545   /// Run-time helper that generates a new origin value for a stack
546   /// allocation.
547   Value *MsanSetAllocaOrigin4Fn;
548 
549   /// Run-time helper that poisons stack on function entry.
550   Value *MsanPoisonStackFn;
551 
552   /// Run-time helper that records a store (or any event) of an
553   /// uninitialized value and returns an updated origin id encoding this info.
554   Value *MsanChainOriginFn;
555 
556   /// MSan runtime replacements for memmove, memcpy and memset.
557   Value *MemmoveFn, *MemcpyFn, *MemsetFn;
558 
559   /// KMSAN callback for task-local function argument shadow.
560   Value *MsanGetContextStateFn;
561 
562   /// Functions for poisoning/unpoisoning local variables
563   Value *MsanPoisonAllocaFn, *MsanUnpoisonAllocaFn;
564 
565   /// Each of the MsanMetadataPtrXxx functions returns a pair of shadow/origin
566   /// pointers.
567   Value *MsanMetadataPtrForLoadN, *MsanMetadataPtrForStoreN;
568   Value *MsanMetadataPtrForLoad_1_8[4];
569   Value *MsanMetadataPtrForStore_1_8[4];
570   Value *MsanInstrumentAsmStoreFn;
571 
572   /// Helper to choose between different MsanMetadataPtrXxx().
573   Value *getKmsanShadowOriginAccessFn(bool isStore, int size);
574 
575   /// Memory map parameters used in application-to-shadow calculation.
576   const MemoryMapParams *MapParams;
577 
578   /// Custom memory map parameters used when -msan-shadow-base or
579   // -msan-origin-base is provided.
580   MemoryMapParams CustomMapParams;
581 
582   MDNode *ColdCallWeights;
583 
584   /// Branch weights for origin store.
585   MDNode *OriginStoreWeights;
586 
587   /// An empty volatile inline asm that prevents callback merge.
588   InlineAsm *EmptyAsm;
589 };
590 
591 /// A legacy function pass for msan instrumentation.
592 ///
593 /// Instruments functions to detect unitialized reads.
594 struct MemorySanitizerLegacyPass : public FunctionPass {
595   // Pass identification, replacement for typeid.
596   static char ID;
597 
598   MemorySanitizerLegacyPass(int TrackOrigins = 0, bool Recover = false,
599                             bool EnableKmsan = false)
600       : FunctionPass(ID), TrackOrigins(TrackOrigins), Recover(Recover),
601         EnableKmsan(EnableKmsan) {}
602   StringRef getPassName() const override { return "MemorySanitizerLegacyPass"; }
603 
604   void getAnalysisUsage(AnalysisUsage &AU) const override {
605     AU.addRequired<TargetLibraryInfoWrapperPass>();
606   }
607 
608   bool runOnFunction(Function &F) override {
609     return MSan->sanitizeFunction(
610         F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI());
611   }
612   bool doInitialization(Module &M) override;
613 
614   Optional<MemorySanitizer> MSan;
615   int TrackOrigins;
616   bool Recover;
617   bool EnableKmsan;
618 };
619 
620 } // end anonymous namespace
621 
622 PreservedAnalyses MemorySanitizerPass::run(Function &F,
623                                            FunctionAnalysisManager &FAM) {
624   MemorySanitizer Msan(*F.getParent(), TrackOrigins, Recover, EnableKmsan);
625   if (Msan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)))
626     return PreservedAnalyses::none();
627   return PreservedAnalyses::all();
628 }
629 
630 char MemorySanitizerLegacyPass::ID = 0;
631 
632 INITIALIZE_PASS_BEGIN(MemorySanitizerLegacyPass, "msan",
633                       "MemorySanitizer: detects uninitialized reads.", false,
634                       false)
635 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
636 INITIALIZE_PASS_END(MemorySanitizerLegacyPass, "msan",
637                     "MemorySanitizer: detects uninitialized reads.", false,
638                     false)
639 
640 FunctionPass *llvm::createMemorySanitizerLegacyPassPass(int TrackOrigins,
641                                                         bool Recover,
642                                                         bool CompileKernel) {
643   return new MemorySanitizerLegacyPass(TrackOrigins, Recover, CompileKernel);
644 }
645 
646 /// Create a non-const global initialized with the given string.
647 ///
648 /// Creates a writable global for Str so that we can pass it to the
649 /// run-time lib. Runtime uses first 4 bytes of the string to store the
650 /// frame ID, so the string needs to be mutable.
651 static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
652                                                             StringRef Str) {
653   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
654   return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
655                             GlobalValue::PrivateLinkage, StrConst, "");
656 }
657 
658 /// Create KMSAN API callbacks.
659 void MemorySanitizer::createKernelApi(Module &M) {
660   IRBuilder<> IRB(*C);
661 
662   // These will be initialized in insertKmsanPrologue().
663   RetvalTLS = nullptr;
664   RetvalOriginTLS = nullptr;
665   ParamTLS = nullptr;
666   ParamOriginTLS = nullptr;
667   VAArgTLS = nullptr;
668   VAArgOriginTLS = nullptr;
669   VAArgOverflowSizeTLS = nullptr;
670   // OriginTLS is unused in the kernel.
671   OriginTLS = nullptr;
672 
673   // __msan_warning() in the kernel takes an origin.
674   WarningFn = M.getOrInsertFunction("__msan_warning", IRB.getVoidTy(),
675                                     IRB.getInt32Ty());
676   // Requests the per-task context state (kmsan_context_state*) from the
677   // runtime library.
678   MsanGetContextStateFn = M.getOrInsertFunction(
679       "__msan_get_context_state",
680       PointerType::get(
681           StructType::get(ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
682                           ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8),
683                           ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8),
684                           ArrayType::get(IRB.getInt64Ty(),
685                                          kParamTLSSize / 8), /* va_arg_origin */
686                           IRB.getInt64Ty(),
687                           ArrayType::get(OriginTy, kParamTLSSize / 4), OriginTy,
688                           OriginTy),
689           0));
690 
691   Type *RetTy = StructType::get(PointerType::get(IRB.getInt8Ty(), 0),
692                                 PointerType::get(IRB.getInt32Ty(), 0));
693 
694   for (int ind = 0, size = 1; ind < 4; ind++, size <<= 1) {
695     std::string name_load =
696         "__msan_metadata_ptr_for_load_" + std::to_string(size);
697     std::string name_store =
698         "__msan_metadata_ptr_for_store_" + std::to_string(size);
699     MsanMetadataPtrForLoad_1_8[ind] = M.getOrInsertFunction(
700         name_load, RetTy, PointerType::get(IRB.getInt8Ty(), 0));
701     MsanMetadataPtrForStore_1_8[ind] = M.getOrInsertFunction(
702         name_store, RetTy, PointerType::get(IRB.getInt8Ty(), 0));
703   }
704 
705   MsanMetadataPtrForLoadN = M.getOrInsertFunction(
706       "__msan_metadata_ptr_for_load_n", RetTy,
707       PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty());
708   MsanMetadataPtrForStoreN = M.getOrInsertFunction(
709       "__msan_metadata_ptr_for_store_n", RetTy,
710       PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty());
711 
712   // Functions for poisoning and unpoisoning memory.
713   MsanPoisonAllocaFn =
714       M.getOrInsertFunction("__msan_poison_alloca", IRB.getVoidTy(),
715                             IRB.getInt8PtrTy(), IntptrTy, IRB.getInt8PtrTy());
716   MsanUnpoisonAllocaFn = M.getOrInsertFunction(
717       "__msan_unpoison_alloca", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy);
718 }
719 
720 static Constant *getOrInsertGlobal(Module &M, StringRef Name, Type *Ty) {
721   return M.getOrInsertGlobal(Name, Ty, [&] {
722     return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage,
723                               nullptr, Name, nullptr,
724                               GlobalVariable::InitialExecTLSModel);
725   });
726 }
727 
728 /// Insert declarations for userspace-specific functions and globals.
729 void MemorySanitizer::createUserspaceApi(Module &M) {
730   IRBuilder<> IRB(*C);
731   // Create the callback.
732   // FIXME: this function should have "Cold" calling conv,
733   // which is not yet implemented.
734   StringRef WarningFnName = Recover ? "__msan_warning"
735                                     : "__msan_warning_noreturn";
736   WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy());
737 
738   // Create the global TLS variables.
739   RetvalTLS =
740       getOrInsertGlobal(M, "__msan_retval_tls",
741                         ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8));
742 
743   RetvalOriginTLS = getOrInsertGlobal(M, "__msan_retval_origin_tls", OriginTy);
744 
745   ParamTLS =
746       getOrInsertGlobal(M, "__msan_param_tls",
747                         ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
748 
749   ParamOriginTLS =
750       getOrInsertGlobal(M, "__msan_param_origin_tls",
751                         ArrayType::get(OriginTy, kParamTLSSize / 4));
752 
753   VAArgTLS =
754       getOrInsertGlobal(M, "__msan_va_arg_tls",
755                         ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8));
756 
757   VAArgOriginTLS =
758       getOrInsertGlobal(M, "__msan_va_arg_origin_tls",
759                         ArrayType::get(OriginTy, kParamTLSSize / 4));
760 
761   VAArgOverflowSizeTLS =
762       getOrInsertGlobal(M, "__msan_va_arg_overflow_size_tls", IRB.getInt64Ty());
763   OriginTLS = getOrInsertGlobal(M, "__msan_origin_tls", IRB.getInt32Ty());
764 
765   for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
766        AccessSizeIndex++) {
767     unsigned AccessSize = 1 << AccessSizeIndex;
768     std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
769     MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
770         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
771         IRB.getInt32Ty());
772 
773     FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
774     MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
775         FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
776         IRB.getInt8PtrTy(), IRB.getInt32Ty());
777   }
778 
779   MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
780     "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
781     IRB.getInt8PtrTy(), IntptrTy);
782   MsanPoisonStackFn =
783       M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
784                             IRB.getInt8PtrTy(), IntptrTy);
785 }
786 
787 /// Insert extern declaration of runtime-provided functions and globals.
788 void MemorySanitizer::initializeCallbacks(Module &M) {
789   // Only do this once.
790   if (CallbacksInitialized)
791     return;
792 
793   IRBuilder<> IRB(*C);
794   // Initialize callbacks that are common for kernel and userspace
795   // instrumentation.
796   MsanChainOriginFn = M.getOrInsertFunction(
797     "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty());
798   MemmoveFn = M.getOrInsertFunction(
799     "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
800     IRB.getInt8PtrTy(), IntptrTy);
801   MemcpyFn = M.getOrInsertFunction(
802     "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
803     IntptrTy);
804   MemsetFn = M.getOrInsertFunction(
805     "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
806     IntptrTy);
807   // We insert an empty inline asm after __msan_report* to avoid callback merge.
808   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
809                             StringRef(""), StringRef(""),
810                             /*hasSideEffects=*/true);
811 
812   MsanInstrumentAsmStoreFn =
813       M.getOrInsertFunction("__msan_instrument_asm_store", IRB.getVoidTy(),
814                             PointerType::get(IRB.getInt8Ty(), 0), IntptrTy);
815 
816   if (CompileKernel) {
817     createKernelApi(M);
818   } else {
819     createUserspaceApi(M);
820   }
821   CallbacksInitialized = true;
822 }
823 
824 Value *MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore, int size) {
825   Value **Fns =
826       isStore ? MsanMetadataPtrForStore_1_8 : MsanMetadataPtrForLoad_1_8;
827   switch (size) {
828   case 1:
829     return Fns[0];
830   case 2:
831     return Fns[1];
832   case 4:
833     return Fns[2];
834   case 8:
835     return Fns[3];
836   default:
837     return nullptr;
838   }
839 }
840 
841 /// Module-level initialization.
842 void MemorySanitizer::initializeModule(Module &M) {
843   auto &DL = M.getDataLayout();
844 
845   bool ShadowPassed = ClShadowBase.getNumOccurrences() > 0;
846   bool OriginPassed = ClOriginBase.getNumOccurrences() > 0;
847   // Check the overrides first
848   if (ShadowPassed || OriginPassed) {
849     CustomMapParams.AndMask = ClAndMask;
850     CustomMapParams.XorMask = ClXorMask;
851     CustomMapParams.ShadowBase = ClShadowBase;
852     CustomMapParams.OriginBase = ClOriginBase;
853     MapParams = &CustomMapParams;
854   } else {
855     Triple TargetTriple(M.getTargetTriple());
856     switch (TargetTriple.getOS()) {
857       case Triple::FreeBSD:
858         switch (TargetTriple.getArch()) {
859           case Triple::x86_64:
860             MapParams = FreeBSD_X86_MemoryMapParams.bits64;
861             break;
862           case Triple::x86:
863             MapParams = FreeBSD_X86_MemoryMapParams.bits32;
864             break;
865           default:
866             report_fatal_error("unsupported architecture");
867         }
868         break;
869       case Triple::NetBSD:
870         switch (TargetTriple.getArch()) {
871           case Triple::x86_64:
872             MapParams = NetBSD_X86_MemoryMapParams.bits64;
873             break;
874           default:
875             report_fatal_error("unsupported architecture");
876         }
877         break;
878       case Triple::Linux:
879         switch (TargetTriple.getArch()) {
880           case Triple::x86_64:
881             MapParams = Linux_X86_MemoryMapParams.bits64;
882             break;
883           case Triple::x86:
884             MapParams = Linux_X86_MemoryMapParams.bits32;
885             break;
886           case Triple::mips64:
887           case Triple::mips64el:
888             MapParams = Linux_MIPS_MemoryMapParams.bits64;
889             break;
890           case Triple::ppc64:
891           case Triple::ppc64le:
892             MapParams = Linux_PowerPC_MemoryMapParams.bits64;
893             break;
894           case Triple::aarch64:
895           case Triple::aarch64_be:
896             MapParams = Linux_ARM_MemoryMapParams.bits64;
897             break;
898           default:
899             report_fatal_error("unsupported architecture");
900         }
901         break;
902       default:
903         report_fatal_error("unsupported operating system");
904     }
905   }
906 
907   C = &(M.getContext());
908   IRBuilder<> IRB(*C);
909   IntptrTy = IRB.getIntPtrTy(DL);
910   OriginTy = IRB.getInt32Ty();
911 
912   ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
913   OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
914 
915   if (!CompileKernel) {
916     getOrCreateInitFunction(M, kMsanInitName);
917 
918     if (TrackOrigins)
919       M.getOrInsertGlobal("__msan_track_origins", IRB.getInt32Ty(), [&] {
920         return new GlobalVariable(
921             M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
922             IRB.getInt32(TrackOrigins), "__msan_track_origins");
923       });
924 
925     if (Recover)
926       M.getOrInsertGlobal("__msan_keep_going", IRB.getInt32Ty(), [&] {
927         return new GlobalVariable(M, IRB.getInt32Ty(), true,
928                                   GlobalValue::WeakODRLinkage,
929                                   IRB.getInt32(Recover), "__msan_keep_going");
930       });
931 }
932 }
933 
934 bool MemorySanitizerLegacyPass::doInitialization(Module &M) {
935   MSan.emplace(M, TrackOrigins, Recover, EnableKmsan);
936   return true;
937 }
938 
939 namespace {
940 
941 /// A helper class that handles instrumentation of VarArg
942 /// functions on a particular platform.
943 ///
944 /// Implementations are expected to insert the instrumentation
945 /// necessary to propagate argument shadow through VarArg function
946 /// calls. Visit* methods are called during an InstVisitor pass over
947 /// the function, and should avoid creating new basic blocks. A new
948 /// instance of this class is created for each instrumented function.
949 struct VarArgHelper {
950   virtual ~VarArgHelper() = default;
951 
952   /// Visit a CallSite.
953   virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
954 
955   /// Visit a va_start call.
956   virtual void visitVAStartInst(VAStartInst &I) = 0;
957 
958   /// Visit a va_copy call.
959   virtual void visitVACopyInst(VACopyInst &I) = 0;
960 
961   /// Finalize function instrumentation.
962   ///
963   /// This method is called after visiting all interesting (see above)
964   /// instructions in a function.
965   virtual void finalizeInstrumentation() = 0;
966 };
967 
968 struct MemorySanitizerVisitor;
969 
970 } // end anonymous namespace
971 
972 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
973                                         MemorySanitizerVisitor &Visitor);
974 
975 static unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
976   if (TypeSize <= 8) return 0;
977   return Log2_32_Ceil((TypeSize + 7) / 8);
978 }
979 
980 namespace {
981 
982 /// This class does all the work for a given function. Store and Load
983 /// instructions store and load corresponding shadow and origin
984 /// values. Most instructions propagate shadow from arguments to their
985 /// return values. Certain instructions (most importantly, BranchInst)
986 /// test their argument shadow and print reports (with a runtime call) if it's
987 /// non-zero.
988 struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
989   Function &F;
990   MemorySanitizer &MS;
991   SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
992   ValueMap<Value*, Value*> ShadowMap, OriginMap;
993   std::unique_ptr<VarArgHelper> VAHelper;
994   const TargetLibraryInfo *TLI;
995   BasicBlock *ActualFnStart;
996 
997   // The following flags disable parts of MSan instrumentation based on
998   // blacklist contents and command-line options.
999   bool InsertChecks;
1000   bool PropagateShadow;
1001   bool PoisonStack;
1002   bool PoisonUndef;
1003   bool CheckReturnValue;
1004 
1005   struct ShadowOriginAndInsertPoint {
1006     Value *Shadow;
1007     Value *Origin;
1008     Instruction *OrigIns;
1009 
1010     ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
1011       : Shadow(S), Origin(O), OrigIns(I) {}
1012   };
1013   SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
1014   SmallVector<StoreInst *, 16> StoreList;
1015 
1016   MemorySanitizerVisitor(Function &F, MemorySanitizer &MS,
1017                          const TargetLibraryInfo &TLI)
1018       : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)), TLI(&TLI) {
1019     bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
1020     InsertChecks = SanitizeFunction;
1021     PropagateShadow = SanitizeFunction;
1022     PoisonStack = SanitizeFunction && ClPoisonStack;
1023     PoisonUndef = SanitizeFunction && ClPoisonUndef;
1024     // FIXME: Consider using SpecialCaseList to specify a list of functions that
1025     // must always return fully initialized values. For now, we hardcode "main".
1026     CheckReturnValue = SanitizeFunction && (F.getName() == "main");
1027 
1028     MS.initializeCallbacks(*F.getParent());
1029     if (MS.CompileKernel)
1030       ActualFnStart = insertKmsanPrologue(F);
1031     else
1032       ActualFnStart = &F.getEntryBlock();
1033 
1034     LLVM_DEBUG(if (!InsertChecks) dbgs()
1035                << "MemorySanitizer is not inserting checks into '"
1036                << F.getName() << "'\n");
1037   }
1038 
1039   Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
1040     if (MS.TrackOrigins <= 1) return V;
1041     return IRB.CreateCall(MS.MsanChainOriginFn, V);
1042   }
1043 
1044   Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
1045     const DataLayout &DL = F.getParent()->getDataLayout();
1046     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1047     if (IntptrSize == kOriginSize) return Origin;
1048     assert(IntptrSize == kOriginSize * 2);
1049     Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
1050     return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
1051   }
1052 
1053   /// Fill memory range with the given origin value.
1054   void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
1055                    unsigned Size, unsigned Alignment) {
1056     const DataLayout &DL = F.getParent()->getDataLayout();
1057     unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
1058     unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
1059     assert(IntptrAlignment >= kMinOriginAlignment);
1060     assert(IntptrSize >= kOriginSize);
1061 
1062     unsigned Ofs = 0;
1063     unsigned CurrentAlignment = Alignment;
1064     if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
1065       Value *IntptrOrigin = originToIntptr(IRB, Origin);
1066       Value *IntptrOriginPtr =
1067           IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
1068       for (unsigned i = 0; i < Size / IntptrSize; ++i) {
1069         Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
1070                        : IntptrOriginPtr;
1071         IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
1072         Ofs += IntptrSize / kOriginSize;
1073         CurrentAlignment = IntptrAlignment;
1074       }
1075     }
1076 
1077     for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
1078       Value *GEP =
1079           i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
1080       IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
1081       CurrentAlignment = kMinOriginAlignment;
1082     }
1083   }
1084 
1085   void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
1086                    Value *OriginPtr, unsigned Alignment, bool AsCall) {
1087     const DataLayout &DL = F.getParent()->getDataLayout();
1088     unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1089     unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
1090     if (Shadow->getType()->isAggregateType()) {
1091       paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1092                   OriginAlignment);
1093     } else {
1094       Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
1095       Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
1096       if (ConstantShadow) {
1097         if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
1098           paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize,
1099                       OriginAlignment);
1100         return;
1101       }
1102 
1103       unsigned TypeSizeInBits =
1104           DL.getTypeSizeInBits(ConvertedShadow->getType());
1105       unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1106       if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1107         Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
1108         Value *ConvertedShadow2 = IRB.CreateZExt(
1109             ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1110         IRB.CreateCall(Fn, {ConvertedShadow2,
1111                             IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
1112                             Origin});
1113       } else {
1114         Value *Cmp = IRB.CreateICmpNE(
1115             ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
1116         Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1117             Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
1118         IRBuilder<> IRBNew(CheckTerm);
1119         paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), OriginPtr, StoreSize,
1120                     OriginAlignment);
1121       }
1122     }
1123   }
1124 
1125   void materializeStores(bool InstrumentWithCalls) {
1126     for (StoreInst *SI : StoreList) {
1127       IRBuilder<> IRB(SI);
1128       Value *Val = SI->getValueOperand();
1129       Value *Addr = SI->getPointerOperand();
1130       Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val);
1131       Value *ShadowPtr, *OriginPtr;
1132       Type *ShadowTy = Shadow->getType();
1133       unsigned Alignment = SI->getAlignment();
1134       unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1135       std::tie(ShadowPtr, OriginPtr) =
1136           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ true);
1137 
1138       StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, Alignment);
1139       LLVM_DEBUG(dbgs() << "  STORE: " << *NewSI << "\n");
1140       (void)NewSI;
1141 
1142       if (SI->isAtomic())
1143         SI->setOrdering(addReleaseOrdering(SI->getOrdering()));
1144 
1145       if (MS.TrackOrigins && !SI->isAtomic())
1146         storeOrigin(IRB, Addr, Shadow, getOrigin(Val), OriginPtr,
1147                     OriginAlignment, InstrumentWithCalls);
1148     }
1149   }
1150 
1151   /// Helper function to insert a warning at IRB's current insert point.
1152   void insertWarningFn(IRBuilder<> &IRB, Value *Origin) {
1153     if (!Origin)
1154       Origin = (Value *)IRB.getInt32(0);
1155     if (MS.CompileKernel) {
1156       IRB.CreateCall(MS.WarningFn, Origin);
1157     } else {
1158       if (MS.TrackOrigins) {
1159         IRB.CreateStore(Origin, MS.OriginTLS);
1160       }
1161       IRB.CreateCall(MS.WarningFn, {});
1162     }
1163     IRB.CreateCall(MS.EmptyAsm, {});
1164     // FIXME: Insert UnreachableInst if !MS.Recover?
1165     // This may invalidate some of the following checks and needs to be done
1166     // at the very end.
1167   }
1168 
1169   void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
1170                            bool AsCall) {
1171     IRBuilder<> IRB(OrigIns);
1172     LLVM_DEBUG(dbgs() << "  SHAD0 : " << *Shadow << "\n");
1173     Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
1174     LLVM_DEBUG(dbgs() << "  SHAD1 : " << *ConvertedShadow << "\n");
1175 
1176     Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
1177     if (ConstantShadow) {
1178       if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
1179         insertWarningFn(IRB, Origin);
1180       }
1181       return;
1182     }
1183 
1184     const DataLayout &DL = OrigIns->getModule()->getDataLayout();
1185 
1186     unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
1187     unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
1188     if (AsCall && SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) {
1189       Value *Fn = MS.MaybeWarningFn[SizeIndex];
1190       Value *ConvertedShadow2 =
1191           IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
1192       IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
1193                                                 ? Origin
1194                                                 : (Value *)IRB.getInt32(0)});
1195     } else {
1196       Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
1197                                     getCleanShadow(ConvertedShadow), "_mscmp");
1198       Instruction *CheckTerm = SplitBlockAndInsertIfThen(
1199           Cmp, OrigIns,
1200           /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
1201 
1202       IRB.SetInsertPoint(CheckTerm);
1203       insertWarningFn(IRB, Origin);
1204       LLVM_DEBUG(dbgs() << "  CHECK: " << *Cmp << "\n");
1205     }
1206   }
1207 
1208   void materializeChecks(bool InstrumentWithCalls) {
1209     for (const auto &ShadowData : InstrumentationList) {
1210       Instruction *OrigIns = ShadowData.OrigIns;
1211       Value *Shadow = ShadowData.Shadow;
1212       Value *Origin = ShadowData.Origin;
1213       materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
1214     }
1215     LLVM_DEBUG(dbgs() << "DONE:\n" << F);
1216   }
1217 
1218   BasicBlock *insertKmsanPrologue(Function &F) {
1219     BasicBlock *ret =
1220         SplitBlock(&F.getEntryBlock(), F.getEntryBlock().getFirstNonPHI());
1221     IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
1222     Value *ContextState = IRB.CreateCall(MS.MsanGetContextStateFn, {});
1223     Constant *Zero = IRB.getInt32(0);
1224     MS.ParamTLS =
1225         IRB.CreateGEP(ContextState, {Zero, IRB.getInt32(0)}, "param_shadow");
1226     MS.RetvalTLS =
1227         IRB.CreateGEP(ContextState, {Zero, IRB.getInt32(1)}, "retval_shadow");
1228     MS.VAArgTLS =
1229         IRB.CreateGEP(ContextState, {Zero, IRB.getInt32(2)}, "va_arg_shadow");
1230     MS.VAArgOriginTLS =
1231         IRB.CreateGEP(ContextState, {Zero, IRB.getInt32(3)}, "va_arg_origin");
1232     MS.VAArgOverflowSizeTLS = IRB.CreateGEP(
1233         ContextState, {Zero, IRB.getInt32(4)}, "va_arg_overflow_size");
1234     MS.ParamOriginTLS =
1235         IRB.CreateGEP(ContextState, {Zero, IRB.getInt32(5)}, "param_origin");
1236     MS.RetvalOriginTLS =
1237         IRB.CreateGEP(ContextState, {Zero, IRB.getInt32(6)}, "retval_origin");
1238     return ret;
1239   }
1240 
1241   /// Add MemorySanitizer instrumentation to a function.
1242   bool runOnFunction() {
1243     // In the presence of unreachable blocks, we may see Phi nodes with
1244     // incoming nodes from such blocks. Since InstVisitor skips unreachable
1245     // blocks, such nodes will not have any shadow value associated with them.
1246     // It's easier to remove unreachable blocks than deal with missing shadow.
1247     removeUnreachableBlocks(F);
1248 
1249     // Iterate all BBs in depth-first order and create shadow instructions
1250     // for all instructions (where applicable).
1251     // For PHI nodes we create dummy shadow PHIs which will be finalized later.
1252     for (BasicBlock *BB : depth_first(ActualFnStart))
1253       visit(*BB);
1254 
1255     // Finalize PHI nodes.
1256     for (PHINode *PN : ShadowPHINodes) {
1257       PHINode *PNS = cast<PHINode>(getShadow(PN));
1258       PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
1259       size_t NumValues = PN->getNumIncomingValues();
1260       for (size_t v = 0; v < NumValues; v++) {
1261         PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
1262         if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
1263       }
1264     }
1265 
1266     VAHelper->finalizeInstrumentation();
1267 
1268     bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
1269                                InstrumentationList.size() + StoreList.size() >
1270                                    (unsigned)ClInstrumentationWithCallThreshold;
1271 
1272     // Insert shadow value checks.
1273     materializeChecks(InstrumentWithCalls);
1274 
1275     // Delayed instrumentation of StoreInst.
1276     // This may not add new address checks.
1277     materializeStores(InstrumentWithCalls);
1278 
1279     return true;
1280   }
1281 
1282   /// Compute the shadow type that corresponds to a given Value.
1283   Type *getShadowTy(Value *V) {
1284     return getShadowTy(V->getType());
1285   }
1286 
1287   /// Compute the shadow type that corresponds to a given Type.
1288   Type *getShadowTy(Type *OrigTy) {
1289     if (!OrigTy->isSized()) {
1290       return nullptr;
1291     }
1292     // For integer type, shadow is the same as the original type.
1293     // This may return weird-sized types like i1.
1294     if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
1295       return IT;
1296     const DataLayout &DL = F.getParent()->getDataLayout();
1297     if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
1298       uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
1299       return VectorType::get(IntegerType::get(*MS.C, EltSize),
1300                              VT->getNumElements());
1301     }
1302     if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
1303       return ArrayType::get(getShadowTy(AT->getElementType()),
1304                             AT->getNumElements());
1305     }
1306     if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
1307       SmallVector<Type*, 4> Elements;
1308       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1309         Elements.push_back(getShadowTy(ST->getElementType(i)));
1310       StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
1311       LLVM_DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
1312       return Res;
1313     }
1314     uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
1315     return IntegerType::get(*MS.C, TypeSize);
1316   }
1317 
1318   /// Flatten a vector type.
1319   Type *getShadowTyNoVec(Type *ty) {
1320     if (VectorType *vt = dyn_cast<VectorType>(ty))
1321       return IntegerType::get(*MS.C, vt->getBitWidth());
1322     return ty;
1323   }
1324 
1325   /// Convert a shadow value to it's flattened variant.
1326   Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
1327     Type *Ty = V->getType();
1328     Type *NoVecTy = getShadowTyNoVec(Ty);
1329     if (Ty == NoVecTy) return V;
1330     return IRB.CreateBitCast(V, NoVecTy);
1331   }
1332 
1333   /// Compute the integer shadow offset that corresponds to a given
1334   /// application address.
1335   ///
1336   /// Offset = (Addr & ~AndMask) ^ XorMask
1337   Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
1338     Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy);
1339 
1340     uint64_t AndMask = MS.MapParams->AndMask;
1341     if (AndMask)
1342       OffsetLong =
1343           IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask));
1344 
1345     uint64_t XorMask = MS.MapParams->XorMask;
1346     if (XorMask)
1347       OffsetLong =
1348           IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask));
1349     return OffsetLong;
1350   }
1351 
1352   /// Compute the shadow and origin addresses corresponding to a given
1353   /// application address.
1354   ///
1355   /// Shadow = ShadowBase + Offset
1356   /// Origin = (OriginBase + Offset) & ~3ULL
1357   std::pair<Value *, Value *> getShadowOriginPtrUserspace(Value *Addr,
1358                                                           IRBuilder<> &IRB,
1359                                                           Type *ShadowTy,
1360                                                           unsigned Alignment) {
1361     Value *ShadowOffset = getShadowPtrOffset(Addr, IRB);
1362     Value *ShadowLong = ShadowOffset;
1363     uint64_t ShadowBase = MS.MapParams->ShadowBase;
1364     if (ShadowBase != 0) {
1365       ShadowLong =
1366         IRB.CreateAdd(ShadowLong,
1367                       ConstantInt::get(MS.IntptrTy, ShadowBase));
1368     }
1369     Value *ShadowPtr =
1370         IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
1371     Value *OriginPtr = nullptr;
1372     if (MS.TrackOrigins) {
1373       Value *OriginLong = ShadowOffset;
1374       uint64_t OriginBase = MS.MapParams->OriginBase;
1375       if (OriginBase != 0)
1376         OriginLong = IRB.CreateAdd(OriginLong,
1377                                    ConstantInt::get(MS.IntptrTy, OriginBase));
1378       if (Alignment < kMinOriginAlignment) {
1379         uint64_t Mask = kMinOriginAlignment - 1;
1380         OriginLong =
1381             IRB.CreateAnd(OriginLong, ConstantInt::get(MS.IntptrTy, ~Mask));
1382       }
1383       OriginPtr =
1384           IRB.CreateIntToPtr(OriginLong, PointerType::get(IRB.getInt32Ty(), 0));
1385     }
1386     return std::make_pair(ShadowPtr, OriginPtr);
1387   }
1388 
1389   std::pair<Value *, Value *>
1390   getShadowOriginPtrKernel(Value *Addr, IRBuilder<> &IRB, Type *ShadowTy,
1391                            unsigned Alignment, bool isStore) {
1392     Value *ShadowOriginPtrs;
1393     const DataLayout &DL = F.getParent()->getDataLayout();
1394     int Size = DL.getTypeStoreSize(ShadowTy);
1395 
1396     Value *Getter = MS.getKmsanShadowOriginAccessFn(isStore, Size);
1397     Value *AddrCast =
1398         IRB.CreatePointerCast(Addr, PointerType::get(IRB.getInt8Ty(), 0));
1399     if (Getter) {
1400       ShadowOriginPtrs = IRB.CreateCall(Getter, AddrCast);
1401     } else {
1402       Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
1403       ShadowOriginPtrs = IRB.CreateCall(isStore ? MS.MsanMetadataPtrForStoreN
1404                                                 : MS.MsanMetadataPtrForLoadN,
1405                                         {AddrCast, SizeVal});
1406     }
1407     Value *ShadowPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 0);
1408     ShadowPtr = IRB.CreatePointerCast(ShadowPtr, PointerType::get(ShadowTy, 0));
1409     Value *OriginPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 1);
1410 
1411     return std::make_pair(ShadowPtr, OriginPtr);
1412   }
1413 
1414   std::pair<Value *, Value *> getShadowOriginPtr(Value *Addr, IRBuilder<> &IRB,
1415                                                  Type *ShadowTy,
1416                                                  unsigned Alignment,
1417                                                  bool isStore) {
1418     std::pair<Value *, Value *> ret;
1419     if (MS.CompileKernel)
1420       ret = getShadowOriginPtrKernel(Addr, IRB, ShadowTy, Alignment, isStore);
1421     else
1422       ret = getShadowOriginPtrUserspace(Addr, IRB, ShadowTy, Alignment);
1423     return ret;
1424   }
1425 
1426   /// Compute the shadow address for a given function argument.
1427   ///
1428   /// Shadow = ParamTLS+ArgOffset.
1429   Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
1430                                  int ArgOffset) {
1431     Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
1432     if (ArgOffset)
1433       Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1434     return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
1435                               "_msarg");
1436   }
1437 
1438   /// Compute the origin address for a given function argument.
1439   Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
1440                                  int ArgOffset) {
1441     if (!MS.TrackOrigins)
1442       return nullptr;
1443     Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
1444     if (ArgOffset)
1445       Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
1446     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
1447                               "_msarg_o");
1448   }
1449 
1450   /// Compute the shadow address for a retval.
1451   Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
1452     return IRB.CreatePointerCast(MS.RetvalTLS,
1453                                  PointerType::get(getShadowTy(A), 0),
1454                                  "_msret");
1455   }
1456 
1457   /// Compute the origin address for a retval.
1458   Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
1459     // We keep a single origin for the entire retval. Might be too optimistic.
1460     return MS.RetvalOriginTLS;
1461   }
1462 
1463   /// Set SV to be the shadow value for V.
1464   void setShadow(Value *V, Value *SV) {
1465     assert(!ShadowMap.count(V) && "Values may only have one shadow");
1466     ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
1467   }
1468 
1469   /// Set Origin to be the origin value for V.
1470   void setOrigin(Value *V, Value *Origin) {
1471     if (!MS.TrackOrigins) return;
1472     assert(!OriginMap.count(V) && "Values may only have one origin");
1473     LLVM_DEBUG(dbgs() << "ORIGIN: " << *V << "  ==> " << *Origin << "\n");
1474     OriginMap[V] = Origin;
1475   }
1476 
1477   Constant *getCleanShadow(Type *OrigTy) {
1478     Type *ShadowTy = getShadowTy(OrigTy);
1479     if (!ShadowTy)
1480       return nullptr;
1481     return Constant::getNullValue(ShadowTy);
1482   }
1483 
1484   /// Create a clean shadow value for a given value.
1485   ///
1486   /// Clean shadow (all zeroes) means all bits of the value are defined
1487   /// (initialized).
1488   Constant *getCleanShadow(Value *V) {
1489     return getCleanShadow(V->getType());
1490   }
1491 
1492   /// Create a dirty shadow of a given shadow type.
1493   Constant *getPoisonedShadow(Type *ShadowTy) {
1494     assert(ShadowTy);
1495     if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
1496       return Constant::getAllOnesValue(ShadowTy);
1497     if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
1498       SmallVector<Constant *, 4> Vals(AT->getNumElements(),
1499                                       getPoisonedShadow(AT->getElementType()));
1500       return ConstantArray::get(AT, Vals);
1501     }
1502     if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
1503       SmallVector<Constant *, 4> Vals;
1504       for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
1505         Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
1506       return ConstantStruct::get(ST, Vals);
1507     }
1508     llvm_unreachable("Unexpected shadow type");
1509   }
1510 
1511   /// Create a dirty shadow for a given value.
1512   Constant *getPoisonedShadow(Value *V) {
1513     Type *ShadowTy = getShadowTy(V);
1514     if (!ShadowTy)
1515       return nullptr;
1516     return getPoisonedShadow(ShadowTy);
1517   }
1518 
1519   /// Create a clean (zero) origin.
1520   Value *getCleanOrigin() {
1521     return Constant::getNullValue(MS.OriginTy);
1522   }
1523 
1524   /// Get the shadow value for a given Value.
1525   ///
1526   /// This function either returns the value set earlier with setShadow,
1527   /// or extracts if from ParamTLS (for function arguments).
1528   Value *getShadow(Value *V) {
1529     if (!PropagateShadow) return getCleanShadow(V);
1530     if (Instruction *I = dyn_cast<Instruction>(V)) {
1531       if (I->getMetadata("nosanitize"))
1532         return getCleanShadow(V);
1533       // For instructions the shadow is already stored in the map.
1534       Value *Shadow = ShadowMap[V];
1535       if (!Shadow) {
1536         LLVM_DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
1537         (void)I;
1538         assert(Shadow && "No shadow for a value");
1539       }
1540       return Shadow;
1541     }
1542     if (UndefValue *U = dyn_cast<UndefValue>(V)) {
1543       Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
1544       LLVM_DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
1545       (void)U;
1546       return AllOnes;
1547     }
1548     if (Argument *A = dyn_cast<Argument>(V)) {
1549       // For arguments we compute the shadow on demand and store it in the map.
1550       Value **ShadowPtr = &ShadowMap[V];
1551       if (*ShadowPtr)
1552         return *ShadowPtr;
1553       Function *F = A->getParent();
1554       IRBuilder<> EntryIRB(ActualFnStart->getFirstNonPHI());
1555       unsigned ArgOffset = 0;
1556       const DataLayout &DL = F->getParent()->getDataLayout();
1557       for (auto &FArg : F->args()) {
1558         if (!FArg.getType()->isSized()) {
1559           LLVM_DEBUG(dbgs() << "Arg is not sized\n");
1560           continue;
1561         }
1562         unsigned Size =
1563             FArg.hasByValAttr()
1564                 ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
1565                 : DL.getTypeAllocSize(FArg.getType());
1566         if (A == &FArg) {
1567           bool Overflow = ArgOffset + Size > kParamTLSSize;
1568           Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
1569           if (FArg.hasByValAttr()) {
1570             // ByVal pointer itself has clean shadow. We copy the actual
1571             // argument shadow to the underlying memory.
1572             // Figure out maximal valid memcpy alignment.
1573             unsigned ArgAlign = FArg.getParamAlignment();
1574             if (ArgAlign == 0) {
1575               Type *EltType = A->getType()->getPointerElementType();
1576               ArgAlign = DL.getABITypeAlignment(EltType);
1577             }
1578             Value *CpShadowPtr =
1579                 getShadowOriginPtr(V, EntryIRB, EntryIRB.getInt8Ty(), ArgAlign,
1580                                    /*isStore*/ true)
1581                     .first;
1582             // TODO(glider): need to copy origins.
1583             if (Overflow) {
1584               // ParamTLS overflow.
1585               EntryIRB.CreateMemSet(
1586                   CpShadowPtr, Constant::getNullValue(EntryIRB.getInt8Ty()),
1587                   Size, ArgAlign);
1588             } else {
1589               unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
1590               Value *Cpy = EntryIRB.CreateMemCpy(CpShadowPtr, CopyAlign, Base,
1591                                                  CopyAlign, Size);
1592               LLVM_DEBUG(dbgs() << "  ByValCpy: " << *Cpy << "\n");
1593               (void)Cpy;
1594             }
1595             *ShadowPtr = getCleanShadow(V);
1596           } else {
1597             if (Overflow) {
1598               // ParamTLS overflow.
1599               *ShadowPtr = getCleanShadow(V);
1600             } else {
1601               *ShadowPtr =
1602                   EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
1603             }
1604           }
1605           LLVM_DEBUG(dbgs()
1606                      << "  ARG:    " << FArg << " ==> " << **ShadowPtr << "\n");
1607           if (MS.TrackOrigins && !Overflow) {
1608             Value *OriginPtr =
1609                 getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
1610             setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
1611           } else {
1612             setOrigin(A, getCleanOrigin());
1613           }
1614         }
1615         ArgOffset += alignTo(Size, kShadowTLSAlignment);
1616       }
1617       assert(*ShadowPtr && "Could not find shadow for an argument");
1618       return *ShadowPtr;
1619     }
1620     // For everything else the shadow is zero.
1621     return getCleanShadow(V);
1622   }
1623 
1624   /// Get the shadow for i-th argument of the instruction I.
1625   Value *getShadow(Instruction *I, int i) {
1626     return getShadow(I->getOperand(i));
1627   }
1628 
1629   /// Get the origin for a value.
1630   Value *getOrigin(Value *V) {
1631     if (!MS.TrackOrigins) return nullptr;
1632     if (!PropagateShadow) return getCleanOrigin();
1633     if (isa<Constant>(V)) return getCleanOrigin();
1634     assert((isa<Instruction>(V) || isa<Argument>(V)) &&
1635            "Unexpected value type in getOrigin()");
1636     if (Instruction *I = dyn_cast<Instruction>(V)) {
1637       if (I->getMetadata("nosanitize"))
1638         return getCleanOrigin();
1639     }
1640     Value *Origin = OriginMap[V];
1641     assert(Origin && "Missing origin");
1642     return Origin;
1643   }
1644 
1645   /// Get the origin for i-th argument of the instruction I.
1646   Value *getOrigin(Instruction *I, int i) {
1647     return getOrigin(I->getOperand(i));
1648   }
1649 
1650   /// Remember the place where a shadow check should be inserted.
1651   ///
1652   /// This location will be later instrumented with a check that will print a
1653   /// UMR warning in runtime if the shadow value is not 0.
1654   void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
1655     assert(Shadow);
1656     if (!InsertChecks) return;
1657 #ifndef NDEBUG
1658     Type *ShadowTy = Shadow->getType();
1659     assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
1660            "Can only insert checks for integer and vector shadow types");
1661 #endif
1662     InstrumentationList.push_back(
1663         ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
1664   }
1665 
1666   /// Remember the place where a shadow check should be inserted.
1667   ///
1668   /// This location will be later instrumented with a check that will print a
1669   /// UMR warning in runtime if the value is not fully defined.
1670   void insertShadowCheck(Value *Val, Instruction *OrigIns) {
1671     assert(Val);
1672     Value *Shadow, *Origin;
1673     if (ClCheckConstantShadow) {
1674       Shadow = getShadow(Val);
1675       if (!Shadow) return;
1676       Origin = getOrigin(Val);
1677     } else {
1678       Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
1679       if (!Shadow) return;
1680       Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
1681     }
1682     insertShadowCheck(Shadow, Origin, OrigIns);
1683   }
1684 
1685   AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
1686     switch (a) {
1687       case AtomicOrdering::NotAtomic:
1688         return AtomicOrdering::NotAtomic;
1689       case AtomicOrdering::Unordered:
1690       case AtomicOrdering::Monotonic:
1691       case AtomicOrdering::Release:
1692         return AtomicOrdering::Release;
1693       case AtomicOrdering::Acquire:
1694       case AtomicOrdering::AcquireRelease:
1695         return AtomicOrdering::AcquireRelease;
1696       case AtomicOrdering::SequentiallyConsistent:
1697         return AtomicOrdering::SequentiallyConsistent;
1698     }
1699     llvm_unreachable("Unknown ordering");
1700   }
1701 
1702   AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
1703     switch (a) {
1704       case AtomicOrdering::NotAtomic:
1705         return AtomicOrdering::NotAtomic;
1706       case AtomicOrdering::Unordered:
1707       case AtomicOrdering::Monotonic:
1708       case AtomicOrdering::Acquire:
1709         return AtomicOrdering::Acquire;
1710       case AtomicOrdering::Release:
1711       case AtomicOrdering::AcquireRelease:
1712         return AtomicOrdering::AcquireRelease;
1713       case AtomicOrdering::SequentiallyConsistent:
1714         return AtomicOrdering::SequentiallyConsistent;
1715     }
1716     llvm_unreachable("Unknown ordering");
1717   }
1718 
1719   // ------------------- Visitors.
1720   using InstVisitor<MemorySanitizerVisitor>::visit;
1721   void visit(Instruction &I) {
1722     if (!I.getMetadata("nosanitize"))
1723       InstVisitor<MemorySanitizerVisitor>::visit(I);
1724   }
1725 
1726   /// Instrument LoadInst
1727   ///
1728   /// Loads the corresponding shadow and (optionally) origin.
1729   /// Optionally, checks that the load address is fully defined.
1730   void visitLoadInst(LoadInst &I) {
1731     assert(I.getType()->isSized() && "Load type must have size");
1732     assert(!I.getMetadata("nosanitize"));
1733     IRBuilder<> IRB(I.getNextNode());
1734     Type *ShadowTy = getShadowTy(&I);
1735     Value *Addr = I.getPointerOperand();
1736     Value *ShadowPtr, *OriginPtr;
1737     unsigned Alignment = I.getAlignment();
1738     if (PropagateShadow) {
1739       std::tie(ShadowPtr, OriginPtr) =
1740           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
1741       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, Alignment, "_msld"));
1742     } else {
1743       setShadow(&I, getCleanShadow(&I));
1744     }
1745 
1746     if (ClCheckAccessAddress)
1747       insertShadowCheck(I.getPointerOperand(), &I);
1748 
1749     if (I.isAtomic())
1750       I.setOrdering(addAcquireOrdering(I.getOrdering()));
1751 
1752     if (MS.TrackOrigins) {
1753       if (PropagateShadow) {
1754         unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
1755         setOrigin(&I, IRB.CreateAlignedLoad(OriginPtr, OriginAlignment));
1756       } else {
1757         setOrigin(&I, getCleanOrigin());
1758       }
1759     }
1760   }
1761 
1762   /// Instrument StoreInst
1763   ///
1764   /// Stores the corresponding shadow and (optionally) origin.
1765   /// Optionally, checks that the store address is fully defined.
1766   void visitStoreInst(StoreInst &I) {
1767     StoreList.push_back(&I);
1768     if (ClCheckAccessAddress)
1769       insertShadowCheck(I.getPointerOperand(), &I);
1770   }
1771 
1772   void handleCASOrRMW(Instruction &I) {
1773     assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
1774 
1775     IRBuilder<> IRB(&I);
1776     Value *Addr = I.getOperand(0);
1777     Value *ShadowPtr = getShadowOriginPtr(Addr, IRB, I.getType(),
1778                                           /*Alignment*/ 1, /*isStore*/ true)
1779                            .first;
1780 
1781     if (ClCheckAccessAddress)
1782       insertShadowCheck(Addr, &I);
1783 
1784     // Only test the conditional argument of cmpxchg instruction.
1785     // The other argument can potentially be uninitialized, but we can not
1786     // detect this situation reliably without possible false positives.
1787     if (isa<AtomicCmpXchgInst>(I))
1788       insertShadowCheck(I.getOperand(1), &I);
1789 
1790     IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
1791 
1792     setShadow(&I, getCleanShadow(&I));
1793     setOrigin(&I, getCleanOrigin());
1794   }
1795 
1796   void visitAtomicRMWInst(AtomicRMWInst &I) {
1797     handleCASOrRMW(I);
1798     I.setOrdering(addReleaseOrdering(I.getOrdering()));
1799   }
1800 
1801   void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
1802     handleCASOrRMW(I);
1803     I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
1804   }
1805 
1806   // Vector manipulation.
1807   void visitExtractElementInst(ExtractElementInst &I) {
1808     insertShadowCheck(I.getOperand(1), &I);
1809     IRBuilder<> IRB(&I);
1810     setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
1811               "_msprop"));
1812     setOrigin(&I, getOrigin(&I, 0));
1813   }
1814 
1815   void visitInsertElementInst(InsertElementInst &I) {
1816     insertShadowCheck(I.getOperand(2), &I);
1817     IRBuilder<> IRB(&I);
1818     setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
1819               I.getOperand(2), "_msprop"));
1820     setOriginForNaryOp(I);
1821   }
1822 
1823   void visitShuffleVectorInst(ShuffleVectorInst &I) {
1824     insertShadowCheck(I.getOperand(2), &I);
1825     IRBuilder<> IRB(&I);
1826     setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
1827               I.getOperand(2), "_msprop"));
1828     setOriginForNaryOp(I);
1829   }
1830 
1831   // Casts.
1832   void visitSExtInst(SExtInst &I) {
1833     IRBuilder<> IRB(&I);
1834     setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
1835     setOrigin(&I, getOrigin(&I, 0));
1836   }
1837 
1838   void visitZExtInst(ZExtInst &I) {
1839     IRBuilder<> IRB(&I);
1840     setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
1841     setOrigin(&I, getOrigin(&I, 0));
1842   }
1843 
1844   void visitTruncInst(TruncInst &I) {
1845     IRBuilder<> IRB(&I);
1846     setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
1847     setOrigin(&I, getOrigin(&I, 0));
1848   }
1849 
1850   void visitBitCastInst(BitCastInst &I) {
1851     // Special case: if this is the bitcast (there is exactly 1 allowed) between
1852     // a musttail call and a ret, don't instrument. New instructions are not
1853     // allowed after a musttail call.
1854     if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
1855       if (CI->isMustTailCall())
1856         return;
1857     IRBuilder<> IRB(&I);
1858     setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
1859     setOrigin(&I, getOrigin(&I, 0));
1860   }
1861 
1862   void visitPtrToIntInst(PtrToIntInst &I) {
1863     IRBuilder<> IRB(&I);
1864     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1865              "_msprop_ptrtoint"));
1866     setOrigin(&I, getOrigin(&I, 0));
1867   }
1868 
1869   void visitIntToPtrInst(IntToPtrInst &I) {
1870     IRBuilder<> IRB(&I);
1871     setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
1872              "_msprop_inttoptr"));
1873     setOrigin(&I, getOrigin(&I, 0));
1874   }
1875 
1876   void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
1877   void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
1878   void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
1879   void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
1880   void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
1881   void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
1882 
1883   /// Propagate shadow for bitwise AND.
1884   ///
1885   /// This code is exact, i.e. if, for example, a bit in the left argument
1886   /// is defined and 0, then neither the value not definedness of the
1887   /// corresponding bit in B don't affect the resulting shadow.
1888   void visitAnd(BinaryOperator &I) {
1889     IRBuilder<> IRB(&I);
1890     //  "And" of 0 and a poisoned value results in unpoisoned value.
1891     //  1&1 => 1;     0&1 => 0;     p&1 => p;
1892     //  1&0 => 0;     0&0 => 0;     p&0 => 0;
1893     //  1&p => p;     0&p => 0;     p&p => p;
1894     //  S = (S1 & S2) | (V1 & S2) | (S1 & V2)
1895     Value *S1 = getShadow(&I, 0);
1896     Value *S2 = getShadow(&I, 1);
1897     Value *V1 = I.getOperand(0);
1898     Value *V2 = I.getOperand(1);
1899     if (V1->getType() != S1->getType()) {
1900       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1901       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1902     }
1903     Value *S1S2 = IRB.CreateAnd(S1, S2);
1904     Value *V1S2 = IRB.CreateAnd(V1, S2);
1905     Value *S1V2 = IRB.CreateAnd(S1, V2);
1906     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1907     setOriginForNaryOp(I);
1908   }
1909 
1910   void visitOr(BinaryOperator &I) {
1911     IRBuilder<> IRB(&I);
1912     //  "Or" of 1 and a poisoned value results in unpoisoned value.
1913     //  1|1 => 1;     0|1 => 1;     p|1 => 1;
1914     //  1|0 => 1;     0|0 => 0;     p|0 => p;
1915     //  1|p => 1;     0|p => p;     p|p => p;
1916     //  S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
1917     Value *S1 = getShadow(&I, 0);
1918     Value *S2 = getShadow(&I, 1);
1919     Value *V1 = IRB.CreateNot(I.getOperand(0));
1920     Value *V2 = IRB.CreateNot(I.getOperand(1));
1921     if (V1->getType() != S1->getType()) {
1922       V1 = IRB.CreateIntCast(V1, S1->getType(), false);
1923       V2 = IRB.CreateIntCast(V2, S2->getType(), false);
1924     }
1925     Value *S1S2 = IRB.CreateAnd(S1, S2);
1926     Value *V1S2 = IRB.CreateAnd(V1, S2);
1927     Value *S1V2 = IRB.CreateAnd(S1, V2);
1928     setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
1929     setOriginForNaryOp(I);
1930   }
1931 
1932   /// Default propagation of shadow and/or origin.
1933   ///
1934   /// This class implements the general case of shadow propagation, used in all
1935   /// cases where we don't know and/or don't care about what the operation
1936   /// actually does. It converts all input shadow values to a common type
1937   /// (extending or truncating as necessary), and bitwise OR's them.
1938   ///
1939   /// This is much cheaper than inserting checks (i.e. requiring inputs to be
1940   /// fully initialized), and less prone to false positives.
1941   ///
1942   /// This class also implements the general case of origin propagation. For a
1943   /// Nary operation, result origin is set to the origin of an argument that is
1944   /// not entirely initialized. If there is more than one such arguments, the
1945   /// rightmost of them is picked. It does not matter which one is picked if all
1946   /// arguments are initialized.
1947   template <bool CombineShadow>
1948   class Combiner {
1949     Value *Shadow = nullptr;
1950     Value *Origin = nullptr;
1951     IRBuilder<> &IRB;
1952     MemorySanitizerVisitor *MSV;
1953 
1954   public:
1955     Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB)
1956         : IRB(IRB), MSV(MSV) {}
1957 
1958     /// Add a pair of shadow and origin values to the mix.
1959     Combiner &Add(Value *OpShadow, Value *OpOrigin) {
1960       if (CombineShadow) {
1961         assert(OpShadow);
1962         if (!Shadow)
1963           Shadow = OpShadow;
1964         else {
1965           OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
1966           Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
1967         }
1968       }
1969 
1970       if (MSV->MS.TrackOrigins) {
1971         assert(OpOrigin);
1972         if (!Origin) {
1973           Origin = OpOrigin;
1974         } else {
1975           Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
1976           // No point in adding something that might result in 0 origin value.
1977           if (!ConstOrigin || !ConstOrigin->isNullValue()) {
1978             Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
1979             Value *Cond =
1980                 IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
1981             Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
1982           }
1983         }
1984       }
1985       return *this;
1986     }
1987 
1988     /// Add an application value to the mix.
1989     Combiner &Add(Value *V) {
1990       Value *OpShadow = MSV->getShadow(V);
1991       Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
1992       return Add(OpShadow, OpOrigin);
1993     }
1994 
1995     /// Set the current combined values as the given instruction's shadow
1996     /// and origin.
1997     void Done(Instruction *I) {
1998       if (CombineShadow) {
1999         assert(Shadow);
2000         Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
2001         MSV->setShadow(I, Shadow);
2002       }
2003       if (MSV->MS.TrackOrigins) {
2004         assert(Origin);
2005         MSV->setOrigin(I, Origin);
2006       }
2007     }
2008   };
2009 
2010   using ShadowAndOriginCombiner = Combiner<true>;
2011   using OriginCombiner = Combiner<false>;
2012 
2013   /// Propagate origin for arbitrary operation.
2014   void setOriginForNaryOp(Instruction &I) {
2015     if (!MS.TrackOrigins) return;
2016     IRBuilder<> IRB(&I);
2017     OriginCombiner OC(this, IRB);
2018     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
2019       OC.Add(OI->get());
2020     OC.Done(&I);
2021   }
2022 
2023   size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
2024     assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
2025            "Vector of pointers is not a valid shadow type");
2026     return Ty->isVectorTy() ?
2027       Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
2028       Ty->getPrimitiveSizeInBits();
2029   }
2030 
2031   /// Cast between two shadow types, extending or truncating as
2032   /// necessary.
2033   Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
2034                           bool Signed = false) {
2035     Type *srcTy = V->getType();
2036     size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
2037     size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
2038     if (srcSizeInBits > 1 && dstSizeInBits == 1)
2039       return IRB.CreateICmpNE(V, getCleanShadow(V));
2040 
2041     if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
2042       return IRB.CreateIntCast(V, dstTy, Signed);
2043     if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
2044         dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
2045       return IRB.CreateIntCast(V, dstTy, Signed);
2046     Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
2047     Value *V2 =
2048       IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
2049     return IRB.CreateBitCast(V2, dstTy);
2050     // TODO: handle struct types.
2051   }
2052 
2053   /// Cast an application value to the type of its own shadow.
2054   Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
2055     Type *ShadowTy = getShadowTy(V);
2056     if (V->getType() == ShadowTy)
2057       return V;
2058     if (V->getType()->isPtrOrPtrVectorTy())
2059       return IRB.CreatePtrToInt(V, ShadowTy);
2060     else
2061       return IRB.CreateBitCast(V, ShadowTy);
2062   }
2063 
2064   /// Propagate shadow for arbitrary operation.
2065   void handleShadowOr(Instruction &I) {
2066     IRBuilder<> IRB(&I);
2067     ShadowAndOriginCombiner SC(this, IRB);
2068     for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
2069       SC.Add(OI->get());
2070     SC.Done(&I);
2071   }
2072 
2073   // Handle multiplication by constant.
2074   //
2075   // Handle a special case of multiplication by constant that may have one or
2076   // more zeros in the lower bits. This makes corresponding number of lower bits
2077   // of the result zero as well. We model it by shifting the other operand
2078   // shadow left by the required number of bits. Effectively, we transform
2079   // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
2080   // We use multiplication by 2**N instead of shift to cover the case of
2081   // multiplication by 0, which may occur in some elements of a vector operand.
2082   void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
2083                            Value *OtherArg) {
2084     Constant *ShadowMul;
2085     Type *Ty = ConstArg->getType();
2086     if (Ty->isVectorTy()) {
2087       unsigned NumElements = Ty->getVectorNumElements();
2088       Type *EltTy = Ty->getSequentialElementType();
2089       SmallVector<Constant *, 16> Elements;
2090       for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
2091         if (ConstantInt *Elt =
2092                 dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) {
2093           const APInt &V = Elt->getValue();
2094           APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
2095           Elements.push_back(ConstantInt::get(EltTy, V2));
2096         } else {
2097           Elements.push_back(ConstantInt::get(EltTy, 1));
2098         }
2099       }
2100       ShadowMul = ConstantVector::get(Elements);
2101     } else {
2102       if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
2103         const APInt &V = Elt->getValue();
2104         APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
2105         ShadowMul = ConstantInt::get(Ty, V2);
2106       } else {
2107         ShadowMul = ConstantInt::get(Ty, 1);
2108       }
2109     }
2110 
2111     IRBuilder<> IRB(&I);
2112     setShadow(&I,
2113               IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
2114     setOrigin(&I, getOrigin(OtherArg));
2115   }
2116 
2117   void visitMul(BinaryOperator &I) {
2118     Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
2119     Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
2120     if (constOp0 && !constOp1)
2121       handleMulByConstant(I, constOp0, I.getOperand(1));
2122     else if (constOp1 && !constOp0)
2123       handleMulByConstant(I, constOp1, I.getOperand(0));
2124     else
2125       handleShadowOr(I);
2126   }
2127 
2128   void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
2129   void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
2130   void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
2131   void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
2132   void visitSub(BinaryOperator &I) { handleShadowOr(I); }
2133   void visitXor(BinaryOperator &I) { handleShadowOr(I); }
2134 
2135   void handleIntegerDiv(Instruction &I) {
2136     IRBuilder<> IRB(&I);
2137     // Strict on the second argument.
2138     insertShadowCheck(I.getOperand(1), &I);
2139     setShadow(&I, getShadow(&I, 0));
2140     setOrigin(&I, getOrigin(&I, 0));
2141   }
2142 
2143   void visitUDiv(BinaryOperator &I) { handleIntegerDiv(I); }
2144   void visitSDiv(BinaryOperator &I) { handleIntegerDiv(I); }
2145   void visitURem(BinaryOperator &I) { handleIntegerDiv(I); }
2146   void visitSRem(BinaryOperator &I) { handleIntegerDiv(I); }
2147 
2148   // Floating point division is side-effect free. We can not require that the
2149   // divisor is fully initialized and must propagate shadow. See PR37523.
2150   void visitFDiv(BinaryOperator &I) { handleShadowOr(I); }
2151   void visitFRem(BinaryOperator &I) { handleShadowOr(I); }
2152 
2153   /// Instrument == and != comparisons.
2154   ///
2155   /// Sometimes the comparison result is known even if some of the bits of the
2156   /// arguments are not.
2157   void handleEqualityComparison(ICmpInst &I) {
2158     IRBuilder<> IRB(&I);
2159     Value *A = I.getOperand(0);
2160     Value *B = I.getOperand(1);
2161     Value *Sa = getShadow(A);
2162     Value *Sb = getShadow(B);
2163 
2164     // Get rid of pointers and vectors of pointers.
2165     // For ints (and vectors of ints), types of A and Sa match,
2166     // and this is a no-op.
2167     A = IRB.CreatePointerCast(A, Sa->getType());
2168     B = IRB.CreatePointerCast(B, Sb->getType());
2169 
2170     // A == B  <==>  (C = A^B) == 0
2171     // A != B  <==>  (C = A^B) != 0
2172     // Sc = Sa | Sb
2173     Value *C = IRB.CreateXor(A, B);
2174     Value *Sc = IRB.CreateOr(Sa, Sb);
2175     // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
2176     // Result is defined if one of the following is true
2177     // * there is a defined 1 bit in C
2178     // * C is fully defined
2179     // Si = !(C & ~Sc) && Sc
2180     Value *Zero = Constant::getNullValue(Sc->getType());
2181     Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
2182     Value *Si =
2183       IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
2184                     IRB.CreateICmpEQ(
2185                       IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
2186     Si->setName("_msprop_icmp");
2187     setShadow(&I, Si);
2188     setOriginForNaryOp(I);
2189   }
2190 
2191   /// Build the lowest possible value of V, taking into account V's
2192   ///        uninitialized bits.
2193   Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
2194                                 bool isSigned) {
2195     if (isSigned) {
2196       // Split shadow into sign bit and other bits.
2197       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
2198       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
2199       // Maximise the undefined shadow bit, minimize other undefined bits.
2200       return
2201         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
2202     } else {
2203       // Minimize undefined bits.
2204       return IRB.CreateAnd(A, IRB.CreateNot(Sa));
2205     }
2206   }
2207 
2208   /// Build the highest possible value of V, taking into account V's
2209   ///        uninitialized bits.
2210   Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
2211                                 bool isSigned) {
2212     if (isSigned) {
2213       // Split shadow into sign bit and other bits.
2214       Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
2215       Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
2216       // Minimise the undefined shadow bit, maximise other undefined bits.
2217       return
2218         IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
2219     } else {
2220       // Maximize undefined bits.
2221       return IRB.CreateOr(A, Sa);
2222     }
2223   }
2224 
2225   /// Instrument relational comparisons.
2226   ///
2227   /// This function does exact shadow propagation for all relational
2228   /// comparisons of integers, pointers and vectors of those.
2229   /// FIXME: output seems suboptimal when one of the operands is a constant
2230   void handleRelationalComparisonExact(ICmpInst &I) {
2231     IRBuilder<> IRB(&I);
2232     Value *A = I.getOperand(0);
2233     Value *B = I.getOperand(1);
2234     Value *Sa = getShadow(A);
2235     Value *Sb = getShadow(B);
2236 
2237     // Get rid of pointers and vectors of pointers.
2238     // For ints (and vectors of ints), types of A and Sa match,
2239     // and this is a no-op.
2240     A = IRB.CreatePointerCast(A, Sa->getType());
2241     B = IRB.CreatePointerCast(B, Sb->getType());
2242 
2243     // Let [a0, a1] be the interval of possible values of A, taking into account
2244     // its undefined bits. Let [b0, b1] be the interval of possible values of B.
2245     // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
2246     bool IsSigned = I.isSigned();
2247     Value *S1 = IRB.CreateICmp(I.getPredicate(),
2248                                getLowestPossibleValue(IRB, A, Sa, IsSigned),
2249                                getHighestPossibleValue(IRB, B, Sb, IsSigned));
2250     Value *S2 = IRB.CreateICmp(I.getPredicate(),
2251                                getHighestPossibleValue(IRB, A, Sa, IsSigned),
2252                                getLowestPossibleValue(IRB, B, Sb, IsSigned));
2253     Value *Si = IRB.CreateXor(S1, S2);
2254     setShadow(&I, Si);
2255     setOriginForNaryOp(I);
2256   }
2257 
2258   /// Instrument signed relational comparisons.
2259   ///
2260   /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
2261   /// bit of the shadow. Everything else is delegated to handleShadowOr().
2262   void handleSignedRelationalComparison(ICmpInst &I) {
2263     Constant *constOp;
2264     Value *op = nullptr;
2265     CmpInst::Predicate pre;
2266     if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
2267       op = I.getOperand(0);
2268       pre = I.getPredicate();
2269     } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
2270       op = I.getOperand(1);
2271       pre = I.getSwappedPredicate();
2272     } else {
2273       handleShadowOr(I);
2274       return;
2275     }
2276 
2277     if ((constOp->isNullValue() &&
2278          (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
2279         (constOp->isAllOnesValue() &&
2280          (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
2281       IRBuilder<> IRB(&I);
2282       Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
2283                                         "_msprop_icmp_s");
2284       setShadow(&I, Shadow);
2285       setOrigin(&I, getOrigin(op));
2286     } else {
2287       handleShadowOr(I);
2288     }
2289   }
2290 
2291   void visitICmpInst(ICmpInst &I) {
2292     if (!ClHandleICmp) {
2293       handleShadowOr(I);
2294       return;
2295     }
2296     if (I.isEquality()) {
2297       handleEqualityComparison(I);
2298       return;
2299     }
2300 
2301     assert(I.isRelational());
2302     if (ClHandleICmpExact) {
2303       handleRelationalComparisonExact(I);
2304       return;
2305     }
2306     if (I.isSigned()) {
2307       handleSignedRelationalComparison(I);
2308       return;
2309     }
2310 
2311     assert(I.isUnsigned());
2312     if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
2313       handleRelationalComparisonExact(I);
2314       return;
2315     }
2316 
2317     handleShadowOr(I);
2318   }
2319 
2320   void visitFCmpInst(FCmpInst &I) {
2321     handleShadowOr(I);
2322   }
2323 
2324   void handleShift(BinaryOperator &I) {
2325     IRBuilder<> IRB(&I);
2326     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2327     // Otherwise perform the same shift on S1.
2328     Value *S1 = getShadow(&I, 0);
2329     Value *S2 = getShadow(&I, 1);
2330     Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
2331                                    S2->getType());
2332     Value *V2 = I.getOperand(1);
2333     Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
2334     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2335     setOriginForNaryOp(I);
2336   }
2337 
2338   void visitShl(BinaryOperator &I) { handleShift(I); }
2339   void visitAShr(BinaryOperator &I) { handleShift(I); }
2340   void visitLShr(BinaryOperator &I) { handleShift(I); }
2341 
2342   /// Instrument llvm.memmove
2343   ///
2344   /// At this point we don't know if llvm.memmove will be inlined or not.
2345   /// If we don't instrument it and it gets inlined,
2346   /// our interceptor will not kick in and we will lose the memmove.
2347   /// If we instrument the call here, but it does not get inlined,
2348   /// we will memove the shadow twice: which is bad in case
2349   /// of overlapping regions. So, we simply lower the intrinsic to a call.
2350   ///
2351   /// Similar situation exists for memcpy and memset.
2352   void visitMemMoveInst(MemMoveInst &I) {
2353     IRBuilder<> IRB(&I);
2354     IRB.CreateCall(
2355         MS.MemmoveFn,
2356         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2357          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2358          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2359     I.eraseFromParent();
2360   }
2361 
2362   // Similar to memmove: avoid copying shadow twice.
2363   // This is somewhat unfortunate as it may slowdown small constant memcpys.
2364   // FIXME: consider doing manual inline for small constant sizes and proper
2365   // alignment.
2366   void visitMemCpyInst(MemCpyInst &I) {
2367     IRBuilder<> IRB(&I);
2368     IRB.CreateCall(
2369         MS.MemcpyFn,
2370         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2371          IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
2372          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2373     I.eraseFromParent();
2374   }
2375 
2376   // Same as memcpy.
2377   void visitMemSetInst(MemSetInst &I) {
2378     IRBuilder<> IRB(&I);
2379     IRB.CreateCall(
2380         MS.MemsetFn,
2381         {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
2382          IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
2383          IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
2384     I.eraseFromParent();
2385   }
2386 
2387   void visitVAStartInst(VAStartInst &I) {
2388     VAHelper->visitVAStartInst(I);
2389   }
2390 
2391   void visitVACopyInst(VACopyInst &I) {
2392     VAHelper->visitVACopyInst(I);
2393   }
2394 
2395   /// Handle vector store-like intrinsics.
2396   ///
2397   /// Instrument intrinsics that look like a simple SIMD store: writes memory,
2398   /// has 1 pointer argument and 1 vector argument, returns void.
2399   bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
2400     IRBuilder<> IRB(&I);
2401     Value* Addr = I.getArgOperand(0);
2402     Value *Shadow = getShadow(&I, 1);
2403     Value *ShadowPtr, *OriginPtr;
2404 
2405     // We don't know the pointer alignment (could be unaligned SSE store!).
2406     // Have to assume to worst case.
2407     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2408         Addr, IRB, Shadow->getType(), /*Alignment*/ 1, /*isStore*/ true);
2409     IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
2410 
2411     if (ClCheckAccessAddress)
2412       insertShadowCheck(Addr, &I);
2413 
2414     // FIXME: factor out common code from materializeStores
2415     if (MS.TrackOrigins) IRB.CreateStore(getOrigin(&I, 1), OriginPtr);
2416     return true;
2417   }
2418 
2419   /// Handle vector load-like intrinsics.
2420   ///
2421   /// Instrument intrinsics that look like a simple SIMD load: reads memory,
2422   /// has 1 pointer argument, returns a vector.
2423   bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
2424     IRBuilder<> IRB(&I);
2425     Value *Addr = I.getArgOperand(0);
2426 
2427     Type *ShadowTy = getShadowTy(&I);
2428     Value *ShadowPtr, *OriginPtr;
2429     if (PropagateShadow) {
2430       // We don't know the pointer alignment (could be unaligned SSE load!).
2431       // Have to assume to worst case.
2432       unsigned Alignment = 1;
2433       std::tie(ShadowPtr, OriginPtr) =
2434           getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false);
2435       setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, Alignment, "_msld"));
2436     } else {
2437       setShadow(&I, getCleanShadow(&I));
2438     }
2439 
2440     if (ClCheckAccessAddress)
2441       insertShadowCheck(Addr, &I);
2442 
2443     if (MS.TrackOrigins) {
2444       if (PropagateShadow)
2445         setOrigin(&I, IRB.CreateLoad(OriginPtr));
2446       else
2447         setOrigin(&I, getCleanOrigin());
2448     }
2449     return true;
2450   }
2451 
2452   /// Handle (SIMD arithmetic)-like intrinsics.
2453   ///
2454   /// Instrument intrinsics with any number of arguments of the same type,
2455   /// equal to the return type. The type should be simple (no aggregates or
2456   /// pointers; vectors are fine).
2457   /// Caller guarantees that this intrinsic does not access memory.
2458   bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
2459     Type *RetTy = I.getType();
2460     if (!(RetTy->isIntOrIntVectorTy() ||
2461           RetTy->isFPOrFPVectorTy() ||
2462           RetTy->isX86_MMXTy()))
2463       return false;
2464 
2465     unsigned NumArgOperands = I.getNumArgOperands();
2466 
2467     for (unsigned i = 0; i < NumArgOperands; ++i) {
2468       Type *Ty = I.getArgOperand(i)->getType();
2469       if (Ty != RetTy)
2470         return false;
2471     }
2472 
2473     IRBuilder<> IRB(&I);
2474     ShadowAndOriginCombiner SC(this, IRB);
2475     for (unsigned i = 0; i < NumArgOperands; ++i)
2476       SC.Add(I.getArgOperand(i));
2477     SC.Done(&I);
2478 
2479     return true;
2480   }
2481 
2482   /// Heuristically instrument unknown intrinsics.
2483   ///
2484   /// The main purpose of this code is to do something reasonable with all
2485   /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
2486   /// We recognize several classes of intrinsics by their argument types and
2487   /// ModRefBehaviour and apply special intrumentation when we are reasonably
2488   /// sure that we know what the intrinsic does.
2489   ///
2490   /// We special-case intrinsics where this approach fails. See llvm.bswap
2491   /// handling as an example of that.
2492   bool handleUnknownIntrinsic(IntrinsicInst &I) {
2493     unsigned NumArgOperands = I.getNumArgOperands();
2494     if (NumArgOperands == 0)
2495       return false;
2496 
2497     if (NumArgOperands == 2 &&
2498         I.getArgOperand(0)->getType()->isPointerTy() &&
2499         I.getArgOperand(1)->getType()->isVectorTy() &&
2500         I.getType()->isVoidTy() &&
2501         !I.onlyReadsMemory()) {
2502       // This looks like a vector store.
2503       return handleVectorStoreIntrinsic(I);
2504     }
2505 
2506     if (NumArgOperands == 1 &&
2507         I.getArgOperand(0)->getType()->isPointerTy() &&
2508         I.getType()->isVectorTy() &&
2509         I.onlyReadsMemory()) {
2510       // This looks like a vector load.
2511       return handleVectorLoadIntrinsic(I);
2512     }
2513 
2514     if (I.doesNotAccessMemory())
2515       if (maybeHandleSimpleNomemIntrinsic(I))
2516         return true;
2517 
2518     // FIXME: detect and handle SSE maskstore/maskload
2519     return false;
2520   }
2521 
2522   void handleBswap(IntrinsicInst &I) {
2523     IRBuilder<> IRB(&I);
2524     Value *Op = I.getArgOperand(0);
2525     Type *OpType = Op->getType();
2526     Function *BswapFunc = Intrinsic::getDeclaration(
2527       F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
2528     setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
2529     setOrigin(&I, getOrigin(Op));
2530   }
2531 
2532   // Instrument vector convert instrinsic.
2533   //
2534   // This function instruments intrinsics like cvtsi2ss:
2535   // %Out = int_xxx_cvtyyy(%ConvertOp)
2536   // or
2537   // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
2538   // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
2539   // number \p Out elements, and (if has 2 arguments) copies the rest of the
2540   // elements from \p CopyOp.
2541   // In most cases conversion involves floating-point value which may trigger a
2542   // hardware exception when not fully initialized. For this reason we require
2543   // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
2544   // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
2545   // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
2546   // return a fully initialized value.
2547   void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
2548     IRBuilder<> IRB(&I);
2549     Value *CopyOp, *ConvertOp;
2550 
2551     switch (I.getNumArgOperands()) {
2552     case 3:
2553       assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
2554       LLVM_FALLTHROUGH;
2555     case 2:
2556       CopyOp = I.getArgOperand(0);
2557       ConvertOp = I.getArgOperand(1);
2558       break;
2559     case 1:
2560       ConvertOp = I.getArgOperand(0);
2561       CopyOp = nullptr;
2562       break;
2563     default:
2564       llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
2565     }
2566 
2567     // The first *NumUsedElements* elements of ConvertOp are converted to the
2568     // same number of output elements. The rest of the output is copied from
2569     // CopyOp, or (if not available) filled with zeroes.
2570     // Combine shadow for elements of ConvertOp that are used in this operation,
2571     // and insert a check.
2572     // FIXME: consider propagating shadow of ConvertOp, at least in the case of
2573     // int->any conversion.
2574     Value *ConvertShadow = getShadow(ConvertOp);
2575     Value *AggShadow = nullptr;
2576     if (ConvertOp->getType()->isVectorTy()) {
2577       AggShadow = IRB.CreateExtractElement(
2578           ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2579       for (int i = 1; i < NumUsedElements; ++i) {
2580         Value *MoreShadow = IRB.CreateExtractElement(
2581             ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2582         AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
2583       }
2584     } else {
2585       AggShadow = ConvertShadow;
2586     }
2587     assert(AggShadow->getType()->isIntegerTy());
2588     insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
2589 
2590     // Build result shadow by zero-filling parts of CopyOp shadow that come from
2591     // ConvertOp.
2592     if (CopyOp) {
2593       assert(CopyOp->getType() == I.getType());
2594       assert(CopyOp->getType()->isVectorTy());
2595       Value *ResultShadow = getShadow(CopyOp);
2596       Type *EltTy = ResultShadow->getType()->getVectorElementType();
2597       for (int i = 0; i < NumUsedElements; ++i) {
2598         ResultShadow = IRB.CreateInsertElement(
2599             ResultShadow, ConstantInt::getNullValue(EltTy),
2600             ConstantInt::get(IRB.getInt32Ty(), i));
2601       }
2602       setShadow(&I, ResultShadow);
2603       setOrigin(&I, getOrigin(CopyOp));
2604     } else {
2605       setShadow(&I, getCleanShadow(&I));
2606       setOrigin(&I, getCleanOrigin());
2607     }
2608   }
2609 
2610   // Given a scalar or vector, extract lower 64 bits (or less), and return all
2611   // zeroes if it is zero, and all ones otherwise.
2612   Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2613     if (S->getType()->isVectorTy())
2614       S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
2615     assert(S->getType()->getPrimitiveSizeInBits() <= 64);
2616     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2617     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2618   }
2619 
2620   // Given a vector, extract its first element, and return all
2621   // zeroes if it is zero, and all ones otherwise.
2622   Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
2623     Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0);
2624     Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1));
2625     return CreateShadowCast(IRB, S2, T, /* Signed */ true);
2626   }
2627 
2628   Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
2629     Type *T = S->getType();
2630     assert(T->isVectorTy());
2631     Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
2632     return IRB.CreateSExt(S2, T);
2633   }
2634 
2635   // Instrument vector shift instrinsic.
2636   //
2637   // This function instruments intrinsics like int_x86_avx2_psll_w.
2638   // Intrinsic shifts %In by %ShiftSize bits.
2639   // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
2640   // size, and the rest is ignored. Behavior is defined even if shift size is
2641   // greater than register (or field) width.
2642   void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
2643     assert(I.getNumArgOperands() == 2);
2644     IRBuilder<> IRB(&I);
2645     // If any of the S2 bits are poisoned, the whole thing is poisoned.
2646     // Otherwise perform the same shift on S1.
2647     Value *S1 = getShadow(&I, 0);
2648     Value *S2 = getShadow(&I, 1);
2649     Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
2650                              : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
2651     Value *V1 = I.getOperand(0);
2652     Value *V2 = I.getOperand(1);
2653     Value *Shift = IRB.CreateCall(I.getCalledValue(),
2654                                   {IRB.CreateBitCast(S1, V1->getType()), V2});
2655     Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
2656     setShadow(&I, IRB.CreateOr(Shift, S2Conv));
2657     setOriginForNaryOp(I);
2658   }
2659 
2660   // Get an X86_MMX-sized vector type.
2661   Type *getMMXVectorTy(unsigned EltSizeInBits) {
2662     const unsigned X86_MMXSizeInBits = 64;
2663     return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
2664                            X86_MMXSizeInBits / EltSizeInBits);
2665   }
2666 
2667   // Returns a signed counterpart for an (un)signed-saturate-and-pack
2668   // intrinsic.
2669   Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
2670     switch (id) {
2671       case Intrinsic::x86_sse2_packsswb_128:
2672       case Intrinsic::x86_sse2_packuswb_128:
2673         return Intrinsic::x86_sse2_packsswb_128;
2674 
2675       case Intrinsic::x86_sse2_packssdw_128:
2676       case Intrinsic::x86_sse41_packusdw:
2677         return Intrinsic::x86_sse2_packssdw_128;
2678 
2679       case Intrinsic::x86_avx2_packsswb:
2680       case Intrinsic::x86_avx2_packuswb:
2681         return Intrinsic::x86_avx2_packsswb;
2682 
2683       case Intrinsic::x86_avx2_packssdw:
2684       case Intrinsic::x86_avx2_packusdw:
2685         return Intrinsic::x86_avx2_packssdw;
2686 
2687       case Intrinsic::x86_mmx_packsswb:
2688       case Intrinsic::x86_mmx_packuswb:
2689         return Intrinsic::x86_mmx_packsswb;
2690 
2691       case Intrinsic::x86_mmx_packssdw:
2692         return Intrinsic::x86_mmx_packssdw;
2693       default:
2694         llvm_unreachable("unexpected intrinsic id");
2695     }
2696   }
2697 
2698   // Instrument vector pack instrinsic.
2699   //
2700   // This function instruments intrinsics like x86_mmx_packsswb, that
2701   // packs elements of 2 input vectors into half as many bits with saturation.
2702   // Shadow is propagated with the signed variant of the same intrinsic applied
2703   // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
2704   // EltSizeInBits is used only for x86mmx arguments.
2705   void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
2706     assert(I.getNumArgOperands() == 2);
2707     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2708     IRBuilder<> IRB(&I);
2709     Value *S1 = getShadow(&I, 0);
2710     Value *S2 = getShadow(&I, 1);
2711     assert(isX86_MMX || S1->getType()->isVectorTy());
2712 
2713     // SExt and ICmpNE below must apply to individual elements of input vectors.
2714     // In case of x86mmx arguments, cast them to appropriate vector types and
2715     // back.
2716     Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
2717     if (isX86_MMX) {
2718       S1 = IRB.CreateBitCast(S1, T);
2719       S2 = IRB.CreateBitCast(S2, T);
2720     }
2721     Value *S1_ext = IRB.CreateSExt(
2722         IRB.CreateICmpNE(S1, Constant::getNullValue(T)), T);
2723     Value *S2_ext = IRB.CreateSExt(
2724         IRB.CreateICmpNE(S2, Constant::getNullValue(T)), T);
2725     if (isX86_MMX) {
2726       Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
2727       S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
2728       S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
2729     }
2730 
2731     Function *ShadowFn = Intrinsic::getDeclaration(
2732         F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
2733 
2734     Value *S =
2735         IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
2736     if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
2737     setShadow(&I, S);
2738     setOriginForNaryOp(I);
2739   }
2740 
2741   // Instrument sum-of-absolute-differencies intrinsic.
2742   void handleVectorSadIntrinsic(IntrinsicInst &I) {
2743     const unsigned SignificantBitsPerResultElement = 16;
2744     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2745     Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
2746     unsigned ZeroBitsPerResultElement =
2747         ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
2748 
2749     IRBuilder<> IRB(&I);
2750     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2751     S = IRB.CreateBitCast(S, ResTy);
2752     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2753                        ResTy);
2754     S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
2755     S = IRB.CreateBitCast(S, getShadowTy(&I));
2756     setShadow(&I, S);
2757     setOriginForNaryOp(I);
2758   }
2759 
2760   // Instrument multiply-add intrinsic.
2761   void handleVectorPmaddIntrinsic(IntrinsicInst &I,
2762                                   unsigned EltSizeInBits = 0) {
2763     bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
2764     Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
2765     IRBuilder<> IRB(&I);
2766     Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2767     S = IRB.CreateBitCast(S, ResTy);
2768     S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
2769                        ResTy);
2770     S = IRB.CreateBitCast(S, getShadowTy(&I));
2771     setShadow(&I, S);
2772     setOriginForNaryOp(I);
2773   }
2774 
2775   // Instrument compare-packed intrinsic.
2776   // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or
2777   // all-ones shadow.
2778   void handleVectorComparePackedIntrinsic(IntrinsicInst &I) {
2779     IRBuilder<> IRB(&I);
2780     Type *ResTy = getShadowTy(&I);
2781     Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2782     Value *S = IRB.CreateSExt(
2783         IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy);
2784     setShadow(&I, S);
2785     setOriginForNaryOp(I);
2786   }
2787 
2788   // Instrument compare-scalar intrinsic.
2789   // This handles both cmp* intrinsics which return the result in the first
2790   // element of a vector, and comi* which return the result as i32.
2791   void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) {
2792     IRBuilder<> IRB(&I);
2793     Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
2794     Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I));
2795     setShadow(&I, S);
2796     setOriginForNaryOp(I);
2797   }
2798 
2799   void handleStmxcsr(IntrinsicInst &I) {
2800     IRBuilder<> IRB(&I);
2801     Value* Addr = I.getArgOperand(0);
2802     Type *Ty = IRB.getInt32Ty();
2803     Value *ShadowPtr =
2804         getShadowOriginPtr(Addr, IRB, Ty, /*Alignment*/ 1, /*isStore*/ true)
2805             .first;
2806 
2807     IRB.CreateStore(getCleanShadow(Ty),
2808                     IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo()));
2809 
2810     if (ClCheckAccessAddress)
2811       insertShadowCheck(Addr, &I);
2812   }
2813 
2814   void handleLdmxcsr(IntrinsicInst &I) {
2815     if (!InsertChecks) return;
2816 
2817     IRBuilder<> IRB(&I);
2818     Value *Addr = I.getArgOperand(0);
2819     Type *Ty = IRB.getInt32Ty();
2820     unsigned Alignment = 1;
2821     Value *ShadowPtr, *OriginPtr;
2822     std::tie(ShadowPtr, OriginPtr) =
2823         getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false);
2824 
2825     if (ClCheckAccessAddress)
2826       insertShadowCheck(Addr, &I);
2827 
2828     Value *Shadow = IRB.CreateAlignedLoad(ShadowPtr, Alignment, "_ldmxcsr");
2829     Value *Origin =
2830         MS.TrackOrigins ? IRB.CreateLoad(OriginPtr) : getCleanOrigin();
2831     insertShadowCheck(Shadow, Origin, &I);
2832   }
2833 
2834   void handleMaskedStore(IntrinsicInst &I) {
2835     IRBuilder<> IRB(&I);
2836     Value *V = I.getArgOperand(0);
2837     Value *Addr = I.getArgOperand(1);
2838     unsigned Align = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
2839     Value *Mask = I.getArgOperand(3);
2840     Value *Shadow = getShadow(V);
2841 
2842     Value *ShadowPtr;
2843     Value *OriginPtr;
2844     std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr(
2845         Addr, IRB, Shadow->getType(), Align, /*isStore*/ true);
2846 
2847     if (ClCheckAccessAddress) {
2848       insertShadowCheck(Addr, &I);
2849       // Uninitialized mask is kind of like uninitialized address, but not as
2850       // scary.
2851       insertShadowCheck(Mask, &I);
2852     }
2853 
2854     IRB.CreateMaskedStore(Shadow, ShadowPtr, Align, Mask);
2855 
2856     if (MS.TrackOrigins) {
2857       auto &DL = F.getParent()->getDataLayout();
2858       paintOrigin(IRB, getOrigin(V), OriginPtr,
2859                   DL.getTypeStoreSize(Shadow->getType()),
2860                   std::max(Align, kMinOriginAlignment));
2861     }
2862   }
2863 
2864   bool handleMaskedLoad(IntrinsicInst &I) {
2865     IRBuilder<> IRB(&I);
2866     Value *Addr = I.getArgOperand(0);
2867     unsigned Align = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
2868     Value *Mask = I.getArgOperand(2);
2869     Value *PassThru = I.getArgOperand(3);
2870 
2871     Type *ShadowTy = getShadowTy(&I);
2872     Value *ShadowPtr, *OriginPtr;
2873     if (PropagateShadow) {
2874       std::tie(ShadowPtr, OriginPtr) =
2875           getShadowOriginPtr(Addr, IRB, ShadowTy, Align, /*isStore*/ false);
2876       setShadow(&I, IRB.CreateMaskedLoad(ShadowPtr, Align, Mask,
2877                                          getShadow(PassThru), "_msmaskedld"));
2878     } else {
2879       setShadow(&I, getCleanShadow(&I));
2880     }
2881 
2882     if (ClCheckAccessAddress) {
2883       insertShadowCheck(Addr, &I);
2884       insertShadowCheck(Mask, &I);
2885     }
2886 
2887     if (MS.TrackOrigins) {
2888       if (PropagateShadow) {
2889         // Choose between PassThru's and the loaded value's origins.
2890         Value *MaskedPassThruShadow = IRB.CreateAnd(
2891             getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy));
2892 
2893         Value *Acc = IRB.CreateExtractElement(
2894             MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
2895         for (int i = 1, N = PassThru->getType()->getVectorNumElements(); i < N;
2896              ++i) {
2897           Value *More = IRB.CreateExtractElement(
2898               MaskedPassThruShadow, ConstantInt::get(IRB.getInt32Ty(), i));
2899           Acc = IRB.CreateOr(Acc, More);
2900         }
2901 
2902         Value *Origin = IRB.CreateSelect(
2903             IRB.CreateICmpNE(Acc, Constant::getNullValue(Acc->getType())),
2904             getOrigin(PassThru), IRB.CreateLoad(OriginPtr));
2905 
2906         setOrigin(&I, Origin);
2907       } else {
2908         setOrigin(&I, getCleanOrigin());
2909       }
2910     }
2911     return true;
2912   }
2913 
2914 
2915   void visitIntrinsicInst(IntrinsicInst &I) {
2916     switch (I.getIntrinsicID()) {
2917     case Intrinsic::bswap:
2918       handleBswap(I);
2919       break;
2920     case Intrinsic::masked_store:
2921       handleMaskedStore(I);
2922       break;
2923     case Intrinsic::masked_load:
2924       handleMaskedLoad(I);
2925       break;
2926     case Intrinsic::x86_sse_stmxcsr:
2927       handleStmxcsr(I);
2928       break;
2929     case Intrinsic::x86_sse_ldmxcsr:
2930       handleLdmxcsr(I);
2931       break;
2932     case Intrinsic::x86_avx512_vcvtsd2usi64:
2933     case Intrinsic::x86_avx512_vcvtsd2usi32:
2934     case Intrinsic::x86_avx512_vcvtss2usi64:
2935     case Intrinsic::x86_avx512_vcvtss2usi32:
2936     case Intrinsic::x86_avx512_cvttss2usi64:
2937     case Intrinsic::x86_avx512_cvttss2usi:
2938     case Intrinsic::x86_avx512_cvttsd2usi64:
2939     case Intrinsic::x86_avx512_cvttsd2usi:
2940     case Intrinsic::x86_avx512_cvtusi2ss:
2941     case Intrinsic::x86_avx512_cvtusi642sd:
2942     case Intrinsic::x86_avx512_cvtusi642ss:
2943     case Intrinsic::x86_sse2_cvtsd2si64:
2944     case Intrinsic::x86_sse2_cvtsd2si:
2945     case Intrinsic::x86_sse2_cvtsd2ss:
2946     case Intrinsic::x86_sse2_cvttsd2si64:
2947     case Intrinsic::x86_sse2_cvttsd2si:
2948     case Intrinsic::x86_sse_cvtss2si64:
2949     case Intrinsic::x86_sse_cvtss2si:
2950     case Intrinsic::x86_sse_cvttss2si64:
2951     case Intrinsic::x86_sse_cvttss2si:
2952       handleVectorConvertIntrinsic(I, 1);
2953       break;
2954     case Intrinsic::x86_sse_cvtps2pi:
2955     case Intrinsic::x86_sse_cvttps2pi:
2956       handleVectorConvertIntrinsic(I, 2);
2957       break;
2958 
2959     case Intrinsic::x86_avx512_psll_w_512:
2960     case Intrinsic::x86_avx512_psll_d_512:
2961     case Intrinsic::x86_avx512_psll_q_512:
2962     case Intrinsic::x86_avx512_pslli_w_512:
2963     case Intrinsic::x86_avx512_pslli_d_512:
2964     case Intrinsic::x86_avx512_pslli_q_512:
2965     case Intrinsic::x86_avx512_psrl_w_512:
2966     case Intrinsic::x86_avx512_psrl_d_512:
2967     case Intrinsic::x86_avx512_psrl_q_512:
2968     case Intrinsic::x86_avx512_psra_w_512:
2969     case Intrinsic::x86_avx512_psra_d_512:
2970     case Intrinsic::x86_avx512_psra_q_512:
2971     case Intrinsic::x86_avx512_psrli_w_512:
2972     case Intrinsic::x86_avx512_psrli_d_512:
2973     case Intrinsic::x86_avx512_psrli_q_512:
2974     case Intrinsic::x86_avx512_psrai_w_512:
2975     case Intrinsic::x86_avx512_psrai_d_512:
2976     case Intrinsic::x86_avx512_psrai_q_512:
2977     case Intrinsic::x86_avx512_psra_q_256:
2978     case Intrinsic::x86_avx512_psra_q_128:
2979     case Intrinsic::x86_avx512_psrai_q_256:
2980     case Intrinsic::x86_avx512_psrai_q_128:
2981     case Intrinsic::x86_avx2_psll_w:
2982     case Intrinsic::x86_avx2_psll_d:
2983     case Intrinsic::x86_avx2_psll_q:
2984     case Intrinsic::x86_avx2_pslli_w:
2985     case Intrinsic::x86_avx2_pslli_d:
2986     case Intrinsic::x86_avx2_pslli_q:
2987     case Intrinsic::x86_avx2_psrl_w:
2988     case Intrinsic::x86_avx2_psrl_d:
2989     case Intrinsic::x86_avx2_psrl_q:
2990     case Intrinsic::x86_avx2_psra_w:
2991     case Intrinsic::x86_avx2_psra_d:
2992     case Intrinsic::x86_avx2_psrli_w:
2993     case Intrinsic::x86_avx2_psrli_d:
2994     case Intrinsic::x86_avx2_psrli_q:
2995     case Intrinsic::x86_avx2_psrai_w:
2996     case Intrinsic::x86_avx2_psrai_d:
2997     case Intrinsic::x86_sse2_psll_w:
2998     case Intrinsic::x86_sse2_psll_d:
2999     case Intrinsic::x86_sse2_psll_q:
3000     case Intrinsic::x86_sse2_pslli_w:
3001     case Intrinsic::x86_sse2_pslli_d:
3002     case Intrinsic::x86_sse2_pslli_q:
3003     case Intrinsic::x86_sse2_psrl_w:
3004     case Intrinsic::x86_sse2_psrl_d:
3005     case Intrinsic::x86_sse2_psrl_q:
3006     case Intrinsic::x86_sse2_psra_w:
3007     case Intrinsic::x86_sse2_psra_d:
3008     case Intrinsic::x86_sse2_psrli_w:
3009     case Intrinsic::x86_sse2_psrli_d:
3010     case Intrinsic::x86_sse2_psrli_q:
3011     case Intrinsic::x86_sse2_psrai_w:
3012     case Intrinsic::x86_sse2_psrai_d:
3013     case Intrinsic::x86_mmx_psll_w:
3014     case Intrinsic::x86_mmx_psll_d:
3015     case Intrinsic::x86_mmx_psll_q:
3016     case Intrinsic::x86_mmx_pslli_w:
3017     case Intrinsic::x86_mmx_pslli_d:
3018     case Intrinsic::x86_mmx_pslli_q:
3019     case Intrinsic::x86_mmx_psrl_w:
3020     case Intrinsic::x86_mmx_psrl_d:
3021     case Intrinsic::x86_mmx_psrl_q:
3022     case Intrinsic::x86_mmx_psra_w:
3023     case Intrinsic::x86_mmx_psra_d:
3024     case Intrinsic::x86_mmx_psrli_w:
3025     case Intrinsic::x86_mmx_psrli_d:
3026     case Intrinsic::x86_mmx_psrli_q:
3027     case Intrinsic::x86_mmx_psrai_w:
3028     case Intrinsic::x86_mmx_psrai_d:
3029       handleVectorShiftIntrinsic(I, /* Variable */ false);
3030       break;
3031     case Intrinsic::x86_avx2_psllv_d:
3032     case Intrinsic::x86_avx2_psllv_d_256:
3033     case Intrinsic::x86_avx512_psllv_d_512:
3034     case Intrinsic::x86_avx2_psllv_q:
3035     case Intrinsic::x86_avx2_psllv_q_256:
3036     case Intrinsic::x86_avx512_psllv_q_512:
3037     case Intrinsic::x86_avx2_psrlv_d:
3038     case Intrinsic::x86_avx2_psrlv_d_256:
3039     case Intrinsic::x86_avx512_psrlv_d_512:
3040     case Intrinsic::x86_avx2_psrlv_q:
3041     case Intrinsic::x86_avx2_psrlv_q_256:
3042     case Intrinsic::x86_avx512_psrlv_q_512:
3043     case Intrinsic::x86_avx2_psrav_d:
3044     case Intrinsic::x86_avx2_psrav_d_256:
3045     case Intrinsic::x86_avx512_psrav_d_512:
3046     case Intrinsic::x86_avx512_psrav_q_128:
3047     case Intrinsic::x86_avx512_psrav_q_256:
3048     case Intrinsic::x86_avx512_psrav_q_512:
3049       handleVectorShiftIntrinsic(I, /* Variable */ true);
3050       break;
3051 
3052     case Intrinsic::x86_sse2_packsswb_128:
3053     case Intrinsic::x86_sse2_packssdw_128:
3054     case Intrinsic::x86_sse2_packuswb_128:
3055     case Intrinsic::x86_sse41_packusdw:
3056     case Intrinsic::x86_avx2_packsswb:
3057     case Intrinsic::x86_avx2_packssdw:
3058     case Intrinsic::x86_avx2_packuswb:
3059     case Intrinsic::x86_avx2_packusdw:
3060       handleVectorPackIntrinsic(I);
3061       break;
3062 
3063     case Intrinsic::x86_mmx_packsswb:
3064     case Intrinsic::x86_mmx_packuswb:
3065       handleVectorPackIntrinsic(I, 16);
3066       break;
3067 
3068     case Intrinsic::x86_mmx_packssdw:
3069       handleVectorPackIntrinsic(I, 32);
3070       break;
3071 
3072     case Intrinsic::x86_mmx_psad_bw:
3073     case Intrinsic::x86_sse2_psad_bw:
3074     case Intrinsic::x86_avx2_psad_bw:
3075       handleVectorSadIntrinsic(I);
3076       break;
3077 
3078     case Intrinsic::x86_sse2_pmadd_wd:
3079     case Intrinsic::x86_avx2_pmadd_wd:
3080     case Intrinsic::x86_ssse3_pmadd_ub_sw_128:
3081     case Intrinsic::x86_avx2_pmadd_ub_sw:
3082       handleVectorPmaddIntrinsic(I);
3083       break;
3084 
3085     case Intrinsic::x86_ssse3_pmadd_ub_sw:
3086       handleVectorPmaddIntrinsic(I, 8);
3087       break;
3088 
3089     case Intrinsic::x86_mmx_pmadd_wd:
3090       handleVectorPmaddIntrinsic(I, 16);
3091       break;
3092 
3093     case Intrinsic::x86_sse_cmp_ss:
3094     case Intrinsic::x86_sse2_cmp_sd:
3095     case Intrinsic::x86_sse_comieq_ss:
3096     case Intrinsic::x86_sse_comilt_ss:
3097     case Intrinsic::x86_sse_comile_ss:
3098     case Intrinsic::x86_sse_comigt_ss:
3099     case Intrinsic::x86_sse_comige_ss:
3100     case Intrinsic::x86_sse_comineq_ss:
3101     case Intrinsic::x86_sse_ucomieq_ss:
3102     case Intrinsic::x86_sse_ucomilt_ss:
3103     case Intrinsic::x86_sse_ucomile_ss:
3104     case Intrinsic::x86_sse_ucomigt_ss:
3105     case Intrinsic::x86_sse_ucomige_ss:
3106     case Intrinsic::x86_sse_ucomineq_ss:
3107     case Intrinsic::x86_sse2_comieq_sd:
3108     case Intrinsic::x86_sse2_comilt_sd:
3109     case Intrinsic::x86_sse2_comile_sd:
3110     case Intrinsic::x86_sse2_comigt_sd:
3111     case Intrinsic::x86_sse2_comige_sd:
3112     case Intrinsic::x86_sse2_comineq_sd:
3113     case Intrinsic::x86_sse2_ucomieq_sd:
3114     case Intrinsic::x86_sse2_ucomilt_sd:
3115     case Intrinsic::x86_sse2_ucomile_sd:
3116     case Intrinsic::x86_sse2_ucomigt_sd:
3117     case Intrinsic::x86_sse2_ucomige_sd:
3118     case Intrinsic::x86_sse2_ucomineq_sd:
3119       handleVectorCompareScalarIntrinsic(I);
3120       break;
3121 
3122     case Intrinsic::x86_sse_cmp_ps:
3123     case Intrinsic::x86_sse2_cmp_pd:
3124       // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function
3125       // generates reasonably looking IR that fails in the backend with "Do not
3126       // know how to split the result of this operator!".
3127       handleVectorComparePackedIntrinsic(I);
3128       break;
3129 
3130     case Intrinsic::is_constant:
3131       // The result of llvm.is.constant() is always defined.
3132       setShadow(&I, getCleanShadow(&I));
3133       setOrigin(&I, getCleanOrigin());
3134       break;
3135 
3136     default:
3137       if (!handleUnknownIntrinsic(I))
3138         visitInstruction(I);
3139       break;
3140     }
3141   }
3142 
3143   void visitCallSite(CallSite CS) {
3144     Instruction &I = *CS.getInstruction();
3145     assert(!I.getMetadata("nosanitize"));
3146     assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
3147     if (CS.isCall()) {
3148       CallInst *Call = cast<CallInst>(&I);
3149 
3150       // For inline asm, do the usual thing: check argument shadow and mark all
3151       // outputs as clean. Note that any side effects of the inline asm that are
3152       // not immediately visible in its constraints are not handled.
3153       if (Call->isInlineAsm()) {
3154         if (ClHandleAsmConservative && MS.CompileKernel)
3155           visitAsmInstruction(I);
3156         else
3157           visitInstruction(I);
3158         return;
3159       }
3160 
3161       assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
3162 
3163       // We are going to insert code that relies on the fact that the callee
3164       // will become a non-readonly function after it is instrumented by us. To
3165       // prevent this code from being optimized out, mark that function
3166       // non-readonly in advance.
3167       if (Function *Func = Call->getCalledFunction()) {
3168         // Clear out readonly/readnone attributes.
3169         AttrBuilder B;
3170         B.addAttribute(Attribute::ReadOnly)
3171           .addAttribute(Attribute::ReadNone);
3172         Func->removeAttributes(AttributeList::FunctionIndex, B);
3173       }
3174 
3175       maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI);
3176     }
3177     IRBuilder<> IRB(&I);
3178 
3179     unsigned ArgOffset = 0;
3180     LLVM_DEBUG(dbgs() << "  CallSite: " << I << "\n");
3181     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3182          ArgIt != End; ++ArgIt) {
3183       Value *A = *ArgIt;
3184       unsigned i = ArgIt - CS.arg_begin();
3185       if (!A->getType()->isSized()) {
3186         LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
3187         continue;
3188       }
3189       unsigned Size = 0;
3190       Value *Store = nullptr;
3191       // Compute the Shadow for arg even if it is ByVal, because
3192       // in that case getShadow() will copy the actual arg shadow to
3193       // __msan_param_tls.
3194       Value *ArgShadow = getShadow(A);
3195       Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
3196       LLVM_DEBUG(dbgs() << "  Arg#" << i << ": " << *A
3197                         << " Shadow: " << *ArgShadow << "\n");
3198       bool ArgIsInitialized = false;
3199       const DataLayout &DL = F.getParent()->getDataLayout();
3200       if (CS.paramHasAttr(i, Attribute::ByVal)) {
3201         assert(A->getType()->isPointerTy() &&
3202                "ByVal argument is not a pointer!");
3203         Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
3204         if (ArgOffset + Size > kParamTLSSize) break;
3205         unsigned ParamAlignment = CS.getParamAlignment(i);
3206         unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
3207         Value *AShadowPtr =
3208             getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment,
3209                                /*isStore*/ false)
3210                 .first;
3211 
3212         Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr,
3213                                  Alignment, Size);
3214         // TODO(glider): need to copy origins.
3215       } else {
3216         Size = DL.getTypeAllocSize(A->getType());
3217         if (ArgOffset + Size > kParamTLSSize) break;
3218         Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
3219                                        kShadowTLSAlignment);
3220         Constant *Cst = dyn_cast<Constant>(ArgShadow);
3221         if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
3222       }
3223       if (MS.TrackOrigins && !ArgIsInitialized)
3224         IRB.CreateStore(getOrigin(A),
3225                         getOriginPtrForArgument(A, IRB, ArgOffset));
3226       (void)Store;
3227       assert(Size != 0 && Store != nullptr);
3228       LLVM_DEBUG(dbgs() << "  Param:" << *Store << "\n");
3229       ArgOffset += alignTo(Size, 8);
3230     }
3231     LLVM_DEBUG(dbgs() << "  done with call args\n");
3232 
3233     FunctionType *FT =
3234       cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
3235     if (FT->isVarArg()) {
3236       VAHelper->visitCallSite(CS, IRB);
3237     }
3238 
3239     // Now, get the shadow for the RetVal.
3240     if (!I.getType()->isSized()) return;
3241     // Don't emit the epilogue for musttail call returns.
3242     if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
3243     IRBuilder<> IRBBefore(&I);
3244     // Until we have full dynamic coverage, make sure the retval shadow is 0.
3245     Value *Base = getShadowPtrForRetval(&I, IRBBefore);
3246     IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
3247     BasicBlock::iterator NextInsn;
3248     if (CS.isCall()) {
3249       NextInsn = ++I.getIterator();
3250       assert(NextInsn != I.getParent()->end());
3251     } else {
3252       BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
3253       if (!NormalDest->getSinglePredecessor()) {
3254         // FIXME: this case is tricky, so we are just conservative here.
3255         // Perhaps we need to split the edge between this BB and NormalDest,
3256         // but a naive attempt to use SplitEdge leads to a crash.
3257         setShadow(&I, getCleanShadow(&I));
3258         setOrigin(&I, getCleanOrigin());
3259         return;
3260       }
3261       // FIXME: NextInsn is likely in a basic block that has not been visited yet.
3262       // Anything inserted there will be instrumented by MSan later!
3263       NextInsn = NormalDest->getFirstInsertionPt();
3264       assert(NextInsn != NormalDest->end() &&
3265              "Could not find insertion point for retval shadow load");
3266     }
3267     IRBuilder<> IRBAfter(&*NextInsn);
3268     Value *RetvalShadow =
3269       IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
3270                                  kShadowTLSAlignment, "_msret");
3271     setShadow(&I, RetvalShadow);
3272     if (MS.TrackOrigins)
3273       setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
3274   }
3275 
3276   bool isAMustTailRetVal(Value *RetVal) {
3277     if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
3278       RetVal = I->getOperand(0);
3279     }
3280     if (auto *I = dyn_cast<CallInst>(RetVal)) {
3281       return I->isMustTailCall();
3282     }
3283     return false;
3284   }
3285 
3286   void visitReturnInst(ReturnInst &I) {
3287     IRBuilder<> IRB(&I);
3288     Value *RetVal = I.getReturnValue();
3289     if (!RetVal) return;
3290     // Don't emit the epilogue for musttail call returns.
3291     if (isAMustTailRetVal(RetVal)) return;
3292     Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
3293     if (CheckReturnValue) {
3294       insertShadowCheck(RetVal, &I);
3295       Value *Shadow = getCleanShadow(RetVal);
3296       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3297     } else {
3298       Value *Shadow = getShadow(RetVal);
3299       IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
3300       if (MS.TrackOrigins)
3301         IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
3302     }
3303   }
3304 
3305   void visitPHINode(PHINode &I) {
3306     IRBuilder<> IRB(&I);
3307     if (!PropagateShadow) {
3308       setShadow(&I, getCleanShadow(&I));
3309       setOrigin(&I, getCleanOrigin());
3310       return;
3311     }
3312 
3313     ShadowPHINodes.push_back(&I);
3314     setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
3315                                 "_msphi_s"));
3316     if (MS.TrackOrigins)
3317       setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
3318                                   "_msphi_o"));
3319   }
3320 
3321   Value *getLocalVarDescription(AllocaInst &I) {
3322     SmallString<2048> StackDescriptionStorage;
3323     raw_svector_ostream StackDescription(StackDescriptionStorage);
3324     // We create a string with a description of the stack allocation and
3325     // pass it into __msan_set_alloca_origin.
3326     // It will be printed by the run-time if stack-originated UMR is found.
3327     // The first 4 bytes of the string are set to '----' and will be replaced
3328     // by __msan_va_arg_overflow_size_tls at the first call.
3329     StackDescription << "----" << I.getName() << "@" << F.getName();
3330     return createPrivateNonConstGlobalForString(*F.getParent(),
3331                                                 StackDescription.str());
3332   }
3333 
3334   void instrumentAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3335     if (PoisonStack && ClPoisonStackWithCall) {
3336       IRB.CreateCall(MS.MsanPoisonStackFn,
3337                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3338     } else {
3339       Value *ShadowBase, *OriginBase;
3340       std::tie(ShadowBase, OriginBase) =
3341           getShadowOriginPtr(&I, IRB, IRB.getInt8Ty(), 1, /*isStore*/ true);
3342 
3343       Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
3344       IRB.CreateMemSet(ShadowBase, PoisonValue, Len, I.getAlignment());
3345     }
3346 
3347     if (PoisonStack && MS.TrackOrigins) {
3348       Value *Descr = getLocalVarDescription(I);
3349       IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
3350                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3351                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
3352                       IRB.CreatePointerCast(&F, MS.IntptrTy)});
3353     }
3354   }
3355 
3356   void instrumentAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) {
3357     Value *Descr = getLocalVarDescription(I);
3358     if (PoisonStack) {
3359       IRB.CreateCall(MS.MsanPoisonAllocaFn,
3360                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
3361                       IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())});
3362     } else {
3363       IRB.CreateCall(MS.MsanUnpoisonAllocaFn,
3364                      {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
3365     }
3366   }
3367 
3368   void visitAllocaInst(AllocaInst &I) {
3369     setShadow(&I, getCleanShadow(&I));
3370     setOrigin(&I, getCleanOrigin());
3371     IRBuilder<> IRB(I.getNextNode());
3372     const DataLayout &DL = F.getParent()->getDataLayout();
3373     uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType());
3374     Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize);
3375     if (I.isArrayAllocation())
3376       Len = IRB.CreateMul(Len, I.getArraySize());
3377 
3378     if (MS.CompileKernel)
3379       instrumentAllocaKmsan(I, IRB, Len);
3380     else
3381       instrumentAllocaUserspace(I, IRB, Len);
3382   }
3383 
3384   void visitSelectInst(SelectInst& I) {
3385     IRBuilder<> IRB(&I);
3386     // a = select b, c, d
3387     Value *B = I.getCondition();
3388     Value *C = I.getTrueValue();
3389     Value *D = I.getFalseValue();
3390     Value *Sb = getShadow(B);
3391     Value *Sc = getShadow(C);
3392     Value *Sd = getShadow(D);
3393 
3394     // Result shadow if condition shadow is 0.
3395     Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
3396     Value *Sa1;
3397     if (I.getType()->isAggregateType()) {
3398       // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
3399       // an extra "select". This results in much more compact IR.
3400       // Sa = select Sb, poisoned, (select b, Sc, Sd)
3401       Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
3402     } else {
3403       // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
3404       // If Sb (condition is poisoned), look for bits in c and d that are equal
3405       // and both unpoisoned.
3406       // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
3407 
3408       // Cast arguments to shadow-compatible type.
3409       C = CreateAppToShadowCast(IRB, C);
3410       D = CreateAppToShadowCast(IRB, D);
3411 
3412       // Result shadow if condition shadow is 1.
3413       Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
3414     }
3415     Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
3416     setShadow(&I, Sa);
3417     if (MS.TrackOrigins) {
3418       // Origins are always i32, so any vector conditions must be flattened.
3419       // FIXME: consider tracking vector origins for app vectors?
3420       if (B->getType()->isVectorTy()) {
3421         Type *FlatTy = getShadowTyNoVec(B->getType());
3422         B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
3423                                 ConstantInt::getNullValue(FlatTy));
3424         Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
3425                                       ConstantInt::getNullValue(FlatTy));
3426       }
3427       // a = select b, c, d
3428       // Oa = Sb ? Ob : (b ? Oc : Od)
3429       setOrigin(
3430           &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
3431                                IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
3432                                                 getOrigin(I.getFalseValue()))));
3433     }
3434   }
3435 
3436   void visitLandingPadInst(LandingPadInst &I) {
3437     // Do nothing.
3438     // See https://github.com/google/sanitizers/issues/504
3439     setShadow(&I, getCleanShadow(&I));
3440     setOrigin(&I, getCleanOrigin());
3441   }
3442 
3443   void visitCatchSwitchInst(CatchSwitchInst &I) {
3444     setShadow(&I, getCleanShadow(&I));
3445     setOrigin(&I, getCleanOrigin());
3446   }
3447 
3448   void visitFuncletPadInst(FuncletPadInst &I) {
3449     setShadow(&I, getCleanShadow(&I));
3450     setOrigin(&I, getCleanOrigin());
3451   }
3452 
3453   void visitGetElementPtrInst(GetElementPtrInst &I) {
3454     handleShadowOr(I);
3455   }
3456 
3457   void visitExtractValueInst(ExtractValueInst &I) {
3458     IRBuilder<> IRB(&I);
3459     Value *Agg = I.getAggregateOperand();
3460     LLVM_DEBUG(dbgs() << "ExtractValue:  " << I << "\n");
3461     Value *AggShadow = getShadow(Agg);
3462     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3463     Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
3464     LLVM_DEBUG(dbgs() << "   ResShadow:  " << *ResShadow << "\n");
3465     setShadow(&I, ResShadow);
3466     setOriginForNaryOp(I);
3467   }
3468 
3469   void visitInsertValueInst(InsertValueInst &I) {
3470     IRBuilder<> IRB(&I);
3471     LLVM_DEBUG(dbgs() << "InsertValue:  " << I << "\n");
3472     Value *AggShadow = getShadow(I.getAggregateOperand());
3473     Value *InsShadow = getShadow(I.getInsertedValueOperand());
3474     LLVM_DEBUG(dbgs() << "   AggShadow:  " << *AggShadow << "\n");
3475     LLVM_DEBUG(dbgs() << "   InsShadow:  " << *InsShadow << "\n");
3476     Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
3477     LLVM_DEBUG(dbgs() << "   Res:        " << *Res << "\n");
3478     setShadow(&I, Res);
3479     setOriginForNaryOp(I);
3480   }
3481 
3482   void dumpInst(Instruction &I) {
3483     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
3484       errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
3485     } else {
3486       errs() << "ZZZ " << I.getOpcodeName() << "\n";
3487     }
3488     errs() << "QQQ " << I << "\n";
3489   }
3490 
3491   void visitResumeInst(ResumeInst &I) {
3492     LLVM_DEBUG(dbgs() << "Resume: " << I << "\n");
3493     // Nothing to do here.
3494   }
3495 
3496   void visitCleanupReturnInst(CleanupReturnInst &CRI) {
3497     LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
3498     // Nothing to do here.
3499   }
3500 
3501   void visitCatchReturnInst(CatchReturnInst &CRI) {
3502     LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
3503     // Nothing to do here.
3504   }
3505 
3506   void instrumentAsmArgument(Value *Operand, Instruction &I, IRBuilder<> &IRB,
3507                              const DataLayout &DL, bool isOutput) {
3508     // For each assembly argument, we check its value for being initialized.
3509     // If the argument is a pointer, we assume it points to a single element
3510     // of the corresponding type (or to a 8-byte word, if the type is unsized).
3511     // Each such pointer is instrumented with a call to the runtime library.
3512     Type *OpType = Operand->getType();
3513     // Check the operand value itself.
3514     insertShadowCheck(Operand, &I);
3515     if (!OpType->isPointerTy() || !isOutput) {
3516       assert(!isOutput);
3517       return;
3518     }
3519     Type *ElType = OpType->getPointerElementType();
3520     if (!ElType->isSized())
3521       return;
3522     int Size = DL.getTypeStoreSize(ElType);
3523     Value *Ptr = IRB.CreatePointerCast(Operand, IRB.getInt8PtrTy());
3524     Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size);
3525     IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Ptr, SizeVal});
3526   }
3527 
3528   /// Get the number of output arguments returned by pointers.
3529   int getNumOutputArgs(InlineAsm *IA, CallInst *CI) {
3530     int NumRetOutputs = 0;
3531     int NumOutputs = 0;
3532     Type *RetTy = dyn_cast<Value>(CI)->getType();
3533     if (!RetTy->isVoidTy()) {
3534       // Register outputs are returned via the CallInst return value.
3535       StructType *ST = dyn_cast_or_null<StructType>(RetTy);
3536       if (ST)
3537         NumRetOutputs = ST->getNumElements();
3538       else
3539         NumRetOutputs = 1;
3540     }
3541     InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
3542     for (size_t i = 0, n = Constraints.size(); i < n; i++) {
3543       InlineAsm::ConstraintInfo Info = Constraints[i];
3544       switch (Info.Type) {
3545       case InlineAsm::isOutput:
3546         NumOutputs++;
3547         break;
3548       default:
3549         break;
3550       }
3551     }
3552     return NumOutputs - NumRetOutputs;
3553   }
3554 
3555   void visitAsmInstruction(Instruction &I) {
3556     // Conservative inline assembly handling: check for poisoned shadow of
3557     // asm() arguments, then unpoison the result and all the memory locations
3558     // pointed to by those arguments.
3559     // An inline asm() statement in C++ contains lists of input and output
3560     // arguments used by the assembly code. These are mapped to operands of the
3561     // CallInst as follows:
3562     //  - nR register outputs ("=r) are returned by value in a single structure
3563     //  (SSA value of the CallInst);
3564     //  - nO other outputs ("=m" and others) are returned by pointer as first
3565     // nO operands of the CallInst;
3566     //  - nI inputs ("r", "m" and others) are passed to CallInst as the
3567     // remaining nI operands.
3568     // The total number of asm() arguments in the source is nR+nO+nI, and the
3569     // corresponding CallInst has nO+nI+1 operands (the last operand is the
3570     // function to be called).
3571     const DataLayout &DL = F.getParent()->getDataLayout();
3572     CallInst *CI = dyn_cast<CallInst>(&I);
3573     IRBuilder<> IRB(&I);
3574     InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
3575     int OutputArgs = getNumOutputArgs(IA, CI);
3576     // The last operand of a CallInst is the function itself.
3577     int NumOperands = CI->getNumOperands() - 1;
3578 
3579     // Check input arguments. Doing so before unpoisoning output arguments, so
3580     // that we won't overwrite uninit values before checking them.
3581     for (int i = OutputArgs; i < NumOperands; i++) {
3582       Value *Operand = CI->getOperand(i);
3583       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ false);
3584     }
3585     // Unpoison output arguments. This must happen before the actual InlineAsm
3586     // call, so that the shadow for memory published in the asm() statement
3587     // remains valid.
3588     for (int i = 0; i < OutputArgs; i++) {
3589       Value *Operand = CI->getOperand(i);
3590       instrumentAsmArgument(Operand, I, IRB, DL, /*isOutput*/ true);
3591     }
3592 
3593     setShadow(&I, getCleanShadow(&I));
3594     setOrigin(&I, getCleanOrigin());
3595   }
3596 
3597   void visitInstruction(Instruction &I) {
3598     // Everything else: stop propagating and check for poisoned shadow.
3599     if (ClDumpStrictInstructions)
3600       dumpInst(I);
3601     LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n");
3602     for (size_t i = 0, n = I.getNumOperands(); i < n; i++) {
3603       Value *Operand = I.getOperand(i);
3604       if (Operand->getType()->isSized())
3605         insertShadowCheck(Operand, &I);
3606     }
3607     setShadow(&I, getCleanShadow(&I));
3608     setOrigin(&I, getCleanOrigin());
3609   }
3610 };
3611 
3612 /// AMD64-specific implementation of VarArgHelper.
3613 struct VarArgAMD64Helper : public VarArgHelper {
3614   // An unfortunate workaround for asymmetric lowering of va_arg stuff.
3615   // See a comment in visitCallSite for more details.
3616   static const unsigned AMD64GpEndOffset = 48;  // AMD64 ABI Draft 0.99.6 p3.5.7
3617   static const unsigned AMD64FpEndOffsetSSE = 176;
3618   // If SSE is disabled, fp_offset in va_list is zero.
3619   static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset;
3620 
3621   unsigned AMD64FpEndOffset;
3622   Function &F;
3623   MemorySanitizer &MS;
3624   MemorySanitizerVisitor &MSV;
3625   Value *VAArgTLSCopy = nullptr;
3626   Value *VAArgTLSOriginCopy = nullptr;
3627   Value *VAArgOverflowSize = nullptr;
3628 
3629   SmallVector<CallInst*, 16> VAStartInstrumentationList;
3630 
3631   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
3632 
3633   VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
3634                     MemorySanitizerVisitor &MSV)
3635       : F(F), MS(MS), MSV(MSV) {
3636     AMD64FpEndOffset = AMD64FpEndOffsetSSE;
3637     for (const auto &Attr : F.getAttributes().getFnAttributes()) {
3638       if (Attr.isStringAttribute() &&
3639           (Attr.getKindAsString() == "target-features")) {
3640         if (Attr.getValueAsString().contains("-sse"))
3641           AMD64FpEndOffset = AMD64FpEndOffsetNoSSE;
3642         break;
3643       }
3644     }
3645   }
3646 
3647   ArgKind classifyArgument(Value* arg) {
3648     // A very rough approximation of X86_64 argument classification rules.
3649     Type *T = arg->getType();
3650     if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
3651       return AK_FloatingPoint;
3652     if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
3653       return AK_GeneralPurpose;
3654     if (T->isPointerTy())
3655       return AK_GeneralPurpose;
3656     return AK_Memory;
3657   }
3658 
3659   // For VarArg functions, store the argument shadow in an ABI-specific format
3660   // that corresponds to va_list layout.
3661   // We do this because Clang lowers va_arg in the frontend, and this pass
3662   // only sees the low level code that deals with va_list internals.
3663   // A much easier alternative (provided that Clang emits va_arg instructions)
3664   // would have been to associate each live instance of va_list with a copy of
3665   // MSanParamTLS, and extract shadow on va_arg() call in the argument list
3666   // order.
3667   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3668     unsigned GpOffset = 0;
3669     unsigned FpOffset = AMD64GpEndOffset;
3670     unsigned OverflowOffset = AMD64FpEndOffset;
3671     const DataLayout &DL = F.getParent()->getDataLayout();
3672     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
3673          ArgIt != End; ++ArgIt) {
3674       Value *A = *ArgIt;
3675       unsigned ArgNo = CS.getArgumentNo(ArgIt);
3676       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
3677       bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
3678       if (IsByVal) {
3679         // ByVal arguments always go to the overflow area.
3680         // Fixed arguments passed through the overflow area will be stepped
3681         // over by va_start, so don't count them towards the offset.
3682         if (IsFixed)
3683           continue;
3684         assert(A->getType()->isPointerTy());
3685         Type *RealTy = A->getType()->getPointerElementType();
3686         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
3687         Value *ShadowBase = getShadowPtrForVAArgument(
3688             RealTy, IRB, OverflowOffset, alignTo(ArgSize, 8));
3689         Value *OriginBase = nullptr;
3690         if (MS.TrackOrigins)
3691           OriginBase = getOriginPtrForVAArgument(RealTy, IRB, OverflowOffset);
3692         OverflowOffset += alignTo(ArgSize, 8);
3693         if (!ShadowBase)
3694           continue;
3695         Value *ShadowPtr, *OriginPtr;
3696         std::tie(ShadowPtr, OriginPtr) =
3697             MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment,
3698                                    /*isStore*/ false);
3699 
3700         IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr,
3701                          kShadowTLSAlignment, ArgSize);
3702         if (MS.TrackOrigins)
3703           IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr,
3704                            kShadowTLSAlignment, ArgSize);
3705       } else {
3706         ArgKind AK = classifyArgument(A);
3707         if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
3708           AK = AK_Memory;
3709         if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
3710           AK = AK_Memory;
3711         Value *ShadowBase, *OriginBase = nullptr;
3712         switch (AK) {
3713           case AK_GeneralPurpose:
3714             ShadowBase =
3715                 getShadowPtrForVAArgument(A->getType(), IRB, GpOffset, 8);
3716             if (MS.TrackOrigins)
3717               OriginBase =
3718                   getOriginPtrForVAArgument(A->getType(), IRB, GpOffset);
3719             GpOffset += 8;
3720             break;
3721           case AK_FloatingPoint:
3722             ShadowBase =
3723                 getShadowPtrForVAArgument(A->getType(), IRB, FpOffset, 16);
3724             if (MS.TrackOrigins)
3725               OriginBase =
3726                   getOriginPtrForVAArgument(A->getType(), IRB, FpOffset);
3727             FpOffset += 16;
3728             break;
3729           case AK_Memory:
3730             if (IsFixed)
3731               continue;
3732             uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3733             ShadowBase =
3734                 getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 8);
3735             if (MS.TrackOrigins)
3736               OriginBase =
3737                   getOriginPtrForVAArgument(A->getType(), IRB, OverflowOffset);
3738             OverflowOffset += alignTo(ArgSize, 8);
3739         }
3740         // Take fixed arguments into account for GpOffset and FpOffset,
3741         // but don't actually store shadows for them.
3742         // TODO(glider): don't call get*PtrForVAArgument() for them.
3743         if (IsFixed)
3744           continue;
3745         if (!ShadowBase)
3746           continue;
3747         Value *Shadow = MSV.getShadow(A);
3748         IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment);
3749         if (MS.TrackOrigins) {
3750           Value *Origin = MSV.getOrigin(A);
3751           unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
3752           MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize,
3753                           std::max(kShadowTLSAlignment, kMinOriginAlignment));
3754         }
3755       }
3756     }
3757     Constant *OverflowSize =
3758       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
3759     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
3760   }
3761 
3762   /// Compute the shadow address for a given va_arg.
3763   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3764                                    unsigned ArgOffset, unsigned ArgSize) {
3765     // Make sure we don't overflow __msan_va_arg_tls.
3766     if (ArgOffset + ArgSize > kParamTLSSize)
3767       return nullptr;
3768     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3769     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3770     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3771                               "_msarg_va_s");
3772   }
3773 
3774   /// Compute the origin address for a given va_arg.
3775   Value *getOriginPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, int ArgOffset) {
3776     Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy);
3777     // getOriginPtrForVAArgument() is always called after
3778     // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never
3779     // overflow.
3780     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3781     return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
3782                               "_msarg_va_o");
3783   }
3784 
3785   void unpoisonVAListTagForInst(IntrinsicInst &I) {
3786     IRBuilder<> IRB(&I);
3787     Value *VAListTag = I.getArgOperand(0);
3788     Value *ShadowPtr, *OriginPtr;
3789     unsigned Alignment = 8;
3790     std::tie(ShadowPtr, OriginPtr) =
3791         MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment,
3792                                /*isStore*/ true);
3793 
3794     // Unpoison the whole __va_list_tag.
3795     // FIXME: magic ABI constants.
3796     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3797                      /* size */ 24, Alignment, false);
3798     // We shouldn't need to zero out the origins, as they're only checked for
3799     // nonzero shadow.
3800   }
3801 
3802   void visitVAStartInst(VAStartInst &I) override {
3803     if (F.getCallingConv() == CallingConv::Win64)
3804       return;
3805     VAStartInstrumentationList.push_back(&I);
3806     unpoisonVAListTagForInst(I);
3807   }
3808 
3809   void visitVACopyInst(VACopyInst &I) override {
3810     if (F.getCallingConv() == CallingConv::Win64) return;
3811     unpoisonVAListTagForInst(I);
3812   }
3813 
3814   void finalizeInstrumentation() override {
3815     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
3816            "finalizeInstrumentation called twice");
3817     if (!VAStartInstrumentationList.empty()) {
3818       // If there is a va_start in this function, make a backup copy of
3819       // va_arg_tls somewhere in the function entry block.
3820       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
3821       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3822       Value *CopySize =
3823         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
3824                       VAArgOverflowSize);
3825       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3826       IRB.CreateMemCpy(VAArgTLSCopy, 8, MS.VAArgTLS, 8, CopySize);
3827       if (MS.TrackOrigins) {
3828         VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3829         IRB.CreateMemCpy(VAArgTLSOriginCopy, 8, MS.VAArgOriginTLS, 8, CopySize);
3830       }
3831     }
3832 
3833     // Instrument va_start.
3834     // Copy va_list shadow from the backup copy of the TLS contents.
3835     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3836       CallInst *OrigInst = VAStartInstrumentationList[i];
3837       IRBuilder<> IRB(OrigInst->getNextNode());
3838       Value *VAListTag = OrigInst->getArgOperand(0);
3839 
3840       Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr(
3841           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3842                         ConstantInt::get(MS.IntptrTy, 16)),
3843           PointerType::get(Type::getInt64PtrTy(*MS.C), 0));
3844       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3845       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
3846       unsigned Alignment = 16;
3847       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
3848           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
3849                                  Alignment, /*isStore*/ true);
3850       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
3851                        AMD64FpEndOffset);
3852       if (MS.TrackOrigins)
3853         IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy,
3854                          Alignment, AMD64FpEndOffset);
3855       Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr(
3856           IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3857                         ConstantInt::get(MS.IntptrTy, 8)),
3858           PointerType::get(Type::getInt64PtrTy(*MS.C), 0));
3859       Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
3860       Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr;
3861       std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) =
3862           MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(),
3863                                  Alignment, /*isStore*/ true);
3864       Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
3865                                              AMD64FpEndOffset);
3866       IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment,
3867                        VAArgOverflowSize);
3868       if (MS.TrackOrigins) {
3869         SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy,
3870                                         AMD64FpEndOffset);
3871         IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment,
3872                          VAArgOverflowSize);
3873       }
3874     }
3875   }
3876 };
3877 
3878 /// MIPS64-specific implementation of VarArgHelper.
3879 struct VarArgMIPS64Helper : public VarArgHelper {
3880   Function &F;
3881   MemorySanitizer &MS;
3882   MemorySanitizerVisitor &MSV;
3883   Value *VAArgTLSCopy = nullptr;
3884   Value *VAArgSize = nullptr;
3885 
3886   SmallVector<CallInst*, 16> VAStartInstrumentationList;
3887 
3888   VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
3889                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
3890 
3891   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
3892     unsigned VAArgOffset = 0;
3893     const DataLayout &DL = F.getParent()->getDataLayout();
3894     for (CallSite::arg_iterator ArgIt = CS.arg_begin() +
3895          CS.getFunctionType()->getNumParams(), End = CS.arg_end();
3896          ArgIt != End; ++ArgIt) {
3897       Triple TargetTriple(F.getParent()->getTargetTriple());
3898       Value *A = *ArgIt;
3899       Value *Base;
3900       uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
3901       if (TargetTriple.getArch() == Triple::mips64) {
3902         // Adjusting the shadow for argument with size < 8 to match the placement
3903         // of bits in big endian system
3904         if (ArgSize < 8)
3905           VAArgOffset += (8 - ArgSize);
3906       }
3907       Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset, ArgSize);
3908       VAArgOffset += ArgSize;
3909       VAArgOffset = alignTo(VAArgOffset, 8);
3910       if (!Base)
3911         continue;
3912       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
3913     }
3914 
3915     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
3916     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
3917     // a new class member i.e. it is the total size of all VarArgs.
3918     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
3919   }
3920 
3921   /// Compute the shadow address for a given va_arg.
3922   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
3923                                    unsigned ArgOffset, unsigned ArgSize) {
3924     // Make sure we don't overflow __msan_va_arg_tls.
3925     if (ArgOffset + ArgSize > kParamTLSSize)
3926       return nullptr;
3927     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
3928     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
3929     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
3930                               "_msarg");
3931   }
3932 
3933   void visitVAStartInst(VAStartInst &I) override {
3934     IRBuilder<> IRB(&I);
3935     VAStartInstrumentationList.push_back(&I);
3936     Value *VAListTag = I.getArgOperand(0);
3937     Value *ShadowPtr, *OriginPtr;
3938     unsigned Alignment = 8;
3939     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
3940         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
3941     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3942                      /* size */ 8, Alignment, false);
3943   }
3944 
3945   void visitVACopyInst(VACopyInst &I) override {
3946     IRBuilder<> IRB(&I);
3947     VAStartInstrumentationList.push_back(&I);
3948     Value *VAListTag = I.getArgOperand(0);
3949     Value *ShadowPtr, *OriginPtr;
3950     unsigned Alignment = 8;
3951     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
3952         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
3953     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
3954                      /* size */ 8, Alignment, false);
3955   }
3956 
3957   void finalizeInstrumentation() override {
3958     assert(!VAArgSize && !VAArgTLSCopy &&
3959            "finalizeInstrumentation called twice");
3960     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
3961     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
3962     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
3963                                     VAArgSize);
3964 
3965     if (!VAStartInstrumentationList.empty()) {
3966       // If there is a va_start in this function, make a backup copy of
3967       // va_arg_tls somewhere in the function entry block.
3968       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
3969       IRB.CreateMemCpy(VAArgTLSCopy, 8, MS.VAArgTLS, 8, CopySize);
3970     }
3971 
3972     // Instrument va_start.
3973     // Copy va_list shadow from the backup copy of the TLS contents.
3974     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
3975       CallInst *OrigInst = VAStartInstrumentationList[i];
3976       IRBuilder<> IRB(OrigInst->getNextNode());
3977       Value *VAListTag = OrigInst->getArgOperand(0);
3978       Value *RegSaveAreaPtrPtr =
3979           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
3980                              PointerType::get(Type::getInt64PtrTy(*MS.C), 0));
3981       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
3982       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
3983       unsigned Alignment = 8;
3984       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
3985           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
3986                                  Alignment, /*isStore*/ true);
3987       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
3988                        CopySize);
3989     }
3990   }
3991 };
3992 
3993 /// AArch64-specific implementation of VarArgHelper.
3994 struct VarArgAArch64Helper : public VarArgHelper {
3995   static const unsigned kAArch64GrArgSize = 64;
3996   static const unsigned kAArch64VrArgSize = 128;
3997 
3998   static const unsigned AArch64GrBegOffset = 0;
3999   static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
4000   // Make VR space aligned to 16 bytes.
4001   static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
4002   static const unsigned AArch64VrEndOffset = AArch64VrBegOffset
4003                                              + kAArch64VrArgSize;
4004   static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
4005 
4006   Function &F;
4007   MemorySanitizer &MS;
4008   MemorySanitizerVisitor &MSV;
4009   Value *VAArgTLSCopy = nullptr;
4010   Value *VAArgOverflowSize = nullptr;
4011 
4012   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4013 
4014   enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
4015 
4016   VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
4017                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4018 
4019   ArgKind classifyArgument(Value* arg) {
4020     Type *T = arg->getType();
4021     if (T->isFPOrFPVectorTy())
4022       return AK_FloatingPoint;
4023     if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
4024         || (T->isPointerTy()))
4025       return AK_GeneralPurpose;
4026     return AK_Memory;
4027   }
4028 
4029   // The instrumentation stores the argument shadow in a non ABI-specific
4030   // format because it does not know which argument is named (since Clang,
4031   // like x86_64 case, lowers the va_args in the frontend and this pass only
4032   // sees the low level code that deals with va_list internals).
4033   // The first seven GR registers are saved in the first 56 bytes of the
4034   // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then
4035   // the remaining arguments.
4036   // Using constant offset within the va_arg TLS array allows fast copy
4037   // in the finalize instrumentation.
4038   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4039     unsigned GrOffset = AArch64GrBegOffset;
4040     unsigned VrOffset = AArch64VrBegOffset;
4041     unsigned OverflowOffset = AArch64VAEndOffset;
4042 
4043     const DataLayout &DL = F.getParent()->getDataLayout();
4044     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
4045          ArgIt != End; ++ArgIt) {
4046       Value *A = *ArgIt;
4047       unsigned ArgNo = CS.getArgumentNo(ArgIt);
4048       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
4049       ArgKind AK = classifyArgument(A);
4050       if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset)
4051         AK = AK_Memory;
4052       if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset)
4053         AK = AK_Memory;
4054       Value *Base;
4055       switch (AK) {
4056         case AK_GeneralPurpose:
4057           Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset, 8);
4058           GrOffset += 8;
4059           break;
4060         case AK_FloatingPoint:
4061           Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset, 8);
4062           VrOffset += 16;
4063           break;
4064         case AK_Memory:
4065           // Don't count fixed arguments in the overflow area - va_start will
4066           // skip right over them.
4067           if (IsFixed)
4068             continue;
4069           uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4070           Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset,
4071                                            alignTo(ArgSize, 8));
4072           OverflowOffset += alignTo(ArgSize, 8);
4073           break;
4074       }
4075       // Count Gp/Vr fixed arguments to their respective offsets, but don't
4076       // bother to actually store a shadow.
4077       if (IsFixed)
4078         continue;
4079       if (!Base)
4080         continue;
4081       IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4082     }
4083     Constant *OverflowSize =
4084       ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
4085     IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
4086   }
4087 
4088   /// Compute the shadow address for a given va_arg.
4089   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4090                                    unsigned ArgOffset, unsigned ArgSize) {
4091     // Make sure we don't overflow __msan_va_arg_tls.
4092     if (ArgOffset + ArgSize > kParamTLSSize)
4093       return nullptr;
4094     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4095     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4096     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4097                               "_msarg");
4098   }
4099 
4100   void visitVAStartInst(VAStartInst &I) override {
4101     IRBuilder<> IRB(&I);
4102     VAStartInstrumentationList.push_back(&I);
4103     Value *VAListTag = I.getArgOperand(0);
4104     Value *ShadowPtr, *OriginPtr;
4105     unsigned Alignment = 8;
4106     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4107         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4108     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4109                      /* size */ 32, Alignment, false);
4110   }
4111 
4112   void visitVACopyInst(VACopyInst &I) override {
4113     IRBuilder<> IRB(&I);
4114     VAStartInstrumentationList.push_back(&I);
4115     Value *VAListTag = I.getArgOperand(0);
4116     Value *ShadowPtr, *OriginPtr;
4117     unsigned Alignment = 8;
4118     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4119         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4120     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4121                      /* size */ 32, Alignment, false);
4122   }
4123 
4124   // Retrieve a va_list field of 'void*' size.
4125   Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4126     Value *SaveAreaPtrPtr =
4127       IRB.CreateIntToPtr(
4128         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4129                       ConstantInt::get(MS.IntptrTy, offset)),
4130         Type::getInt64PtrTy(*MS.C));
4131     return IRB.CreateLoad(SaveAreaPtrPtr);
4132   }
4133 
4134   // Retrieve a va_list field of 'int' size.
4135   Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) {
4136     Value *SaveAreaPtr =
4137       IRB.CreateIntToPtr(
4138         IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4139                       ConstantInt::get(MS.IntptrTy, offset)),
4140         Type::getInt32PtrTy(*MS.C));
4141     Value *SaveArea32 = IRB.CreateLoad(SaveAreaPtr);
4142     return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
4143   }
4144 
4145   void finalizeInstrumentation() override {
4146     assert(!VAArgOverflowSize && !VAArgTLSCopy &&
4147            "finalizeInstrumentation called twice");
4148     if (!VAStartInstrumentationList.empty()) {
4149       // If there is a va_start in this function, make a backup copy of
4150       // va_arg_tls somewhere in the function entry block.
4151       IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4152       VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
4153       Value *CopySize =
4154         IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset),
4155                       VAArgOverflowSize);
4156       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4157       IRB.CreateMemCpy(VAArgTLSCopy, 8, MS.VAArgTLS, 8, CopySize);
4158     }
4159 
4160     Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
4161     Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
4162 
4163     // Instrument va_start, copy va_list shadow from the backup copy of
4164     // the TLS contents.
4165     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4166       CallInst *OrigInst = VAStartInstrumentationList[i];
4167       IRBuilder<> IRB(OrigInst->getNextNode());
4168 
4169       Value *VAListTag = OrigInst->getArgOperand(0);
4170 
4171       // The variadic ABI for AArch64 creates two areas to save the incoming
4172       // argument registers (one for 64-bit general register xn-x7 and another
4173       // for 128-bit FP/SIMD vn-v7).
4174       // We need then to propagate the shadow arguments on both regions
4175       // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
4176       // The remaning arguments are saved on shadow for 'va::stack'.
4177       // One caveat is it requires only to propagate the non-named arguments,
4178       // however on the call site instrumentation 'all' the arguments are
4179       // saved. So to copy the shadow values from the va_arg TLS array
4180       // we need to adjust the offset for both GR and VR fields based on
4181       // the __{gr,vr}_offs value (since they are stores based on incoming
4182       // named arguments).
4183 
4184       // Read the stack pointer from the va_list.
4185       Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0);
4186 
4187       // Read both the __gr_top and __gr_off and add them up.
4188       Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
4189       Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
4190 
4191       Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea);
4192 
4193       // Read both the __vr_top and __vr_off and add them up.
4194       Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
4195       Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
4196 
4197       Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea);
4198 
4199       // It does not know how many named arguments is being used and, on the
4200       // callsite all the arguments were saved.  Since __gr_off is defined as
4201       // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
4202       // argument by ignoring the bytes of shadow from named arguments.
4203       Value *GrRegSaveAreaShadowPtrOff =
4204         IRB.CreateAdd(GrArgSize, GrOffSaveArea);
4205 
4206       Value *GrRegSaveAreaShadowPtr =
4207           MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4208                                  /*Alignment*/ 8, /*isStore*/ true)
4209               .first;
4210 
4211       Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4212                                               GrRegSaveAreaShadowPtrOff);
4213       Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
4214 
4215       IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, 8, GrSrcPtr, 8, GrCopySize);
4216 
4217       // Again, but for FP/SIMD values.
4218       Value *VrRegSaveAreaShadowPtrOff =
4219           IRB.CreateAdd(VrArgSize, VrOffSaveArea);
4220 
4221       Value *VrRegSaveAreaShadowPtr =
4222           MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4223                                  /*Alignment*/ 8, /*isStore*/ true)
4224               .first;
4225 
4226       Value *VrSrcPtr = IRB.CreateInBoundsGEP(
4227         IRB.getInt8Ty(),
4228         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4229                               IRB.getInt32(AArch64VrBegOffset)),
4230         VrRegSaveAreaShadowPtrOff);
4231       Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
4232 
4233       IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, 8, VrSrcPtr, 8, VrCopySize);
4234 
4235       // And finally for remaining arguments.
4236       Value *StackSaveAreaShadowPtr =
4237           MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(),
4238                                  /*Alignment*/ 16, /*isStore*/ true)
4239               .first;
4240 
4241       Value *StackSrcPtr =
4242         IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
4243                               IRB.getInt32(AArch64VAEndOffset));
4244 
4245       IRB.CreateMemCpy(StackSaveAreaShadowPtr, 16, StackSrcPtr, 16,
4246                        VAArgOverflowSize);
4247     }
4248   }
4249 };
4250 
4251 /// PowerPC64-specific implementation of VarArgHelper.
4252 struct VarArgPowerPC64Helper : public VarArgHelper {
4253   Function &F;
4254   MemorySanitizer &MS;
4255   MemorySanitizerVisitor &MSV;
4256   Value *VAArgTLSCopy = nullptr;
4257   Value *VAArgSize = nullptr;
4258 
4259   SmallVector<CallInst*, 16> VAStartInstrumentationList;
4260 
4261   VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
4262                     MemorySanitizerVisitor &MSV) : F(F), MS(MS), MSV(MSV) {}
4263 
4264   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
4265     // For PowerPC, we need to deal with alignment of stack arguments -
4266     // they are mostly aligned to 8 bytes, but vectors and i128 arrays
4267     // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
4268     // and QPX vectors are aligned to 32 bytes.  For that reason, we
4269     // compute current offset from stack pointer (which is always properly
4270     // aligned), and offset for the first vararg, then subtract them.
4271     unsigned VAArgBase;
4272     Triple TargetTriple(F.getParent()->getTargetTriple());
4273     // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
4274     // and 32 bytes for ABIv2.  This is usually determined by target
4275     // endianness, but in theory could be overriden by function attribute.
4276     // For simplicity, we ignore it here (it'd only matter for QPX vectors).
4277     if (TargetTriple.getArch() == Triple::ppc64)
4278       VAArgBase = 48;
4279     else
4280       VAArgBase = 32;
4281     unsigned VAArgOffset = VAArgBase;
4282     const DataLayout &DL = F.getParent()->getDataLayout();
4283     for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
4284          ArgIt != End; ++ArgIt) {
4285       Value *A = *ArgIt;
4286       unsigned ArgNo = CS.getArgumentNo(ArgIt);
4287       bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
4288       bool IsByVal = CS.paramHasAttr(ArgNo, Attribute::ByVal);
4289       if (IsByVal) {
4290         assert(A->getType()->isPointerTy());
4291         Type *RealTy = A->getType()->getPointerElementType();
4292         uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
4293         uint64_t ArgAlign = CS.getParamAlignment(ArgNo);
4294         if (ArgAlign < 8)
4295           ArgAlign = 8;
4296         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4297         if (!IsFixed) {
4298           Value *Base = getShadowPtrForVAArgument(
4299               RealTy, IRB, VAArgOffset - VAArgBase, ArgSize);
4300           if (Base) {
4301             Value *AShadowPtr, *AOriginPtr;
4302             std::tie(AShadowPtr, AOriginPtr) =
4303                 MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(),
4304                                        kShadowTLSAlignment, /*isStore*/ false);
4305 
4306             IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr,
4307                              kShadowTLSAlignment, ArgSize);
4308           }
4309         }
4310         VAArgOffset += alignTo(ArgSize, 8);
4311       } else {
4312         Value *Base;
4313         uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
4314         uint64_t ArgAlign = 8;
4315         if (A->getType()->isArrayTy()) {
4316           // Arrays are aligned to element size, except for long double
4317           // arrays, which are aligned to 8 bytes.
4318           Type *ElementTy = A->getType()->getArrayElementType();
4319           if (!ElementTy->isPPC_FP128Ty())
4320             ArgAlign = DL.getTypeAllocSize(ElementTy);
4321         } else if (A->getType()->isVectorTy()) {
4322           // Vectors are naturally aligned.
4323           ArgAlign = DL.getTypeAllocSize(A->getType());
4324         }
4325         if (ArgAlign < 8)
4326           ArgAlign = 8;
4327         VAArgOffset = alignTo(VAArgOffset, ArgAlign);
4328         if (DL.isBigEndian()) {
4329           // Adjusting the shadow for argument with size < 8 to match the placement
4330           // of bits in big endian system
4331           if (ArgSize < 8)
4332             VAArgOffset += (8 - ArgSize);
4333         }
4334         if (!IsFixed) {
4335           Base = getShadowPtrForVAArgument(A->getType(), IRB,
4336                                            VAArgOffset - VAArgBase, ArgSize);
4337           if (Base)
4338             IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
4339         }
4340         VAArgOffset += ArgSize;
4341         VAArgOffset = alignTo(VAArgOffset, 8);
4342       }
4343       if (IsFixed)
4344         VAArgBase = VAArgOffset;
4345     }
4346 
4347     Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(),
4348                                                 VAArgOffset - VAArgBase);
4349     // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
4350     // a new class member i.e. it is the total size of all VarArgs.
4351     IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
4352   }
4353 
4354   /// Compute the shadow address for a given va_arg.
4355   Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
4356                                    unsigned ArgOffset, unsigned ArgSize) {
4357     // Make sure we don't overflow __msan_va_arg_tls.
4358     if (ArgOffset + ArgSize > kParamTLSSize)
4359       return nullptr;
4360     Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
4361     Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
4362     return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
4363                               "_msarg");
4364   }
4365 
4366   void visitVAStartInst(VAStartInst &I) override {
4367     IRBuilder<> IRB(&I);
4368     VAStartInstrumentationList.push_back(&I);
4369     Value *VAListTag = I.getArgOperand(0);
4370     Value *ShadowPtr, *OriginPtr;
4371     unsigned Alignment = 8;
4372     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4373         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4374     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4375                      /* size */ 8, Alignment, false);
4376   }
4377 
4378   void visitVACopyInst(VACopyInst &I) override {
4379     IRBuilder<> IRB(&I);
4380     Value *VAListTag = I.getArgOperand(0);
4381     Value *ShadowPtr, *OriginPtr;
4382     unsigned Alignment = 8;
4383     std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr(
4384         VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true);
4385     // Unpoison the whole __va_list_tag.
4386     // FIXME: magic ABI constants.
4387     IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
4388                      /* size */ 8, Alignment, false);
4389   }
4390 
4391   void finalizeInstrumentation() override {
4392     assert(!VAArgSize && !VAArgTLSCopy &&
4393            "finalizeInstrumentation called twice");
4394     IRBuilder<> IRB(MSV.ActualFnStart->getFirstNonPHI());
4395     VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
4396     Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
4397                                     VAArgSize);
4398 
4399     if (!VAStartInstrumentationList.empty()) {
4400       // If there is a va_start in this function, make a backup copy of
4401       // va_arg_tls somewhere in the function entry block.
4402       VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
4403       IRB.CreateMemCpy(VAArgTLSCopy, 8, MS.VAArgTLS, 8, CopySize);
4404     }
4405 
4406     // Instrument va_start.
4407     // Copy va_list shadow from the backup copy of the TLS contents.
4408     for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
4409       CallInst *OrigInst = VAStartInstrumentationList[i];
4410       IRBuilder<> IRB(OrigInst->getNextNode());
4411       Value *VAListTag = OrigInst->getArgOperand(0);
4412       Value *RegSaveAreaPtrPtr =
4413           IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
4414                              PointerType::get(Type::getInt64PtrTy(*MS.C), 0));
4415       Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
4416       Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr;
4417       unsigned Alignment = 8;
4418       std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) =
4419           MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(),
4420                                  Alignment, /*isStore*/ true);
4421       IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment,
4422                        CopySize);
4423     }
4424   }
4425 };
4426 
4427 /// A no-op implementation of VarArgHelper.
4428 struct VarArgNoOpHelper : public VarArgHelper {
4429   VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
4430                    MemorySanitizerVisitor &MSV) {}
4431 
4432   void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
4433 
4434   void visitVAStartInst(VAStartInst &I) override {}
4435 
4436   void visitVACopyInst(VACopyInst &I) override {}
4437 
4438   void finalizeInstrumentation() override {}
4439 };
4440 
4441 } // end anonymous namespace
4442 
4443 static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
4444                                         MemorySanitizerVisitor &Visitor) {
4445   // VarArg handling is only implemented on AMD64. False positives are possible
4446   // on other platforms.
4447   Triple TargetTriple(Func.getParent()->getTargetTriple());
4448   if (TargetTriple.getArch() == Triple::x86_64)
4449     return new VarArgAMD64Helper(Func, Msan, Visitor);
4450   else if (TargetTriple.isMIPS64())
4451     return new VarArgMIPS64Helper(Func, Msan, Visitor);
4452   else if (TargetTriple.getArch() == Triple::aarch64)
4453     return new VarArgAArch64Helper(Func, Msan, Visitor);
4454   else if (TargetTriple.getArch() == Triple::ppc64 ||
4455            TargetTriple.getArch() == Triple::ppc64le)
4456     return new VarArgPowerPC64Helper(Func, Msan, Visitor);
4457   else
4458     return new VarArgNoOpHelper(Func, Msan, Visitor);
4459 }
4460 
4461 bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) {
4462   MemorySanitizerVisitor Visitor(F, *this, TLI);
4463 
4464   // Clear out readonly/readnone attributes.
4465   AttrBuilder B;
4466   B.addAttribute(Attribute::ReadOnly)
4467     .addAttribute(Attribute::ReadNone);
4468   F.removeAttributes(AttributeList::FunctionIndex, B);
4469 
4470   return Visitor.runOnFunction();
4471 }
4472