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