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