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