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