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