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