| File: | build/source/llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp |
| Warning: | line 1927, column 7 Forming reference to null pointer |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
| 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 | /// Note that the sanitizer code has to deal with how shadow/origin pairs | ||||
| 126 | /// returned by the these functions are represented in different ABIs. In | ||||
| 127 | /// the X86_64 ABI they are returned in RDX:RAX, and in the SystemZ ABI they | ||||
| 128 | /// are written to memory pointed to by a hidden parameter. | ||||
| 129 | /// - TLS variables are stored in a single per-task struct. A call to a | ||||
| 130 | /// function __msan_get_context_state() returning a pointer to that struct | ||||
| 131 | /// is inserted into every instrumented function before the entry block; | ||||
| 132 | /// - __msan_warning() takes a 32-bit origin parameter; | ||||
| 133 | /// - local variables are poisoned with __msan_poison_alloca() upon function | ||||
| 134 | /// entry and unpoisoned with __msan_unpoison_alloca() before leaving the | ||||
| 135 | /// function; | ||||
| 136 | /// - the pass doesn't declare any global variables or add global constructors | ||||
| 137 | /// to the translation unit. | ||||
| 138 | /// | ||||
| 139 | /// Also, KMSAN currently ignores uninitialized memory passed into inline asm | ||||
| 140 | /// calls, making sure we're on the safe side wrt. possible false positives. | ||||
| 141 | /// | ||||
| 142 | /// KernelMemorySanitizer only supports X86_64 and SystemZ at the moment. | ||||
| 143 | /// | ||||
| 144 | // | ||||
| 145 | // FIXME: This sanitizer does not yet handle scalable vectors | ||||
| 146 | // | ||||
| 147 | //===----------------------------------------------------------------------===// | ||||
| 148 | |||||
| 149 | #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" | ||||
| 150 | #include "llvm/ADT/APInt.h" | ||||
| 151 | #include "llvm/ADT/ArrayRef.h" | ||||
| 152 | #include "llvm/ADT/DenseMap.h" | ||||
| 153 | #include "llvm/ADT/DepthFirstIterator.h" | ||||
| 154 | #include "llvm/ADT/SetVector.h" | ||||
| 155 | #include "llvm/ADT/SmallString.h" | ||||
| 156 | #include "llvm/ADT/SmallVector.h" | ||||
| 157 | #include "llvm/ADT/StringExtras.h" | ||||
| 158 | #include "llvm/ADT/StringRef.h" | ||||
| 159 | #include "llvm/Analysis/GlobalsModRef.h" | ||||
| 160 | #include "llvm/Analysis/TargetLibraryInfo.h" | ||||
| 161 | #include "llvm/Analysis/ValueTracking.h" | ||||
| 162 | #include "llvm/IR/Argument.h" | ||||
| 163 | #include "llvm/IR/Attributes.h" | ||||
| 164 | #include "llvm/IR/BasicBlock.h" | ||||
| 165 | #include "llvm/IR/CallingConv.h" | ||||
| 166 | #include "llvm/IR/Constant.h" | ||||
| 167 | #include "llvm/IR/Constants.h" | ||||
| 168 | #include "llvm/IR/DataLayout.h" | ||||
| 169 | #include "llvm/IR/DerivedTypes.h" | ||||
| 170 | #include "llvm/IR/Function.h" | ||||
| 171 | #include "llvm/IR/GlobalValue.h" | ||||
| 172 | #include "llvm/IR/GlobalVariable.h" | ||||
| 173 | #include "llvm/IR/IRBuilder.h" | ||||
| 174 | #include "llvm/IR/InlineAsm.h" | ||||
| 175 | #include "llvm/IR/InstVisitor.h" | ||||
| 176 | #include "llvm/IR/InstrTypes.h" | ||||
| 177 | #include "llvm/IR/Instruction.h" | ||||
| 178 | #include "llvm/IR/Instructions.h" | ||||
| 179 | #include "llvm/IR/IntrinsicInst.h" | ||||
| 180 | #include "llvm/IR/Intrinsics.h" | ||||
| 181 | #include "llvm/IR/IntrinsicsX86.h" | ||||
| 182 | #include "llvm/IR/MDBuilder.h" | ||||
| 183 | #include "llvm/IR/Module.h" | ||||
| 184 | #include "llvm/IR/Type.h" | ||||
| 185 | #include "llvm/IR/Value.h" | ||||
| 186 | #include "llvm/IR/ValueMap.h" | ||||
| 187 | #include "llvm/Support/Alignment.h" | ||||
| 188 | #include "llvm/Support/AtomicOrdering.h" | ||||
| 189 | #include "llvm/Support/Casting.h" | ||||
| 190 | #include "llvm/Support/CommandLine.h" | ||||
| 191 | #include "llvm/Support/Debug.h" | ||||
| 192 | #include "llvm/Support/DebugCounter.h" | ||||
| 193 | #include "llvm/Support/ErrorHandling.h" | ||||
| 194 | #include "llvm/Support/MathExtras.h" | ||||
| 195 | #include "llvm/Support/raw_ostream.h" | ||||
| 196 | #include "llvm/TargetParser/Triple.h" | ||||
| 197 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" | ||||
| 198 | #include "llvm/Transforms/Utils/Local.h" | ||||
| 199 | #include "llvm/Transforms/Utils/ModuleUtils.h" | ||||
| 200 | #include <algorithm> | ||||
| 201 | #include <cassert> | ||||
| 202 | #include <cstddef> | ||||
| 203 | #include <cstdint> | ||||
| 204 | #include <memory> | ||||
| 205 | #include <string> | ||||
| 206 | #include <tuple> | ||||
| 207 | |||||
| 208 | using namespace llvm; | ||||
| 209 | |||||
| 210 | #define DEBUG_TYPE"msan" "msan" | ||||
| 211 | |||||
| 212 | DEBUG_COUNTER(DebugInsertCheck, "msan-insert-check",static const unsigned DebugInsertCheck = DebugCounter::registerCounter ("msan-insert-check", "Controls which checks to insert") | ||||
| 213 | "Controls which checks to insert")static const unsigned DebugInsertCheck = DebugCounter::registerCounter ("msan-insert-check", "Controls which checks to insert"); | ||||
| 214 | |||||
| 215 | static const unsigned kOriginSize = 4; | ||||
| 216 | static const Align kMinOriginAlignment = Align(4); | ||||
| 217 | static const Align kShadowTLSAlignment = Align(8); | ||||
| 218 | |||||
| 219 | // These constants must be kept in sync with the ones in msan.h. | ||||
| 220 | static const unsigned kParamTLSSize = 800; | ||||
| 221 | static const unsigned kRetvalTLSSize = 800; | ||||
| 222 | |||||
| 223 | // Accesses sizes are powers of two: 1, 2, 4, 8. | ||||
| 224 | static const size_t kNumberOfAccessSizes = 4; | ||||
| 225 | |||||
| 226 | /// Track origins of uninitialized values. | ||||
| 227 | /// | ||||
| 228 | /// Adds a section to MemorySanitizer report that points to the allocation | ||||
| 229 | /// (stack or heap) the uninitialized bits came from originally. | ||||
| 230 | static cl::opt<int> ClTrackOrigins( | ||||
| 231 | "msan-track-origins", | ||||
| 232 | cl::desc("Track origins (allocation sites) of poisoned memory"), cl::Hidden, | ||||
| 233 | cl::init(0)); | ||||
| 234 | |||||
| 235 | static cl::opt<bool> ClKeepGoing("msan-keep-going", | ||||
| 236 | cl::desc("keep going after reporting a UMR"), | ||||
| 237 | cl::Hidden, cl::init(false)); | ||||
| 238 | |||||
| 239 | static cl::opt<bool> | ||||
| 240 | ClPoisonStack("msan-poison-stack", | ||||
| 241 | cl::desc("poison uninitialized stack variables"), cl::Hidden, | ||||
| 242 | cl::init(true)); | ||||
| 243 | |||||
| 244 | static cl::opt<bool> ClPoisonStackWithCall( | ||||
| 245 | "msan-poison-stack-with-call", | ||||
| 246 | cl::desc("poison uninitialized stack variables with a call"), cl::Hidden, | ||||
| 247 | cl::init(false)); | ||||
| 248 | |||||
| 249 | static cl::opt<int> ClPoisonStackPattern( | ||||
| 250 | "msan-poison-stack-pattern", | ||||
| 251 | cl::desc("poison uninitialized stack variables with the given pattern"), | ||||
| 252 | cl::Hidden, cl::init(0xff)); | ||||
| 253 | |||||
| 254 | static cl::opt<bool> | ||||
| 255 | ClPrintStackNames("msan-print-stack-names", | ||||
| 256 | cl::desc("Print name of local stack variable"), | ||||
| 257 | cl::Hidden, cl::init(true)); | ||||
| 258 | |||||
| 259 | static cl::opt<bool> ClPoisonUndef("msan-poison-undef", | ||||
| 260 | cl::desc("poison undef temps"), cl::Hidden, | ||||
| 261 | cl::init(true)); | ||||
| 262 | |||||
| 263 | static cl::opt<bool> | ||||
| 264 | ClHandleICmp("msan-handle-icmp", | ||||
| 265 | cl::desc("propagate shadow through ICmpEQ and ICmpNE"), | ||||
| 266 | cl::Hidden, cl::init(true)); | ||||
| 267 | |||||
| 268 | static cl::opt<bool> | ||||
| 269 | ClHandleICmpExact("msan-handle-icmp-exact", | ||||
| 270 | cl::desc("exact handling of relational integer ICmp"), | ||||
| 271 | cl::Hidden, cl::init(false)); | ||||
| 272 | |||||
| 273 | static cl::opt<bool> ClHandleLifetimeIntrinsics( | ||||
| 274 | "msan-handle-lifetime-intrinsics", | ||||
| 275 | cl::desc( | ||||
| 276 | "when possible, poison scoped variables at the beginning of the scope " | ||||
| 277 | "(slower, but more precise)"), | ||||
| 278 | cl::Hidden, cl::init(true)); | ||||
| 279 | |||||
| 280 | // When compiling the Linux kernel, we sometimes see false positives related to | ||||
| 281 | // MSan being unable to understand that inline assembly calls may initialize | ||||
| 282 | // local variables. | ||||
| 283 | // This flag makes the compiler conservatively unpoison every memory location | ||||
| 284 | // passed into an assembly call. Note that this may cause false positives. | ||||
| 285 | // Because it's impossible to figure out the array sizes, we can only unpoison | ||||
| 286 | // the first sizeof(type) bytes for each type* pointer. | ||||
| 287 | // The instrumentation is only enabled in KMSAN builds, and only if | ||||
| 288 | // -msan-handle-asm-conservative is on. This is done because we may want to | ||||
| 289 | // quickly disable assembly instrumentation when it breaks. | ||||
| 290 | static cl::opt<bool> ClHandleAsmConservative( | ||||
| 291 | "msan-handle-asm-conservative", | ||||
| 292 | cl::desc("conservative handling of inline assembly"), cl::Hidden, | ||||
| 293 | cl::init(true)); | ||||
| 294 | |||||
| 295 | // This flag controls whether we check the shadow of the address | ||||
| 296 | // operand of load or store. Such bugs are very rare, since load from | ||||
| 297 | // a garbage address typically results in SEGV, but still happen | ||||
| 298 | // (e.g. only lower bits of address are garbage, or the access happens | ||||
| 299 | // early at program startup where malloc-ed memory is more likely to | ||||
| 300 | // be zeroed. As of 2012-08-28 this flag adds 20% slowdown. | ||||
| 301 | static cl::opt<bool> ClCheckAccessAddress( | ||||
| 302 | "msan-check-access-address", | ||||
| 303 | cl::desc("report accesses through a pointer which has poisoned shadow"), | ||||
| 304 | cl::Hidden, cl::init(true)); | ||||
| 305 | |||||
| 306 | static cl::opt<bool> ClEagerChecks( | ||||
| 307 | "msan-eager-checks", | ||||
| 308 | cl::desc("check arguments and return values at function call boundaries"), | ||||
| 309 | cl::Hidden, cl::init(false)); | ||||
| 310 | |||||
| 311 | static cl::opt<bool> ClDumpStrictInstructions( | ||||
| 312 | "msan-dump-strict-instructions", | ||||
| 313 | cl::desc("print out instructions with default strict semantics"), | ||||
| 314 | cl::Hidden, cl::init(false)); | ||||
| 315 | |||||
| 316 | static cl::opt<int> ClInstrumentationWithCallThreshold( | ||||
| 317 | "msan-instrumentation-with-call-threshold", | ||||
| 318 | cl::desc( | ||||
| 319 | "If the function being instrumented requires more than " | ||||
| 320 | "this number of checks and origin stores, use callbacks instead of " | ||||
| 321 | "inline checks (-1 means never use callbacks)."), | ||||
| 322 | cl::Hidden, cl::init(3500)); | ||||
| 323 | |||||
| 324 | static cl::opt<bool> | ||||
| 325 | ClEnableKmsan("msan-kernel", | ||||
| 326 | cl::desc("Enable KernelMemorySanitizer instrumentation"), | ||||
| 327 | cl::Hidden, cl::init(false)); | ||||
| 328 | |||||
| 329 | static cl::opt<bool> | ||||
| 330 | ClDisableChecks("msan-disable-checks", | ||||
| 331 | cl::desc("Apply no_sanitize to the whole file"), cl::Hidden, | ||||
| 332 | cl::init(false)); | ||||
| 333 | |||||
| 334 | static cl::opt<bool> | ||||
| 335 | ClCheckConstantShadow("msan-check-constant-shadow", | ||||
| 336 | cl::desc("Insert checks for constant shadow values"), | ||||
| 337 | cl::Hidden, cl::init(true)); | ||||
| 338 | |||||
| 339 | // This is off by default because of a bug in gold: | ||||
| 340 | // https://sourceware.org/bugzilla/show_bug.cgi?id=19002 | ||||
| 341 | static cl::opt<bool> | ||||
| 342 | ClWithComdat("msan-with-comdat", | ||||
| 343 | cl::desc("Place MSan constructors in comdat sections"), | ||||
| 344 | cl::Hidden, cl::init(false)); | ||||
| 345 | |||||
| 346 | // These options allow to specify custom memory map parameters | ||||
| 347 | // See MemoryMapParams for details. | ||||
| 348 | static cl::opt<uint64_t> ClAndMask("msan-and-mask", | ||||
| 349 | cl::desc("Define custom MSan AndMask"), | ||||
| 350 | cl::Hidden, cl::init(0)); | ||||
| 351 | |||||
| 352 | static cl::opt<uint64_t> ClXorMask("msan-xor-mask", | ||||
| 353 | cl::desc("Define custom MSan XorMask"), | ||||
| 354 | cl::Hidden, cl::init(0)); | ||||
| 355 | |||||
| 356 | static cl::opt<uint64_t> ClShadowBase("msan-shadow-base", | ||||
| 357 | cl::desc("Define custom MSan ShadowBase"), | ||||
| 358 | cl::Hidden, cl::init(0)); | ||||
| 359 | |||||
| 360 | static cl::opt<uint64_t> ClOriginBase("msan-origin-base", | ||||
| 361 | cl::desc("Define custom MSan OriginBase"), | ||||
| 362 | cl::Hidden, cl::init(0)); | ||||
| 363 | |||||
| 364 | static cl::opt<int> | ||||
| 365 | ClDisambiguateWarning("msan-disambiguate-warning-threshold", | ||||
| 366 | cl::desc("Define threshold for number of checks per " | ||||
| 367 | "debug location to force origin update."), | ||||
| 368 | cl::Hidden, cl::init(3)); | ||||
| 369 | |||||
| 370 | const char kMsanModuleCtorName[] = "msan.module_ctor"; | ||||
| 371 | const char kMsanInitName[] = "__msan_init"; | ||||
| 372 | |||||
| 373 | namespace { | ||||
| 374 | |||||
| 375 | // Memory map parameters used in application-to-shadow address calculation. | ||||
| 376 | // Offset = (Addr & ~AndMask) ^ XorMask | ||||
| 377 | // Shadow = ShadowBase + Offset | ||||
| 378 | // Origin = OriginBase + Offset | ||||
| 379 | struct MemoryMapParams { | ||||
| 380 | uint64_t AndMask; | ||||
| 381 | uint64_t XorMask; | ||||
| 382 | uint64_t ShadowBase; | ||||
| 383 | uint64_t OriginBase; | ||||
| 384 | }; | ||||
| 385 | |||||
| 386 | struct PlatformMemoryMapParams { | ||||
| 387 | const MemoryMapParams *bits32; | ||||
| 388 | const MemoryMapParams *bits64; | ||||
| 389 | }; | ||||
| 390 | |||||
| 391 | } // end anonymous namespace | ||||
| 392 | |||||
| 393 | // i386 Linux | ||||
| 394 | static const MemoryMapParams Linux_I386_MemoryMapParams = { | ||||
| 395 | 0x000080000000, // AndMask | ||||
| 396 | 0, // XorMask (not used) | ||||
| 397 | 0, // ShadowBase (not used) | ||||
| 398 | 0x000040000000, // OriginBase | ||||
| 399 | }; | ||||
| 400 | |||||
| 401 | // x86_64 Linux | ||||
| 402 | static const MemoryMapParams Linux_X86_64_MemoryMapParams = { | ||||
| 403 | 0, // AndMask (not used) | ||||
| 404 | 0x500000000000, // XorMask | ||||
| 405 | 0, // ShadowBase (not used) | ||||
| 406 | 0x100000000000, // OriginBase | ||||
| 407 | }; | ||||
| 408 | |||||
| 409 | // mips64 Linux | ||||
| 410 | static const MemoryMapParams Linux_MIPS64_MemoryMapParams = { | ||||
| 411 | 0, // AndMask (not used) | ||||
| 412 | 0x008000000000, // XorMask | ||||
| 413 | 0, // ShadowBase (not used) | ||||
| 414 | 0x002000000000, // OriginBase | ||||
| 415 | }; | ||||
| 416 | |||||
| 417 | // ppc64 Linux | ||||
| 418 | static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = { | ||||
| 419 | 0xE00000000000, // AndMask | ||||
| 420 | 0x100000000000, // XorMask | ||||
| 421 | 0x080000000000, // ShadowBase | ||||
| 422 | 0x1C0000000000, // OriginBase | ||||
| 423 | }; | ||||
| 424 | |||||
| 425 | // s390x Linux | ||||
| 426 | static const MemoryMapParams Linux_S390X_MemoryMapParams = { | ||||
| 427 | 0xC00000000000, // AndMask | ||||
| 428 | 0, // XorMask (not used) | ||||
| 429 | 0x080000000000, // ShadowBase | ||||
| 430 | 0x1C0000000000, // OriginBase | ||||
| 431 | }; | ||||
| 432 | |||||
| 433 | // aarch64 Linux | ||||
| 434 | static const MemoryMapParams Linux_AArch64_MemoryMapParams = { | ||||
| 435 | 0, // AndMask (not used) | ||||
| 436 | 0x0B00000000000, // XorMask | ||||
| 437 | 0, // ShadowBase (not used) | ||||
| 438 | 0x0200000000000, // OriginBase | ||||
| 439 | }; | ||||
| 440 | |||||
| 441 | // aarch64 FreeBSD | ||||
| 442 | static const MemoryMapParams FreeBSD_AArch64_MemoryMapParams = { | ||||
| 443 | 0x1800000000000, // AndMask | ||||
| 444 | 0x0400000000000, // XorMask | ||||
| 445 | 0x0200000000000, // ShadowBase | ||||
| 446 | 0x0700000000000, // OriginBase | ||||
| 447 | }; | ||||
| 448 | |||||
| 449 | // i386 FreeBSD | ||||
| 450 | static const MemoryMapParams FreeBSD_I386_MemoryMapParams = { | ||||
| 451 | 0x000180000000, // AndMask | ||||
| 452 | 0x000040000000, // XorMask | ||||
| 453 | 0x000020000000, // ShadowBase | ||||
| 454 | 0x000700000000, // OriginBase | ||||
| 455 | }; | ||||
| 456 | |||||
| 457 | // x86_64 FreeBSD | ||||
| 458 | static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = { | ||||
| 459 | 0xc00000000000, // AndMask | ||||
| 460 | 0x200000000000, // XorMask | ||||
| 461 | 0x100000000000, // ShadowBase | ||||
| 462 | 0x380000000000, // OriginBase | ||||
| 463 | }; | ||||
| 464 | |||||
| 465 | // x86_64 NetBSD | ||||
| 466 | static const MemoryMapParams NetBSD_X86_64_MemoryMapParams = { | ||||
| 467 | 0, // AndMask | ||||
| 468 | 0x500000000000, // XorMask | ||||
| 469 | 0, // ShadowBase | ||||
| 470 | 0x100000000000, // OriginBase | ||||
| 471 | }; | ||||
| 472 | |||||
| 473 | static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = { | ||||
| 474 | &Linux_I386_MemoryMapParams, | ||||
| 475 | &Linux_X86_64_MemoryMapParams, | ||||
| 476 | }; | ||||
| 477 | |||||
| 478 | static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = { | ||||
| 479 | nullptr, | ||||
| 480 | &Linux_MIPS64_MemoryMapParams, | ||||
| 481 | }; | ||||
| 482 | |||||
| 483 | static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = { | ||||
| 484 | nullptr, | ||||
| 485 | &Linux_PowerPC64_MemoryMapParams, | ||||
| 486 | }; | ||||
| 487 | |||||
| 488 | static const PlatformMemoryMapParams Linux_S390_MemoryMapParams = { | ||||
| 489 | nullptr, | ||||
| 490 | &Linux_S390X_MemoryMapParams, | ||||
| 491 | }; | ||||
| 492 | |||||
| 493 | static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = { | ||||
| 494 | nullptr, | ||||
| 495 | &Linux_AArch64_MemoryMapParams, | ||||
| 496 | }; | ||||
| 497 | |||||
| 498 | static const PlatformMemoryMapParams FreeBSD_ARM_MemoryMapParams = { | ||||
| 499 | nullptr, | ||||
| 500 | &FreeBSD_AArch64_MemoryMapParams, | ||||
| 501 | }; | ||||
| 502 | |||||
| 503 | static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = { | ||||
| 504 | &FreeBSD_I386_MemoryMapParams, | ||||
| 505 | &FreeBSD_X86_64_MemoryMapParams, | ||||
| 506 | }; | ||||
| 507 | |||||
| 508 | static const PlatformMemoryMapParams NetBSD_X86_MemoryMapParams = { | ||||
| 509 | nullptr, | ||||
| 510 | &NetBSD_X86_64_MemoryMapParams, | ||||
| 511 | }; | ||||
| 512 | |||||
| 513 | namespace { | ||||
| 514 | |||||
| 515 | /// Instrument functions of a module to detect uninitialized reads. | ||||
| 516 | /// | ||||
| 517 | /// Instantiating MemorySanitizer inserts the msan runtime library API function | ||||
| 518 | /// declarations into the module if they don't exist already. Instantiating | ||||
| 519 | /// ensures the __msan_init function is in the list of global constructors for | ||||
| 520 | /// the module. | ||||
| 521 | class MemorySanitizer { | ||||
| 522 | public: | ||||
| 523 | MemorySanitizer(Module &M, MemorySanitizerOptions Options) | ||||
| 524 | : CompileKernel(Options.Kernel), TrackOrigins(Options.TrackOrigins), | ||||
| 525 | Recover(Options.Recover), EagerChecks(Options.EagerChecks) { | ||||
| 526 | initializeModule(M); | ||||
| 527 | } | ||||
| 528 | |||||
| 529 | // MSan cannot be moved or copied because of MapParams. | ||||
| 530 | MemorySanitizer(MemorySanitizer &&) = delete; | ||||
| 531 | MemorySanitizer &operator=(MemorySanitizer &&) = delete; | ||||
| 532 | MemorySanitizer(const MemorySanitizer &) = delete; | ||||
| 533 | MemorySanitizer &operator=(const MemorySanitizer &) = delete; | ||||
| 534 | |||||
| 535 | bool sanitizeFunction(Function &F, TargetLibraryInfo &TLI); | ||||
| 536 | |||||
| 537 | private: | ||||
| 538 | friend struct MemorySanitizerVisitor; | ||||
| 539 | friend struct VarArgAMD64Helper; | ||||
| 540 | friend struct VarArgMIPS64Helper; | ||||
| 541 | friend struct VarArgAArch64Helper; | ||||
| 542 | friend struct VarArgPowerPC64Helper; | ||||
| 543 | friend struct VarArgSystemZHelper; | ||||
| 544 | |||||
| 545 | void initializeModule(Module &M); | ||||
| 546 | void initializeCallbacks(Module &M, const TargetLibraryInfo &TLI); | ||||
| 547 | void createKernelApi(Module &M, const TargetLibraryInfo &TLI); | ||||
| 548 | void createUserspaceApi(Module &M, const TargetLibraryInfo &TLI); | ||||
| 549 | |||||
| 550 | template <typename... ArgsTy> | ||||
| 551 | FunctionCallee getOrInsertMsanMetadataFunction(Module &M, StringRef Name, | ||||
| 552 | ArgsTy... Args); | ||||
| 553 | |||||
| 554 | /// True if we're compiling the Linux kernel. | ||||
| 555 | bool CompileKernel; | ||||
| 556 | /// Track origins (allocation points) of uninitialized values. | ||||
| 557 | int TrackOrigins; | ||||
| 558 | bool Recover; | ||||
| 559 | bool EagerChecks; | ||||
| 560 | |||||
| 561 | Triple TargetTriple; | ||||
| 562 | LLVMContext *C; | ||||
| 563 | Type *IntptrTy; | ||||
| 564 | Type *OriginTy; | ||||
| 565 | |||||
| 566 | // XxxTLS variables represent the per-thread state in MSan and per-task state | ||||
| 567 | // in KMSAN. | ||||
| 568 | // For the userspace these point to thread-local globals. In the kernel land | ||||
| 569 | // they point to the members of a per-task struct obtained via a call to | ||||
| 570 | // __msan_get_context_state(). | ||||
| 571 | |||||
| 572 | /// Thread-local shadow storage for function parameters. | ||||
| 573 | Value *ParamTLS; | ||||
| 574 | |||||
| 575 | /// Thread-local origin storage for function parameters. | ||||
| 576 | Value *ParamOriginTLS; | ||||
| 577 | |||||
| 578 | /// Thread-local shadow storage for function return value. | ||||
| 579 | Value *RetvalTLS; | ||||
| 580 | |||||
| 581 | /// Thread-local origin storage for function return value. | ||||
| 582 | Value *RetvalOriginTLS; | ||||
| 583 | |||||
| 584 | /// Thread-local shadow storage for in-register va_arg function | ||||
| 585 | /// parameters (x86_64-specific). | ||||
| 586 | Value *VAArgTLS; | ||||
| 587 | |||||
| 588 | /// Thread-local shadow storage for in-register va_arg function | ||||
| 589 | /// parameters (x86_64-specific). | ||||
| 590 | Value *VAArgOriginTLS; | ||||
| 591 | |||||
| 592 | /// Thread-local shadow storage for va_arg overflow area | ||||
| 593 | /// (x86_64-specific). | ||||
| 594 | Value *VAArgOverflowSizeTLS; | ||||
| 595 | |||||
| 596 | /// Are the instrumentation callbacks set up? | ||||
| 597 | bool CallbacksInitialized = false; | ||||
| 598 | |||||
| 599 | /// The run-time callback to print a warning. | ||||
| 600 | FunctionCallee WarningFn; | ||||
| 601 | |||||
| 602 | // These arrays are indexed by log2(AccessSize). | ||||
| 603 | FunctionCallee MaybeWarningFn[kNumberOfAccessSizes]; | ||||
| 604 | FunctionCallee MaybeStoreOriginFn[kNumberOfAccessSizes]; | ||||
| 605 | |||||
| 606 | /// Run-time helper that generates a new origin value for a stack | ||||
| 607 | /// allocation. | ||||
| 608 | FunctionCallee MsanSetAllocaOriginWithDescriptionFn; | ||||
| 609 | // No description version | ||||
| 610 | FunctionCallee MsanSetAllocaOriginNoDescriptionFn; | ||||
| 611 | |||||
| 612 | /// Run-time helper that poisons stack on function entry. | ||||
| 613 | FunctionCallee MsanPoisonStackFn; | ||||
| 614 | |||||
| 615 | /// Run-time helper that records a store (or any event) of an | ||||
| 616 | /// uninitialized value and returns an updated origin id encoding this info. | ||||
| 617 | FunctionCallee MsanChainOriginFn; | ||||
| 618 | |||||
| 619 | /// Run-time helper that paints an origin over a region. | ||||
| 620 | FunctionCallee MsanSetOriginFn; | ||||
| 621 | |||||
| 622 | /// MSan runtime replacements for memmove, memcpy and memset. | ||||
| 623 | FunctionCallee MemmoveFn, MemcpyFn, MemsetFn; | ||||
| 624 | |||||
| 625 | /// KMSAN callback for task-local function argument shadow. | ||||
| 626 | StructType *MsanContextStateTy; | ||||
| 627 | FunctionCallee MsanGetContextStateFn; | ||||
| 628 | |||||
| 629 | /// Functions for poisoning/unpoisoning local variables | ||||
| 630 | FunctionCallee MsanPoisonAllocaFn, MsanUnpoisonAllocaFn; | ||||
| 631 | |||||
| 632 | /// Pair of shadow/origin pointers. | ||||
| 633 | Type *MsanMetadata; | ||||
| 634 | |||||
| 635 | /// Each of the MsanMetadataPtrXxx functions returns a MsanMetadata. | ||||
| 636 | FunctionCallee MsanMetadataPtrForLoadN, MsanMetadataPtrForStoreN; | ||||
| 637 | FunctionCallee MsanMetadataPtrForLoad_1_8[4]; | ||||
| 638 | FunctionCallee MsanMetadataPtrForStore_1_8[4]; | ||||
| 639 | FunctionCallee MsanInstrumentAsmStoreFn; | ||||
| 640 | |||||
| 641 | /// Storage for return values of the MsanMetadataPtrXxx functions. | ||||
| 642 | Value *MsanMetadataAlloca; | ||||
| 643 | |||||
| 644 | /// Helper to choose between different MsanMetadataPtrXxx(). | ||||
| 645 | FunctionCallee getKmsanShadowOriginAccessFn(bool isStore, int size); | ||||
| 646 | |||||
| 647 | /// Memory map parameters used in application-to-shadow calculation. | ||||
| 648 | const MemoryMapParams *MapParams; | ||||
| 649 | |||||
| 650 | /// Custom memory map parameters used when -msan-shadow-base or | ||||
| 651 | // -msan-origin-base is provided. | ||||
| 652 | MemoryMapParams CustomMapParams; | ||||
| 653 | |||||
| 654 | MDNode *ColdCallWeights; | ||||
| 655 | |||||
| 656 | /// Branch weights for origin store. | ||||
| 657 | MDNode *OriginStoreWeights; | ||||
| 658 | }; | ||||
| 659 | |||||
| 660 | void insertModuleCtor(Module &M) { | ||||
| 661 | getOrCreateSanitizerCtorAndInitFunctions( | ||||
| 662 | M, kMsanModuleCtorName, kMsanInitName, | ||||
| 663 | /*InitArgTypes=*/{}, | ||||
| 664 | /*InitArgs=*/{}, | ||||
| 665 | // This callback is invoked when the functions are created the first | ||||
| 666 | // time. Hook them into the global ctors list in that case: | ||||
| 667 | [&](Function *Ctor, FunctionCallee) { | ||||
| 668 | if (!ClWithComdat) { | ||||
| 669 | appendToGlobalCtors(M, Ctor, 0); | ||||
| 670 | return; | ||||
| 671 | } | ||||
| 672 | Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName); | ||||
| 673 | Ctor->setComdat(MsanCtorComdat); | ||||
| 674 | appendToGlobalCtors(M, Ctor, 0, Ctor); | ||||
| 675 | }); | ||||
| 676 | } | ||||
| 677 | |||||
| 678 | template <class T> T getOptOrDefault(const cl::opt<T> &Opt, T Default) { | ||||
| 679 | return (Opt.getNumOccurrences() > 0) ? Opt : Default; | ||||
| 680 | } | ||||
| 681 | |||||
| 682 | } // end anonymous namespace | ||||
| 683 | |||||
| 684 | MemorySanitizerOptions::MemorySanitizerOptions(int TO, bool R, bool K, | ||||
| 685 | bool EagerChecks) | ||||
| 686 | : Kernel(getOptOrDefault(ClEnableKmsan, K)), | ||||
| 687 | TrackOrigins(getOptOrDefault(ClTrackOrigins, Kernel ? 2 : TO)), | ||||
| 688 | Recover(getOptOrDefault(ClKeepGoing, Kernel || R)), | ||||
| 689 | EagerChecks(getOptOrDefault(ClEagerChecks, EagerChecks)) {} | ||||
| 690 | |||||
| 691 | PreservedAnalyses MemorySanitizerPass::run(Module &M, | ||||
| 692 | ModuleAnalysisManager &AM) { | ||||
| 693 | bool Modified = false; | ||||
| 694 | if (!Options.Kernel) { | ||||
| 695 | insertModuleCtor(M); | ||||
| 696 | Modified = true; | ||||
| 697 | } | ||||
| 698 | |||||
| 699 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); | ||||
| 700 | for (Function &F : M) { | ||||
| 701 | if (F.empty()) | ||||
| 702 | continue; | ||||
| 703 | MemorySanitizer Msan(*F.getParent(), Options); | ||||
| 704 | Modified |= | ||||
| 705 | Msan.sanitizeFunction(F, FAM.getResult<TargetLibraryAnalysis>(F)); | ||||
| 706 | } | ||||
| 707 | |||||
| 708 | if (!Modified) | ||||
| 709 | return PreservedAnalyses::all(); | ||||
| 710 | |||||
| 711 | PreservedAnalyses PA = PreservedAnalyses::none(); | ||||
| 712 | // GlobalsAA is considered stateless and does not get invalidated unless | ||||
| 713 | // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers | ||||
| 714 | // make changes that require GlobalsAA to be invalidated. | ||||
| 715 | PA.abandon<GlobalsAA>(); | ||||
| 716 | return PA; | ||||
| 717 | } | ||||
| 718 | |||||
| 719 | void MemorySanitizerPass::printPipeline( | ||||
| 720 | raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { | ||||
| 721 | static_cast<PassInfoMixin<MemorySanitizerPass> *>(this)->printPipeline( | ||||
| 722 | OS, MapClassName2PassName); | ||||
| 723 | OS << '<'; | ||||
| 724 | if (Options.Recover) | ||||
| 725 | OS << "recover;"; | ||||
| 726 | if (Options.Kernel) | ||||
| 727 | OS << "kernel;"; | ||||
| 728 | if (Options.EagerChecks) | ||||
| 729 | OS << "eager-checks;"; | ||||
| 730 | OS << "track-origins=" << Options.TrackOrigins; | ||||
| 731 | OS << '>'; | ||||
| 732 | } | ||||
| 733 | |||||
| 734 | /// Create a non-const global initialized with the given string. | ||||
| 735 | /// | ||||
| 736 | /// Creates a writable global for Str so that we can pass it to the | ||||
| 737 | /// run-time lib. Runtime uses first 4 bytes of the string to store the | ||||
| 738 | /// frame ID, so the string needs to be mutable. | ||||
| 739 | static GlobalVariable *createPrivateConstGlobalForString(Module &M, | ||||
| 740 | StringRef Str) { | ||||
| 741 | Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str); | ||||
| 742 | return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/true, | ||||
| 743 | GlobalValue::PrivateLinkage, StrConst, ""); | ||||
| 744 | } | ||||
| 745 | |||||
| 746 | template <typename... ArgsTy> | ||||
| 747 | FunctionCallee | ||||
| 748 | MemorySanitizer::getOrInsertMsanMetadataFunction(Module &M, StringRef Name, | ||||
| 749 | ArgsTy... Args) { | ||||
| 750 | if (TargetTriple.getArch() == Triple::systemz) { | ||||
| 751 | // SystemZ ABI: shadow/origin pair is returned via a hidden parameter. | ||||
| 752 | return M.getOrInsertFunction(Name, Type::getVoidTy(*C), | ||||
| 753 | PointerType::get(MsanMetadata, 0), | ||||
| 754 | std::forward<ArgsTy>(Args)...); | ||||
| 755 | } | ||||
| 756 | |||||
| 757 | return M.getOrInsertFunction(Name, MsanMetadata, | ||||
| 758 | std::forward<ArgsTy>(Args)...); | ||||
| 759 | } | ||||
| 760 | |||||
| 761 | /// Create KMSAN API callbacks. | ||||
| 762 | void MemorySanitizer::createKernelApi(Module &M, const TargetLibraryInfo &TLI) { | ||||
| 763 | IRBuilder<> IRB(*C); | ||||
| 764 | |||||
| 765 | // These will be initialized in insertKmsanPrologue(). | ||||
| 766 | RetvalTLS = nullptr; | ||||
| 767 | RetvalOriginTLS = nullptr; | ||||
| 768 | ParamTLS = nullptr; | ||||
| 769 | ParamOriginTLS = nullptr; | ||||
| 770 | VAArgTLS = nullptr; | ||||
| 771 | VAArgOriginTLS = nullptr; | ||||
| 772 | VAArgOverflowSizeTLS = nullptr; | ||||
| 773 | |||||
| 774 | WarningFn = M.getOrInsertFunction("__msan_warning", | ||||
| 775 | TLI.getAttrList(C, {0}, /*Signed=*/false), | ||||
| 776 | IRB.getVoidTy(), IRB.getInt32Ty()); | ||||
| 777 | |||||
| 778 | // Requests the per-task context state (kmsan_context_state*) from the | ||||
| 779 | // runtime library. | ||||
| 780 | MsanContextStateTy = StructType::get( | ||||
| 781 | ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), | ||||
| 782 | ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), | ||||
| 783 | ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), | ||||
| 784 | ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), /* va_arg_origin */ | ||||
| 785 | IRB.getInt64Ty(), ArrayType::get(OriginTy, kParamTLSSize / 4), OriginTy, | ||||
| 786 | OriginTy); | ||||
| 787 | MsanGetContextStateFn = M.getOrInsertFunction( | ||||
| 788 | "__msan_get_context_state", PointerType::get(MsanContextStateTy, 0)); | ||||
| 789 | |||||
| 790 | MsanMetadata = StructType::get(PointerType::get(IRB.getInt8Ty(), 0), | ||||
| 791 | PointerType::get(IRB.getInt32Ty(), 0)); | ||||
| 792 | |||||
| 793 | for (int ind = 0, size = 1; ind < 4; ind++, size <<= 1) { | ||||
| 794 | std::string name_load = | ||||
| 795 | "__msan_metadata_ptr_for_load_" + std::to_string(size); | ||||
| 796 | std::string name_store = | ||||
| 797 | "__msan_metadata_ptr_for_store_" + std::to_string(size); | ||||
| 798 | MsanMetadataPtrForLoad_1_8[ind] = getOrInsertMsanMetadataFunction( | ||||
| 799 | M, name_load, PointerType::get(IRB.getInt8Ty(), 0)); | ||||
| 800 | MsanMetadataPtrForStore_1_8[ind] = getOrInsertMsanMetadataFunction( | ||||
| 801 | M, name_store, PointerType::get(IRB.getInt8Ty(), 0)); | ||||
| 802 | } | ||||
| 803 | |||||
| 804 | MsanMetadataPtrForLoadN = getOrInsertMsanMetadataFunction( | ||||
| 805 | M, "__msan_metadata_ptr_for_load_n", PointerType::get(IRB.getInt8Ty(), 0), | ||||
| 806 | IRB.getInt64Ty()); | ||||
| 807 | MsanMetadataPtrForStoreN = getOrInsertMsanMetadataFunction( | ||||
| 808 | M, "__msan_metadata_ptr_for_store_n", | ||||
| 809 | PointerType::get(IRB.getInt8Ty(), 0), IRB.getInt64Ty()); | ||||
| 810 | |||||
| 811 | // Functions for poisoning and unpoisoning memory. | ||||
| 812 | MsanPoisonAllocaFn = | ||||
| 813 | M.getOrInsertFunction("__msan_poison_alloca", IRB.getVoidTy(), | ||||
| 814 | IRB.getInt8PtrTy(), IntptrTy, IRB.getInt8PtrTy()); | ||||
| 815 | MsanUnpoisonAllocaFn = M.getOrInsertFunction( | ||||
| 816 | "__msan_unpoison_alloca", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy); | ||||
| 817 | } | ||||
| 818 | |||||
| 819 | static Constant *getOrInsertGlobal(Module &M, StringRef Name, Type *Ty) { | ||||
| 820 | return M.getOrInsertGlobal(Name, Ty, [&] { | ||||
| 821 | return new GlobalVariable(M, Ty, false, GlobalVariable::ExternalLinkage, | ||||
| 822 | nullptr, Name, nullptr, | ||||
| 823 | GlobalVariable::InitialExecTLSModel); | ||||
| 824 | }); | ||||
| 825 | } | ||||
| 826 | |||||
| 827 | /// Insert declarations for userspace-specific functions and globals. | ||||
| 828 | void MemorySanitizer::createUserspaceApi(Module &M, const TargetLibraryInfo &TLI) { | ||||
| 829 | IRBuilder<> IRB(*C); | ||||
| 830 | |||||
| 831 | // Create the callback. | ||||
| 832 | // FIXME: this function should have "Cold" calling conv, | ||||
| 833 | // which is not yet implemented. | ||||
| 834 | if (TrackOrigins) { | ||||
| 835 | StringRef WarningFnName = Recover ? "__msan_warning_with_origin" | ||||
| 836 | : "__msan_warning_with_origin_noreturn"; | ||||
| 837 | WarningFn = M.getOrInsertFunction(WarningFnName, | ||||
| 838 | TLI.getAttrList(C, {0}, /*Signed=*/false), | ||||
| 839 | IRB.getVoidTy(), IRB.getInt32Ty()); | ||||
| 840 | } else { | ||||
| 841 | StringRef WarningFnName = | ||||
| 842 | Recover ? "__msan_warning" : "__msan_warning_noreturn"; | ||||
| 843 | WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy()); | ||||
| 844 | } | ||||
| 845 | |||||
| 846 | // Create the global TLS variables. | ||||
| 847 | RetvalTLS = | ||||
| 848 | getOrInsertGlobal(M, "__msan_retval_tls", | ||||
| 849 | ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8)); | ||||
| 850 | |||||
| 851 | RetvalOriginTLS = getOrInsertGlobal(M, "__msan_retval_origin_tls", OriginTy); | ||||
| 852 | |||||
| 853 | ParamTLS = | ||||
| 854 | getOrInsertGlobal(M, "__msan_param_tls", | ||||
| 855 | ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8)); | ||||
| 856 | |||||
| 857 | ParamOriginTLS = | ||||
| 858 | getOrInsertGlobal(M, "__msan_param_origin_tls", | ||||
| 859 | ArrayType::get(OriginTy, kParamTLSSize / 4)); | ||||
| 860 | |||||
| 861 | VAArgTLS = | ||||
| 862 | getOrInsertGlobal(M, "__msan_va_arg_tls", | ||||
| 863 | ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8)); | ||||
| 864 | |||||
| 865 | VAArgOriginTLS = | ||||
| 866 | getOrInsertGlobal(M, "__msan_va_arg_origin_tls", | ||||
| 867 | ArrayType::get(OriginTy, kParamTLSSize / 4)); | ||||
| 868 | |||||
| 869 | VAArgOverflowSizeTLS = | ||||
| 870 | getOrInsertGlobal(M, "__msan_va_arg_overflow_size_tls", IRB.getInt64Ty()); | ||||
| 871 | |||||
| 872 | for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes; | ||||
| 873 | AccessSizeIndex++) { | ||||
| 874 | unsigned AccessSize = 1 << AccessSizeIndex; | ||||
| 875 | std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize); | ||||
| 876 | MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction( | ||||
| 877 | FunctionName, TLI.getAttrList(C, {0, 1}, /*Signed=*/false), | ||||
| 878 | IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt32Ty()); | ||||
| 879 | |||||
| 880 | FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize); | ||||
| 881 | MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction( | ||||
| 882 | FunctionName, TLI.getAttrList(C, {0, 2}, /*Signed=*/false), | ||||
| 883 | IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8), IRB.getInt8PtrTy(), | ||||
| 884 | IRB.getInt32Ty()); | ||||
| 885 | } | ||||
| 886 | |||||
| 887 | MsanSetAllocaOriginWithDescriptionFn = M.getOrInsertFunction( | ||||
| 888 | "__msan_set_alloca_origin_with_descr", IRB.getVoidTy(), | ||||
| 889 | IRB.getInt8PtrTy(), IntptrTy, IRB.getInt8PtrTy(), IRB.getInt8PtrTy()); | ||||
| 890 | MsanSetAllocaOriginNoDescriptionFn = M.getOrInsertFunction( | ||||
| 891 | "__msan_set_alloca_origin_no_descr", IRB.getVoidTy(), IRB.getInt8PtrTy(), | ||||
| 892 | IntptrTy, IRB.getInt8PtrTy()); | ||||
| 893 | MsanPoisonStackFn = M.getOrInsertFunction( | ||||
| 894 | "__msan_poison_stack", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy); | ||||
| 895 | } | ||||
| 896 | |||||
| 897 | /// Insert extern declaration of runtime-provided functions and globals. | ||||
| 898 | void MemorySanitizer::initializeCallbacks(Module &M, const TargetLibraryInfo &TLI) { | ||||
| 899 | // Only do this once. | ||||
| 900 | if (CallbacksInitialized) | ||||
| 901 | return; | ||||
| 902 | |||||
| 903 | IRBuilder<> IRB(*C); | ||||
| 904 | // Initialize callbacks that are common for kernel and userspace | ||||
| 905 | // instrumentation. | ||||
| 906 | MsanChainOriginFn = M.getOrInsertFunction( | ||||
| 907 | "__msan_chain_origin", | ||||
| 908 | TLI.getAttrList(C, {0}, /*Signed=*/false, /*Ret=*/true), IRB.getInt32Ty(), | ||||
| 909 | IRB.getInt32Ty()); | ||||
| 910 | MsanSetOriginFn = M.getOrInsertFunction( | ||||
| 911 | "__msan_set_origin", TLI.getAttrList(C, {2}, /*Signed=*/false), | ||||
| 912 | IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy, IRB.getInt32Ty()); | ||||
| 913 | MemmoveFn = | ||||
| 914 | M.getOrInsertFunction("__msan_memmove", IRB.getInt8PtrTy(), | ||||
| 915 | IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy); | ||||
| 916 | MemcpyFn = | ||||
| 917 | M.getOrInsertFunction("__msan_memcpy", IRB.getInt8PtrTy(), | ||||
| 918 | IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy); | ||||
| 919 | MemsetFn = M.getOrInsertFunction( | ||||
| 920 | "__msan_memset", TLI.getAttrList(C, {1}, /*Signed=*/true), | ||||
| 921 | IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy); | ||||
| 922 | |||||
| 923 | MsanInstrumentAsmStoreFn = | ||||
| 924 | M.getOrInsertFunction("__msan_instrument_asm_store", IRB.getVoidTy(), | ||||
| 925 | PointerType::get(IRB.getInt8Ty(), 0), IntptrTy); | ||||
| 926 | |||||
| 927 | if (CompileKernel) { | ||||
| 928 | createKernelApi(M, TLI); | ||||
| 929 | } else { | ||||
| 930 | createUserspaceApi(M, TLI); | ||||
| 931 | } | ||||
| 932 | CallbacksInitialized = true; | ||||
| 933 | } | ||||
| 934 | |||||
| 935 | FunctionCallee MemorySanitizer::getKmsanShadowOriginAccessFn(bool isStore, | ||||
| 936 | int size) { | ||||
| 937 | FunctionCallee *Fns = | ||||
| 938 | isStore ? MsanMetadataPtrForStore_1_8 : MsanMetadataPtrForLoad_1_8; | ||||
| 939 | switch (size) { | ||||
| 940 | case 1: | ||||
| 941 | return Fns[0]; | ||||
| 942 | case 2: | ||||
| 943 | return Fns[1]; | ||||
| 944 | case 4: | ||||
| 945 | return Fns[2]; | ||||
| 946 | case 8: | ||||
| 947 | return Fns[3]; | ||||
| 948 | default: | ||||
| 949 | return nullptr; | ||||
| 950 | } | ||||
| 951 | } | ||||
| 952 | |||||
| 953 | /// Module-level initialization. | ||||
| 954 | /// | ||||
| 955 | /// inserts a call to __msan_init to the module's constructor list. | ||||
| 956 | void MemorySanitizer::initializeModule(Module &M) { | ||||
| 957 | auto &DL = M.getDataLayout(); | ||||
| 958 | |||||
| 959 | TargetTriple = Triple(M.getTargetTriple()); | ||||
| 960 | |||||
| 961 | bool ShadowPassed = ClShadowBase.getNumOccurrences() > 0; | ||||
| 962 | bool OriginPassed = ClOriginBase.getNumOccurrences() > 0; | ||||
| 963 | // Check the overrides first | ||||
| 964 | if (ShadowPassed || OriginPassed) { | ||||
| 965 | CustomMapParams.AndMask = ClAndMask; | ||||
| 966 | CustomMapParams.XorMask = ClXorMask; | ||||
| 967 | CustomMapParams.ShadowBase = ClShadowBase; | ||||
| 968 | CustomMapParams.OriginBase = ClOriginBase; | ||||
| 969 | MapParams = &CustomMapParams; | ||||
| 970 | } else { | ||||
| 971 | switch (TargetTriple.getOS()) { | ||||
| 972 | case Triple::FreeBSD: | ||||
| 973 | switch (TargetTriple.getArch()) { | ||||
| 974 | case Triple::aarch64: | ||||
| 975 | MapParams = FreeBSD_ARM_MemoryMapParams.bits64; | ||||
| 976 | break; | ||||
| 977 | case Triple::x86_64: | ||||
| 978 | MapParams = FreeBSD_X86_MemoryMapParams.bits64; | ||||
| 979 | break; | ||||
| 980 | case Triple::x86: | ||||
| 981 | MapParams = FreeBSD_X86_MemoryMapParams.bits32; | ||||
| 982 | break; | ||||
| 983 | default: | ||||
| 984 | report_fatal_error("unsupported architecture"); | ||||
| 985 | } | ||||
| 986 | break; | ||||
| 987 | case Triple::NetBSD: | ||||
| 988 | switch (TargetTriple.getArch()) { | ||||
| 989 | case Triple::x86_64: | ||||
| 990 | MapParams = NetBSD_X86_MemoryMapParams.bits64; | ||||
| 991 | break; | ||||
| 992 | default: | ||||
| 993 | report_fatal_error("unsupported architecture"); | ||||
| 994 | } | ||||
| 995 | break; | ||||
| 996 | case Triple::Linux: | ||||
| 997 | switch (TargetTriple.getArch()) { | ||||
| 998 | case Triple::x86_64: | ||||
| 999 | MapParams = Linux_X86_MemoryMapParams.bits64; | ||||
| 1000 | break; | ||||
| 1001 | case Triple::x86: | ||||
| 1002 | MapParams = Linux_X86_MemoryMapParams.bits32; | ||||
| 1003 | break; | ||||
| 1004 | case Triple::mips64: | ||||
| 1005 | case Triple::mips64el: | ||||
| 1006 | MapParams = Linux_MIPS_MemoryMapParams.bits64; | ||||
| 1007 | break; | ||||
| 1008 | case Triple::ppc64: | ||||
| 1009 | case Triple::ppc64le: | ||||
| 1010 | MapParams = Linux_PowerPC_MemoryMapParams.bits64; | ||||
| 1011 | break; | ||||
| 1012 | case Triple::systemz: | ||||
| 1013 | MapParams = Linux_S390_MemoryMapParams.bits64; | ||||
| 1014 | break; | ||||
| 1015 | case Triple::aarch64: | ||||
| 1016 | case Triple::aarch64_be: | ||||
| 1017 | MapParams = Linux_ARM_MemoryMapParams.bits64; | ||||
| 1018 | break; | ||||
| 1019 | default: | ||||
| 1020 | report_fatal_error("unsupported architecture"); | ||||
| 1021 | } | ||||
| 1022 | break; | ||||
| 1023 | default: | ||||
| 1024 | report_fatal_error("unsupported operating system"); | ||||
| 1025 | } | ||||
| 1026 | } | ||||
| 1027 | |||||
| 1028 | C = &(M.getContext()); | ||||
| 1029 | IRBuilder<> IRB(*C); | ||||
| 1030 | IntptrTy = IRB.getIntPtrTy(DL); | ||||
| 1031 | OriginTy = IRB.getInt32Ty(); | ||||
| 1032 | |||||
| 1033 | ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000); | ||||
| 1034 | OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000); | ||||
| 1035 | |||||
| 1036 | if (!CompileKernel) { | ||||
| 1037 | if (TrackOrigins) | ||||
| 1038 | M.getOrInsertGlobal("__msan_track_origins", IRB.getInt32Ty(), [&] { | ||||
| 1039 | return new GlobalVariable( | ||||
| 1040 | M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage, | ||||
| 1041 | IRB.getInt32(TrackOrigins), "__msan_track_origins"); | ||||
| 1042 | }); | ||||
| 1043 | |||||
| 1044 | if (Recover) | ||||
| 1045 | M.getOrInsertGlobal("__msan_keep_going", IRB.getInt32Ty(), [&] { | ||||
| 1046 | return new GlobalVariable(M, IRB.getInt32Ty(), true, | ||||
| 1047 | GlobalValue::WeakODRLinkage, | ||||
| 1048 | IRB.getInt32(Recover), "__msan_keep_going"); | ||||
| 1049 | }); | ||||
| 1050 | } | ||||
| 1051 | } | ||||
| 1052 | |||||
| 1053 | namespace { | ||||
| 1054 | |||||
| 1055 | /// A helper class that handles instrumentation of VarArg | ||||
| 1056 | /// functions on a particular platform. | ||||
| 1057 | /// | ||||
| 1058 | /// Implementations are expected to insert the instrumentation | ||||
| 1059 | /// necessary to propagate argument shadow through VarArg function | ||||
| 1060 | /// calls. Visit* methods are called during an InstVisitor pass over | ||||
| 1061 | /// the function, and should avoid creating new basic blocks. A new | ||||
| 1062 | /// instance of this class is created for each instrumented function. | ||||
| 1063 | struct VarArgHelper { | ||||
| 1064 | virtual ~VarArgHelper() = default; | ||||
| 1065 | |||||
| 1066 | /// Visit a CallBase. | ||||
| 1067 | virtual void visitCallBase(CallBase &CB, IRBuilder<> &IRB) = 0; | ||||
| 1068 | |||||
| 1069 | /// Visit a va_start call. | ||||
| 1070 | virtual void visitVAStartInst(VAStartInst &I) = 0; | ||||
| 1071 | |||||
| 1072 | /// Visit a va_copy call. | ||||
| 1073 | virtual void visitVACopyInst(VACopyInst &I) = 0; | ||||
| 1074 | |||||
| 1075 | /// Finalize function instrumentation. | ||||
| 1076 | /// | ||||
| 1077 | /// This method is called after visiting all interesting (see above) | ||||
| 1078 | /// instructions in a function. | ||||
| 1079 | virtual void finalizeInstrumentation() = 0; | ||||
| 1080 | }; | ||||
| 1081 | |||||
| 1082 | struct MemorySanitizerVisitor; | ||||
| 1083 | |||||
| 1084 | } // end anonymous namespace | ||||
| 1085 | |||||
| 1086 | static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, | ||||
| 1087 | MemorySanitizerVisitor &Visitor); | ||||
| 1088 | |||||
| 1089 | static unsigned TypeSizeToSizeIndex(TypeSize TS) { | ||||
| 1090 | if (TS.isScalable()) | ||||
| 1091 | // Scalable types unconditionally take slowpaths. | ||||
| 1092 | return kNumberOfAccessSizes; | ||||
| 1093 | unsigned TypeSizeFixed = TS.getFixedValue(); | ||||
| 1094 | if (TypeSizeFixed <= 8) | ||||
| 1095 | return 0; | ||||
| 1096 | return Log2_32_Ceil((TypeSizeFixed + 7) / 8); | ||||
| 1097 | } | ||||
| 1098 | |||||
| 1099 | namespace { | ||||
| 1100 | |||||
| 1101 | /// Helper class to attach debug information of the given instruction onto new | ||||
| 1102 | /// instructions inserted after. | ||||
| 1103 | class NextNodeIRBuilder : public IRBuilder<> { | ||||
| 1104 | public: | ||||
| 1105 | explicit NextNodeIRBuilder(Instruction *IP) : IRBuilder<>(IP->getNextNode()) { | ||||
| 1106 | SetCurrentDebugLocation(IP->getDebugLoc()); | ||||
| 1107 | } | ||||
| 1108 | }; | ||||
| 1109 | |||||
| 1110 | /// This class does all the work for a given function. Store and Load | ||||
| 1111 | /// instructions store and load corresponding shadow and origin | ||||
| 1112 | /// values. Most instructions propagate shadow from arguments to their | ||||
| 1113 | /// return values. Certain instructions (most importantly, BranchInst) | ||||
| 1114 | /// test their argument shadow and print reports (with a runtime call) if it's | ||||
| 1115 | /// non-zero. | ||||
| 1116 | struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> { | ||||
| 1117 | Function &F; | ||||
| 1118 | MemorySanitizer &MS; | ||||
| 1119 | SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes; | ||||
| 1120 | ValueMap<Value *, Value *> ShadowMap, OriginMap; | ||||
| 1121 | std::unique_ptr<VarArgHelper> VAHelper; | ||||
| 1122 | const TargetLibraryInfo *TLI; | ||||
| 1123 | Instruction *FnPrologueEnd; | ||||
| 1124 | |||||
| 1125 | // The following flags disable parts of MSan instrumentation based on | ||||
| 1126 | // exclusion list contents and command-line options. | ||||
| 1127 | bool InsertChecks; | ||||
| 1128 | bool PropagateShadow; | ||||
| 1129 | bool PoisonStack; | ||||
| 1130 | bool PoisonUndef; | ||||
| 1131 | |||||
| 1132 | struct ShadowOriginAndInsertPoint { | ||||
| 1133 | Value *Shadow; | ||||
| 1134 | Value *Origin; | ||||
| 1135 | Instruction *OrigIns; | ||||
| 1136 | |||||
| 1137 | ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I) | ||||
| 1138 | : Shadow(S), Origin(O), OrigIns(I) {} | ||||
| 1139 | }; | ||||
| 1140 | SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList; | ||||
| 1141 | DenseMap<const DILocation *, int> LazyWarningDebugLocationCount; | ||||
| 1142 | bool InstrumentLifetimeStart = ClHandleLifetimeIntrinsics; | ||||
| 1143 | SmallSetVector<AllocaInst *, 16> AllocaSet; | ||||
| 1144 | SmallVector<std::pair<IntrinsicInst *, AllocaInst *>, 16> LifetimeStartList; | ||||
| 1145 | SmallVector<StoreInst *, 16> StoreList; | ||||
| 1146 | int64_t SplittableBlocksCount = 0; | ||||
| 1147 | |||||
| 1148 | MemorySanitizerVisitor(Function &F, MemorySanitizer &MS, | ||||
| 1149 | const TargetLibraryInfo &TLI) | ||||
| 1150 | : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)), TLI(&TLI) { | ||||
| 1151 | bool SanitizeFunction = | ||||
| 1152 | F.hasFnAttribute(Attribute::SanitizeMemory) && !ClDisableChecks; | ||||
| 1153 | InsertChecks = SanitizeFunction; | ||||
| 1154 | PropagateShadow = SanitizeFunction; | ||||
| 1155 | PoisonStack = SanitizeFunction && ClPoisonStack; | ||||
| 1156 | PoisonUndef = SanitizeFunction && ClPoisonUndef; | ||||
| 1157 | |||||
| 1158 | // In the presence of unreachable blocks, we may see Phi nodes with | ||||
| 1159 | // incoming nodes from such blocks. Since InstVisitor skips unreachable | ||||
| 1160 | // blocks, such nodes will not have any shadow value associated with them. | ||||
| 1161 | // It's easier to remove unreachable blocks than deal with missing shadow. | ||||
| 1162 | removeUnreachableBlocks(F); | ||||
| 1163 | |||||
| 1164 | MS.initializeCallbacks(*F.getParent(), TLI); | ||||
| 1165 | FnPrologueEnd = IRBuilder<>(F.getEntryBlock().getFirstNonPHI()) | ||||
| 1166 | .CreateIntrinsic(Intrinsic::donothing, {}, {}); | ||||
| 1167 | |||||
| 1168 | if (MS.CompileKernel) { | ||||
| 1169 | IRBuilder<> IRB(FnPrologueEnd); | ||||
| 1170 | insertKmsanPrologue(IRB); | ||||
| 1171 | } | ||||
| 1172 | |||||
| 1173 | LLVM_DEBUG(if (!InsertChecks) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { if (!InsertChecks) dbgs() << "MemorySanitizer is not inserting checks into '" << F.getName() << "'\n"; } } while (false) | ||||
| 1174 | << "MemorySanitizer is not inserting checks into '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { if (!InsertChecks) dbgs() << "MemorySanitizer is not inserting checks into '" << F.getName() << "'\n"; } } while (false) | ||||
| 1175 | << F.getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { if (!InsertChecks) dbgs() << "MemorySanitizer is not inserting checks into '" << F.getName() << "'\n"; } } while (false); | ||||
| 1176 | } | ||||
| 1177 | |||||
| 1178 | bool instrumentWithCalls(Value *V) { | ||||
| 1179 | // Constants likely will be eliminated by follow-up passes. | ||||
| 1180 | if (isa<Constant>(V)) | ||||
| 1181 | return false; | ||||
| 1182 | |||||
| 1183 | ++SplittableBlocksCount; | ||||
| 1184 | return ClInstrumentationWithCallThreshold >= 0 && | ||||
| 1185 | SplittableBlocksCount > ClInstrumentationWithCallThreshold; | ||||
| 1186 | } | ||||
| 1187 | |||||
| 1188 | bool isInPrologue(Instruction &I) { | ||||
| 1189 | return I.getParent() == FnPrologueEnd->getParent() && | ||||
| 1190 | (&I == FnPrologueEnd || I.comesBefore(FnPrologueEnd)); | ||||
| 1191 | } | ||||
| 1192 | |||||
| 1193 | // Creates a new origin and records the stack trace. In general we can call | ||||
| 1194 | // this function for any origin manipulation we like. However it will cost | ||||
| 1195 | // runtime resources. So use this wisely only if it can provide additional | ||||
| 1196 | // information helpful to a user. | ||||
| 1197 | Value *updateOrigin(Value *V, IRBuilder<> &IRB) { | ||||
| 1198 | if (MS.TrackOrigins <= 1) | ||||
| 1199 | return V; | ||||
| 1200 | return IRB.CreateCall(MS.MsanChainOriginFn, V); | ||||
| 1201 | } | ||||
| 1202 | |||||
| 1203 | Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) { | ||||
| 1204 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1205 | unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy); | ||||
| 1206 | if (IntptrSize == kOriginSize) | ||||
| 1207 | return Origin; | ||||
| 1208 | assert(IntptrSize == kOriginSize * 2)(static_cast <bool> (IntptrSize == kOriginSize * 2) ? void (0) : __assert_fail ("IntptrSize == kOriginSize * 2", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1208, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1209 | Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false); | ||||
| 1210 | return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8)); | ||||
| 1211 | } | ||||
| 1212 | |||||
| 1213 | /// Fill memory range with the given origin value. | ||||
| 1214 | void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr, | ||||
| 1215 | TypeSize TS, Align Alignment) { | ||||
| 1216 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1217 | const Align IntptrAlignment = DL.getABITypeAlign(MS.IntptrTy); | ||||
| 1218 | unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy); | ||||
| 1219 | assert(IntptrAlignment >= kMinOriginAlignment)(static_cast <bool> (IntptrAlignment >= kMinOriginAlignment ) ? void (0) : __assert_fail ("IntptrAlignment >= kMinOriginAlignment" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1219 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1220 | assert(IntptrSize >= kOriginSize)(static_cast <bool> (IntptrSize >= kOriginSize) ? void (0) : __assert_fail ("IntptrSize >= kOriginSize", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1220, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1221 | |||||
| 1222 | // Note: The loop based formation works for fixed length vectors too, | ||||
| 1223 | // however we prefer to unroll and specialize alignment below. | ||||
| 1224 | if (TS.isScalable()) { | ||||
| 1225 | Value *Size = IRB.CreateTypeSize(IRB.getInt32Ty(), TS); | ||||
| 1226 | Value *RoundUp = IRB.CreateAdd(Size, IRB.getInt32(kOriginSize - 1)); | ||||
| 1227 | Value *End = IRB.CreateUDiv(RoundUp, IRB.getInt32(kOriginSize)); | ||||
| 1228 | auto [InsertPt, Index] = | ||||
| 1229 | SplitBlockAndInsertSimpleForLoop(End, &*IRB.GetInsertPoint()); | ||||
| 1230 | IRB.SetInsertPoint(InsertPt); | ||||
| 1231 | |||||
| 1232 | Value *GEP = IRB.CreateGEP(MS.OriginTy, OriginPtr, Index); | ||||
| 1233 | IRB.CreateAlignedStore(Origin, GEP, kMinOriginAlignment); | ||||
| 1234 | return; | ||||
| 1235 | } | ||||
| 1236 | |||||
| 1237 | unsigned Size = TS.getFixedValue(); | ||||
| 1238 | |||||
| 1239 | unsigned Ofs = 0; | ||||
| 1240 | Align CurrentAlignment = Alignment; | ||||
| 1241 | if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) { | ||||
| 1242 | Value *IntptrOrigin = originToIntptr(IRB, Origin); | ||||
| 1243 | Value *IntptrOriginPtr = | ||||
| 1244 | IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0)); | ||||
| 1245 | for (unsigned i = 0; i < Size / IntptrSize; ++i) { | ||||
| 1246 | Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i) | ||||
| 1247 | : IntptrOriginPtr; | ||||
| 1248 | IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment); | ||||
| 1249 | Ofs += IntptrSize / kOriginSize; | ||||
| 1250 | CurrentAlignment = IntptrAlignment; | ||||
| 1251 | } | ||||
| 1252 | } | ||||
| 1253 | |||||
| 1254 | for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) { | ||||
| 1255 | Value *GEP = | ||||
| 1256 | i ? IRB.CreateConstGEP1_32(MS.OriginTy, OriginPtr, i) : OriginPtr; | ||||
| 1257 | IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment); | ||||
| 1258 | CurrentAlignment = kMinOriginAlignment; | ||||
| 1259 | } | ||||
| 1260 | } | ||||
| 1261 | |||||
| 1262 | void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin, | ||||
| 1263 | Value *OriginPtr, Align Alignment) { | ||||
| 1264 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1265 | const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment); | ||||
| 1266 | TypeSize StoreSize = DL.getTypeStoreSize(Shadow->getType()); | ||||
| 1267 | Value *ConvertedShadow = convertShadowToScalar(Shadow, IRB); | ||||
| 1268 | if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) { | ||||
| 1269 | if (!ClCheckConstantShadow || ConstantShadow->isZeroValue()) { | ||||
| 1270 | // Origin is not needed: value is initialized or const shadow is | ||||
| 1271 | // ignored. | ||||
| 1272 | return; | ||||
| 1273 | } | ||||
| 1274 | if (llvm::isKnownNonZero(ConvertedShadow, DL)) { | ||||
| 1275 | // Copy origin as the value is definitely uninitialized. | ||||
| 1276 | paintOrigin(IRB, updateOrigin(Origin, IRB), OriginPtr, StoreSize, | ||||
| 1277 | OriginAlignment); | ||||
| 1278 | return; | ||||
| 1279 | } | ||||
| 1280 | // Fallback to runtime check, which still can be optimized out later. | ||||
| 1281 | } | ||||
| 1282 | |||||
| 1283 | TypeSize TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType()); | ||||
| 1284 | unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits); | ||||
| 1285 | if (instrumentWithCalls(ConvertedShadow) && | ||||
| 1286 | SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) { | ||||
| 1287 | FunctionCallee Fn = MS.MaybeStoreOriginFn[SizeIndex]; | ||||
| 1288 | Value *ConvertedShadow2 = | ||||
| 1289 | IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex))); | ||||
| 1290 | CallBase *CB = IRB.CreateCall( | ||||
| 1291 | Fn, {ConvertedShadow2, | ||||
| 1292 | IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()), Origin}); | ||||
| 1293 | CB->addParamAttr(0, Attribute::ZExt); | ||||
| 1294 | CB->addParamAttr(2, Attribute::ZExt); | ||||
| 1295 | } else { | ||||
| 1296 | Value *Cmp = convertToBool(ConvertedShadow, IRB, "_mscmp"); | ||||
| 1297 | Instruction *CheckTerm = SplitBlockAndInsertIfThen( | ||||
| 1298 | Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights); | ||||
| 1299 | IRBuilder<> IRBNew(CheckTerm); | ||||
| 1300 | paintOrigin(IRBNew, updateOrigin(Origin, IRBNew), OriginPtr, StoreSize, | ||||
| 1301 | OriginAlignment); | ||||
| 1302 | } | ||||
| 1303 | } | ||||
| 1304 | |||||
| 1305 | void materializeStores() { | ||||
| 1306 | for (StoreInst *SI : StoreList) { | ||||
| 1307 | IRBuilder<> IRB(SI); | ||||
| 1308 | Value *Val = SI->getValueOperand(); | ||||
| 1309 | Value *Addr = SI->getPointerOperand(); | ||||
| 1310 | Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val); | ||||
| 1311 | Value *ShadowPtr, *OriginPtr; | ||||
| 1312 | Type *ShadowTy = Shadow->getType(); | ||||
| 1313 | const Align Alignment = SI->getAlign(); | ||||
| 1314 | const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment); | ||||
| 1315 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 1316 | getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ true); | ||||
| 1317 | |||||
| 1318 | StoreInst *NewSI = IRB.CreateAlignedStore(Shadow, ShadowPtr, Alignment); | ||||
| 1319 | LLVM_DEBUG(dbgs() << " STORE: " << *NewSI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " STORE: " << *NewSI << "\n"; } } while (false); | ||||
| 1320 | (void)NewSI; | ||||
| 1321 | |||||
| 1322 | if (SI->isAtomic()) | ||||
| 1323 | SI->setOrdering(addReleaseOrdering(SI->getOrdering())); | ||||
| 1324 | |||||
| 1325 | if (MS.TrackOrigins && !SI->isAtomic()) | ||||
| 1326 | storeOrigin(IRB, Addr, Shadow, getOrigin(Val), OriginPtr, | ||||
| 1327 | OriginAlignment); | ||||
| 1328 | } | ||||
| 1329 | } | ||||
| 1330 | |||||
| 1331 | // Returns true if Debug Location curresponds to multiple warnings. | ||||
| 1332 | bool shouldDisambiguateWarningLocation(const DebugLoc &DebugLoc) { | ||||
| 1333 | if (MS.TrackOrigins < 2) | ||||
| 1334 | return false; | ||||
| 1335 | |||||
| 1336 | if (LazyWarningDebugLocationCount.empty()) | ||||
| 1337 | for (const auto &I : InstrumentationList) | ||||
| 1338 | ++LazyWarningDebugLocationCount[I.OrigIns->getDebugLoc()]; | ||||
| 1339 | |||||
| 1340 | return LazyWarningDebugLocationCount[DebugLoc] >= ClDisambiguateWarning; | ||||
| 1341 | } | ||||
| 1342 | |||||
| 1343 | /// Helper function to insert a warning at IRB's current insert point. | ||||
| 1344 | void insertWarningFn(IRBuilder<> &IRB, Value *Origin) { | ||||
| 1345 | if (!Origin) | ||||
| 1346 | Origin = (Value *)IRB.getInt32(0); | ||||
| 1347 | assert(Origin->getType()->isIntegerTy())(static_cast <bool> (Origin->getType()->isIntegerTy ()) ? void (0) : __assert_fail ("Origin->getType()->isIntegerTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1347 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1348 | |||||
| 1349 | if (shouldDisambiguateWarningLocation(IRB.getCurrentDebugLocation())) { | ||||
| 1350 | // Try to create additional origin with debug info of the last origin | ||||
| 1351 | // instruction. It may provide additional information to the user. | ||||
| 1352 | if (Instruction *OI = dyn_cast_or_null<Instruction>(Origin)) { | ||||
| 1353 | assert(MS.TrackOrigins)(static_cast <bool> (MS.TrackOrigins) ? void (0) : __assert_fail ("MS.TrackOrigins", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1353, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1354 | auto NewDebugLoc = OI->getDebugLoc(); | ||||
| 1355 | // Origin update with missing or the same debug location provides no | ||||
| 1356 | // additional value. | ||||
| 1357 | if (NewDebugLoc && NewDebugLoc != IRB.getCurrentDebugLocation()) { | ||||
| 1358 | // Insert update just before the check, so we call runtime only just | ||||
| 1359 | // before the report. | ||||
| 1360 | IRBuilder<> IRBOrigin(&*IRB.GetInsertPoint()); | ||||
| 1361 | IRBOrigin.SetCurrentDebugLocation(NewDebugLoc); | ||||
| 1362 | Origin = updateOrigin(Origin, IRBOrigin); | ||||
| 1363 | } | ||||
| 1364 | } | ||||
| 1365 | } | ||||
| 1366 | |||||
| 1367 | if (MS.CompileKernel || MS.TrackOrigins) | ||||
| 1368 | IRB.CreateCall(MS.WarningFn, Origin)->setCannotMerge(); | ||||
| 1369 | else | ||||
| 1370 | IRB.CreateCall(MS.WarningFn)->setCannotMerge(); | ||||
| 1371 | // FIXME: Insert UnreachableInst if !MS.Recover? | ||||
| 1372 | // This may invalidate some of the following checks and needs to be done | ||||
| 1373 | // at the very end. | ||||
| 1374 | } | ||||
| 1375 | |||||
| 1376 | void materializeOneCheck(IRBuilder<> &IRB, Value *ConvertedShadow, | ||||
| 1377 | Value *Origin) { | ||||
| 1378 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1379 | TypeSize TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType()); | ||||
| 1380 | unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits); | ||||
| 1381 | if (instrumentWithCalls(ConvertedShadow) && | ||||
| 1382 | SizeIndex < kNumberOfAccessSizes && !MS.CompileKernel) { | ||||
| 1383 | FunctionCallee Fn = MS.MaybeWarningFn[SizeIndex]; | ||||
| 1384 | Value *ConvertedShadow2 = | ||||
| 1385 | IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex))); | ||||
| 1386 | CallBase *CB = IRB.CreateCall( | ||||
| 1387 | Fn, {ConvertedShadow2, | ||||
| 1388 | MS.TrackOrigins && Origin ? Origin : (Value *)IRB.getInt32(0)}); | ||||
| 1389 | CB->addParamAttr(0, Attribute::ZExt); | ||||
| 1390 | CB->addParamAttr(1, Attribute::ZExt); | ||||
| 1391 | } else { | ||||
| 1392 | Value *Cmp = convertToBool(ConvertedShadow, IRB, "_mscmp"); | ||||
| 1393 | Instruction *CheckTerm = SplitBlockAndInsertIfThen( | ||||
| 1394 | Cmp, &*IRB.GetInsertPoint(), | ||||
| 1395 | /* Unreachable */ !MS.Recover, MS.ColdCallWeights); | ||||
| 1396 | |||||
| 1397 | IRB.SetInsertPoint(CheckTerm); | ||||
| 1398 | insertWarningFn(IRB, Origin); | ||||
| 1399 | LLVM_DEBUG(dbgs() << " CHECK: " << *Cmp << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " CHECK: " << *Cmp << "\n"; } } while (false); | ||||
| 1400 | } | ||||
| 1401 | } | ||||
| 1402 | |||||
| 1403 | void materializeInstructionChecks( | ||||
| 1404 | ArrayRef<ShadowOriginAndInsertPoint> InstructionChecks) { | ||||
| 1405 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1406 | // Disable combining in some cases. TrackOrigins checks each shadow to pick | ||||
| 1407 | // correct origin. | ||||
| 1408 | bool Combine = !MS.TrackOrigins; | ||||
| 1409 | Instruction *Instruction = InstructionChecks.front().OrigIns; | ||||
| 1410 | Value *Shadow = nullptr; | ||||
| 1411 | for (const auto &ShadowData : InstructionChecks) { | ||||
| 1412 | assert(ShadowData.OrigIns == Instruction)(static_cast <bool> (ShadowData.OrigIns == Instruction) ? void (0) : __assert_fail ("ShadowData.OrigIns == Instruction" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1412 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1413 | IRBuilder<> IRB(Instruction); | ||||
| 1414 | |||||
| 1415 | Value *ConvertedShadow = ShadowData.Shadow; | ||||
| 1416 | |||||
| 1417 | if (auto *ConstantShadow = dyn_cast<Constant>(ConvertedShadow)) { | ||||
| 1418 | if (!ClCheckConstantShadow || ConstantShadow->isZeroValue()) { | ||||
| 1419 | // Skip, value is initialized or const shadow is ignored. | ||||
| 1420 | continue; | ||||
| 1421 | } | ||||
| 1422 | if (llvm::isKnownNonZero(ConvertedShadow, DL)) { | ||||
| 1423 | // Report as the value is definitely uninitialized. | ||||
| 1424 | insertWarningFn(IRB, ShadowData.Origin); | ||||
| 1425 | if (!MS.Recover) | ||||
| 1426 | return; // Always fail and stop here, not need to check the rest. | ||||
| 1427 | // Skip entire instruction, | ||||
| 1428 | continue; | ||||
| 1429 | } | ||||
| 1430 | // Fallback to runtime check, which still can be optimized out later. | ||||
| 1431 | } | ||||
| 1432 | |||||
| 1433 | if (!Combine) { | ||||
| 1434 | materializeOneCheck(IRB, ConvertedShadow, ShadowData.Origin); | ||||
| 1435 | continue; | ||||
| 1436 | } | ||||
| 1437 | |||||
| 1438 | if (!Shadow) { | ||||
| 1439 | Shadow = ConvertedShadow; | ||||
| 1440 | continue; | ||||
| 1441 | } | ||||
| 1442 | |||||
| 1443 | Shadow = convertToBool(Shadow, IRB, "_mscmp"); | ||||
| 1444 | ConvertedShadow = convertToBool(ConvertedShadow, IRB, "_mscmp"); | ||||
| 1445 | Shadow = IRB.CreateOr(Shadow, ConvertedShadow, "_msor"); | ||||
| 1446 | } | ||||
| 1447 | |||||
| 1448 | if (Shadow) { | ||||
| 1449 | assert(Combine)(static_cast <bool> (Combine) ? void (0) : __assert_fail ("Combine", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1449, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1450 | IRBuilder<> IRB(Instruction); | ||||
| 1451 | materializeOneCheck(IRB, Shadow, nullptr); | ||||
| 1452 | } | ||||
| 1453 | } | ||||
| 1454 | |||||
| 1455 | void materializeChecks() { | ||||
| 1456 | llvm::stable_sort(InstrumentationList, | ||||
| 1457 | [](const ShadowOriginAndInsertPoint &L, | ||||
| 1458 | const ShadowOriginAndInsertPoint &R) { | ||||
| 1459 | return L.OrigIns < R.OrigIns; | ||||
| 1460 | }); | ||||
| 1461 | |||||
| 1462 | for (auto I = InstrumentationList.begin(); | ||||
| 1463 | I != InstrumentationList.end();) { | ||||
| 1464 | auto J = | ||||
| 1465 | std::find_if(I + 1, InstrumentationList.end(), | ||||
| 1466 | [L = I->OrigIns](const ShadowOriginAndInsertPoint &R) { | ||||
| 1467 | return L != R.OrigIns; | ||||
| 1468 | }); | ||||
| 1469 | // Process all checks of instruction at once. | ||||
| 1470 | materializeInstructionChecks(ArrayRef<ShadowOriginAndInsertPoint>(I, J)); | ||||
| 1471 | I = J; | ||||
| 1472 | } | ||||
| 1473 | |||||
| 1474 | LLVM_DEBUG(dbgs() << "DONE:\n" << F)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "DONE:\n" << F; } } while ( false); | ||||
| 1475 | } | ||||
| 1476 | |||||
| 1477 | // Returns the last instruction in the new prologue | ||||
| 1478 | void insertKmsanPrologue(IRBuilder<> &IRB) { | ||||
| 1479 | Value *ContextState = IRB.CreateCall(MS.MsanGetContextStateFn, {}); | ||||
| 1480 | Constant *Zero = IRB.getInt32(0); | ||||
| 1481 | MS.ParamTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1482 | {Zero, IRB.getInt32(0)}, "param_shadow"); | ||||
| 1483 | MS.RetvalTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1484 | {Zero, IRB.getInt32(1)}, "retval_shadow"); | ||||
| 1485 | MS.VAArgTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1486 | {Zero, IRB.getInt32(2)}, "va_arg_shadow"); | ||||
| 1487 | MS.VAArgOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1488 | {Zero, IRB.getInt32(3)}, "va_arg_origin"); | ||||
| 1489 | MS.VAArgOverflowSizeTLS = | ||||
| 1490 | IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1491 | {Zero, IRB.getInt32(4)}, "va_arg_overflow_size"); | ||||
| 1492 | MS.ParamOriginTLS = IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1493 | {Zero, IRB.getInt32(5)}, "param_origin"); | ||||
| 1494 | MS.RetvalOriginTLS = | ||||
| 1495 | IRB.CreateGEP(MS.MsanContextStateTy, ContextState, | ||||
| 1496 | {Zero, IRB.getInt32(6)}, "retval_origin"); | ||||
| 1497 | if (MS.TargetTriple.getArch() == Triple::systemz) | ||||
| 1498 | MS.MsanMetadataAlloca = IRB.CreateAlloca(MS.MsanMetadata, 0u); | ||||
| 1499 | } | ||||
| 1500 | |||||
| 1501 | /// Add MemorySanitizer instrumentation to a function. | ||||
| 1502 | bool runOnFunction() { | ||||
| 1503 | // Iterate all BBs in depth-first order and create shadow instructions | ||||
| 1504 | // for all instructions (where applicable). | ||||
| 1505 | // For PHI nodes we create dummy shadow PHIs which will be finalized later. | ||||
| 1506 | for (BasicBlock *BB : depth_first(FnPrologueEnd->getParent())) | ||||
| 1507 | visit(*BB); | ||||
| 1508 | |||||
| 1509 | // Finalize PHI nodes. | ||||
| 1510 | for (PHINode *PN : ShadowPHINodes) { | ||||
| 1511 | PHINode *PNS = cast<PHINode>(getShadow(PN)); | ||||
| 1512 | PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr; | ||||
| 1513 | size_t NumValues = PN->getNumIncomingValues(); | ||||
| 1514 | for (size_t v = 0; v < NumValues; v++) { | ||||
| 1515 | PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v)); | ||||
| 1516 | if (PNO) | ||||
| 1517 | PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v)); | ||||
| 1518 | } | ||||
| 1519 | } | ||||
| 1520 | |||||
| 1521 | VAHelper->finalizeInstrumentation(); | ||||
| 1522 | |||||
| 1523 | // Poison llvm.lifetime.start intrinsics, if we haven't fallen back to | ||||
| 1524 | // instrumenting only allocas. | ||||
| 1525 | if (InstrumentLifetimeStart) { | ||||
| 1526 | for (auto Item : LifetimeStartList) { | ||||
| 1527 | instrumentAlloca(*Item.second, Item.first); | ||||
| 1528 | AllocaSet.remove(Item.second); | ||||
| 1529 | } | ||||
| 1530 | } | ||||
| 1531 | // Poison the allocas for which we didn't instrument the corresponding | ||||
| 1532 | // lifetime intrinsics. | ||||
| 1533 | for (AllocaInst *AI : AllocaSet) | ||||
| 1534 | instrumentAlloca(*AI); | ||||
| 1535 | |||||
| 1536 | // Insert shadow value checks. | ||||
| 1537 | materializeChecks(); | ||||
| 1538 | |||||
| 1539 | // Delayed instrumentation of StoreInst. | ||||
| 1540 | // This may not add new address checks. | ||||
| 1541 | materializeStores(); | ||||
| 1542 | |||||
| 1543 | return true; | ||||
| 1544 | } | ||||
| 1545 | |||||
| 1546 | /// Compute the shadow type that corresponds to a given Value. | ||||
| 1547 | Type *getShadowTy(Value *V) { return getShadowTy(V->getType()); } | ||||
| 1548 | |||||
| 1549 | /// Compute the shadow type that corresponds to a given Type. | ||||
| 1550 | Type *getShadowTy(Type *OrigTy) { | ||||
| 1551 | if (!OrigTy->isSized()) { | ||||
| 1552 | return nullptr; | ||||
| 1553 | } | ||||
| 1554 | // For integer type, shadow is the same as the original type. | ||||
| 1555 | // This may return weird-sized types like i1. | ||||
| 1556 | if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy)) | ||||
| 1557 | return IT; | ||||
| 1558 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1559 | if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) { | ||||
| 1560 | uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType()); | ||||
| 1561 | return VectorType::get(IntegerType::get(*MS.C, EltSize), | ||||
| 1562 | VT->getElementCount()); | ||||
| 1563 | } | ||||
| 1564 | if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) { | ||||
| 1565 | return ArrayType::get(getShadowTy(AT->getElementType()), | ||||
| 1566 | AT->getNumElements()); | ||||
| 1567 | } | ||||
| 1568 | if (StructType *ST = dyn_cast<StructType>(OrigTy)) { | ||||
| 1569 | SmallVector<Type *, 4> Elements; | ||||
| 1570 | for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) | ||||
| 1571 | Elements.push_back(getShadowTy(ST->getElementType(i))); | ||||
| 1572 | StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked()); | ||||
| 1573 | LLVM_DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n"; } } while (false); | ||||
| 1574 | return Res; | ||||
| 1575 | } | ||||
| 1576 | uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy); | ||||
| 1577 | return IntegerType::get(*MS.C, TypeSize); | ||||
| 1578 | } | ||||
| 1579 | |||||
| 1580 | /// Extract combined shadow of struct elements as a bool | ||||
| 1581 | Value *collapseStructShadow(StructType *Struct, Value *Shadow, | ||||
| 1582 | IRBuilder<> &IRB) { | ||||
| 1583 | Value *FalseVal = IRB.getIntN(/* width */ 1, /* value */ 0); | ||||
| 1584 | Value *Aggregator = FalseVal; | ||||
| 1585 | |||||
| 1586 | for (unsigned Idx = 0; Idx < Struct->getNumElements(); Idx++) { | ||||
| 1587 | // Combine by ORing together each element's bool shadow | ||||
| 1588 | Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx); | ||||
| 1589 | Value *ShadowBool = convertToBool(ShadowItem, IRB); | ||||
| 1590 | |||||
| 1591 | if (Aggregator != FalseVal) | ||||
| 1592 | Aggregator = IRB.CreateOr(Aggregator, ShadowBool); | ||||
| 1593 | else | ||||
| 1594 | Aggregator = ShadowBool; | ||||
| 1595 | } | ||||
| 1596 | |||||
| 1597 | return Aggregator; | ||||
| 1598 | } | ||||
| 1599 | |||||
| 1600 | // Extract combined shadow of array elements | ||||
| 1601 | Value *collapseArrayShadow(ArrayType *Array, Value *Shadow, | ||||
| 1602 | IRBuilder<> &IRB) { | ||||
| 1603 | if (!Array->getNumElements()) | ||||
| 1604 | return IRB.getIntN(/* width */ 1, /* value */ 0); | ||||
| 1605 | |||||
| 1606 | Value *FirstItem = IRB.CreateExtractValue(Shadow, 0); | ||||
| 1607 | Value *Aggregator = convertShadowToScalar(FirstItem, IRB); | ||||
| 1608 | |||||
| 1609 | for (unsigned Idx = 1; Idx < Array->getNumElements(); Idx++) { | ||||
| 1610 | Value *ShadowItem = IRB.CreateExtractValue(Shadow, Idx); | ||||
| 1611 | Value *ShadowInner = convertShadowToScalar(ShadowItem, IRB); | ||||
| 1612 | Aggregator = IRB.CreateOr(Aggregator, ShadowInner); | ||||
| 1613 | } | ||||
| 1614 | return Aggregator; | ||||
| 1615 | } | ||||
| 1616 | |||||
| 1617 | /// Convert a shadow value to it's flattened variant. The resulting | ||||
| 1618 | /// shadow may not necessarily have the same bit width as the input | ||||
| 1619 | /// value, but it will always be comparable to zero. | ||||
| 1620 | Value *convertShadowToScalar(Value *V, IRBuilder<> &IRB) { | ||||
| 1621 | if (StructType *Struct = dyn_cast<StructType>(V->getType())) | ||||
| 1622 | return collapseStructShadow(Struct, V, IRB); | ||||
| 1623 | if (ArrayType *Array = dyn_cast<ArrayType>(V->getType())) | ||||
| 1624 | return collapseArrayShadow(Array, V, IRB); | ||||
| 1625 | if (isa<VectorType>(V->getType())) { | ||||
| 1626 | if (isa<ScalableVectorType>(V->getType())) | ||||
| 1627 | return convertShadowToScalar(IRB.CreateOrReduce(V), IRB); | ||||
| 1628 | unsigned BitWidth = | ||||
| 1629 | V->getType()->getPrimitiveSizeInBits().getFixedValue(); | ||||
| 1630 | return IRB.CreateBitCast(V, IntegerType::get(*MS.C, BitWidth)); | ||||
| 1631 | } | ||||
| 1632 | return V; | ||||
| 1633 | } | ||||
| 1634 | |||||
| 1635 | // Convert a scalar value to an i1 by comparing with 0 | ||||
| 1636 | Value *convertToBool(Value *V, IRBuilder<> &IRB, const Twine &name = "") { | ||||
| 1637 | Type *VTy = V->getType(); | ||||
| 1638 | if (!VTy->isIntegerTy()) | ||||
| 1639 | return convertToBool(convertShadowToScalar(V, IRB), IRB, name); | ||||
| 1640 | if (VTy->getIntegerBitWidth() == 1) | ||||
| 1641 | // Just converting a bool to a bool, so do nothing. | ||||
| 1642 | return V; | ||||
| 1643 | return IRB.CreateICmpNE(V, ConstantInt::get(VTy, 0), name); | ||||
| 1644 | } | ||||
| 1645 | |||||
| 1646 | Type *ptrToIntPtrType(Type *PtrTy) const { | ||||
| 1647 | if (VectorType *VectTy = dyn_cast<VectorType>(PtrTy)) { | ||||
| 1648 | return VectorType::get(ptrToIntPtrType(VectTy->getElementType()), | ||||
| 1649 | VectTy->getElementCount()); | ||||
| 1650 | } | ||||
| 1651 | assert(PtrTy->isIntOrPtrTy())(static_cast <bool> (PtrTy->isIntOrPtrTy()) ? void ( 0) : __assert_fail ("PtrTy->isIntOrPtrTy()", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1651, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1652 | return MS.IntptrTy; | ||||
| 1653 | } | ||||
| 1654 | |||||
| 1655 | Type *getPtrToShadowPtrType(Type *IntPtrTy, Type *ShadowTy) const { | ||||
| 1656 | if (VectorType *VectTy = dyn_cast<VectorType>(IntPtrTy)) { | ||||
| 1657 | return VectorType::get( | ||||
| 1658 | getPtrToShadowPtrType(VectTy->getElementType(), ShadowTy), | ||||
| 1659 | VectTy->getElementCount()); | ||||
| 1660 | } | ||||
| 1661 | assert(IntPtrTy == MS.IntptrTy)(static_cast <bool> (IntPtrTy == MS.IntptrTy) ? void (0 ) : __assert_fail ("IntPtrTy == MS.IntptrTy", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1661, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1662 | return ShadowTy->getPointerTo(); | ||||
| 1663 | } | ||||
| 1664 | |||||
| 1665 | Constant *constToIntPtr(Type *IntPtrTy, uint64_t C) const { | ||||
| 1666 | if (VectorType *VectTy = dyn_cast<VectorType>(IntPtrTy)) { | ||||
| 1667 | return ConstantVector::getSplat( | ||||
| 1668 | VectTy->getElementCount(), constToIntPtr(VectTy->getElementType(), C)); | ||||
| 1669 | } | ||||
| 1670 | assert(IntPtrTy == MS.IntptrTy)(static_cast <bool> (IntPtrTy == MS.IntptrTy) ? void (0 ) : __assert_fail ("IntPtrTy == MS.IntptrTy", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1670, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1671 | return ConstantInt::get(MS.IntptrTy, C); | ||||
| 1672 | } | ||||
| 1673 | |||||
| 1674 | /// Compute the integer shadow offset that corresponds to a given | ||||
| 1675 | /// application address. | ||||
| 1676 | /// | ||||
| 1677 | /// Offset = (Addr & ~AndMask) ^ XorMask | ||||
| 1678 | /// Addr can be a ptr or <N x ptr>. In both cases ShadowTy the shadow type of | ||||
| 1679 | /// a single pointee. | ||||
| 1680 | /// Returns <shadow_ptr, origin_ptr> or <<N x shadow_ptr>, <N x origin_ptr>>. | ||||
| 1681 | Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) { | ||||
| 1682 | Type *IntptrTy = ptrToIntPtrType(Addr->getType()); | ||||
| 1683 | Value *OffsetLong = IRB.CreatePointerCast(Addr, IntptrTy); | ||||
| 1684 | |||||
| 1685 | if (uint64_t AndMask = MS.MapParams->AndMask) | ||||
| 1686 | OffsetLong = IRB.CreateAnd(OffsetLong, constToIntPtr(IntptrTy, ~AndMask)); | ||||
| 1687 | |||||
| 1688 | if (uint64_t XorMask = MS.MapParams->XorMask) | ||||
| 1689 | OffsetLong = IRB.CreateXor(OffsetLong, constToIntPtr(IntptrTy, XorMask)); | ||||
| 1690 | return OffsetLong; | ||||
| 1691 | } | ||||
| 1692 | |||||
| 1693 | /// Compute the shadow and origin addresses corresponding to a given | ||||
| 1694 | /// application address. | ||||
| 1695 | /// | ||||
| 1696 | /// Shadow = ShadowBase + Offset | ||||
| 1697 | /// Origin = (OriginBase + Offset) & ~3ULL | ||||
| 1698 | /// Addr can be a ptr or <N x ptr>. In both cases ShadowTy the shadow type of | ||||
| 1699 | /// a single pointee. | ||||
| 1700 | /// Returns <shadow_ptr, origin_ptr> or <<N x shadow_ptr>, <N x origin_ptr>>. | ||||
| 1701 | std::pair<Value *, Value *> | ||||
| 1702 | getShadowOriginPtrUserspace(Value *Addr, IRBuilder<> &IRB, Type *ShadowTy, | ||||
| 1703 | MaybeAlign Alignment) { | ||||
| 1704 | Type *IntptrTy = ptrToIntPtrType(Addr->getType()); | ||||
| 1705 | Value *ShadowOffset = getShadowPtrOffset(Addr, IRB); | ||||
| 1706 | Value *ShadowLong = ShadowOffset; | ||||
| 1707 | if (uint64_t ShadowBase = MS.MapParams->ShadowBase) { | ||||
| 1708 | ShadowLong = | ||||
| 1709 | IRB.CreateAdd(ShadowLong, constToIntPtr(IntptrTy, ShadowBase)); | ||||
| 1710 | } | ||||
| 1711 | Value *ShadowPtr = IRB.CreateIntToPtr( | ||||
| 1712 | ShadowLong, getPtrToShadowPtrType(IntptrTy, ShadowTy)); | ||||
| 1713 | |||||
| 1714 | Value *OriginPtr = nullptr; | ||||
| 1715 | if (MS.TrackOrigins) { | ||||
| 1716 | Value *OriginLong = ShadowOffset; | ||||
| 1717 | uint64_t OriginBase = MS.MapParams->OriginBase; | ||||
| 1718 | if (OriginBase != 0) | ||||
| 1719 | OriginLong = | ||||
| 1720 | IRB.CreateAdd(OriginLong, constToIntPtr(IntptrTy, OriginBase)); | ||||
| 1721 | if (!Alignment || *Alignment < kMinOriginAlignment) { | ||||
| 1722 | uint64_t Mask = kMinOriginAlignment.value() - 1; | ||||
| 1723 | OriginLong = IRB.CreateAnd(OriginLong, constToIntPtr(IntptrTy, ~Mask)); | ||||
| 1724 | } | ||||
| 1725 | OriginPtr = IRB.CreateIntToPtr( | ||||
| 1726 | OriginLong, getPtrToShadowPtrType(IntptrTy, MS.OriginTy)); | ||||
| 1727 | } | ||||
| 1728 | return std::make_pair(ShadowPtr, OriginPtr); | ||||
| 1729 | } | ||||
| 1730 | |||||
| 1731 | template <typename... ArgsTy> | ||||
| 1732 | Value *createMetadataCall(IRBuilder<> &IRB, FunctionCallee Callee, | ||||
| 1733 | ArgsTy... Args) { | ||||
| 1734 | if (MS.TargetTriple.getArch() == Triple::systemz) { | ||||
| 1735 | IRB.CreateCall(Callee, | ||||
| 1736 | {MS.MsanMetadataAlloca, std::forward<ArgsTy>(Args)...}); | ||||
| 1737 | return IRB.CreateLoad(MS.MsanMetadata, MS.MsanMetadataAlloca); | ||||
| 1738 | } | ||||
| 1739 | |||||
| 1740 | return IRB.CreateCall(Callee, {std::forward<ArgsTy>(Args)...}); | ||||
| 1741 | } | ||||
| 1742 | |||||
| 1743 | std::pair<Value *, Value *> getShadowOriginPtrKernelNoVec(Value *Addr, | ||||
| 1744 | IRBuilder<> &IRB, | ||||
| 1745 | Type *ShadowTy, | ||||
| 1746 | bool isStore) { | ||||
| 1747 | Value *ShadowOriginPtrs; | ||||
| 1748 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 1749 | TypeSize Size = DL.getTypeStoreSize(ShadowTy); | ||||
| 1750 | |||||
| 1751 | FunctionCallee Getter = MS.getKmsanShadowOriginAccessFn(isStore, Size); | ||||
| 1752 | Value *AddrCast = | ||||
| 1753 | IRB.CreatePointerCast(Addr, PointerType::get(IRB.getInt8Ty(), 0)); | ||||
| 1754 | if (Getter) { | ||||
| 1755 | ShadowOriginPtrs = createMetadataCall(IRB, Getter, AddrCast); | ||||
| 1756 | } else { | ||||
| 1757 | Value *SizeVal = ConstantInt::get(MS.IntptrTy, Size); | ||||
| 1758 | ShadowOriginPtrs = createMetadataCall( | ||||
| 1759 | IRB, | ||||
| 1760 | isStore ? MS.MsanMetadataPtrForStoreN : MS.MsanMetadataPtrForLoadN, | ||||
| 1761 | AddrCast, SizeVal); | ||||
| 1762 | } | ||||
| 1763 | Value *ShadowPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 0); | ||||
| 1764 | ShadowPtr = IRB.CreatePointerCast(ShadowPtr, PointerType::get(ShadowTy, 0)); | ||||
| 1765 | Value *OriginPtr = IRB.CreateExtractValue(ShadowOriginPtrs, 1); | ||||
| 1766 | |||||
| 1767 | return std::make_pair(ShadowPtr, OriginPtr); | ||||
| 1768 | } | ||||
| 1769 | |||||
| 1770 | /// Addr can be a ptr or <N x ptr>. In both cases ShadowTy the shadow type of | ||||
| 1771 | /// a single pointee. | ||||
| 1772 | /// Returns <shadow_ptr, origin_ptr> or <<N x shadow_ptr>, <N x origin_ptr>>. | ||||
| 1773 | std::pair<Value *, Value *> getShadowOriginPtrKernel(Value *Addr, | ||||
| 1774 | IRBuilder<> &IRB, | ||||
| 1775 | Type *ShadowTy, | ||||
| 1776 | bool isStore) { | ||||
| 1777 | VectorType *VectTy = dyn_cast<VectorType>(Addr->getType()); | ||||
| 1778 | if (!VectTy) { | ||||
| 1779 | assert(Addr->getType()->isPointerTy())(static_cast <bool> (Addr->getType()->isPointerTy ()) ? void (0) : __assert_fail ("Addr->getType()->isPointerTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1779 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1780 | return getShadowOriginPtrKernelNoVec(Addr, IRB, ShadowTy, isStore); | ||||
| 1781 | } | ||||
| 1782 | |||||
| 1783 | // TODO: Support callbacs with vectors of addresses. | ||||
| 1784 | unsigned NumElements = cast<FixedVectorType>(VectTy)->getNumElements(); | ||||
| 1785 | Value *ShadowPtrs = ConstantInt::getNullValue( | ||||
| 1786 | FixedVectorType::get(ShadowTy->getPointerTo(), NumElements)); | ||||
| 1787 | Value *OriginPtrs = nullptr; | ||||
| 1788 | if (MS.TrackOrigins) | ||||
| 1789 | OriginPtrs = ConstantInt::getNullValue( | ||||
| 1790 | FixedVectorType::get(MS.OriginTy->getPointerTo(), NumElements)); | ||||
| 1791 | for (unsigned i = 0; i < NumElements; ++i) { | ||||
| 1792 | Value *OneAddr = | ||||
| 1793 | IRB.CreateExtractElement(Addr, ConstantInt::get(IRB.getInt32Ty(), i)); | ||||
| 1794 | auto [ShadowPtr, OriginPtr] = | ||||
| 1795 | getShadowOriginPtrKernelNoVec(OneAddr, IRB, ShadowTy, isStore); | ||||
| 1796 | |||||
| 1797 | ShadowPtrs = IRB.CreateInsertElement( | ||||
| 1798 | ShadowPtrs, ShadowPtr, ConstantInt::get(IRB.getInt32Ty(), i)); | ||||
| 1799 | if (MS.TrackOrigins) | ||||
| 1800 | OriginPtrs = IRB.CreateInsertElement( | ||||
| 1801 | OriginPtrs, OriginPtr, ConstantInt::get(IRB.getInt32Ty(), i)); | ||||
| 1802 | } | ||||
| 1803 | return {ShadowPtrs, OriginPtrs}; | ||||
| 1804 | } | ||||
| 1805 | |||||
| 1806 | std::pair<Value *, Value *> getShadowOriginPtr(Value *Addr, IRBuilder<> &IRB, | ||||
| 1807 | Type *ShadowTy, | ||||
| 1808 | MaybeAlign Alignment, | ||||
| 1809 | bool isStore) { | ||||
| 1810 | if (MS.CompileKernel) | ||||
| 1811 | return getShadowOriginPtrKernel(Addr, IRB, ShadowTy, isStore); | ||||
| 1812 | return getShadowOriginPtrUserspace(Addr, IRB, ShadowTy, Alignment); | ||||
| 1813 | } | ||||
| 1814 | |||||
| 1815 | /// Compute the shadow address for a given function argument. | ||||
| 1816 | /// | ||||
| 1817 | /// Shadow = ParamTLS+ArgOffset. | ||||
| 1818 | Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB, int ArgOffset) { | ||||
| 1819 | Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy); | ||||
| 1820 | if (ArgOffset) | ||||
| 1821 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 1822 | return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0), | ||||
| 1823 | "_msarg"); | ||||
| 1824 | } | ||||
| 1825 | |||||
| 1826 | /// Compute the origin address for a given function argument. | ||||
| 1827 | Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB, int ArgOffset) { | ||||
| 1828 | if (!MS.TrackOrigins) | ||||
| 1829 | return nullptr; | ||||
| 1830 | Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy); | ||||
| 1831 | if (ArgOffset) | ||||
| 1832 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 1833 | return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), | ||||
| 1834 | "_msarg_o"); | ||||
| 1835 | } | ||||
| 1836 | |||||
| 1837 | /// Compute the shadow address for a retval. | ||||
| 1838 | Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) { | ||||
| 1839 | return IRB.CreatePointerCast(MS.RetvalTLS, | ||||
| 1840 | PointerType::get(getShadowTy(A), 0), "_msret"); | ||||
| 1841 | } | ||||
| 1842 | |||||
| 1843 | /// Compute the origin address for a retval. | ||||
| 1844 | Value *getOriginPtrForRetval(IRBuilder<> &IRB) { | ||||
| 1845 | // We keep a single origin for the entire retval. Might be too optimistic. | ||||
| 1846 | return MS.RetvalOriginTLS; | ||||
| 1847 | } | ||||
| 1848 | |||||
| 1849 | /// Set SV to be the shadow value for V. | ||||
| 1850 | void setShadow(Value *V, Value *SV) { | ||||
| 1851 | assert(!ShadowMap.count(V) && "Values may only have one shadow")(static_cast <bool> (!ShadowMap.count(V) && "Values may only have one shadow" ) ? void (0) : __assert_fail ("!ShadowMap.count(V) && \"Values may only have one shadow\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1851 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1852 | ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V); | ||||
| 1853 | } | ||||
| 1854 | |||||
| 1855 | /// Set Origin to be the origin value for V. | ||||
| 1856 | void setOrigin(Value *V, Value *Origin) { | ||||
| 1857 | if (!MS.TrackOrigins) | ||||
| 1858 | return; | ||||
| 1859 | assert(!OriginMap.count(V) && "Values may only have one origin")(static_cast <bool> (!OriginMap.count(V) && "Values may only have one origin" ) ? void (0) : __assert_fail ("!OriginMap.count(V) && \"Values may only have one origin\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1859 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1860 | LLVM_DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n"; } } while (false); | ||||
| 1861 | OriginMap[V] = Origin; | ||||
| 1862 | } | ||||
| 1863 | |||||
| 1864 | Constant *getCleanShadow(Type *OrigTy) { | ||||
| 1865 | Type *ShadowTy = getShadowTy(OrigTy); | ||||
| 1866 | if (!ShadowTy) | ||||
| 1867 | return nullptr; | ||||
| 1868 | return Constant::getNullValue(ShadowTy); | ||||
| 1869 | } | ||||
| 1870 | |||||
| 1871 | /// Create a clean shadow value for a given value. | ||||
| 1872 | /// | ||||
| 1873 | /// Clean shadow (all zeroes) means all bits of the value are defined | ||||
| 1874 | /// (initialized). | ||||
| 1875 | Constant *getCleanShadow(Value *V) { return getCleanShadow(V->getType()); } | ||||
| 1876 | |||||
| 1877 | /// Create a dirty shadow of a given shadow type. | ||||
| 1878 | Constant *getPoisonedShadow(Type *ShadowTy) { | ||||
| 1879 | assert(ShadowTy)(static_cast <bool> (ShadowTy) ? void (0) : __assert_fail ("ShadowTy", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1879, __extension__ __PRETTY_FUNCTION__)); | ||||
| 1880 | if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) | ||||
| 1881 | return Constant::getAllOnesValue(ShadowTy); | ||||
| 1882 | if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) { | ||||
| 1883 | SmallVector<Constant *, 4> Vals(AT->getNumElements(), | ||||
| 1884 | getPoisonedShadow(AT->getElementType())); | ||||
| 1885 | return ConstantArray::get(AT, Vals); | ||||
| 1886 | } | ||||
| 1887 | if (StructType *ST = dyn_cast<StructType>(ShadowTy)) { | ||||
| 1888 | SmallVector<Constant *, 4> Vals; | ||||
| 1889 | for (unsigned i = 0, n = ST->getNumElements(); i < n; i++) | ||||
| 1890 | Vals.push_back(getPoisonedShadow(ST->getElementType(i))); | ||||
| 1891 | return ConstantStruct::get(ST, Vals); | ||||
| 1892 | } | ||||
| 1893 | llvm_unreachable("Unexpected shadow type")::llvm::llvm_unreachable_internal("Unexpected shadow type", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 1893); | ||||
| 1894 | } | ||||
| 1895 | |||||
| 1896 | /// Create a dirty shadow for a given value. | ||||
| 1897 | Constant *getPoisonedShadow(Value *V) { | ||||
| 1898 | Type *ShadowTy = getShadowTy(V); | ||||
| 1899 | if (!ShadowTy) | ||||
| 1900 | return nullptr; | ||||
| 1901 | return getPoisonedShadow(ShadowTy); | ||||
| 1902 | } | ||||
| 1903 | |||||
| 1904 | /// Create a clean (zero) origin. | ||||
| 1905 | Value *getCleanOrigin() { return Constant::getNullValue(MS.OriginTy); } | ||||
| 1906 | |||||
| 1907 | /// Get the shadow value for a given Value. | ||||
| 1908 | /// | ||||
| 1909 | /// This function either returns the value set earlier with setShadow, | ||||
| 1910 | /// or extracts if from ParamTLS (for function arguments). | ||||
| 1911 | Value *getShadow(Value *V) { | ||||
| 1912 | if (Instruction *I
| ||||
| 1913 | if (!PropagateShadow || I->getMetadata(LLVMContext::MD_nosanitize)) | ||||
| 1914 | return getCleanShadow(V); | ||||
| 1915 | // For instructions the shadow is already stored in the map. | ||||
| 1916 | Value *Shadow = ShadowMap[V]; | ||||
| 1917 | if (!Shadow) { | ||||
| 1918 | LLVM_DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()); } } while (false); | ||||
| 1919 | (void)I; | ||||
| 1920 | assert(Shadow && "No shadow for a value")(static_cast <bool> (Shadow && "No shadow for a value" ) ? void (0) : __assert_fail ("Shadow && \"No shadow for a value\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 1920 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 1921 | } | ||||
| 1922 | return Shadow; | ||||
| 1923 | } | ||||
| 1924 | if (UndefValue *U
| ||||
| 1925 | Value *AllOnes = (PropagateShadow && PoisonUndef) ? getPoisonedShadow(V) | ||||
| 1926 | : getCleanShadow(V); | ||||
| 1927 | LLVM_DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n"; } } while (false); | ||||
| |||||
| 1928 | (void)U; | ||||
| 1929 | return AllOnes; | ||||
| 1930 | } | ||||
| 1931 | if (Argument *A = dyn_cast<Argument>(V)) { | ||||
| 1932 | // For arguments we compute the shadow on demand and store it in the map. | ||||
| 1933 | Value *&ShadowPtr = ShadowMap[V]; | ||||
| 1934 | if (ShadowPtr) | ||||
| 1935 | return ShadowPtr; | ||||
| 1936 | Function *F = A->getParent(); | ||||
| 1937 | IRBuilder<> EntryIRB(FnPrologueEnd); | ||||
| 1938 | unsigned ArgOffset = 0; | ||||
| 1939 | const DataLayout &DL = F->getParent()->getDataLayout(); | ||||
| 1940 | for (auto &FArg : F->args()) { | ||||
| 1941 | if (!FArg.getType()->isSized()) { | ||||
| 1942 | LLVM_DEBUG(dbgs() << "Arg is not sized\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "Arg is not sized\n"; } } while ( false); | ||||
| 1943 | continue; | ||||
| 1944 | } | ||||
| 1945 | |||||
| 1946 | unsigned Size = FArg.hasByValAttr() | ||||
| 1947 | ? DL.getTypeAllocSize(FArg.getParamByValType()) | ||||
| 1948 | : DL.getTypeAllocSize(FArg.getType()); | ||||
| 1949 | |||||
| 1950 | if (A == &FArg) { | ||||
| 1951 | bool Overflow = ArgOffset + Size > kParamTLSSize; | ||||
| 1952 | if (FArg.hasByValAttr()) { | ||||
| 1953 | // ByVal pointer itself has clean shadow. We copy the actual | ||||
| 1954 | // argument shadow to the underlying memory. | ||||
| 1955 | // Figure out maximal valid memcpy alignment. | ||||
| 1956 | const Align ArgAlign = DL.getValueOrABITypeAlignment( | ||||
| 1957 | FArg.getParamAlign(), FArg.getParamByValType()); | ||||
| 1958 | Value *CpShadowPtr, *CpOriginPtr; | ||||
| 1959 | std::tie(CpShadowPtr, CpOriginPtr) = | ||||
| 1960 | getShadowOriginPtr(V, EntryIRB, EntryIRB.getInt8Ty(), ArgAlign, | ||||
| 1961 | /*isStore*/ true); | ||||
| 1962 | if (!PropagateShadow || Overflow) { | ||||
| 1963 | // ParamTLS overflow. | ||||
| 1964 | EntryIRB.CreateMemSet( | ||||
| 1965 | CpShadowPtr, Constant::getNullValue(EntryIRB.getInt8Ty()), | ||||
| 1966 | Size, ArgAlign); | ||||
| 1967 | } else { | ||||
| 1968 | Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset); | ||||
| 1969 | const Align CopyAlign = std::min(ArgAlign, kShadowTLSAlignment); | ||||
| 1970 | Value *Cpy = EntryIRB.CreateMemCpy(CpShadowPtr, CopyAlign, Base, | ||||
| 1971 | CopyAlign, Size); | ||||
| 1972 | LLVM_DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " ByValCpy: " << *Cpy << "\n"; } } while (false); | ||||
| 1973 | (void)Cpy; | ||||
| 1974 | |||||
| 1975 | if (MS.TrackOrigins) { | ||||
| 1976 | Value *OriginPtr = | ||||
| 1977 | getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset); | ||||
| 1978 | // FIXME: OriginSize should be: | ||||
| 1979 | // alignTo(V % kMinOriginAlignment + Size, kMinOriginAlignment) | ||||
| 1980 | unsigned OriginSize = alignTo(Size, kMinOriginAlignment); | ||||
| 1981 | EntryIRB.CreateMemCpy( | ||||
| 1982 | CpOriginPtr, | ||||
| 1983 | /* by getShadowOriginPtr */ kMinOriginAlignment, OriginPtr, | ||||
| 1984 | /* by origin_tls[ArgOffset] */ kMinOriginAlignment, | ||||
| 1985 | OriginSize); | ||||
| 1986 | } | ||||
| 1987 | } | ||||
| 1988 | } | ||||
| 1989 | |||||
| 1990 | if (!PropagateShadow || Overflow || FArg.hasByValAttr() || | ||||
| 1991 | (MS.EagerChecks && FArg.hasAttribute(Attribute::NoUndef))) { | ||||
| 1992 | ShadowPtr = getCleanShadow(V); | ||||
| 1993 | setOrigin(A, getCleanOrigin()); | ||||
| 1994 | } else { | ||||
| 1995 | // Shadow over TLS | ||||
| 1996 | Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset); | ||||
| 1997 | ShadowPtr = EntryIRB.CreateAlignedLoad(getShadowTy(&FArg), Base, | ||||
| 1998 | kShadowTLSAlignment); | ||||
| 1999 | if (MS.TrackOrigins) { | ||||
| 2000 | Value *OriginPtr = | ||||
| 2001 | getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset); | ||||
| 2002 | setOrigin(A, EntryIRB.CreateLoad(MS.OriginTy, OriginPtr)); | ||||
| 2003 | } | ||||
| 2004 | } | ||||
| 2005 | LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " ARG: " << FArg << " ==> " << *ShadowPtr << "\n"; } } while (false ) | ||||
| 2006 | << " ARG: " << FArg << " ==> " << *ShadowPtr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " ARG: " << FArg << " ==> " << *ShadowPtr << "\n"; } } while (false ); | ||||
| 2007 | break; | ||||
| 2008 | } | ||||
| 2009 | |||||
| 2010 | ArgOffset += alignTo(Size, kShadowTLSAlignment); | ||||
| 2011 | } | ||||
| 2012 | assert(ShadowPtr && "Could not find shadow for an argument")(static_cast <bool> (ShadowPtr && "Could not find shadow for an argument" ) ? void (0) : __assert_fail ("ShadowPtr && \"Could not find shadow for an argument\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2012 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2013 | return ShadowPtr; | ||||
| 2014 | } | ||||
| 2015 | // For everything else the shadow is zero. | ||||
| 2016 | return getCleanShadow(V); | ||||
| 2017 | } | ||||
| 2018 | |||||
| 2019 | /// Get the shadow for i-th argument of the instruction I. | ||||
| 2020 | Value *getShadow(Instruction *I, int i) { | ||||
| 2021 | return getShadow(I->getOperand(i)); | ||||
| 2022 | } | ||||
| 2023 | |||||
| 2024 | /// Get the origin for a value. | ||||
| 2025 | Value *getOrigin(Value *V) { | ||||
| 2026 | if (!MS.TrackOrigins) | ||||
| 2027 | return nullptr; | ||||
| 2028 | if (!PropagateShadow || isa<Constant>(V) || isa<InlineAsm>(V)) | ||||
| 2029 | return getCleanOrigin(); | ||||
| 2030 | assert((isa<Instruction>(V) || isa<Argument>(V)) &&(static_cast <bool> ((isa<Instruction>(V) || isa< Argument>(V)) && "Unexpected value type in getOrigin()" ) ? void (0) : __assert_fail ("(isa<Instruction>(V) || isa<Argument>(V)) && \"Unexpected value type in getOrigin()\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2031 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 2031 | "Unexpected value type in getOrigin()")(static_cast <bool> ((isa<Instruction>(V) || isa< Argument>(V)) && "Unexpected value type in getOrigin()" ) ? void (0) : __assert_fail ("(isa<Instruction>(V) || isa<Argument>(V)) && \"Unexpected value type in getOrigin()\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2031 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2032 | if (Instruction *I = dyn_cast<Instruction>(V)) { | ||||
| 2033 | if (I->getMetadata(LLVMContext::MD_nosanitize)) | ||||
| 2034 | return getCleanOrigin(); | ||||
| 2035 | } | ||||
| 2036 | Value *Origin = OriginMap[V]; | ||||
| 2037 | assert(Origin && "Missing origin")(static_cast <bool> (Origin && "Missing origin" ) ? void (0) : __assert_fail ("Origin && \"Missing origin\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2037 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2038 | return Origin; | ||||
| 2039 | } | ||||
| 2040 | |||||
| 2041 | /// Get the origin for i-th argument of the instruction I. | ||||
| 2042 | Value *getOrigin(Instruction *I, int i) { | ||||
| 2043 | return getOrigin(I->getOperand(i)); | ||||
| 2044 | } | ||||
| 2045 | |||||
| 2046 | /// Remember the place where a shadow check should be inserted. | ||||
| 2047 | /// | ||||
| 2048 | /// This location will be later instrumented with a check that will print a | ||||
| 2049 | /// UMR warning in runtime if the shadow value is not 0. | ||||
| 2050 | void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) { | ||||
| 2051 | assert(Shadow)(static_cast <bool> (Shadow) ? void (0) : __assert_fail ("Shadow", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2051, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2052 | if (!InsertChecks) | ||||
| 2053 | return; | ||||
| 2054 | |||||
| 2055 | if (!DebugCounter::shouldExecute(DebugInsertCheck)) { | ||||
| 2056 | LLVM_DEBUG(dbgs() << "Skipping check of " << *Shadow << " before "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "Skipping check of " << *Shadow << " before " << *OrigIns << "\n"; } } while (false) | ||||
| 2057 | << *OrigIns << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "Skipping check of " << *Shadow << " before " << *OrigIns << "\n"; } } while (false); | ||||
| 2058 | return; | ||||
| 2059 | } | ||||
| 2060 | #ifndef NDEBUG | ||||
| 2061 | Type *ShadowTy = Shadow->getType(); | ||||
| 2062 | assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) ||(static_cast <bool> ((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy ) || isa<ArrayType>(ShadowTy)) && "Can only insert checks for integer, vector, and aggregate shadow " "types") ? void (0) : __assert_fail ("(isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy) || isa<ArrayType>(ShadowTy)) && \"Can only insert checks for integer, vector, and aggregate shadow \" \"types\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2065 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 2063 | isa<StructType>(ShadowTy) || isa<ArrayType>(ShadowTy)) &&(static_cast <bool> ((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy ) || isa<ArrayType>(ShadowTy)) && "Can only insert checks for integer, vector, and aggregate shadow " "types") ? void (0) : __assert_fail ("(isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy) || isa<ArrayType>(ShadowTy)) && \"Can only insert checks for integer, vector, and aggregate shadow \" \"types\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2065 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 2064 | "Can only insert checks for integer, vector, and aggregate shadow "(static_cast <bool> ((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy ) || isa<ArrayType>(ShadowTy)) && "Can only insert checks for integer, vector, and aggregate shadow " "types") ? void (0) : __assert_fail ("(isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy) || isa<ArrayType>(ShadowTy)) && \"Can only insert checks for integer, vector, and aggregate shadow \" \"types\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2065 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 2065 | "types")(static_cast <bool> ((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy ) || isa<ArrayType>(ShadowTy)) && "Can only insert checks for integer, vector, and aggregate shadow " "types") ? void (0) : __assert_fail ("(isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy) || isa<StructType>(ShadowTy) || isa<ArrayType>(ShadowTy)) && \"Can only insert checks for integer, vector, and aggregate shadow \" \"types\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2065 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2066 | #endif | ||||
| 2067 | InstrumentationList.push_back( | ||||
| 2068 | ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns)); | ||||
| 2069 | } | ||||
| 2070 | |||||
| 2071 | /// Remember the place where a shadow check should be inserted. | ||||
| 2072 | /// | ||||
| 2073 | /// This location will be later instrumented with a check that will print a | ||||
| 2074 | /// UMR warning in runtime if the value is not fully defined. | ||||
| 2075 | void insertShadowCheck(Value *Val, Instruction *OrigIns) { | ||||
| 2076 | assert(Val)(static_cast <bool> (Val) ? void (0) : __assert_fail ("Val" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2076 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2077 | Value *Shadow, *Origin; | ||||
| 2078 | if (ClCheckConstantShadow) { | ||||
| 2079 | Shadow = getShadow(Val); | ||||
| 2080 | if (!Shadow) | ||||
| 2081 | return; | ||||
| 2082 | Origin = getOrigin(Val); | ||||
| 2083 | } else { | ||||
| 2084 | Shadow = dyn_cast_or_null<Instruction>(getShadow(Val)); | ||||
| 2085 | if (!Shadow) | ||||
| 2086 | return; | ||||
| 2087 | Origin = dyn_cast_or_null<Instruction>(getOrigin(Val)); | ||||
| 2088 | } | ||||
| 2089 | insertShadowCheck(Shadow, Origin, OrigIns); | ||||
| 2090 | } | ||||
| 2091 | |||||
| 2092 | AtomicOrdering addReleaseOrdering(AtomicOrdering a) { | ||||
| 2093 | switch (a) { | ||||
| 2094 | case AtomicOrdering::NotAtomic: | ||||
| 2095 | return AtomicOrdering::NotAtomic; | ||||
| 2096 | case AtomicOrdering::Unordered: | ||||
| 2097 | case AtomicOrdering::Monotonic: | ||||
| 2098 | case AtomicOrdering::Release: | ||||
| 2099 | return AtomicOrdering::Release; | ||||
| 2100 | case AtomicOrdering::Acquire: | ||||
| 2101 | case AtomicOrdering::AcquireRelease: | ||||
| 2102 | return AtomicOrdering::AcquireRelease; | ||||
| 2103 | case AtomicOrdering::SequentiallyConsistent: | ||||
| 2104 | return AtomicOrdering::SequentiallyConsistent; | ||||
| 2105 | } | ||||
| 2106 | llvm_unreachable("Unknown ordering")::llvm::llvm_unreachable_internal("Unknown ordering", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2106); | ||||
| 2107 | } | ||||
| 2108 | |||||
| 2109 | Value *makeAddReleaseOrderingTable(IRBuilder<> &IRB) { | ||||
| 2110 | constexpr int NumOrderings = (int)AtomicOrderingCABI::seq_cst + 1; | ||||
| 2111 | uint32_t OrderingTable[NumOrderings] = {}; | ||||
| 2112 | |||||
| 2113 | OrderingTable[(int)AtomicOrderingCABI::relaxed] = | ||||
| 2114 | OrderingTable[(int)AtomicOrderingCABI::release] = | ||||
| 2115 | (int)AtomicOrderingCABI::release; | ||||
| 2116 | OrderingTable[(int)AtomicOrderingCABI::consume] = | ||||
| 2117 | OrderingTable[(int)AtomicOrderingCABI::acquire] = | ||||
| 2118 | OrderingTable[(int)AtomicOrderingCABI::acq_rel] = | ||||
| 2119 | (int)AtomicOrderingCABI::acq_rel; | ||||
| 2120 | OrderingTable[(int)AtomicOrderingCABI::seq_cst] = | ||||
| 2121 | (int)AtomicOrderingCABI::seq_cst; | ||||
| 2122 | |||||
| 2123 | return ConstantDataVector::get(IRB.getContext(), | ||||
| 2124 | ArrayRef(OrderingTable, NumOrderings)); | ||||
| 2125 | } | ||||
| 2126 | |||||
| 2127 | AtomicOrdering addAcquireOrdering(AtomicOrdering a) { | ||||
| 2128 | switch (a) { | ||||
| 2129 | case AtomicOrdering::NotAtomic: | ||||
| 2130 | return AtomicOrdering::NotAtomic; | ||||
| 2131 | case AtomicOrdering::Unordered: | ||||
| 2132 | case AtomicOrdering::Monotonic: | ||||
| 2133 | case AtomicOrdering::Acquire: | ||||
| 2134 | return AtomicOrdering::Acquire; | ||||
| 2135 | case AtomicOrdering::Release: | ||||
| 2136 | case AtomicOrdering::AcquireRelease: | ||||
| 2137 | return AtomicOrdering::AcquireRelease; | ||||
| 2138 | case AtomicOrdering::SequentiallyConsistent: | ||||
| 2139 | return AtomicOrdering::SequentiallyConsistent; | ||||
| 2140 | } | ||||
| 2141 | llvm_unreachable("Unknown ordering")::llvm::llvm_unreachable_internal("Unknown ordering", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2141); | ||||
| 2142 | } | ||||
| 2143 | |||||
| 2144 | Value *makeAddAcquireOrderingTable(IRBuilder<> &IRB) { | ||||
| 2145 | constexpr int NumOrderings = (int)AtomicOrderingCABI::seq_cst + 1; | ||||
| 2146 | uint32_t OrderingTable[NumOrderings] = {}; | ||||
| 2147 | |||||
| 2148 | OrderingTable[(int)AtomicOrderingCABI::relaxed] = | ||||
| 2149 | OrderingTable[(int)AtomicOrderingCABI::acquire] = | ||||
| 2150 | OrderingTable[(int)AtomicOrderingCABI::consume] = | ||||
| 2151 | (int)AtomicOrderingCABI::acquire; | ||||
| 2152 | OrderingTable[(int)AtomicOrderingCABI::release] = | ||||
| 2153 | OrderingTable[(int)AtomicOrderingCABI::acq_rel] = | ||||
| 2154 | (int)AtomicOrderingCABI::acq_rel; | ||||
| 2155 | OrderingTable[(int)AtomicOrderingCABI::seq_cst] = | ||||
| 2156 | (int)AtomicOrderingCABI::seq_cst; | ||||
| 2157 | |||||
| 2158 | return ConstantDataVector::get(IRB.getContext(), | ||||
| 2159 | ArrayRef(OrderingTable, NumOrderings)); | ||||
| 2160 | } | ||||
| 2161 | |||||
| 2162 | // ------------------- Visitors. | ||||
| 2163 | using InstVisitor<MemorySanitizerVisitor>::visit; | ||||
| 2164 | void visit(Instruction &I) { | ||||
| 2165 | if (I.getMetadata(LLVMContext::MD_nosanitize)) | ||||
| 2166 | return; | ||||
| 2167 | // Don't want to visit if we're in the prologue | ||||
| 2168 | if (isInPrologue(I)) | ||||
| 2169 | return; | ||||
| 2170 | InstVisitor<MemorySanitizerVisitor>::visit(I); | ||||
| 2171 | } | ||||
| 2172 | |||||
| 2173 | /// Instrument LoadInst | ||||
| 2174 | /// | ||||
| 2175 | /// Loads the corresponding shadow and (optionally) origin. | ||||
| 2176 | /// Optionally, checks that the load address is fully defined. | ||||
| 2177 | void visitLoadInst(LoadInst &I) { | ||||
| 2178 | assert(I.getType()->isSized() && "Load type must have size")(static_cast <bool> (I.getType()->isSized() && "Load type must have size") ? void (0) : __assert_fail ("I.getType()->isSized() && \"Load type must have size\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2178 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2179 | assert(!I.getMetadata(LLVMContext::MD_nosanitize))(static_cast <bool> (!I.getMetadata(LLVMContext::MD_nosanitize )) ? void (0) : __assert_fail ("!I.getMetadata(LLVMContext::MD_nosanitize)" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2179 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2180 | NextNodeIRBuilder IRB(&I); | ||||
| 2181 | Type *ShadowTy = getShadowTy(&I); | ||||
| 2182 | Value *Addr = I.getPointerOperand(); | ||||
| 2183 | Value *ShadowPtr = nullptr, *OriginPtr = nullptr; | ||||
| 2184 | const Align Alignment = I.getAlign(); | ||||
| 2185 | if (PropagateShadow) { | ||||
| 2186 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 2187 | getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false); | ||||
| 2188 | setShadow(&I, | ||||
| 2189 | IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld")); | ||||
| 2190 | } else { | ||||
| 2191 | setShadow(&I, getCleanShadow(&I)); | ||||
| 2192 | } | ||||
| 2193 | |||||
| 2194 | if (ClCheckAccessAddress) | ||||
| 2195 | insertShadowCheck(I.getPointerOperand(), &I); | ||||
| 2196 | |||||
| 2197 | if (I.isAtomic()) | ||||
| 2198 | I.setOrdering(addAcquireOrdering(I.getOrdering())); | ||||
| 2199 | |||||
| 2200 | if (MS.TrackOrigins) { | ||||
| 2201 | if (PropagateShadow) { | ||||
| 2202 | const Align OriginAlignment = std::max(kMinOriginAlignment, Alignment); | ||||
| 2203 | setOrigin( | ||||
| 2204 | &I, IRB.CreateAlignedLoad(MS.OriginTy, OriginPtr, OriginAlignment)); | ||||
| 2205 | } else { | ||||
| 2206 | setOrigin(&I, getCleanOrigin()); | ||||
| 2207 | } | ||||
| 2208 | } | ||||
| 2209 | } | ||||
| 2210 | |||||
| 2211 | /// Instrument StoreInst | ||||
| 2212 | /// | ||||
| 2213 | /// Stores the corresponding shadow and (optionally) origin. | ||||
| 2214 | /// Optionally, checks that the store address is fully defined. | ||||
| 2215 | void visitStoreInst(StoreInst &I) { | ||||
| 2216 | StoreList.push_back(&I); | ||||
| 2217 | if (ClCheckAccessAddress) | ||||
| 2218 | insertShadowCheck(I.getPointerOperand(), &I); | ||||
| 2219 | } | ||||
| 2220 | |||||
| 2221 | void handleCASOrRMW(Instruction &I) { | ||||
| 2222 | assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I))(static_cast <bool> (isa<AtomicRMWInst>(I) || isa <AtomicCmpXchgInst>(I)) ? void (0) : __assert_fail ("isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I)" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2222 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2223 | |||||
| 2224 | IRBuilder<> IRB(&I); | ||||
| 2225 | Value *Addr = I.getOperand(0); | ||||
| 2226 | Value *Val = I.getOperand(1); | ||||
| 2227 | Value *ShadowPtr = getShadowOriginPtr(Addr, IRB, getShadowTy(Val), Align(1), | ||||
| 2228 | /*isStore*/ true) | ||||
| 2229 | .first; | ||||
| 2230 | |||||
| 2231 | if (ClCheckAccessAddress) | ||||
| 2232 | insertShadowCheck(Addr, &I); | ||||
| 2233 | |||||
| 2234 | // Only test the conditional argument of cmpxchg instruction. | ||||
| 2235 | // The other argument can potentially be uninitialized, but we can not | ||||
| 2236 | // detect this situation reliably without possible false positives. | ||||
| 2237 | if (isa<AtomicCmpXchgInst>(I)) | ||||
| 2238 | insertShadowCheck(Val, &I); | ||||
| 2239 | |||||
| 2240 | IRB.CreateStore(getCleanShadow(Val), ShadowPtr); | ||||
| 2241 | |||||
| 2242 | setShadow(&I, getCleanShadow(&I)); | ||||
| 2243 | setOrigin(&I, getCleanOrigin()); | ||||
| 2244 | } | ||||
| 2245 | |||||
| 2246 | void visitAtomicRMWInst(AtomicRMWInst &I) { | ||||
| 2247 | handleCASOrRMW(I); | ||||
| 2248 | I.setOrdering(addReleaseOrdering(I.getOrdering())); | ||||
| 2249 | } | ||||
| 2250 | |||||
| 2251 | void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) { | ||||
| 2252 | handleCASOrRMW(I); | ||||
| 2253 | I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering())); | ||||
| 2254 | } | ||||
| 2255 | |||||
| 2256 | // Vector manipulation. | ||||
| 2257 | void visitExtractElementInst(ExtractElementInst &I) { | ||||
| 2258 | insertShadowCheck(I.getOperand(1), &I); | ||||
| 2259 | IRBuilder<> IRB(&I); | ||||
| 2260 | setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1), | ||||
| 2261 | "_msprop")); | ||||
| 2262 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2263 | } | ||||
| 2264 | |||||
| 2265 | void visitInsertElementInst(InsertElementInst &I) { | ||||
| 2266 | insertShadowCheck(I.getOperand(2), &I); | ||||
| 2267 | IRBuilder<> IRB(&I); | ||||
| 2268 | auto *Shadow0 = getShadow(&I, 0); | ||||
| 2269 | auto *Shadow1 = getShadow(&I, 1); | ||||
| 2270 | setShadow(&I, IRB.CreateInsertElement(Shadow0, Shadow1, I.getOperand(2), | ||||
| 2271 | "_msprop")); | ||||
| 2272 | setOriginForNaryOp(I); | ||||
| 2273 | } | ||||
| 2274 | |||||
| 2275 | void visitShuffleVectorInst(ShuffleVectorInst &I) { | ||||
| 2276 | IRBuilder<> IRB(&I); | ||||
| 2277 | auto *Shadow0 = getShadow(&I, 0); | ||||
| 2278 | auto *Shadow1 = getShadow(&I, 1); | ||||
| 2279 | setShadow(&I, IRB.CreateShuffleVector(Shadow0, Shadow1, I.getShuffleMask(), | ||||
| 2280 | "_msprop")); | ||||
| 2281 | setOriginForNaryOp(I); | ||||
| 2282 | } | ||||
| 2283 | |||||
| 2284 | // Casts. | ||||
| 2285 | void visitSExtInst(SExtInst &I) { | ||||
| 2286 | IRBuilder<> IRB(&I); | ||||
| 2287 | setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop")); | ||||
| 2288 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2289 | } | ||||
| 2290 | |||||
| 2291 | void visitZExtInst(ZExtInst &I) { | ||||
| 2292 | IRBuilder<> IRB(&I); | ||||
| 2293 | setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop")); | ||||
| 2294 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2295 | } | ||||
| 2296 | |||||
| 2297 | void visitTruncInst(TruncInst &I) { | ||||
| 2298 | IRBuilder<> IRB(&I); | ||||
| 2299 | setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop")); | ||||
| 2300 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2301 | } | ||||
| 2302 | |||||
| 2303 | void visitBitCastInst(BitCastInst &I) { | ||||
| 2304 | // Special case: if this is the bitcast (there is exactly 1 allowed) between | ||||
| 2305 | // a musttail call and a ret, don't instrument. New instructions are not | ||||
| 2306 | // allowed after a musttail call. | ||||
| 2307 | if (auto *CI = dyn_cast<CallInst>(I.getOperand(0))) | ||||
| 2308 | if (CI->isMustTailCall()) | ||||
| 2309 | return; | ||||
| 2310 | IRBuilder<> IRB(&I); | ||||
| 2311 | setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I))); | ||||
| 2312 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2313 | } | ||||
| 2314 | |||||
| 2315 | void visitPtrToIntInst(PtrToIntInst &I) { | ||||
| 2316 | IRBuilder<> IRB(&I); | ||||
| 2317 | setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, | ||||
| 2318 | "_msprop_ptrtoint")); | ||||
| 2319 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2320 | } | ||||
| 2321 | |||||
| 2322 | void visitIntToPtrInst(IntToPtrInst &I) { | ||||
| 2323 | IRBuilder<> IRB(&I); | ||||
| 2324 | setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false, | ||||
| 2325 | "_msprop_inttoptr")); | ||||
| 2326 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2327 | } | ||||
| 2328 | |||||
| 2329 | void visitFPToSIInst(CastInst &I) { handleShadowOr(I); } | ||||
| 2330 | void visitFPToUIInst(CastInst &I) { handleShadowOr(I); } | ||||
| 2331 | void visitSIToFPInst(CastInst &I) { handleShadowOr(I); } | ||||
| 2332 | void visitUIToFPInst(CastInst &I) { handleShadowOr(I); } | ||||
| 2333 | void visitFPExtInst(CastInst &I) { handleShadowOr(I); } | ||||
| 2334 | void visitFPTruncInst(CastInst &I) { handleShadowOr(I); } | ||||
| 2335 | |||||
| 2336 | /// Propagate shadow for bitwise AND. | ||||
| 2337 | /// | ||||
| 2338 | /// This code is exact, i.e. if, for example, a bit in the left argument | ||||
| 2339 | /// is defined and 0, then neither the value not definedness of the | ||||
| 2340 | /// corresponding bit in B don't affect the resulting shadow. | ||||
| 2341 | void visitAnd(BinaryOperator &I) { | ||||
| 2342 | IRBuilder<> IRB(&I); | ||||
| 2343 | // "And" of 0 and a poisoned value results in unpoisoned value. | ||||
| 2344 | // 1&1 => 1; 0&1 => 0; p&1 => p; | ||||
| 2345 | // 1&0 => 0; 0&0 => 0; p&0 => 0; | ||||
| 2346 | // 1&p => p; 0&p => 0; p&p => p; | ||||
| 2347 | // S = (S1 & S2) | (V1 & S2) | (S1 & V2) | ||||
| 2348 | Value *S1 = getShadow(&I, 0); | ||||
| 2349 | Value *S2 = getShadow(&I, 1); | ||||
| 2350 | Value *V1 = I.getOperand(0); | ||||
| 2351 | Value *V2 = I.getOperand(1); | ||||
| 2352 | if (V1->getType() != S1->getType()) { | ||||
| 2353 | V1 = IRB.CreateIntCast(V1, S1->getType(), false); | ||||
| 2354 | V2 = IRB.CreateIntCast(V2, S2->getType(), false); | ||||
| 2355 | } | ||||
| 2356 | Value *S1S2 = IRB.CreateAnd(S1, S2); | ||||
| 2357 | Value *V1S2 = IRB.CreateAnd(V1, S2); | ||||
| 2358 | Value *S1V2 = IRB.CreateAnd(S1, V2); | ||||
| 2359 | setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2})); | ||||
| 2360 | setOriginForNaryOp(I); | ||||
| 2361 | } | ||||
| 2362 | |||||
| 2363 | void visitOr(BinaryOperator &I) { | ||||
| 2364 | IRBuilder<> IRB(&I); | ||||
| 2365 | // "Or" of 1 and a poisoned value results in unpoisoned value. | ||||
| 2366 | // 1|1 => 1; 0|1 => 1; p|1 => 1; | ||||
| 2367 | // 1|0 => 1; 0|0 => 0; p|0 => p; | ||||
| 2368 | // 1|p => 1; 0|p => p; p|p => p; | ||||
| 2369 | // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2) | ||||
| 2370 | Value *S1 = getShadow(&I, 0); | ||||
| 2371 | Value *S2 = getShadow(&I, 1); | ||||
| 2372 | Value *V1 = IRB.CreateNot(I.getOperand(0)); | ||||
| 2373 | Value *V2 = IRB.CreateNot(I.getOperand(1)); | ||||
| 2374 | if (V1->getType() != S1->getType()) { | ||||
| 2375 | V1 = IRB.CreateIntCast(V1, S1->getType(), false); | ||||
| 2376 | V2 = IRB.CreateIntCast(V2, S2->getType(), false); | ||||
| 2377 | } | ||||
| 2378 | Value *S1S2 = IRB.CreateAnd(S1, S2); | ||||
| 2379 | Value *V1S2 = IRB.CreateAnd(V1, S2); | ||||
| 2380 | Value *S1V2 = IRB.CreateAnd(S1, V2); | ||||
| 2381 | setShadow(&I, IRB.CreateOr({S1S2, V1S2, S1V2})); | ||||
| 2382 | setOriginForNaryOp(I); | ||||
| 2383 | } | ||||
| 2384 | |||||
| 2385 | /// Default propagation of shadow and/or origin. | ||||
| 2386 | /// | ||||
| 2387 | /// This class implements the general case of shadow propagation, used in all | ||||
| 2388 | /// cases where we don't know and/or don't care about what the operation | ||||
| 2389 | /// actually does. It converts all input shadow values to a common type | ||||
| 2390 | /// (extending or truncating as necessary), and bitwise OR's them. | ||||
| 2391 | /// | ||||
| 2392 | /// This is much cheaper than inserting checks (i.e. requiring inputs to be | ||||
| 2393 | /// fully initialized), and less prone to false positives. | ||||
| 2394 | /// | ||||
| 2395 | /// This class also implements the general case of origin propagation. For a | ||||
| 2396 | /// Nary operation, result origin is set to the origin of an argument that is | ||||
| 2397 | /// not entirely initialized. If there is more than one such arguments, the | ||||
| 2398 | /// rightmost of them is picked. It does not matter which one is picked if all | ||||
| 2399 | /// arguments are initialized. | ||||
| 2400 | template <bool CombineShadow> class Combiner { | ||||
| 2401 | Value *Shadow = nullptr; | ||||
| 2402 | Value *Origin = nullptr; | ||||
| 2403 | IRBuilder<> &IRB; | ||||
| 2404 | MemorySanitizerVisitor *MSV; | ||||
| 2405 | |||||
| 2406 | public: | ||||
| 2407 | Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) | ||||
| 2408 | : IRB(IRB), MSV(MSV) {} | ||||
| 2409 | |||||
| 2410 | /// Add a pair of shadow and origin values to the mix. | ||||
| 2411 | Combiner &Add(Value *OpShadow, Value *OpOrigin) { | ||||
| 2412 | if (CombineShadow) { | ||||
| 2413 | assert(OpShadow)(static_cast <bool> (OpShadow) ? void (0) : __assert_fail ("OpShadow", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2413, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2414 | if (!Shadow) | ||||
| 2415 | Shadow = OpShadow; | ||||
| 2416 | else { | ||||
| 2417 | OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType()); | ||||
| 2418 | Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop"); | ||||
| 2419 | } | ||||
| 2420 | } | ||||
| 2421 | |||||
| 2422 | if (MSV->MS.TrackOrigins) { | ||||
| 2423 | assert(OpOrigin)(static_cast <bool> (OpOrigin) ? void (0) : __assert_fail ("OpOrigin", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2423, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2424 | if (!Origin) { | ||||
| 2425 | Origin = OpOrigin; | ||||
| 2426 | } else { | ||||
| 2427 | Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin); | ||||
| 2428 | // No point in adding something that might result in 0 origin value. | ||||
| 2429 | if (!ConstOrigin || !ConstOrigin->isNullValue()) { | ||||
| 2430 | Value *Cond = MSV->convertToBool(OpShadow, IRB); | ||||
| 2431 | Origin = IRB.CreateSelect(Cond, OpOrigin, Origin); | ||||
| 2432 | } | ||||
| 2433 | } | ||||
| 2434 | } | ||||
| 2435 | return *this; | ||||
| 2436 | } | ||||
| 2437 | |||||
| 2438 | /// Add an application value to the mix. | ||||
| 2439 | Combiner &Add(Value *V) { | ||||
| 2440 | Value *OpShadow = MSV->getShadow(V); | ||||
| 2441 | Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr; | ||||
| 2442 | return Add(OpShadow, OpOrigin); | ||||
| 2443 | } | ||||
| 2444 | |||||
| 2445 | /// Set the current combined values as the given instruction's shadow | ||||
| 2446 | /// and origin. | ||||
| 2447 | void Done(Instruction *I) { | ||||
| 2448 | if (CombineShadow) { | ||||
| 2449 | assert(Shadow)(static_cast <bool> (Shadow) ? void (0) : __assert_fail ("Shadow", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2449, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2450 | Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I)); | ||||
| 2451 | MSV->setShadow(I, Shadow); | ||||
| 2452 | } | ||||
| 2453 | if (MSV->MS.TrackOrigins) { | ||||
| 2454 | assert(Origin)(static_cast <bool> (Origin) ? void (0) : __assert_fail ("Origin", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2454, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2455 | MSV->setOrigin(I, Origin); | ||||
| 2456 | } | ||||
| 2457 | } | ||||
| 2458 | }; | ||||
| 2459 | |||||
| 2460 | using ShadowAndOriginCombiner = Combiner<true>; | ||||
| 2461 | using OriginCombiner = Combiner<false>; | ||||
| 2462 | |||||
| 2463 | /// Propagate origin for arbitrary operation. | ||||
| 2464 | void setOriginForNaryOp(Instruction &I) { | ||||
| 2465 | if (!MS.TrackOrigins) | ||||
| 2466 | return; | ||||
| 2467 | IRBuilder<> IRB(&I); | ||||
| 2468 | OriginCombiner OC(this, IRB); | ||||
| 2469 | for (Use &Op : I.operands()) | ||||
| 2470 | OC.Add(Op.get()); | ||||
| 2471 | OC.Done(&I); | ||||
| 2472 | } | ||||
| 2473 | |||||
| 2474 | size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) { | ||||
| 2475 | assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&(static_cast <bool> (!(Ty->isVectorTy() && Ty ->getScalarType()->isPointerTy()) && "Vector of pointers is not a valid shadow type" ) ? void (0) : __assert_fail ("!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) && \"Vector of pointers is not a valid shadow type\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2476 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 2476 | "Vector of pointers is not a valid shadow type")(static_cast <bool> (!(Ty->isVectorTy() && Ty ->getScalarType()->isPointerTy()) && "Vector of pointers is not a valid shadow type" ) ? void (0) : __assert_fail ("!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) && \"Vector of pointers is not a valid shadow type\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 2476 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 2477 | return Ty->isVectorTy() ? cast<FixedVectorType>(Ty)->getNumElements() * | ||||
| 2478 | Ty->getScalarSizeInBits() | ||||
| 2479 | : Ty->getPrimitiveSizeInBits(); | ||||
| 2480 | } | ||||
| 2481 | |||||
| 2482 | /// Cast between two shadow types, extending or truncating as | ||||
| 2483 | /// necessary. | ||||
| 2484 | Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy, | ||||
| 2485 | bool Signed = false) { | ||||
| 2486 | Type *srcTy = V->getType(); | ||||
| 2487 | size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy); | ||||
| 2488 | size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy); | ||||
| 2489 | if (srcSizeInBits > 1 && dstSizeInBits == 1) | ||||
| 2490 | return IRB.CreateICmpNE(V, getCleanShadow(V)); | ||||
| 2491 | |||||
| 2492 | if (dstTy->isIntegerTy() && srcTy->isIntegerTy()) | ||||
| 2493 | return IRB.CreateIntCast(V, dstTy, Signed); | ||||
| 2494 | if (dstTy->isVectorTy() && srcTy->isVectorTy() && | ||||
| 2495 | cast<VectorType>(dstTy)->getElementCount() == | ||||
| 2496 | cast<VectorType>(srcTy)->getElementCount()) | ||||
| 2497 | return IRB.CreateIntCast(V, dstTy, Signed); | ||||
| 2498 | Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits)); | ||||
| 2499 | Value *V2 = | ||||
| 2500 | IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed); | ||||
| 2501 | return IRB.CreateBitCast(V2, dstTy); | ||||
| 2502 | // TODO: handle struct types. | ||||
| 2503 | } | ||||
| 2504 | |||||
| 2505 | /// Cast an application value to the type of its own shadow. | ||||
| 2506 | Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) { | ||||
| 2507 | Type *ShadowTy = getShadowTy(V); | ||||
| 2508 | if (V->getType() == ShadowTy) | ||||
| 2509 | return V; | ||||
| 2510 | if (V->getType()->isPtrOrPtrVectorTy()) | ||||
| 2511 | return IRB.CreatePtrToInt(V, ShadowTy); | ||||
| 2512 | else | ||||
| 2513 | return IRB.CreateBitCast(V, ShadowTy); | ||||
| 2514 | } | ||||
| 2515 | |||||
| 2516 | /// Propagate shadow for arbitrary operation. | ||||
| 2517 | void handleShadowOr(Instruction &I) { | ||||
| 2518 | IRBuilder<> IRB(&I); | ||||
| 2519 | ShadowAndOriginCombiner SC(this, IRB); | ||||
| 2520 | for (Use &Op : I.operands()) | ||||
| 2521 | SC.Add(Op.get()); | ||||
| 2522 | SC.Done(&I); | ||||
| 2523 | } | ||||
| 2524 | |||||
| 2525 | void visitFNeg(UnaryOperator &I) { handleShadowOr(I); } | ||||
| 2526 | |||||
| 2527 | // Handle multiplication by constant. | ||||
| 2528 | // | ||||
| 2529 | // Handle a special case of multiplication by constant that may have one or | ||||
| 2530 | // more zeros in the lower bits. This makes corresponding number of lower bits | ||||
| 2531 | // of the result zero as well. We model it by shifting the other operand | ||||
| 2532 | // shadow left by the required number of bits. Effectively, we transform | ||||
| 2533 | // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B). | ||||
| 2534 | // We use multiplication by 2**N instead of shift to cover the case of | ||||
| 2535 | // multiplication by 0, which may occur in some elements of a vector operand. | ||||
| 2536 | void handleMulByConstant(BinaryOperator &I, Constant *ConstArg, | ||||
| 2537 | Value *OtherArg) { | ||||
| 2538 | Constant *ShadowMul; | ||||
| 2539 | Type *Ty = ConstArg->getType(); | ||||
| 2540 | if (auto *VTy = dyn_cast<VectorType>(Ty)) { | ||||
| 2541 | unsigned NumElements = cast<FixedVectorType>(VTy)->getNumElements(); | ||||
| 2542 | Type *EltTy = VTy->getElementType(); | ||||
| 2543 | SmallVector<Constant *, 16> Elements; | ||||
| 2544 | for (unsigned Idx = 0; Idx < NumElements; ++Idx) { | ||||
| 2545 | if (ConstantInt *Elt = | ||||
| 2546 | dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) { | ||||
| 2547 | const APInt &V = Elt->getValue(); | ||||
| 2548 | APInt V2 = APInt(V.getBitWidth(), 1) << V.countr_zero(); | ||||
| 2549 | Elements.push_back(ConstantInt::get(EltTy, V2)); | ||||
| 2550 | } else { | ||||
| 2551 | Elements.push_back(ConstantInt::get(EltTy, 1)); | ||||
| 2552 | } | ||||
| 2553 | } | ||||
| 2554 | ShadowMul = ConstantVector::get(Elements); | ||||
| 2555 | } else { | ||||
| 2556 | if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) { | ||||
| 2557 | const APInt &V = Elt->getValue(); | ||||
| 2558 | APInt V2 = APInt(V.getBitWidth(), 1) << V.countr_zero(); | ||||
| 2559 | ShadowMul = ConstantInt::get(Ty, V2); | ||||
| 2560 | } else { | ||||
| 2561 | ShadowMul = ConstantInt::get(Ty, 1); | ||||
| 2562 | } | ||||
| 2563 | } | ||||
| 2564 | |||||
| 2565 | IRBuilder<> IRB(&I); | ||||
| 2566 | setShadow(&I, | ||||
| 2567 | IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst")); | ||||
| 2568 | setOrigin(&I, getOrigin(OtherArg)); | ||||
| 2569 | } | ||||
| 2570 | |||||
| 2571 | void visitMul(BinaryOperator &I) { | ||||
| 2572 | Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0)); | ||||
| 2573 | Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1)); | ||||
| 2574 | if (constOp0 && !constOp1) | ||||
| 2575 | handleMulByConstant(I, constOp0, I.getOperand(1)); | ||||
| 2576 | else if (constOp1 && !constOp0) | ||||
| 2577 | handleMulByConstant(I, constOp1, I.getOperand(0)); | ||||
| 2578 | else | ||||
| 2579 | handleShadowOr(I); | ||||
| 2580 | } | ||||
| 2581 | |||||
| 2582 | void visitFAdd(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2583 | void visitFSub(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2584 | void visitFMul(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2585 | void visitAdd(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2586 | void visitSub(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2587 | void visitXor(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2588 | |||||
| 2589 | void handleIntegerDiv(Instruction &I) { | ||||
| 2590 | IRBuilder<> IRB(&I); | ||||
| 2591 | // Strict on the second argument. | ||||
| 2592 | insertShadowCheck(I.getOperand(1), &I); | ||||
| 2593 | setShadow(&I, getShadow(&I, 0)); | ||||
| 2594 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2595 | } | ||||
| 2596 | |||||
| 2597 | void visitUDiv(BinaryOperator &I) { handleIntegerDiv(I); } | ||||
| 2598 | void visitSDiv(BinaryOperator &I) { handleIntegerDiv(I); } | ||||
| 2599 | void visitURem(BinaryOperator &I) { handleIntegerDiv(I); } | ||||
| 2600 | void visitSRem(BinaryOperator &I) { handleIntegerDiv(I); } | ||||
| 2601 | |||||
| 2602 | // Floating point division is side-effect free. We can not require that the | ||||
| 2603 | // divisor is fully initialized and must propagate shadow. See PR37523. | ||||
| 2604 | void visitFDiv(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2605 | void visitFRem(BinaryOperator &I) { handleShadowOr(I); } | ||||
| 2606 | |||||
| 2607 | /// Instrument == and != comparisons. | ||||
| 2608 | /// | ||||
| 2609 | /// Sometimes the comparison result is known even if some of the bits of the | ||||
| 2610 | /// arguments are not. | ||||
| 2611 | void handleEqualityComparison(ICmpInst &I) { | ||||
| 2612 | IRBuilder<> IRB(&I); | ||||
| 2613 | Value *A = I.getOperand(0); | ||||
| 2614 | Value *B = I.getOperand(1); | ||||
| 2615 | Value *Sa = getShadow(A); | ||||
| 2616 | Value *Sb = getShadow(B); | ||||
| 2617 | |||||
| 2618 | // Get rid of pointers and vectors of pointers. | ||||
| 2619 | // For ints (and vectors of ints), types of A and Sa match, | ||||
| 2620 | // and this is a no-op. | ||||
| 2621 | A = IRB.CreatePointerCast(A, Sa->getType()); | ||||
| 2622 | B = IRB.CreatePointerCast(B, Sb->getType()); | ||||
| 2623 | |||||
| 2624 | // A == B <==> (C = A^B) == 0 | ||||
| 2625 | // A != B <==> (C = A^B) != 0 | ||||
| 2626 | // Sc = Sa | Sb | ||||
| 2627 | Value *C = IRB.CreateXor(A, B); | ||||
| 2628 | Value *Sc = IRB.CreateOr(Sa, Sb); | ||||
| 2629 | // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now) | ||||
| 2630 | // Result is defined if one of the following is true | ||||
| 2631 | // * there is a defined 1 bit in C | ||||
| 2632 | // * C is fully defined | ||||
| 2633 | // Si = !(C & ~Sc) && Sc | ||||
| 2634 | Value *Zero = Constant::getNullValue(Sc->getType()); | ||||
| 2635 | Value *MinusOne = Constant::getAllOnesValue(Sc->getType()); | ||||
| 2636 | Value *LHS = IRB.CreateICmpNE(Sc, Zero); | ||||
| 2637 | Value *RHS = | ||||
| 2638 | IRB.CreateICmpEQ(IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero); | ||||
| 2639 | Value *Si = IRB.CreateAnd(LHS, RHS); | ||||
| 2640 | Si->setName("_msprop_icmp"); | ||||
| 2641 | setShadow(&I, Si); | ||||
| 2642 | setOriginForNaryOp(I); | ||||
| 2643 | } | ||||
| 2644 | |||||
| 2645 | /// Build the lowest possible value of V, taking into account V's | ||||
| 2646 | /// uninitialized bits. | ||||
| 2647 | Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa, | ||||
| 2648 | bool isSigned) { | ||||
| 2649 | if (isSigned) { | ||||
| 2650 | // Split shadow into sign bit and other bits. | ||||
| 2651 | Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1); | ||||
| 2652 | Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits); | ||||
| 2653 | // Maximise the undefined shadow bit, minimize other undefined bits. | ||||
| 2654 | return IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), | ||||
| 2655 | SaSignBit); | ||||
| 2656 | } else { | ||||
| 2657 | // Minimize undefined bits. | ||||
| 2658 | return IRB.CreateAnd(A, IRB.CreateNot(Sa)); | ||||
| 2659 | } | ||||
| 2660 | } | ||||
| 2661 | |||||
| 2662 | /// Build the highest possible value of V, taking into account V's | ||||
| 2663 | /// uninitialized bits. | ||||
| 2664 | Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa, | ||||
| 2665 | bool isSigned) { | ||||
| 2666 | if (isSigned) { | ||||
| 2667 | // Split shadow into sign bit and other bits. | ||||
| 2668 | Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1); | ||||
| 2669 | Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits); | ||||
| 2670 | // Minimise the undefined shadow bit, maximise other undefined bits. | ||||
| 2671 | return IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), | ||||
| 2672 | SaOtherBits); | ||||
| 2673 | } else { | ||||
| 2674 | // Maximize undefined bits. | ||||
| 2675 | return IRB.CreateOr(A, Sa); | ||||
| 2676 | } | ||||
| 2677 | } | ||||
| 2678 | |||||
| 2679 | /// Instrument relational comparisons. | ||||
| 2680 | /// | ||||
| 2681 | /// This function does exact shadow propagation for all relational | ||||
| 2682 | /// comparisons of integers, pointers and vectors of those. | ||||
| 2683 | /// FIXME: output seems suboptimal when one of the operands is a constant | ||||
| 2684 | void handleRelationalComparisonExact(ICmpInst &I) { | ||||
| 2685 | IRBuilder<> IRB(&I); | ||||
| 2686 | Value *A = I.getOperand(0); | ||||
| 2687 | Value *B = I.getOperand(1); | ||||
| 2688 | Value *Sa = getShadow(A); | ||||
| 2689 | Value *Sb = getShadow(B); | ||||
| 2690 | |||||
| 2691 | // Get rid of pointers and vectors of pointers. | ||||
| 2692 | // For ints (and vectors of ints), types of A and Sa match, | ||||
| 2693 | // and this is a no-op. | ||||
| 2694 | A = IRB.CreatePointerCast(A, Sa->getType()); | ||||
| 2695 | B = IRB.CreatePointerCast(B, Sb->getType()); | ||||
| 2696 | |||||
| 2697 | // Let [a0, a1] be the interval of possible values of A, taking into account | ||||
| 2698 | // its undefined bits. Let [b0, b1] be the interval of possible values of B. | ||||
| 2699 | // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0). | ||||
| 2700 | bool IsSigned = I.isSigned(); | ||||
| 2701 | Value *S1 = IRB.CreateICmp(I.getPredicate(), | ||||
| 2702 | getLowestPossibleValue(IRB, A, Sa, IsSigned), | ||||
| 2703 | getHighestPossibleValue(IRB, B, Sb, IsSigned)); | ||||
| 2704 | Value *S2 = IRB.CreateICmp(I.getPredicate(), | ||||
| 2705 | getHighestPossibleValue(IRB, A, Sa, IsSigned), | ||||
| 2706 | getLowestPossibleValue(IRB, B, Sb, IsSigned)); | ||||
| 2707 | Value *Si = IRB.CreateXor(S1, S2); | ||||
| 2708 | setShadow(&I, Si); | ||||
| 2709 | setOriginForNaryOp(I); | ||||
| 2710 | } | ||||
| 2711 | |||||
| 2712 | /// Instrument signed relational comparisons. | ||||
| 2713 | /// | ||||
| 2714 | /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest | ||||
| 2715 | /// bit of the shadow. Everything else is delegated to handleShadowOr(). | ||||
| 2716 | void handleSignedRelationalComparison(ICmpInst &I) { | ||||
| 2717 | Constant *constOp; | ||||
| 2718 | Value *op = nullptr; | ||||
| 2719 | CmpInst::Predicate pre; | ||||
| 2720 | if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) { | ||||
| 2721 | op = I.getOperand(0); | ||||
| 2722 | pre = I.getPredicate(); | ||||
| 2723 | } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) { | ||||
| 2724 | op = I.getOperand(1); | ||||
| 2725 | pre = I.getSwappedPredicate(); | ||||
| 2726 | } else { | ||||
| 2727 | handleShadowOr(I); | ||||
| 2728 | return; | ||||
| 2729 | } | ||||
| 2730 | |||||
| 2731 | if ((constOp->isNullValue() && | ||||
| 2732 | (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) || | ||||
| 2733 | (constOp->isAllOnesValue() && | ||||
| 2734 | (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) { | ||||
| 2735 | IRBuilder<> IRB(&I); | ||||
| 2736 | Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op), | ||||
| 2737 | "_msprop_icmp_s"); | ||||
| 2738 | setShadow(&I, Shadow); | ||||
| 2739 | setOrigin(&I, getOrigin(op)); | ||||
| 2740 | } else { | ||||
| 2741 | handleShadowOr(I); | ||||
| 2742 | } | ||||
| 2743 | } | ||||
| 2744 | |||||
| 2745 | void visitICmpInst(ICmpInst &I) { | ||||
| 2746 | if (!ClHandleICmp) { | ||||
| 2747 | handleShadowOr(I); | ||||
| 2748 | return; | ||||
| 2749 | } | ||||
| 2750 | if (I.isEquality()) { | ||||
| 2751 | handleEqualityComparison(I); | ||||
| 2752 | return; | ||||
| 2753 | } | ||||
| 2754 | |||||
| 2755 | assert(I.isRelational())(static_cast <bool> (I.isRelational()) ? void (0) : __assert_fail ("I.isRelational()", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2755, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2756 | if (ClHandleICmpExact) { | ||||
| 2757 | handleRelationalComparisonExact(I); | ||||
| 2758 | return; | ||||
| 2759 | } | ||||
| 2760 | if (I.isSigned()) { | ||||
| 2761 | handleSignedRelationalComparison(I); | ||||
| 2762 | return; | ||||
| 2763 | } | ||||
| 2764 | |||||
| 2765 | assert(I.isUnsigned())(static_cast <bool> (I.isUnsigned()) ? void (0) : __assert_fail ("I.isUnsigned()", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 2765, __extension__ __PRETTY_FUNCTION__)); | ||||
| 2766 | if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) { | ||||
| 2767 | handleRelationalComparisonExact(I); | ||||
| 2768 | return; | ||||
| 2769 | } | ||||
| 2770 | |||||
| 2771 | handleShadowOr(I); | ||||
| 2772 | } | ||||
| 2773 | |||||
| 2774 | void visitFCmpInst(FCmpInst &I) { handleShadowOr(I); } | ||||
| 2775 | |||||
| 2776 | void handleShift(BinaryOperator &I) { | ||||
| 2777 | IRBuilder<> IRB(&I); | ||||
| 2778 | // If any of the S2 bits are poisoned, the whole thing is poisoned. | ||||
| 2779 | // Otherwise perform the same shift on S1. | ||||
| 2780 | Value *S1 = getShadow(&I, 0); | ||||
| 2781 | Value *S2 = getShadow(&I, 1); | ||||
| 2782 | Value *S2Conv = | ||||
| 2783 | IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), S2->getType()); | ||||
| 2784 | Value *V2 = I.getOperand(1); | ||||
| 2785 | Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2); | ||||
| 2786 | setShadow(&I, IRB.CreateOr(Shift, S2Conv)); | ||||
| 2787 | setOriginForNaryOp(I); | ||||
| 2788 | } | ||||
| 2789 | |||||
| 2790 | void visitShl(BinaryOperator &I) { handleShift(I); } | ||||
| 2791 | void visitAShr(BinaryOperator &I) { handleShift(I); } | ||||
| 2792 | void visitLShr(BinaryOperator &I) { handleShift(I); } | ||||
| 2793 | |||||
| 2794 | void handleFunnelShift(IntrinsicInst &I) { | ||||
| 2795 | IRBuilder<> IRB(&I); | ||||
| 2796 | // If any of the S2 bits are poisoned, the whole thing is poisoned. | ||||
| 2797 | // Otherwise perform the same shift on S0 and S1. | ||||
| 2798 | Value *S0 = getShadow(&I, 0); | ||||
| 2799 | Value *S1 = getShadow(&I, 1); | ||||
| 2800 | Value *S2 = getShadow(&I, 2); | ||||
| 2801 | Value *S2Conv = | ||||
| 2802 | IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)), S2->getType()); | ||||
| 2803 | Value *V2 = I.getOperand(2); | ||||
| 2804 | Function *Intrin = Intrinsic::getDeclaration( | ||||
| 2805 | I.getModule(), I.getIntrinsicID(), S2Conv->getType()); | ||||
| 2806 | Value *Shift = IRB.CreateCall(Intrin, {S0, S1, V2}); | ||||
| 2807 | setShadow(&I, IRB.CreateOr(Shift, S2Conv)); | ||||
| 2808 | setOriginForNaryOp(I); | ||||
| 2809 | } | ||||
| 2810 | |||||
| 2811 | /// Instrument llvm.memmove | ||||
| 2812 | /// | ||||
| 2813 | /// At this point we don't know if llvm.memmove will be inlined or not. | ||||
| 2814 | /// If we don't instrument it and it gets inlined, | ||||
| 2815 | /// our interceptor will not kick in and we will lose the memmove. | ||||
| 2816 | /// If we instrument the call here, but it does not get inlined, | ||||
| 2817 | /// we will memove the shadow twice: which is bad in case | ||||
| 2818 | /// of overlapping regions. So, we simply lower the intrinsic to a call. | ||||
| 2819 | /// | ||||
| 2820 | /// Similar situation exists for memcpy and memset. | ||||
| 2821 | void visitMemMoveInst(MemMoveInst &I) { | ||||
| 2822 | getShadow(I.getArgOperand(1)); // Ensure shadow initialized | ||||
| 2823 | IRBuilder<> IRB(&I); | ||||
| 2824 | IRB.CreateCall( | ||||
| 2825 | MS.MemmoveFn, | ||||
| 2826 | {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), | ||||
| 2827 | IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), | ||||
| 2828 | IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)}); | ||||
| 2829 | I.eraseFromParent(); | ||||
| 2830 | } | ||||
| 2831 | |||||
| 2832 | /// Instrument memcpy | ||||
| 2833 | /// | ||||
| 2834 | /// Similar to memmove: avoid copying shadow twice. This is somewhat | ||||
| 2835 | /// unfortunate as it may slowdown small constant memcpys. | ||||
| 2836 | /// FIXME: consider doing manual inline for small constant sizes and proper | ||||
| 2837 | /// alignment. | ||||
| 2838 | /// | ||||
| 2839 | /// Note: This also handles memcpy.inline, which promises no calls to external | ||||
| 2840 | /// functions as an optimization. However, with instrumentation enabled this | ||||
| 2841 | /// is difficult to promise; additionally, we know that the MSan runtime | ||||
| 2842 | /// exists and provides __msan_memcpy(). Therefore, we assume that with | ||||
| 2843 | /// instrumentation it's safe to turn memcpy.inline into a call to | ||||
| 2844 | /// __msan_memcpy(). Should this be wrong, such as when implementing memcpy() | ||||
| 2845 | /// itself, instrumentation should be disabled with the no_sanitize attribute. | ||||
| 2846 | void visitMemCpyInst(MemCpyInst &I) { | ||||
| 2847 | getShadow(I.getArgOperand(1)); // Ensure shadow initialized | ||||
| 2848 | IRBuilder<> IRB(&I); | ||||
| 2849 | IRB.CreateCall( | ||||
| 2850 | MS.MemcpyFn, | ||||
| 2851 | {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), | ||||
| 2852 | IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()), | ||||
| 2853 | IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)}); | ||||
| 2854 | I.eraseFromParent(); | ||||
| 2855 | } | ||||
| 2856 | |||||
| 2857 | // Same as memcpy. | ||||
| 2858 | void visitMemSetInst(MemSetInst &I) { | ||||
| 2859 | IRBuilder<> IRB(&I); | ||||
| 2860 | IRB.CreateCall( | ||||
| 2861 | MS.MemsetFn, | ||||
| 2862 | {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()), | ||||
| 2863 | IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false), | ||||
| 2864 | IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)}); | ||||
| 2865 | I.eraseFromParent(); | ||||
| 2866 | } | ||||
| 2867 | |||||
| 2868 | void visitVAStartInst(VAStartInst &I) { VAHelper->visitVAStartInst(I); } | ||||
| 2869 | |||||
| 2870 | void visitVACopyInst(VACopyInst &I) { VAHelper->visitVACopyInst(I); } | ||||
| 2871 | |||||
| 2872 | /// Handle vector store-like intrinsics. | ||||
| 2873 | /// | ||||
| 2874 | /// Instrument intrinsics that look like a simple SIMD store: writes memory, | ||||
| 2875 | /// has 1 pointer argument and 1 vector argument, returns void. | ||||
| 2876 | bool handleVectorStoreIntrinsic(IntrinsicInst &I) { | ||||
| 2877 | IRBuilder<> IRB(&I); | ||||
| 2878 | Value *Addr = I.getArgOperand(0); | ||||
| 2879 | Value *Shadow = getShadow(&I, 1); | ||||
| 2880 | Value *ShadowPtr, *OriginPtr; | ||||
| 2881 | |||||
| 2882 | // We don't know the pointer alignment (could be unaligned SSE store!). | ||||
| 2883 | // Have to assume to worst case. | ||||
| 2884 | std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr( | ||||
| 2885 | Addr, IRB, Shadow->getType(), Align(1), /*isStore*/ true); | ||||
| 2886 | IRB.CreateAlignedStore(Shadow, ShadowPtr, Align(1)); | ||||
| 2887 | |||||
| 2888 | if (ClCheckAccessAddress) | ||||
| 2889 | insertShadowCheck(Addr, &I); | ||||
| 2890 | |||||
| 2891 | // FIXME: factor out common code from materializeStores | ||||
| 2892 | if (MS.TrackOrigins) | ||||
| 2893 | IRB.CreateStore(getOrigin(&I, 1), OriginPtr); | ||||
| 2894 | return true; | ||||
| 2895 | } | ||||
| 2896 | |||||
| 2897 | /// Handle vector load-like intrinsics. | ||||
| 2898 | /// | ||||
| 2899 | /// Instrument intrinsics that look like a simple SIMD load: reads memory, | ||||
| 2900 | /// has 1 pointer argument, returns a vector. | ||||
| 2901 | bool handleVectorLoadIntrinsic(IntrinsicInst &I) { | ||||
| 2902 | IRBuilder<> IRB(&I); | ||||
| 2903 | Value *Addr = I.getArgOperand(0); | ||||
| 2904 | |||||
| 2905 | Type *ShadowTy = getShadowTy(&I); | ||||
| 2906 | Value *ShadowPtr = nullptr, *OriginPtr = nullptr; | ||||
| 2907 | if (PropagateShadow) { | ||||
| 2908 | // We don't know the pointer alignment (could be unaligned SSE load!). | ||||
| 2909 | // Have to assume to worst case. | ||||
| 2910 | const Align Alignment = Align(1); | ||||
| 2911 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 2912 | getShadowOriginPtr(Addr, IRB, ShadowTy, Alignment, /*isStore*/ false); | ||||
| 2913 | setShadow(&I, | ||||
| 2914 | IRB.CreateAlignedLoad(ShadowTy, ShadowPtr, Alignment, "_msld")); | ||||
| 2915 | } else { | ||||
| 2916 | setShadow(&I, getCleanShadow(&I)); | ||||
| 2917 | } | ||||
| 2918 | |||||
| 2919 | if (ClCheckAccessAddress) | ||||
| 2920 | insertShadowCheck(Addr, &I); | ||||
| 2921 | |||||
| 2922 | if (MS.TrackOrigins) { | ||||
| 2923 | if (PropagateShadow) | ||||
| 2924 | setOrigin(&I, IRB.CreateLoad(MS.OriginTy, OriginPtr)); | ||||
| 2925 | else | ||||
| 2926 | setOrigin(&I, getCleanOrigin()); | ||||
| 2927 | } | ||||
| 2928 | return true; | ||||
| 2929 | } | ||||
| 2930 | |||||
| 2931 | /// Handle (SIMD arithmetic)-like intrinsics. | ||||
| 2932 | /// | ||||
| 2933 | /// Instrument intrinsics with any number of arguments of the same type, | ||||
| 2934 | /// equal to the return type. The type should be simple (no aggregates or | ||||
| 2935 | /// pointers; vectors are fine). | ||||
| 2936 | /// Caller guarantees that this intrinsic does not access memory. | ||||
| 2937 | bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) { | ||||
| 2938 | Type *RetTy = I.getType(); | ||||
| 2939 | if (!(RetTy->isIntOrIntVectorTy() || RetTy->isFPOrFPVectorTy() || | ||||
| 2940 | RetTy->isX86_MMXTy())) | ||||
| 2941 | return false; | ||||
| 2942 | |||||
| 2943 | unsigned NumArgOperands = I.arg_size(); | ||||
| 2944 | for (unsigned i = 0; i < NumArgOperands; ++i) { | ||||
| 2945 | Type *Ty = I.getArgOperand(i)->getType(); | ||||
| 2946 | if (Ty != RetTy) | ||||
| 2947 | return false; | ||||
| 2948 | } | ||||
| 2949 | |||||
| 2950 | IRBuilder<> IRB(&I); | ||||
| 2951 | ShadowAndOriginCombiner SC(this, IRB); | ||||
| 2952 | for (unsigned i = 0; i < NumArgOperands; ++i) | ||||
| 2953 | SC.Add(I.getArgOperand(i)); | ||||
| 2954 | SC.Done(&I); | ||||
| 2955 | |||||
| 2956 | return true; | ||||
| 2957 | } | ||||
| 2958 | |||||
| 2959 | /// Heuristically instrument unknown intrinsics. | ||||
| 2960 | /// | ||||
| 2961 | /// The main purpose of this code is to do something reasonable with all | ||||
| 2962 | /// random intrinsics we might encounter, most importantly - SIMD intrinsics. | ||||
| 2963 | /// We recognize several classes of intrinsics by their argument types and | ||||
| 2964 | /// ModRefBehaviour and apply special instrumentation when we are reasonably | ||||
| 2965 | /// sure that we know what the intrinsic does. | ||||
| 2966 | /// | ||||
| 2967 | /// We special-case intrinsics where this approach fails. See llvm.bswap | ||||
| 2968 | /// handling as an example of that. | ||||
| 2969 | bool handleUnknownIntrinsic(IntrinsicInst &I) { | ||||
| 2970 | unsigned NumArgOperands = I.arg_size(); | ||||
| 2971 | if (NumArgOperands == 0) | ||||
| 2972 | return false; | ||||
| 2973 | |||||
| 2974 | if (NumArgOperands == 2 && I.getArgOperand(0)->getType()->isPointerTy() && | ||||
| 2975 | I.getArgOperand(1)->getType()->isVectorTy() && | ||||
| 2976 | I.getType()->isVoidTy() && !I.onlyReadsMemory()) { | ||||
| 2977 | // This looks like a vector store. | ||||
| 2978 | return handleVectorStoreIntrinsic(I); | ||||
| 2979 | } | ||||
| 2980 | |||||
| 2981 | if (NumArgOperands == 1 && I.getArgOperand(0)->getType()->isPointerTy() && | ||||
| 2982 | I.getType()->isVectorTy() && I.onlyReadsMemory()) { | ||||
| 2983 | // This looks like a vector load. | ||||
| 2984 | return handleVectorLoadIntrinsic(I); | ||||
| 2985 | } | ||||
| 2986 | |||||
| 2987 | if (I.doesNotAccessMemory()) | ||||
| 2988 | if (maybeHandleSimpleNomemIntrinsic(I)) | ||||
| 2989 | return true; | ||||
| 2990 | |||||
| 2991 | // FIXME: detect and handle SSE maskstore/maskload | ||||
| 2992 | return false; | ||||
| 2993 | } | ||||
| 2994 | |||||
| 2995 | void handleInvariantGroup(IntrinsicInst &I) { | ||||
| 2996 | setShadow(&I, getShadow(&I, 0)); | ||||
| 2997 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 2998 | } | ||||
| 2999 | |||||
| 3000 | void handleLifetimeStart(IntrinsicInst &I) { | ||||
| 3001 | if (!PoisonStack) | ||||
| 3002 | return; | ||||
| 3003 | AllocaInst *AI = llvm::findAllocaForValue(I.getArgOperand(1)); | ||||
| 3004 | if (!AI) | ||||
| 3005 | InstrumentLifetimeStart = false; | ||||
| 3006 | LifetimeStartList.push_back(std::make_pair(&I, AI)); | ||||
| 3007 | } | ||||
| 3008 | |||||
| 3009 | void handleBswap(IntrinsicInst &I) { | ||||
| 3010 | IRBuilder<> IRB(&I); | ||||
| 3011 | Value *Op = I.getArgOperand(0); | ||||
| 3012 | Type *OpType = Op->getType(); | ||||
| 3013 | Function *BswapFunc = Intrinsic::getDeclaration( | ||||
| 3014 | F.getParent(), Intrinsic::bswap, ArrayRef(&OpType, 1)); | ||||
| 3015 | setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op))); | ||||
| 3016 | setOrigin(&I, getOrigin(Op)); | ||||
| 3017 | } | ||||
| 3018 | |||||
| 3019 | void handleCountZeroes(IntrinsicInst &I) { | ||||
| 3020 | IRBuilder<> IRB(&I); | ||||
| 3021 | Value *Src = I.getArgOperand(0); | ||||
| 3022 | |||||
| 3023 | // Set the Output shadow based on input Shadow | ||||
| 3024 | Value *BoolShadow = IRB.CreateIsNotNull(getShadow(Src), "_mscz_bs"); | ||||
| 3025 | |||||
| 3026 | // If zero poison is requested, mix in with the shadow | ||||
| 3027 | Constant *IsZeroPoison = cast<Constant>(I.getOperand(1)); | ||||
| 3028 | if (!IsZeroPoison->isZeroValue()) { | ||||
| 3029 | Value *BoolZeroPoison = IRB.CreateIsNull(Src, "_mscz_bzp"); | ||||
| 3030 | BoolShadow = IRB.CreateOr(BoolShadow, BoolZeroPoison, "_mscz_bs"); | ||||
| 3031 | } | ||||
| 3032 | |||||
| 3033 | Value *OutputShadow = | ||||
| 3034 | IRB.CreateSExt(BoolShadow, getShadowTy(Src), "_mscz_os"); | ||||
| 3035 | |||||
| 3036 | setShadow(&I, OutputShadow); | ||||
| 3037 | setOriginForNaryOp(I); | ||||
| 3038 | } | ||||
| 3039 | |||||
| 3040 | // Instrument vector convert intrinsic. | ||||
| 3041 | // | ||||
| 3042 | // This function instruments intrinsics like cvtsi2ss: | ||||
| 3043 | // %Out = int_xxx_cvtyyy(%ConvertOp) | ||||
| 3044 | // or | ||||
| 3045 | // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp) | ||||
| 3046 | // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same | ||||
| 3047 | // number \p Out elements, and (if has 2 arguments) copies the rest of the | ||||
| 3048 | // elements from \p CopyOp. | ||||
| 3049 | // In most cases conversion involves floating-point value which may trigger a | ||||
| 3050 | // hardware exception when not fully initialized. For this reason we require | ||||
| 3051 | // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise. | ||||
| 3052 | // We copy the shadow of \p CopyOp[NumUsedElements:] to \p | ||||
| 3053 | // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always | ||||
| 3054 | // return a fully initialized value. | ||||
| 3055 | void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements, | ||||
| 3056 | bool HasRoundingMode = false) { | ||||
| 3057 | IRBuilder<> IRB(&I); | ||||
| 3058 | Value *CopyOp, *ConvertOp; | ||||
| 3059 | |||||
| 3060 | assert((!HasRoundingMode ||(static_cast <bool> ((!HasRoundingMode || isa<ConstantInt >(I.getArgOperand(I.arg_size() - 1))) && "Invalid rounding mode" ) ? void (0) : __assert_fail ("(!HasRoundingMode || isa<ConstantInt>(I.getArgOperand(I.arg_size() - 1))) && \"Invalid rounding mode\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3062 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 3061 | isa<ConstantInt>(I.getArgOperand(I.arg_size() - 1))) &&(static_cast <bool> ((!HasRoundingMode || isa<ConstantInt >(I.getArgOperand(I.arg_size() - 1))) && "Invalid rounding mode" ) ? void (0) : __assert_fail ("(!HasRoundingMode || isa<ConstantInt>(I.getArgOperand(I.arg_size() - 1))) && \"Invalid rounding mode\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3062 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 3062 | "Invalid rounding mode")(static_cast <bool> ((!HasRoundingMode || isa<ConstantInt >(I.getArgOperand(I.arg_size() - 1))) && "Invalid rounding mode" ) ? void (0) : __assert_fail ("(!HasRoundingMode || isa<ConstantInt>(I.getArgOperand(I.arg_size() - 1))) && \"Invalid rounding mode\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3062 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3063 | |||||
| 3064 | switch (I.arg_size() - HasRoundingMode) { | ||||
| 3065 | case 2: | ||||
| 3066 | CopyOp = I.getArgOperand(0); | ||||
| 3067 | ConvertOp = I.getArgOperand(1); | ||||
| 3068 | break; | ||||
| 3069 | case 1: | ||||
| 3070 | ConvertOp = I.getArgOperand(0); | ||||
| 3071 | CopyOp = nullptr; | ||||
| 3072 | break; | ||||
| 3073 | default: | ||||
| 3074 | llvm_unreachable("Cvt intrinsic with unsupported number of arguments.")::llvm::llvm_unreachable_internal("Cvt intrinsic with unsupported number of arguments." , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3074 ); | ||||
| 3075 | } | ||||
| 3076 | |||||
| 3077 | // The first *NumUsedElements* elements of ConvertOp are converted to the | ||||
| 3078 | // same number of output elements. The rest of the output is copied from | ||||
| 3079 | // CopyOp, or (if not available) filled with zeroes. | ||||
| 3080 | // Combine shadow for elements of ConvertOp that are used in this operation, | ||||
| 3081 | // and insert a check. | ||||
| 3082 | // FIXME: consider propagating shadow of ConvertOp, at least in the case of | ||||
| 3083 | // int->any conversion. | ||||
| 3084 | Value *ConvertShadow = getShadow(ConvertOp); | ||||
| 3085 | Value *AggShadow = nullptr; | ||||
| 3086 | if (ConvertOp->getType()->isVectorTy()) { | ||||
| 3087 | AggShadow = IRB.CreateExtractElement( | ||||
| 3088 | ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0)); | ||||
| 3089 | for (int i = 1; i < NumUsedElements; ++i) { | ||||
| 3090 | Value *MoreShadow = IRB.CreateExtractElement( | ||||
| 3091 | ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i)); | ||||
| 3092 | AggShadow = IRB.CreateOr(AggShadow, MoreShadow); | ||||
| 3093 | } | ||||
| 3094 | } else { | ||||
| 3095 | AggShadow = ConvertShadow; | ||||
| 3096 | } | ||||
| 3097 | assert(AggShadow->getType()->isIntegerTy())(static_cast <bool> (AggShadow->getType()->isIntegerTy ()) ? void (0) : __assert_fail ("AggShadow->getType()->isIntegerTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3097 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3098 | insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I); | ||||
| 3099 | |||||
| 3100 | // Build result shadow by zero-filling parts of CopyOp shadow that come from | ||||
| 3101 | // ConvertOp. | ||||
| 3102 | if (CopyOp) { | ||||
| 3103 | assert(CopyOp->getType() == I.getType())(static_cast <bool> (CopyOp->getType() == I.getType( )) ? void (0) : __assert_fail ("CopyOp->getType() == I.getType()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3103 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3104 | assert(CopyOp->getType()->isVectorTy())(static_cast <bool> (CopyOp->getType()->isVectorTy ()) ? void (0) : __assert_fail ("CopyOp->getType()->isVectorTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3104 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3105 | Value *ResultShadow = getShadow(CopyOp); | ||||
| 3106 | Type *EltTy = cast<VectorType>(ResultShadow->getType())->getElementType(); | ||||
| 3107 | for (int i = 0; i < NumUsedElements; ++i) { | ||||
| 3108 | ResultShadow = IRB.CreateInsertElement( | ||||
| 3109 | ResultShadow, ConstantInt::getNullValue(EltTy), | ||||
| 3110 | ConstantInt::get(IRB.getInt32Ty(), i)); | ||||
| 3111 | } | ||||
| 3112 | setShadow(&I, ResultShadow); | ||||
| 3113 | setOrigin(&I, getOrigin(CopyOp)); | ||||
| 3114 | } else { | ||||
| 3115 | setShadow(&I, getCleanShadow(&I)); | ||||
| 3116 | setOrigin(&I, getCleanOrigin()); | ||||
| 3117 | } | ||||
| 3118 | } | ||||
| 3119 | |||||
| 3120 | // Given a scalar or vector, extract lower 64 bits (or less), and return all | ||||
| 3121 | // zeroes if it is zero, and all ones otherwise. | ||||
| 3122 | Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) { | ||||
| 3123 | if (S->getType()->isVectorTy()) | ||||
| 3124 | S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true); | ||||
| 3125 | assert(S->getType()->getPrimitiveSizeInBits() <= 64)(static_cast <bool> (S->getType()->getPrimitiveSizeInBits () <= 64) ? void (0) : __assert_fail ("S->getType()->getPrimitiveSizeInBits() <= 64" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3125 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3126 | Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S)); | ||||
| 3127 | return CreateShadowCast(IRB, S2, T, /* Signed */ true); | ||||
| 3128 | } | ||||
| 3129 | |||||
| 3130 | // Given a vector, extract its first element, and return all | ||||
| 3131 | // zeroes if it is zero, and all ones otherwise. | ||||
| 3132 | Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) { | ||||
| 3133 | Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0); | ||||
| 3134 | Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1)); | ||||
| 3135 | return CreateShadowCast(IRB, S2, T, /* Signed */ true); | ||||
| 3136 | } | ||||
| 3137 | |||||
| 3138 | Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) { | ||||
| 3139 | Type *T = S->getType(); | ||||
| 3140 | assert(T->isVectorTy())(static_cast <bool> (T->isVectorTy()) ? void (0) : __assert_fail ("T->isVectorTy()", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 3140, __extension__ __PRETTY_FUNCTION__)); | ||||
| 3141 | Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S)); | ||||
| 3142 | return IRB.CreateSExt(S2, T); | ||||
| 3143 | } | ||||
| 3144 | |||||
| 3145 | // Instrument vector shift intrinsic. | ||||
| 3146 | // | ||||
| 3147 | // This function instruments intrinsics like int_x86_avx2_psll_w. | ||||
| 3148 | // Intrinsic shifts %In by %ShiftSize bits. | ||||
| 3149 | // %ShiftSize may be a vector. In that case the lower 64 bits determine shift | ||||
| 3150 | // size, and the rest is ignored. Behavior is defined even if shift size is | ||||
| 3151 | // greater than register (or field) width. | ||||
| 3152 | void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) { | ||||
| 3153 | assert(I.arg_size() == 2)(static_cast <bool> (I.arg_size() == 2) ? void (0) : __assert_fail ("I.arg_size() == 2", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 3153, __extension__ __PRETTY_FUNCTION__)); | ||||
| 3154 | IRBuilder<> IRB(&I); | ||||
| 3155 | // If any of the S2 bits are poisoned, the whole thing is poisoned. | ||||
| 3156 | // Otherwise perform the same shift on S1. | ||||
| 3157 | Value *S1 = getShadow(&I, 0); | ||||
| 3158 | Value *S2 = getShadow(&I, 1); | ||||
| 3159 | Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2) | ||||
| 3160 | : Lower64ShadowExtend(IRB, S2, getShadowTy(&I)); | ||||
| 3161 | Value *V1 = I.getOperand(0); | ||||
| 3162 | Value *V2 = I.getOperand(1); | ||||
| 3163 | Value *Shift = IRB.CreateCall(I.getFunctionType(), I.getCalledOperand(), | ||||
| 3164 | {IRB.CreateBitCast(S1, V1->getType()), V2}); | ||||
| 3165 | Shift = IRB.CreateBitCast(Shift, getShadowTy(&I)); | ||||
| 3166 | setShadow(&I, IRB.CreateOr(Shift, S2Conv)); | ||||
| 3167 | setOriginForNaryOp(I); | ||||
| 3168 | } | ||||
| 3169 | |||||
| 3170 | // Get an X86_MMX-sized vector type. | ||||
| 3171 | Type *getMMXVectorTy(unsigned EltSizeInBits) { | ||||
| 3172 | const unsigned X86_MMXSizeInBits = 64; | ||||
| 3173 | assert(EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 &&(static_cast <bool> (EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 && "Illegal MMX vector element size" ) ? void (0) : __assert_fail ("EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 && \"Illegal MMX vector element size\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3174 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 3174 | "Illegal MMX vector element size")(static_cast <bool> (EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 && "Illegal MMX vector element size" ) ? void (0) : __assert_fail ("EltSizeInBits != 0 && (X86_MMXSizeInBits % EltSizeInBits) == 0 && \"Illegal MMX vector element size\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3174 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3175 | return FixedVectorType::get(IntegerType::get(*MS.C, EltSizeInBits), | ||||
| 3176 | X86_MMXSizeInBits / EltSizeInBits); | ||||
| 3177 | } | ||||
| 3178 | |||||
| 3179 | // Returns a signed counterpart for an (un)signed-saturate-and-pack | ||||
| 3180 | // intrinsic. | ||||
| 3181 | Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) { | ||||
| 3182 | switch (id) { | ||||
| 3183 | case Intrinsic::x86_sse2_packsswb_128: | ||||
| 3184 | case Intrinsic::x86_sse2_packuswb_128: | ||||
| 3185 | return Intrinsic::x86_sse2_packsswb_128; | ||||
| 3186 | |||||
| 3187 | case Intrinsic::x86_sse2_packssdw_128: | ||||
| 3188 | case Intrinsic::x86_sse41_packusdw: | ||||
| 3189 | return Intrinsic::x86_sse2_packssdw_128; | ||||
| 3190 | |||||
| 3191 | case Intrinsic::x86_avx2_packsswb: | ||||
| 3192 | case Intrinsic::x86_avx2_packuswb: | ||||
| 3193 | return Intrinsic::x86_avx2_packsswb; | ||||
| 3194 | |||||
| 3195 | case Intrinsic::x86_avx2_packssdw: | ||||
| 3196 | case Intrinsic::x86_avx2_packusdw: | ||||
| 3197 | return Intrinsic::x86_avx2_packssdw; | ||||
| 3198 | |||||
| 3199 | case Intrinsic::x86_mmx_packsswb: | ||||
| 3200 | case Intrinsic::x86_mmx_packuswb: | ||||
| 3201 | return Intrinsic::x86_mmx_packsswb; | ||||
| 3202 | |||||
| 3203 | case Intrinsic::x86_mmx_packssdw: | ||||
| 3204 | return Intrinsic::x86_mmx_packssdw; | ||||
| 3205 | default: | ||||
| 3206 | llvm_unreachable("unexpected intrinsic id")::llvm::llvm_unreachable_internal("unexpected intrinsic id", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 3206); | ||||
| 3207 | } | ||||
| 3208 | } | ||||
| 3209 | |||||
| 3210 | // Instrument vector pack intrinsic. | ||||
| 3211 | // | ||||
| 3212 | // This function instruments intrinsics like x86_mmx_packsswb, that | ||||
| 3213 | // packs elements of 2 input vectors into half as many bits with saturation. | ||||
| 3214 | // Shadow is propagated with the signed variant of the same intrinsic applied | ||||
| 3215 | // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer). | ||||
| 3216 | // EltSizeInBits is used only for x86mmx arguments. | ||||
| 3217 | void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) { | ||||
| 3218 | assert(I.arg_size() == 2)(static_cast <bool> (I.arg_size() == 2) ? void (0) : __assert_fail ("I.arg_size() == 2", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 3218, __extension__ __PRETTY_FUNCTION__)); | ||||
| 3219 | bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy(); | ||||
| 3220 | IRBuilder<> IRB(&I); | ||||
| 3221 | Value *S1 = getShadow(&I, 0); | ||||
| 3222 | Value *S2 = getShadow(&I, 1); | ||||
| 3223 | assert(isX86_MMX || S1->getType()->isVectorTy())(static_cast <bool> (isX86_MMX || S1->getType()-> isVectorTy()) ? void (0) : __assert_fail ("isX86_MMX || S1->getType()->isVectorTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3223 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3224 | |||||
| 3225 | // SExt and ICmpNE below must apply to individual elements of input vectors. | ||||
| 3226 | // In case of x86mmx arguments, cast them to appropriate vector types and | ||||
| 3227 | // back. | ||||
| 3228 | Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType(); | ||||
| 3229 | if (isX86_MMX) { | ||||
| 3230 | S1 = IRB.CreateBitCast(S1, T); | ||||
| 3231 | S2 = IRB.CreateBitCast(S2, T); | ||||
| 3232 | } | ||||
| 3233 | Value *S1_ext = | ||||
| 3234 | IRB.CreateSExt(IRB.CreateICmpNE(S1, Constant::getNullValue(T)), T); | ||||
| 3235 | Value *S2_ext = | ||||
| 3236 | IRB.CreateSExt(IRB.CreateICmpNE(S2, Constant::getNullValue(T)), T); | ||||
| 3237 | if (isX86_MMX) { | ||||
| 3238 | Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C); | ||||
| 3239 | S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy); | ||||
| 3240 | S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy); | ||||
| 3241 | } | ||||
| 3242 | |||||
| 3243 | Function *ShadowFn = Intrinsic::getDeclaration( | ||||
| 3244 | F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID())); | ||||
| 3245 | |||||
| 3246 | Value *S = | ||||
| 3247 | IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack"); | ||||
| 3248 | if (isX86_MMX) | ||||
| 3249 | S = IRB.CreateBitCast(S, getShadowTy(&I)); | ||||
| 3250 | setShadow(&I, S); | ||||
| 3251 | setOriginForNaryOp(I); | ||||
| 3252 | } | ||||
| 3253 | |||||
| 3254 | // Instrument sum-of-absolute-differences intrinsic. | ||||
| 3255 | void handleVectorSadIntrinsic(IntrinsicInst &I) { | ||||
| 3256 | const unsigned SignificantBitsPerResultElement = 16; | ||||
| 3257 | bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy(); | ||||
| 3258 | Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType(); | ||||
| 3259 | unsigned ZeroBitsPerResultElement = | ||||
| 3260 | ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement; | ||||
| 3261 | |||||
| 3262 | IRBuilder<> IRB(&I); | ||||
| 3263 | auto *Shadow0 = getShadow(&I, 0); | ||||
| 3264 | auto *Shadow1 = getShadow(&I, 1); | ||||
| 3265 | Value *S = IRB.CreateOr(Shadow0, Shadow1); | ||||
| 3266 | S = IRB.CreateBitCast(S, ResTy); | ||||
| 3267 | S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)), | ||||
| 3268 | ResTy); | ||||
| 3269 | S = IRB.CreateLShr(S, ZeroBitsPerResultElement); | ||||
| 3270 | S = IRB.CreateBitCast(S, getShadowTy(&I)); | ||||
| 3271 | setShadow(&I, S); | ||||
| 3272 | setOriginForNaryOp(I); | ||||
| 3273 | } | ||||
| 3274 | |||||
| 3275 | // Instrument multiply-add intrinsic. | ||||
| 3276 | void handleVectorPmaddIntrinsic(IntrinsicInst &I, | ||||
| 3277 | unsigned EltSizeInBits = 0) { | ||||
| 3278 | bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy(); | ||||
| 3279 | Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType(); | ||||
| 3280 | IRBuilder<> IRB(&I); | ||||
| 3281 | auto *Shadow0 = getShadow(&I, 0); | ||||
| 3282 | auto *Shadow1 = getShadow(&I, 1); | ||||
| 3283 | Value *S = IRB.CreateOr(Shadow0, Shadow1); | ||||
| 3284 | S = IRB.CreateBitCast(S, ResTy); | ||||
| 3285 | S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)), | ||||
| 3286 | ResTy); | ||||
| 3287 | S = IRB.CreateBitCast(S, getShadowTy(&I)); | ||||
| 3288 | setShadow(&I, S); | ||||
| 3289 | setOriginForNaryOp(I); | ||||
| 3290 | } | ||||
| 3291 | |||||
| 3292 | // Instrument compare-packed intrinsic. | ||||
| 3293 | // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or | ||||
| 3294 | // all-ones shadow. | ||||
| 3295 | void handleVectorComparePackedIntrinsic(IntrinsicInst &I) { | ||||
| 3296 | IRBuilder<> IRB(&I); | ||||
| 3297 | Type *ResTy = getShadowTy(&I); | ||||
| 3298 | auto *Shadow0 = getShadow(&I, 0); | ||||
| 3299 | auto *Shadow1 = getShadow(&I, 1); | ||||
| 3300 | Value *S0 = IRB.CreateOr(Shadow0, Shadow1); | ||||
| 3301 | Value *S = IRB.CreateSExt( | ||||
| 3302 | IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy); | ||||
| 3303 | setShadow(&I, S); | ||||
| 3304 | setOriginForNaryOp(I); | ||||
| 3305 | } | ||||
| 3306 | |||||
| 3307 | // Instrument compare-scalar intrinsic. | ||||
| 3308 | // This handles both cmp* intrinsics which return the result in the first | ||||
| 3309 | // element of a vector, and comi* which return the result as i32. | ||||
| 3310 | void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) { | ||||
| 3311 | IRBuilder<> IRB(&I); | ||||
| 3312 | auto *Shadow0 = getShadow(&I, 0); | ||||
| 3313 | auto *Shadow1 = getShadow(&I, 1); | ||||
| 3314 | Value *S0 = IRB.CreateOr(Shadow0, Shadow1); | ||||
| 3315 | Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I)); | ||||
| 3316 | setShadow(&I, S); | ||||
| 3317 | setOriginForNaryOp(I); | ||||
| 3318 | } | ||||
| 3319 | |||||
| 3320 | // Instrument generic vector reduction intrinsics | ||||
| 3321 | // by ORing together all their fields. | ||||
| 3322 | void handleVectorReduceIntrinsic(IntrinsicInst &I) { | ||||
| 3323 | IRBuilder<> IRB(&I); | ||||
| 3324 | Value *S = IRB.CreateOrReduce(getShadow(&I, 0)); | ||||
| 3325 | setShadow(&I, S); | ||||
| 3326 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 3327 | } | ||||
| 3328 | |||||
| 3329 | // Instrument vector.reduce.or intrinsic. | ||||
| 3330 | // Valid (non-poisoned) set bits in the operand pull low the | ||||
| 3331 | // corresponding shadow bits. | ||||
| 3332 | void handleVectorReduceOrIntrinsic(IntrinsicInst &I) { | ||||
| 3333 | IRBuilder<> IRB(&I); | ||||
| 3334 | Value *OperandShadow = getShadow(&I, 0); | ||||
| 3335 | Value *OperandUnsetBits = IRB.CreateNot(I.getOperand(0)); | ||||
| 3336 | Value *OperandUnsetOrPoison = IRB.CreateOr(OperandUnsetBits, OperandShadow); | ||||
| 3337 | // Bit N is clean if any field's bit N is 1 and unpoison | ||||
| 3338 | Value *OutShadowMask = IRB.CreateAndReduce(OperandUnsetOrPoison); | ||||
| 3339 | // Otherwise, it is clean if every field's bit N is unpoison | ||||
| 3340 | Value *OrShadow = IRB.CreateOrReduce(OperandShadow); | ||||
| 3341 | Value *S = IRB.CreateAnd(OutShadowMask, OrShadow); | ||||
| 3342 | |||||
| 3343 | setShadow(&I, S); | ||||
| 3344 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 3345 | } | ||||
| 3346 | |||||
| 3347 | // Instrument vector.reduce.and intrinsic. | ||||
| 3348 | // Valid (non-poisoned) unset bits in the operand pull down the | ||||
| 3349 | // corresponding shadow bits. | ||||
| 3350 | void handleVectorReduceAndIntrinsic(IntrinsicInst &I) { | ||||
| 3351 | IRBuilder<> IRB(&I); | ||||
| 3352 | Value *OperandShadow = getShadow(&I, 0); | ||||
| 3353 | Value *OperandSetOrPoison = IRB.CreateOr(I.getOperand(0), OperandShadow); | ||||
| 3354 | // Bit N is clean if any field's bit N is 0 and unpoison | ||||
| 3355 | Value *OutShadowMask = IRB.CreateAndReduce(OperandSetOrPoison); | ||||
| 3356 | // Otherwise, it is clean if every field's bit N is unpoison | ||||
| 3357 | Value *OrShadow = IRB.CreateOrReduce(OperandShadow); | ||||
| 3358 | Value *S = IRB.CreateAnd(OutShadowMask, OrShadow); | ||||
| 3359 | |||||
| 3360 | setShadow(&I, S); | ||||
| 3361 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 3362 | } | ||||
| 3363 | |||||
| 3364 | void handleStmxcsr(IntrinsicInst &I) { | ||||
| 3365 | IRBuilder<> IRB(&I); | ||||
| 3366 | Value *Addr = I.getArgOperand(0); | ||||
| 3367 | Type *Ty = IRB.getInt32Ty(); | ||||
| 3368 | Value *ShadowPtr = | ||||
| 3369 | getShadowOriginPtr(Addr, IRB, Ty, Align(1), /*isStore*/ true).first; | ||||
| 3370 | |||||
| 3371 | IRB.CreateStore(getCleanShadow(Ty), | ||||
| 3372 | IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo())); | ||||
| 3373 | |||||
| 3374 | if (ClCheckAccessAddress) | ||||
| 3375 | insertShadowCheck(Addr, &I); | ||||
| 3376 | } | ||||
| 3377 | |||||
| 3378 | void handleLdmxcsr(IntrinsicInst &I) { | ||||
| 3379 | if (!InsertChecks) | ||||
| 3380 | return; | ||||
| 3381 | |||||
| 3382 | IRBuilder<> IRB(&I); | ||||
| 3383 | Value *Addr = I.getArgOperand(0); | ||||
| 3384 | Type *Ty = IRB.getInt32Ty(); | ||||
| 3385 | const Align Alignment = Align(1); | ||||
| 3386 | Value *ShadowPtr, *OriginPtr; | ||||
| 3387 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 3388 | getShadowOriginPtr(Addr, IRB, Ty, Alignment, /*isStore*/ false); | ||||
| 3389 | |||||
| 3390 | if (ClCheckAccessAddress) | ||||
| 3391 | insertShadowCheck(Addr, &I); | ||||
| 3392 | |||||
| 3393 | Value *Shadow = IRB.CreateAlignedLoad(Ty, ShadowPtr, Alignment, "_ldmxcsr"); | ||||
| 3394 | Value *Origin = MS.TrackOrigins ? IRB.CreateLoad(MS.OriginTy, OriginPtr) | ||||
| 3395 | : getCleanOrigin(); | ||||
| 3396 | insertShadowCheck(Shadow, Origin, &I); | ||||
| 3397 | } | ||||
| 3398 | |||||
| 3399 | void handleMaskedExpandLoad(IntrinsicInst &I) { | ||||
| 3400 | IRBuilder<> IRB(&I); | ||||
| 3401 | Value *Ptr = I.getArgOperand(0); | ||||
| 3402 | Value *Mask = I.getArgOperand(1); | ||||
| 3403 | Value *PassThru = I.getArgOperand(2); | ||||
| 3404 | |||||
| 3405 | if (ClCheckAccessAddress) { | ||||
| 3406 | insertShadowCheck(Ptr, &I); | ||||
| 3407 | insertShadowCheck(Mask, &I); | ||||
| 3408 | } | ||||
| 3409 | |||||
| 3410 | if (!PropagateShadow) { | ||||
| 3411 | setShadow(&I, getCleanShadow(&I)); | ||||
| 3412 | setOrigin(&I, getCleanOrigin()); | ||||
| 3413 | return; | ||||
| 3414 | } | ||||
| 3415 | |||||
| 3416 | Type *ShadowTy = getShadowTy(&I); | ||||
| 3417 | Type *ElementShadowTy = cast<VectorType>(ShadowTy)->getElementType(); | ||||
| 3418 | auto [ShadowPtr, OriginPtr] = | ||||
| 3419 | getShadowOriginPtr(Ptr, IRB, ElementShadowTy, {}, /*isStore*/ false); | ||||
| 3420 | |||||
| 3421 | Value *Shadow = IRB.CreateMaskedExpandLoad( | ||||
| 3422 | ShadowTy, ShadowPtr, Mask, getShadow(PassThru), "_msmaskedexpload"); | ||||
| 3423 | |||||
| 3424 | setShadow(&I, Shadow); | ||||
| 3425 | |||||
| 3426 | // TODO: Store origins. | ||||
| 3427 | setOrigin(&I, getCleanOrigin()); | ||||
| 3428 | } | ||||
| 3429 | |||||
| 3430 | void handleMaskedCompressStore(IntrinsicInst &I) { | ||||
| 3431 | IRBuilder<> IRB(&I); | ||||
| 3432 | Value *Values = I.getArgOperand(0); | ||||
| 3433 | Value *Ptr = I.getArgOperand(1); | ||||
| 3434 | Value *Mask = I.getArgOperand(2); | ||||
| 3435 | |||||
| 3436 | if (ClCheckAccessAddress) { | ||||
| 3437 | insertShadowCheck(Ptr, &I); | ||||
| 3438 | insertShadowCheck(Mask, &I); | ||||
| 3439 | } | ||||
| 3440 | |||||
| 3441 | Value *Shadow = getShadow(Values); | ||||
| 3442 | Type *ElementShadowTy = | ||||
| 3443 | getShadowTy(cast<VectorType>(Values->getType())->getElementType()); | ||||
| 3444 | auto [ShadowPtr, OriginPtrs] = | ||||
| 3445 | getShadowOriginPtr(Ptr, IRB, ElementShadowTy, {}, /*isStore*/ true); | ||||
| 3446 | |||||
| 3447 | IRB.CreateMaskedCompressStore(Shadow, ShadowPtr, Mask); | ||||
| 3448 | |||||
| 3449 | // TODO: Store origins. | ||||
| 3450 | } | ||||
| 3451 | |||||
| 3452 | void handleMaskedGather(IntrinsicInst &I) { | ||||
| 3453 | IRBuilder<> IRB(&I); | ||||
| 3454 | Value *Ptrs = I.getArgOperand(0); | ||||
| 3455 | const Align Alignment( | ||||
| 3456 | cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); | ||||
| 3457 | Value *Mask = I.getArgOperand(2); | ||||
| 3458 | Value *PassThru = I.getArgOperand(3); | ||||
| 3459 | |||||
| 3460 | Type *PtrsShadowTy = getShadowTy(Ptrs); | ||||
| 3461 | if (ClCheckAccessAddress) { | ||||
| 3462 | insertShadowCheck(Mask, &I); | ||||
| 3463 | Value *MaskedPtrShadow = IRB.CreateSelect( | ||||
| 3464 | Mask, getShadow(Ptrs), Constant::getNullValue((PtrsShadowTy)), | ||||
| 3465 | "_msmaskedptrs"); | ||||
| 3466 | insertShadowCheck(MaskedPtrShadow, getOrigin(Ptrs), &I); | ||||
| 3467 | } | ||||
| 3468 | |||||
| 3469 | if (!PropagateShadow) { | ||||
| 3470 | setShadow(&I, getCleanShadow(&I)); | ||||
| 3471 | setOrigin(&I, getCleanOrigin()); | ||||
| 3472 | return; | ||||
| 3473 | } | ||||
| 3474 | |||||
| 3475 | Type *ShadowTy = getShadowTy(&I); | ||||
| 3476 | Type *ElementShadowTy = cast<VectorType>(ShadowTy)->getElementType(); | ||||
| 3477 | auto [ShadowPtrs, OriginPtrs] = getShadowOriginPtr( | ||||
| 3478 | Ptrs, IRB, ElementShadowTy, Alignment, /*isStore*/ false); | ||||
| 3479 | |||||
| 3480 | Value *Shadow = | ||||
| 3481 | IRB.CreateMaskedGather(ShadowTy, ShadowPtrs, Alignment, Mask, | ||||
| 3482 | getShadow(PassThru), "_msmaskedgather"); | ||||
| 3483 | |||||
| 3484 | setShadow(&I, Shadow); | ||||
| 3485 | |||||
| 3486 | // TODO: Store origins. | ||||
| 3487 | setOrigin(&I, getCleanOrigin()); | ||||
| 3488 | } | ||||
| 3489 | |||||
| 3490 | void handleMaskedScatter(IntrinsicInst &I) { | ||||
| 3491 | IRBuilder<> IRB(&I); | ||||
| 3492 | Value *Values = I.getArgOperand(0); | ||||
| 3493 | Value *Ptrs = I.getArgOperand(1); | ||||
| 3494 | const Align Alignment( | ||||
| 3495 | cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); | ||||
| 3496 | Value *Mask = I.getArgOperand(3); | ||||
| 3497 | |||||
| 3498 | Type *PtrsShadowTy = getShadowTy(Ptrs); | ||||
| 3499 | if (ClCheckAccessAddress) { | ||||
| 3500 | insertShadowCheck(Mask, &I); | ||||
| 3501 | Value *MaskedPtrShadow = IRB.CreateSelect( | ||||
| 3502 | Mask, getShadow(Ptrs), Constant::getNullValue((PtrsShadowTy)), | ||||
| 3503 | "_msmaskedptrs"); | ||||
| 3504 | insertShadowCheck(MaskedPtrShadow, getOrigin(Ptrs), &I); | ||||
| 3505 | } | ||||
| 3506 | |||||
| 3507 | Value *Shadow = getShadow(Values); | ||||
| 3508 | Type *ElementShadowTy = | ||||
| 3509 | getShadowTy(cast<VectorType>(Values->getType())->getElementType()); | ||||
| 3510 | auto [ShadowPtrs, OriginPtrs] = getShadowOriginPtr( | ||||
| 3511 | Ptrs, IRB, ElementShadowTy, Alignment, /*isStore*/ true); | ||||
| 3512 | |||||
| 3513 | IRB.CreateMaskedScatter(Shadow, ShadowPtrs, Alignment, Mask); | ||||
| 3514 | |||||
| 3515 | // TODO: Store origin. | ||||
| 3516 | } | ||||
| 3517 | |||||
| 3518 | void handleMaskedStore(IntrinsicInst &I) { | ||||
| 3519 | IRBuilder<> IRB(&I); | ||||
| 3520 | Value *V = I.getArgOperand(0); | ||||
| 3521 | Value *Ptr = I.getArgOperand(1); | ||||
| 3522 | const Align Alignment( | ||||
| 3523 | cast<ConstantInt>(I.getArgOperand(2))->getZExtValue()); | ||||
| 3524 | Value *Mask = I.getArgOperand(3); | ||||
| 3525 | Value *Shadow = getShadow(V); | ||||
| 3526 | |||||
| 3527 | if (ClCheckAccessAddress) { | ||||
| 3528 | insertShadowCheck(Ptr, &I); | ||||
| 3529 | insertShadowCheck(Mask, &I); | ||||
| 3530 | } | ||||
| 3531 | |||||
| 3532 | Value *ShadowPtr; | ||||
| 3533 | Value *OriginPtr; | ||||
| 3534 | std::tie(ShadowPtr, OriginPtr) = getShadowOriginPtr( | ||||
| 3535 | Ptr, IRB, Shadow->getType(), Alignment, /*isStore*/ true); | ||||
| 3536 | |||||
| 3537 | IRB.CreateMaskedStore(Shadow, ShadowPtr, Alignment, Mask); | ||||
| 3538 | |||||
| 3539 | if (!MS.TrackOrigins) | ||||
| 3540 | return; | ||||
| 3541 | |||||
| 3542 | auto &DL = F.getParent()->getDataLayout(); | ||||
| 3543 | paintOrigin(IRB, getOrigin(V), OriginPtr, | ||||
| 3544 | DL.getTypeStoreSize(Shadow->getType()), | ||||
| 3545 | std::max(Alignment, kMinOriginAlignment)); | ||||
| 3546 | } | ||||
| 3547 | |||||
| 3548 | void handleMaskedLoad(IntrinsicInst &I) { | ||||
| 3549 | IRBuilder<> IRB(&I); | ||||
| 3550 | Value *Ptr = I.getArgOperand(0); | ||||
| 3551 | const Align Alignment( | ||||
| 3552 | cast<ConstantInt>(I.getArgOperand(1))->getZExtValue()); | ||||
| 3553 | Value *Mask = I.getArgOperand(2); | ||||
| 3554 | Value *PassThru = I.getArgOperand(3); | ||||
| 3555 | |||||
| 3556 | if (ClCheckAccessAddress) { | ||||
| 3557 | insertShadowCheck(Ptr, &I); | ||||
| 3558 | insertShadowCheck(Mask, &I); | ||||
| 3559 | } | ||||
| 3560 | |||||
| 3561 | if (!PropagateShadow) { | ||||
| 3562 | setShadow(&I, getCleanShadow(&I)); | ||||
| 3563 | setOrigin(&I, getCleanOrigin()); | ||||
| 3564 | return; | ||||
| 3565 | } | ||||
| 3566 | |||||
| 3567 | Type *ShadowTy = getShadowTy(&I); | ||||
| 3568 | Value *ShadowPtr, *OriginPtr; | ||||
| 3569 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 3570 | getShadowOriginPtr(Ptr, IRB, ShadowTy, Alignment, /*isStore*/ false); | ||||
| 3571 | setShadow(&I, IRB.CreateMaskedLoad(ShadowTy, ShadowPtr, Alignment, Mask, | ||||
| 3572 | getShadow(PassThru), "_msmaskedld")); | ||||
| 3573 | |||||
| 3574 | if (!MS.TrackOrigins) | ||||
| 3575 | return; | ||||
| 3576 | |||||
| 3577 | // Choose between PassThru's and the loaded value's origins. | ||||
| 3578 | Value *MaskedPassThruShadow = IRB.CreateAnd( | ||||
| 3579 | getShadow(PassThru), IRB.CreateSExt(IRB.CreateNeg(Mask), ShadowTy)); | ||||
| 3580 | |||||
| 3581 | Value *NotNull = convertToBool(MaskedPassThruShadow, IRB, "_mscmp"); | ||||
| 3582 | |||||
| 3583 | Value *PtrOrigin = IRB.CreateLoad(MS.OriginTy, OriginPtr); | ||||
| 3584 | Value *Origin = IRB.CreateSelect(NotNull, getOrigin(PassThru), PtrOrigin); | ||||
| 3585 | |||||
| 3586 | setOrigin(&I, Origin); | ||||
| 3587 | } | ||||
| 3588 | |||||
| 3589 | // Instrument BMI / BMI2 intrinsics. | ||||
| 3590 | // All of these intrinsics are Z = I(X, Y) | ||||
| 3591 | // where the types of all operands and the result match, and are either i32 or | ||||
| 3592 | // i64. The following instrumentation happens to work for all of them: | ||||
| 3593 | // Sz = I(Sx, Y) | (sext (Sy != 0)) | ||||
| 3594 | void handleBmiIntrinsic(IntrinsicInst &I) { | ||||
| 3595 | IRBuilder<> IRB(&I); | ||||
| 3596 | Type *ShadowTy = getShadowTy(&I); | ||||
| 3597 | |||||
| 3598 | // If any bit of the mask operand is poisoned, then the whole thing is. | ||||
| 3599 | Value *SMask = getShadow(&I, 1); | ||||
| 3600 | SMask = IRB.CreateSExt(IRB.CreateICmpNE(SMask, getCleanShadow(ShadowTy)), | ||||
| 3601 | ShadowTy); | ||||
| 3602 | // Apply the same intrinsic to the shadow of the first operand. | ||||
| 3603 | Value *S = IRB.CreateCall(I.getCalledFunction(), | ||||
| 3604 | {getShadow(&I, 0), I.getOperand(1)}); | ||||
| 3605 | S = IRB.CreateOr(SMask, S); | ||||
| 3606 | setShadow(&I, S); | ||||
| 3607 | setOriginForNaryOp(I); | ||||
| 3608 | } | ||||
| 3609 | |||||
| 3610 | SmallVector<int, 8> getPclmulMask(unsigned Width, bool OddElements) { | ||||
| 3611 | SmallVector<int, 8> Mask; | ||||
| 3612 | for (unsigned X = OddElements ? 1 : 0; X < Width; X += 2) { | ||||
| 3613 | Mask.append(2, X); | ||||
| 3614 | } | ||||
| 3615 | return Mask; | ||||
| 3616 | } | ||||
| 3617 | |||||
| 3618 | // Instrument pclmul intrinsics. | ||||
| 3619 | // These intrinsics operate either on odd or on even elements of the input | ||||
| 3620 | // vectors, depending on the constant in the 3rd argument, ignoring the rest. | ||||
| 3621 | // Replace the unused elements with copies of the used ones, ex: | ||||
| 3622 | // (0, 1, 2, 3) -> (0, 0, 2, 2) (even case) | ||||
| 3623 | // or | ||||
| 3624 | // (0, 1, 2, 3) -> (1, 1, 3, 3) (odd case) | ||||
| 3625 | // and then apply the usual shadow combining logic. | ||||
| 3626 | void handlePclmulIntrinsic(IntrinsicInst &I) { | ||||
| 3627 | IRBuilder<> IRB(&I); | ||||
| 3628 | unsigned Width = | ||||
| 3629 | cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements(); | ||||
| 3630 | assert(isa<ConstantInt>(I.getArgOperand(2)) &&(static_cast <bool> (isa<ConstantInt>(I.getArgOperand (2)) && "pclmul 3rd operand must be a constant") ? void (0) : __assert_fail ("isa<ConstantInt>(I.getArgOperand(2)) && \"pclmul 3rd operand must be a constant\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3631 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 3631 | "pclmul 3rd operand must be a constant")(static_cast <bool> (isa<ConstantInt>(I.getArgOperand (2)) && "pclmul 3rd operand must be a constant") ? void (0) : __assert_fail ("isa<ConstantInt>(I.getArgOperand(2)) && \"pclmul 3rd operand must be a constant\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3631 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3632 | unsigned Imm = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue(); | ||||
| 3633 | Value *Shuf0 = IRB.CreateShuffleVector(getShadow(&I, 0), | ||||
| 3634 | getPclmulMask(Width, Imm & 0x01)); | ||||
| 3635 | Value *Shuf1 = IRB.CreateShuffleVector(getShadow(&I, 1), | ||||
| 3636 | getPclmulMask(Width, Imm & 0x10)); | ||||
| 3637 | ShadowAndOriginCombiner SOC(this, IRB); | ||||
| 3638 | SOC.Add(Shuf0, getOrigin(&I, 0)); | ||||
| 3639 | SOC.Add(Shuf1, getOrigin(&I, 1)); | ||||
| 3640 | SOC.Done(&I); | ||||
| 3641 | } | ||||
| 3642 | |||||
| 3643 | // Instrument _mm_*_sd|ss intrinsics | ||||
| 3644 | void handleUnarySdSsIntrinsic(IntrinsicInst &I) { | ||||
| 3645 | IRBuilder<> IRB(&I); | ||||
| 3646 | unsigned Width = | ||||
| 3647 | cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements(); | ||||
| 3648 | Value *First = getShadow(&I, 0); | ||||
| 3649 | Value *Second = getShadow(&I, 1); | ||||
| 3650 | // First element of second operand, remaining elements of first operand | ||||
| 3651 | SmallVector<int, 16> Mask; | ||||
| 3652 | Mask.push_back(Width); | ||||
| 3653 | for (unsigned i = 1; i < Width; i++) | ||||
| 3654 | Mask.push_back(i); | ||||
| 3655 | Value *Shadow = IRB.CreateShuffleVector(First, Second, Mask); | ||||
| 3656 | |||||
| 3657 | setShadow(&I, Shadow); | ||||
| 3658 | setOriginForNaryOp(I); | ||||
| 3659 | } | ||||
| 3660 | |||||
| 3661 | void handleVtestIntrinsic(IntrinsicInst &I) { | ||||
| 3662 | IRBuilder<> IRB(&I); | ||||
| 3663 | Value *Shadow0 = getShadow(&I, 0); | ||||
| 3664 | Value *Shadow1 = getShadow(&I, 1); | ||||
| 3665 | Value *Or = IRB.CreateOr(Shadow0, Shadow1); | ||||
| 3666 | Value *NZ = IRB.CreateICmpNE(Or, Constant::getNullValue(Or->getType())); | ||||
| 3667 | Value *Scalar = convertShadowToScalar(NZ, IRB); | ||||
| 3668 | Value *Shadow = IRB.CreateZExt(Scalar, getShadowTy(&I)); | ||||
| 3669 | |||||
| 3670 | setShadow(&I, Shadow); | ||||
| 3671 | setOriginForNaryOp(I); | ||||
| 3672 | } | ||||
| 3673 | |||||
| 3674 | void handleBinarySdSsIntrinsic(IntrinsicInst &I) { | ||||
| 3675 | IRBuilder<> IRB(&I); | ||||
| 3676 | unsigned Width = | ||||
| 3677 | cast<FixedVectorType>(I.getArgOperand(0)->getType())->getNumElements(); | ||||
| 3678 | Value *First = getShadow(&I, 0); | ||||
| 3679 | Value *Second = getShadow(&I, 1); | ||||
| 3680 | Value *OrShadow = IRB.CreateOr(First, Second); | ||||
| 3681 | // First element of both OR'd together, remaining elements of first operand | ||||
| 3682 | SmallVector<int, 16> Mask; | ||||
| 3683 | Mask.push_back(Width); | ||||
| 3684 | for (unsigned i = 1; i < Width; i++) | ||||
| 3685 | Mask.push_back(i); | ||||
| 3686 | Value *Shadow = IRB.CreateShuffleVector(First, OrShadow, Mask); | ||||
| 3687 | |||||
| 3688 | setShadow(&I, Shadow); | ||||
| 3689 | setOriginForNaryOp(I); | ||||
| 3690 | } | ||||
| 3691 | |||||
| 3692 | // Instrument abs intrinsic. | ||||
| 3693 | // handleUnknownIntrinsic can't handle it because of the last | ||||
| 3694 | // is_int_min_poison argument which does not match the result type. | ||||
| 3695 | void handleAbsIntrinsic(IntrinsicInst &I) { | ||||
| 3696 | assert(I.getType()->isIntOrIntVectorTy())(static_cast <bool> (I.getType()->isIntOrIntVectorTy ()) ? void (0) : __assert_fail ("I.getType()->isIntOrIntVectorTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3696 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3697 | assert(I.getArgOperand(0)->getType() == I.getType())(static_cast <bool> (I.getArgOperand(0)->getType() == I.getType()) ? void (0) : __assert_fail ("I.getArgOperand(0)->getType() == I.getType()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 3697 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 3698 | |||||
| 3699 | // FIXME: Handle is_int_min_poison. | ||||
| 3700 | IRBuilder<> IRB(&I); | ||||
| 3701 | setShadow(&I, getShadow(&I, 0)); | ||||
| 3702 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 3703 | } | ||||
| 3704 | |||||
| 3705 | void handleIsFpClass(IntrinsicInst &I) { | ||||
| 3706 | IRBuilder<> IRB(&I); | ||||
| 3707 | Value *Shadow = getShadow(&I, 0); | ||||
| 3708 | setShadow(&I, IRB.CreateICmpNE(Shadow, getCleanShadow(Shadow))); | ||||
| 3709 | setOrigin(&I, getOrigin(&I, 0)); | ||||
| 3710 | } | ||||
| 3711 | |||||
| 3712 | void visitIntrinsicInst(IntrinsicInst &I) { | ||||
| 3713 | switch (I.getIntrinsicID()) { | ||||
| 3714 | case Intrinsic::abs: | ||||
| 3715 | handleAbsIntrinsic(I); | ||||
| 3716 | break; | ||||
| 3717 | case Intrinsic::is_fpclass: | ||||
| 3718 | handleIsFpClass(I); | ||||
| 3719 | break; | ||||
| 3720 | case Intrinsic::lifetime_start: | ||||
| 3721 | handleLifetimeStart(I); | ||||
| 3722 | break; | ||||
| 3723 | case Intrinsic::launder_invariant_group: | ||||
| 3724 | case Intrinsic::strip_invariant_group: | ||||
| 3725 | handleInvariantGroup(I); | ||||
| 3726 | break; | ||||
| 3727 | case Intrinsic::bswap: | ||||
| 3728 | handleBswap(I); | ||||
| 3729 | break; | ||||
| 3730 | case Intrinsic::ctlz: | ||||
| 3731 | case Intrinsic::cttz: | ||||
| 3732 | handleCountZeroes(I); | ||||
| 3733 | break; | ||||
| 3734 | case Intrinsic::masked_compressstore: | ||||
| 3735 | handleMaskedCompressStore(I); | ||||
| 3736 | break; | ||||
| 3737 | case Intrinsic::masked_expandload: | ||||
| 3738 | handleMaskedExpandLoad(I); | ||||
| 3739 | break; | ||||
| 3740 | case Intrinsic::masked_gather: | ||||
| 3741 | handleMaskedGather(I); | ||||
| 3742 | break; | ||||
| 3743 | case Intrinsic::masked_scatter: | ||||
| 3744 | handleMaskedScatter(I); | ||||
| 3745 | break; | ||||
| 3746 | case Intrinsic::masked_store: | ||||
| 3747 | handleMaskedStore(I); | ||||
| 3748 | break; | ||||
| 3749 | case Intrinsic::masked_load: | ||||
| 3750 | handleMaskedLoad(I); | ||||
| 3751 | break; | ||||
| 3752 | case Intrinsic::vector_reduce_and: | ||||
| 3753 | handleVectorReduceAndIntrinsic(I); | ||||
| 3754 | break; | ||||
| 3755 | case Intrinsic::vector_reduce_or: | ||||
| 3756 | handleVectorReduceOrIntrinsic(I); | ||||
| 3757 | break; | ||||
| 3758 | case Intrinsic::vector_reduce_add: | ||||
| 3759 | case Intrinsic::vector_reduce_xor: | ||||
| 3760 | case Intrinsic::vector_reduce_mul: | ||||
| 3761 | handleVectorReduceIntrinsic(I); | ||||
| 3762 | break; | ||||
| 3763 | case Intrinsic::x86_sse_stmxcsr: | ||||
| 3764 | handleStmxcsr(I); | ||||
| 3765 | break; | ||||
| 3766 | case Intrinsic::x86_sse_ldmxcsr: | ||||
| 3767 | handleLdmxcsr(I); | ||||
| 3768 | break; | ||||
| 3769 | case Intrinsic::x86_avx512_vcvtsd2usi64: | ||||
| 3770 | case Intrinsic::x86_avx512_vcvtsd2usi32: | ||||
| 3771 | case Intrinsic::x86_avx512_vcvtss2usi64: | ||||
| 3772 | case Intrinsic::x86_avx512_vcvtss2usi32: | ||||
| 3773 | case Intrinsic::x86_avx512_cvttss2usi64: | ||||
| 3774 | case Intrinsic::x86_avx512_cvttss2usi: | ||||
| 3775 | case Intrinsic::x86_avx512_cvttsd2usi64: | ||||
| 3776 | case Intrinsic::x86_avx512_cvttsd2usi: | ||||
| 3777 | case Intrinsic::x86_avx512_cvtusi2ss: | ||||
| 3778 | case Intrinsic::x86_avx512_cvtusi642sd: | ||||
| 3779 | case Intrinsic::x86_avx512_cvtusi642ss: | ||||
| 3780 | handleVectorConvertIntrinsic(I, 1, true); | ||||
| 3781 | break; | ||||
| 3782 | case Intrinsic::x86_sse2_cvtsd2si64: | ||||
| 3783 | case Intrinsic::x86_sse2_cvtsd2si: | ||||
| 3784 | case Intrinsic::x86_sse2_cvtsd2ss: | ||||
| 3785 | case Intrinsic::x86_sse2_cvttsd2si64: | ||||
| 3786 | case Intrinsic::x86_sse2_cvttsd2si: | ||||
| 3787 | case Intrinsic::x86_sse_cvtss2si64: | ||||
| 3788 | case Intrinsic::x86_sse_cvtss2si: | ||||
| 3789 | case Intrinsic::x86_sse_cvttss2si64: | ||||
| 3790 | case Intrinsic::x86_sse_cvttss2si: | ||||
| 3791 | handleVectorConvertIntrinsic(I, 1); | ||||
| 3792 | break; | ||||
| 3793 | case Intrinsic::x86_sse_cvtps2pi: | ||||
| 3794 | case Intrinsic::x86_sse_cvttps2pi: | ||||
| 3795 | handleVectorConvertIntrinsic(I, 2); | ||||
| 3796 | break; | ||||
| 3797 | |||||
| 3798 | case Intrinsic::x86_avx512_psll_w_512: | ||||
| 3799 | case Intrinsic::x86_avx512_psll_d_512: | ||||
| 3800 | case Intrinsic::x86_avx512_psll_q_512: | ||||
| 3801 | case Intrinsic::x86_avx512_pslli_w_512: | ||||
| 3802 | case Intrinsic::x86_avx512_pslli_d_512: | ||||
| 3803 | case Intrinsic::x86_avx512_pslli_q_512: | ||||
| 3804 | case Intrinsic::x86_avx512_psrl_w_512: | ||||
| 3805 | case Intrinsic::x86_avx512_psrl_d_512: | ||||
| 3806 | case Intrinsic::x86_avx512_psrl_q_512: | ||||
| 3807 | case Intrinsic::x86_avx512_psra_w_512: | ||||
| 3808 | case Intrinsic::x86_avx512_psra_d_512: | ||||
| 3809 | case Intrinsic::x86_avx512_psra_q_512: | ||||
| 3810 | case Intrinsic::x86_avx512_psrli_w_512: | ||||
| 3811 | case Intrinsic::x86_avx512_psrli_d_512: | ||||
| 3812 | case Intrinsic::x86_avx512_psrli_q_512: | ||||
| 3813 | case Intrinsic::x86_avx512_psrai_w_512: | ||||
| 3814 | case Intrinsic::x86_avx512_psrai_d_512: | ||||
| 3815 | case Intrinsic::x86_avx512_psrai_q_512: | ||||
| 3816 | case Intrinsic::x86_avx512_psra_q_256: | ||||
| 3817 | case Intrinsic::x86_avx512_psra_q_128: | ||||
| 3818 | case Intrinsic::x86_avx512_psrai_q_256: | ||||
| 3819 | case Intrinsic::x86_avx512_psrai_q_128: | ||||
| 3820 | case Intrinsic::x86_avx2_psll_w: | ||||
| 3821 | case Intrinsic::x86_avx2_psll_d: | ||||
| 3822 | case Intrinsic::x86_avx2_psll_q: | ||||
| 3823 | case Intrinsic::x86_avx2_pslli_w: | ||||
| 3824 | case Intrinsic::x86_avx2_pslli_d: | ||||
| 3825 | case Intrinsic::x86_avx2_pslli_q: | ||||
| 3826 | case Intrinsic::x86_avx2_psrl_w: | ||||
| 3827 | case Intrinsic::x86_avx2_psrl_d: | ||||
| 3828 | case Intrinsic::x86_avx2_psrl_q: | ||||
| 3829 | case Intrinsic::x86_avx2_psra_w: | ||||
| 3830 | case Intrinsic::x86_avx2_psra_d: | ||||
| 3831 | case Intrinsic::x86_avx2_psrli_w: | ||||
| 3832 | case Intrinsic::x86_avx2_psrli_d: | ||||
| 3833 | case Intrinsic::x86_avx2_psrli_q: | ||||
| 3834 | case Intrinsic::x86_avx2_psrai_w: | ||||
| 3835 | case Intrinsic::x86_avx2_psrai_d: | ||||
| 3836 | case Intrinsic::x86_sse2_psll_w: | ||||
| 3837 | case Intrinsic::x86_sse2_psll_d: | ||||
| 3838 | case Intrinsic::x86_sse2_psll_q: | ||||
| 3839 | case Intrinsic::x86_sse2_pslli_w: | ||||
| 3840 | case Intrinsic::x86_sse2_pslli_d: | ||||
| 3841 | case Intrinsic::x86_sse2_pslli_q: | ||||
| 3842 | case Intrinsic::x86_sse2_psrl_w: | ||||
| 3843 | case Intrinsic::x86_sse2_psrl_d: | ||||
| 3844 | case Intrinsic::x86_sse2_psrl_q: | ||||
| 3845 | case Intrinsic::x86_sse2_psra_w: | ||||
| 3846 | case Intrinsic::x86_sse2_psra_d: | ||||
| 3847 | case Intrinsic::x86_sse2_psrli_w: | ||||
| 3848 | case Intrinsic::x86_sse2_psrli_d: | ||||
| 3849 | case Intrinsic::x86_sse2_psrli_q: | ||||
| 3850 | case Intrinsic::x86_sse2_psrai_w: | ||||
| 3851 | case Intrinsic::x86_sse2_psrai_d: | ||||
| 3852 | case Intrinsic::x86_mmx_psll_w: | ||||
| 3853 | case Intrinsic::x86_mmx_psll_d: | ||||
| 3854 | case Intrinsic::x86_mmx_psll_q: | ||||
| 3855 | case Intrinsic::x86_mmx_pslli_w: | ||||
| 3856 | case Intrinsic::x86_mmx_pslli_d: | ||||
| 3857 | case Intrinsic::x86_mmx_pslli_q: | ||||
| 3858 | case Intrinsic::x86_mmx_psrl_w: | ||||
| 3859 | case Intrinsic::x86_mmx_psrl_d: | ||||
| 3860 | case Intrinsic::x86_mmx_psrl_q: | ||||
| 3861 | case Intrinsic::x86_mmx_psra_w: | ||||
| 3862 | case Intrinsic::x86_mmx_psra_d: | ||||
| 3863 | case Intrinsic::x86_mmx_psrli_w: | ||||
| 3864 | case Intrinsic::x86_mmx_psrli_d: | ||||
| 3865 | case Intrinsic::x86_mmx_psrli_q: | ||||
| 3866 | case Intrinsic::x86_mmx_psrai_w: | ||||
| 3867 | case Intrinsic::x86_mmx_psrai_d: | ||||
| 3868 | handleVectorShiftIntrinsic(I, /* Variable */ false); | ||||
| 3869 | break; | ||||
| 3870 | case Intrinsic::x86_avx2_psllv_d: | ||||
| 3871 | case Intrinsic::x86_avx2_psllv_d_256: | ||||
| 3872 | case Intrinsic::x86_avx512_psllv_d_512: | ||||
| 3873 | case Intrinsic::x86_avx2_psllv_q: | ||||
| 3874 | case Intrinsic::x86_avx2_psllv_q_256: | ||||
| 3875 | case Intrinsic::x86_avx512_psllv_q_512: | ||||
| 3876 | case Intrinsic::x86_avx2_psrlv_d: | ||||
| 3877 | case Intrinsic::x86_avx2_psrlv_d_256: | ||||
| 3878 | case Intrinsic::x86_avx512_psrlv_d_512: | ||||
| 3879 | case Intrinsic::x86_avx2_psrlv_q: | ||||
| 3880 | case Intrinsic::x86_avx2_psrlv_q_256: | ||||
| 3881 | case Intrinsic::x86_avx512_psrlv_q_512: | ||||
| 3882 | case Intrinsic::x86_avx2_psrav_d: | ||||
| 3883 | case Intrinsic::x86_avx2_psrav_d_256: | ||||
| 3884 | case Intrinsic::x86_avx512_psrav_d_512: | ||||
| 3885 | case Intrinsic::x86_avx512_psrav_q_128: | ||||
| 3886 | case Intrinsic::x86_avx512_psrav_q_256: | ||||
| 3887 | case Intrinsic::x86_avx512_psrav_q_512: | ||||
| 3888 | handleVectorShiftIntrinsic(I, /* Variable */ true); | ||||
| 3889 | break; | ||||
| 3890 | |||||
| 3891 | case Intrinsic::x86_sse2_packsswb_128: | ||||
| 3892 | case Intrinsic::x86_sse2_packssdw_128: | ||||
| 3893 | case Intrinsic::x86_sse2_packuswb_128: | ||||
| 3894 | case Intrinsic::x86_sse41_packusdw: | ||||
| 3895 | case Intrinsic::x86_avx2_packsswb: | ||||
| 3896 | case Intrinsic::x86_avx2_packssdw: | ||||
| 3897 | case Intrinsic::x86_avx2_packuswb: | ||||
| 3898 | case Intrinsic::x86_avx2_packusdw: | ||||
| 3899 | handleVectorPackIntrinsic(I); | ||||
| 3900 | break; | ||||
| 3901 | |||||
| 3902 | case Intrinsic::x86_mmx_packsswb: | ||||
| 3903 | case Intrinsic::x86_mmx_packuswb: | ||||
| 3904 | handleVectorPackIntrinsic(I, 16); | ||||
| 3905 | break; | ||||
| 3906 | |||||
| 3907 | case Intrinsic::x86_mmx_packssdw: | ||||
| 3908 | handleVectorPackIntrinsic(I, 32); | ||||
| 3909 | break; | ||||
| 3910 | |||||
| 3911 | case Intrinsic::x86_mmx_psad_bw: | ||||
| 3912 | case Intrinsic::x86_sse2_psad_bw: | ||||
| 3913 | case Intrinsic::x86_avx2_psad_bw: | ||||
| 3914 | handleVectorSadIntrinsic(I); | ||||
| 3915 | break; | ||||
| 3916 | |||||
| 3917 | case Intrinsic::x86_sse2_pmadd_wd: | ||||
| 3918 | case Intrinsic::x86_avx2_pmadd_wd: | ||||
| 3919 | case Intrinsic::x86_ssse3_pmadd_ub_sw_128: | ||||
| 3920 | case Intrinsic::x86_avx2_pmadd_ub_sw: | ||||
| 3921 | handleVectorPmaddIntrinsic(I); | ||||
| 3922 | break; | ||||
| 3923 | |||||
| 3924 | case Intrinsic::x86_ssse3_pmadd_ub_sw: | ||||
| 3925 | handleVectorPmaddIntrinsic(I, 8); | ||||
| 3926 | break; | ||||
| 3927 | |||||
| 3928 | case Intrinsic::x86_mmx_pmadd_wd: | ||||
| 3929 | handleVectorPmaddIntrinsic(I, 16); | ||||
| 3930 | break; | ||||
| 3931 | |||||
| 3932 | case Intrinsic::x86_sse_cmp_ss: | ||||
| 3933 | case Intrinsic::x86_sse2_cmp_sd: | ||||
| 3934 | case Intrinsic::x86_sse_comieq_ss: | ||||
| 3935 | case Intrinsic::x86_sse_comilt_ss: | ||||
| 3936 | case Intrinsic::x86_sse_comile_ss: | ||||
| 3937 | case Intrinsic::x86_sse_comigt_ss: | ||||
| 3938 | case Intrinsic::x86_sse_comige_ss: | ||||
| 3939 | case Intrinsic::x86_sse_comineq_ss: | ||||
| 3940 | case Intrinsic::x86_sse_ucomieq_ss: | ||||
| 3941 | case Intrinsic::x86_sse_ucomilt_ss: | ||||
| 3942 | case Intrinsic::x86_sse_ucomile_ss: | ||||
| 3943 | case Intrinsic::x86_sse_ucomigt_ss: | ||||
| 3944 | case Intrinsic::x86_sse_ucomige_ss: | ||||
| 3945 | case Intrinsic::x86_sse_ucomineq_ss: | ||||
| 3946 | case Intrinsic::x86_sse2_comieq_sd: | ||||
| 3947 | case Intrinsic::x86_sse2_comilt_sd: | ||||
| 3948 | case Intrinsic::x86_sse2_comile_sd: | ||||
| 3949 | case Intrinsic::x86_sse2_comigt_sd: | ||||
| 3950 | case Intrinsic::x86_sse2_comige_sd: | ||||
| 3951 | case Intrinsic::x86_sse2_comineq_sd: | ||||
| 3952 | case Intrinsic::x86_sse2_ucomieq_sd: | ||||
| 3953 | case Intrinsic::x86_sse2_ucomilt_sd: | ||||
| 3954 | case Intrinsic::x86_sse2_ucomile_sd: | ||||
| 3955 | case Intrinsic::x86_sse2_ucomigt_sd: | ||||
| 3956 | case Intrinsic::x86_sse2_ucomige_sd: | ||||
| 3957 | case Intrinsic::x86_sse2_ucomineq_sd: | ||||
| 3958 | handleVectorCompareScalarIntrinsic(I); | ||||
| 3959 | break; | ||||
| 3960 | |||||
| 3961 | case Intrinsic::x86_avx_cmp_pd_256: | ||||
| 3962 | case Intrinsic::x86_avx_cmp_ps_256: | ||||
| 3963 | case Intrinsic::x86_sse2_cmp_pd: | ||||
| 3964 | case Intrinsic::x86_sse_cmp_ps: | ||||
| 3965 | handleVectorComparePackedIntrinsic(I); | ||||
| 3966 | break; | ||||
| 3967 | |||||
| 3968 | case Intrinsic::x86_bmi_bextr_32: | ||||
| 3969 | case Intrinsic::x86_bmi_bextr_64: | ||||
| 3970 | case Intrinsic::x86_bmi_bzhi_32: | ||||
| 3971 | case Intrinsic::x86_bmi_bzhi_64: | ||||
| 3972 | case Intrinsic::x86_bmi_pdep_32: | ||||
| 3973 | case Intrinsic::x86_bmi_pdep_64: | ||||
| 3974 | case Intrinsic::x86_bmi_pext_32: | ||||
| 3975 | case Intrinsic::x86_bmi_pext_64: | ||||
| 3976 | handleBmiIntrinsic(I); | ||||
| 3977 | break; | ||||
| 3978 | |||||
| 3979 | case Intrinsic::x86_pclmulqdq: | ||||
| 3980 | case Intrinsic::x86_pclmulqdq_256: | ||||
| 3981 | case Intrinsic::x86_pclmulqdq_512: | ||||
| 3982 | handlePclmulIntrinsic(I); | ||||
| 3983 | break; | ||||
| 3984 | |||||
| 3985 | case Intrinsic::x86_sse41_round_sd: | ||||
| 3986 | case Intrinsic::x86_sse41_round_ss: | ||||
| 3987 | handleUnarySdSsIntrinsic(I); | ||||
| 3988 | break; | ||||
| 3989 | case Intrinsic::x86_sse2_max_sd: | ||||
| 3990 | case Intrinsic::x86_sse_max_ss: | ||||
| 3991 | case Intrinsic::x86_sse2_min_sd: | ||||
| 3992 | case Intrinsic::x86_sse_min_ss: | ||||
| 3993 | handleBinarySdSsIntrinsic(I); | ||||
| 3994 | break; | ||||
| 3995 | |||||
| 3996 | case Intrinsic::x86_avx_vtestc_pd: | ||||
| 3997 | case Intrinsic::x86_avx_vtestc_pd_256: | ||||
| 3998 | case Intrinsic::x86_avx_vtestc_ps: | ||||
| 3999 | case Intrinsic::x86_avx_vtestc_ps_256: | ||||
| 4000 | case Intrinsic::x86_avx_vtestnzc_pd: | ||||
| 4001 | case Intrinsic::x86_avx_vtestnzc_pd_256: | ||||
| 4002 | case Intrinsic::x86_avx_vtestnzc_ps: | ||||
| 4003 | case Intrinsic::x86_avx_vtestnzc_ps_256: | ||||
| 4004 | case Intrinsic::x86_avx_vtestz_pd: | ||||
| 4005 | case Intrinsic::x86_avx_vtestz_pd_256: | ||||
| 4006 | case Intrinsic::x86_avx_vtestz_ps: | ||||
| 4007 | case Intrinsic::x86_avx_vtestz_ps_256: | ||||
| 4008 | case Intrinsic::x86_avx_ptestc_256: | ||||
| 4009 | case Intrinsic::x86_avx_ptestnzc_256: | ||||
| 4010 | case Intrinsic::x86_avx_ptestz_256: | ||||
| 4011 | case Intrinsic::x86_sse41_ptestc: | ||||
| 4012 | case Intrinsic::x86_sse41_ptestnzc: | ||||
| 4013 | case Intrinsic::x86_sse41_ptestz: | ||||
| 4014 | handleVtestIntrinsic(I); | ||||
| 4015 | break; | ||||
| 4016 | |||||
| 4017 | case Intrinsic::fshl: | ||||
| 4018 | case Intrinsic::fshr: | ||||
| 4019 | handleFunnelShift(I); | ||||
| 4020 | break; | ||||
| 4021 | |||||
| 4022 | case Intrinsic::is_constant: | ||||
| 4023 | // The result of llvm.is.constant() is always defined. | ||||
| 4024 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4025 | setOrigin(&I, getCleanOrigin()); | ||||
| 4026 | break; | ||||
| 4027 | |||||
| 4028 | default: | ||||
| 4029 | if (!handleUnknownIntrinsic(I)) | ||||
| 4030 | visitInstruction(I); | ||||
| 4031 | break; | ||||
| 4032 | } | ||||
| 4033 | } | ||||
| 4034 | |||||
| 4035 | void visitLibAtomicLoad(CallBase &CB) { | ||||
| 4036 | // Since we use getNextNode here, we can't have CB terminate the BB. | ||||
| 4037 | assert(isa<CallInst>(CB))(static_cast <bool> (isa<CallInst>(CB)) ? void (0 ) : __assert_fail ("isa<CallInst>(CB)", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 4037, __extension__ __PRETTY_FUNCTION__)); | ||||
| 4038 | |||||
| 4039 | IRBuilder<> IRB(&CB); | ||||
| 4040 | Value *Size = CB.getArgOperand(0); | ||||
| 4041 | Value *SrcPtr = CB.getArgOperand(1); | ||||
| 4042 | Value *DstPtr = CB.getArgOperand(2); | ||||
| 4043 | Value *Ordering = CB.getArgOperand(3); | ||||
| 4044 | // Convert the call to have at least Acquire ordering to make sure | ||||
| 4045 | // the shadow operations aren't reordered before it. | ||||
| 4046 | Value *NewOrdering = | ||||
| 4047 | IRB.CreateExtractElement(makeAddAcquireOrderingTable(IRB), Ordering); | ||||
| 4048 | CB.setArgOperand(3, NewOrdering); | ||||
| 4049 | |||||
| 4050 | NextNodeIRBuilder NextIRB(&CB); | ||||
| 4051 | Value *SrcShadowPtr, *SrcOriginPtr; | ||||
| 4052 | std::tie(SrcShadowPtr, SrcOriginPtr) = | ||||
| 4053 | getShadowOriginPtr(SrcPtr, NextIRB, NextIRB.getInt8Ty(), Align(1), | ||||
| 4054 | /*isStore*/ false); | ||||
| 4055 | Value *DstShadowPtr = | ||||
| 4056 | getShadowOriginPtr(DstPtr, NextIRB, NextIRB.getInt8Ty(), Align(1), | ||||
| 4057 | /*isStore*/ true) | ||||
| 4058 | .first; | ||||
| 4059 | |||||
| 4060 | NextIRB.CreateMemCpy(DstShadowPtr, Align(1), SrcShadowPtr, Align(1), Size); | ||||
| 4061 | if (MS.TrackOrigins) { | ||||
| 4062 | Value *SrcOrigin = NextIRB.CreateAlignedLoad(MS.OriginTy, SrcOriginPtr, | ||||
| 4063 | kMinOriginAlignment); | ||||
| 4064 | Value *NewOrigin = updateOrigin(SrcOrigin, NextIRB); | ||||
| 4065 | NextIRB.CreateCall(MS.MsanSetOriginFn, {DstPtr, Size, NewOrigin}); | ||||
| 4066 | } | ||||
| 4067 | } | ||||
| 4068 | |||||
| 4069 | void visitLibAtomicStore(CallBase &CB) { | ||||
| 4070 | IRBuilder<> IRB(&CB); | ||||
| 4071 | Value *Size = CB.getArgOperand(0); | ||||
| 4072 | Value *DstPtr = CB.getArgOperand(2); | ||||
| 4073 | Value *Ordering = CB.getArgOperand(3); | ||||
| 4074 | // Convert the call to have at least Release ordering to make sure | ||||
| 4075 | // the shadow operations aren't reordered after it. | ||||
| 4076 | Value *NewOrdering = | ||||
| 4077 | IRB.CreateExtractElement(makeAddReleaseOrderingTable(IRB), Ordering); | ||||
| 4078 | CB.setArgOperand(3, NewOrdering); | ||||
| 4079 | |||||
| 4080 | Value *DstShadowPtr = | ||||
| 4081 | getShadowOriginPtr(DstPtr, IRB, IRB.getInt8Ty(), Align(1), | ||||
| 4082 | /*isStore*/ true) | ||||
| 4083 | .first; | ||||
| 4084 | |||||
| 4085 | // Atomic store always paints clean shadow/origin. See file header. | ||||
| 4086 | IRB.CreateMemSet(DstShadowPtr, getCleanShadow(IRB.getInt8Ty()), Size, | ||||
| 4087 | Align(1)); | ||||
| 4088 | } | ||||
| 4089 | |||||
| 4090 | void visitCallBase(CallBase &CB) { | ||||
| 4091 | assert(!CB.getMetadata(LLVMContext::MD_nosanitize))(static_cast <bool> (!CB.getMetadata(LLVMContext::MD_nosanitize )) ? void (0) : __assert_fail ("!CB.getMetadata(LLVMContext::MD_nosanitize)" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4091 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4092 | if (CB.isInlineAsm()) { | ||||
| 4093 | // For inline asm (either a call to asm function, or callbr instruction), | ||||
| 4094 | // do the usual thing: check argument shadow and mark all outputs as | ||||
| 4095 | // clean. Note that any side effects of the inline asm that are not | ||||
| 4096 | // immediately visible in its constraints are not handled. | ||||
| 4097 | if (ClHandleAsmConservative && MS.CompileKernel) | ||||
| 4098 | visitAsmInstruction(CB); | ||||
| 4099 | else | ||||
| 4100 | visitInstruction(CB); | ||||
| 4101 | return; | ||||
| 4102 | } | ||||
| 4103 | LibFunc LF; | ||||
| 4104 | if (TLI->getLibFunc(CB, LF)) { | ||||
| 4105 | // libatomic.a functions need to have special handling because there isn't | ||||
| 4106 | // a good way to intercept them or compile the library with | ||||
| 4107 | // instrumentation. | ||||
| 4108 | switch (LF) { | ||||
| 4109 | case LibFunc_atomic_load: | ||||
| 4110 | if (!isa<CallInst>(CB)) { | ||||
| 4111 | llvm::errs() << "MSAN -- cannot instrument invoke of libatomic load." | ||||
| 4112 | "Ignoring!\n"; | ||||
| 4113 | break; | ||||
| 4114 | } | ||||
| 4115 | visitLibAtomicLoad(CB); | ||||
| 4116 | return; | ||||
| 4117 | case LibFunc_atomic_store: | ||||
| 4118 | visitLibAtomicStore(CB); | ||||
| 4119 | return; | ||||
| 4120 | default: | ||||
| 4121 | break; | ||||
| 4122 | } | ||||
| 4123 | } | ||||
| 4124 | |||||
| 4125 | if (auto *Call = dyn_cast<CallInst>(&CB)) { | ||||
| 4126 | assert(!isa<IntrinsicInst>(Call) && "intrinsics are handled elsewhere")(static_cast <bool> (!isa<IntrinsicInst>(Call) && "intrinsics are handled elsewhere") ? void (0) : __assert_fail ("!isa<IntrinsicInst>(Call) && \"intrinsics are handled elsewhere\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4126 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4127 | |||||
| 4128 | // We are going to insert code that relies on the fact that the callee | ||||
| 4129 | // will become a non-readonly function after it is instrumented by us. To | ||||
| 4130 | // prevent this code from being optimized out, mark that function | ||||
| 4131 | // non-readonly in advance. | ||||
| 4132 | // TODO: We can likely do better than dropping memory() completely here. | ||||
| 4133 | AttributeMask B; | ||||
| 4134 | B.addAttribute(Attribute::Memory).addAttribute(Attribute::Speculatable); | ||||
| 4135 | |||||
| 4136 | Call->removeFnAttrs(B); | ||||
| 4137 | if (Function *Func = Call->getCalledFunction()) { | ||||
| 4138 | Func->removeFnAttrs(B); | ||||
| 4139 | } | ||||
| 4140 | |||||
| 4141 | maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI); | ||||
| 4142 | } | ||||
| 4143 | IRBuilder<> IRB(&CB); | ||||
| 4144 | bool MayCheckCall = MS.EagerChecks; | ||||
| 4145 | if (Function *Func = CB.getCalledFunction()) { | ||||
| 4146 | // __sanitizer_unaligned_{load,store} functions may be called by users | ||||
| 4147 | // and always expects shadows in the TLS. So don't check them. | ||||
| 4148 | MayCheckCall &= !Func->getName().startswith("__sanitizer_unaligned_"); | ||||
| 4149 | } | ||||
| 4150 | |||||
| 4151 | unsigned ArgOffset = 0; | ||||
| 4152 | LLVM_DEBUG(dbgs() << " CallSite: " << CB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " CallSite: " << CB << "\n"; } } while (false); | ||||
| 4153 | for (const auto &[i, A] : llvm::enumerate(CB.args())) { | ||||
| 4154 | if (!A->getType()->isSized()) { | ||||
| 4155 | LLVM_DEBUG(dbgs() << "Arg " << i << " is not sized: " << CB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "Arg " << i << " is not sized: " << CB << "\n"; } } while (false); | ||||
| 4156 | continue; | ||||
| 4157 | } | ||||
| 4158 | unsigned Size = 0; | ||||
| 4159 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 4160 | |||||
| 4161 | bool ByVal = CB.paramHasAttr(i, Attribute::ByVal); | ||||
| 4162 | bool NoUndef = CB.paramHasAttr(i, Attribute::NoUndef); | ||||
| 4163 | bool EagerCheck = MayCheckCall && !ByVal && NoUndef; | ||||
| 4164 | |||||
| 4165 | if (EagerCheck) { | ||||
| 4166 | insertShadowCheck(A, &CB); | ||||
| 4167 | Size = DL.getTypeAllocSize(A->getType()); | ||||
| 4168 | } else { | ||||
| 4169 | Value *Store = nullptr; | ||||
| 4170 | // Compute the Shadow for arg even if it is ByVal, because | ||||
| 4171 | // in that case getShadow() will copy the actual arg shadow to | ||||
| 4172 | // __msan_param_tls. | ||||
| 4173 | Value *ArgShadow = getShadow(A); | ||||
| 4174 | Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset); | ||||
| 4175 | LLVM_DEBUG(dbgs() << " Arg#" << i << ": " << *Ado { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " Arg#" << i << ": " << *A << " Shadow: " << *ArgShadow << "\n"; } } while (false) | ||||
| 4176 | << " Shadow: " << *ArgShadow << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " Arg#" << i << ": " << *A << " Shadow: " << *ArgShadow << "\n"; } } while (false); | ||||
| 4177 | if (ByVal) { | ||||
| 4178 | // ByVal requires some special handling as it's too big for a single | ||||
| 4179 | // load | ||||
| 4180 | assert(A->getType()->isPointerTy() &&(static_cast <bool> (A->getType()->isPointerTy() && "ByVal argument is not a pointer!") ? void (0) : __assert_fail ("A->getType()->isPointerTy() && \"ByVal argument is not a pointer!\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4181 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 4181 | "ByVal argument is not a pointer!")(static_cast <bool> (A->getType()->isPointerTy() && "ByVal argument is not a pointer!") ? void (0) : __assert_fail ("A->getType()->isPointerTy() && \"ByVal argument is not a pointer!\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4181 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4182 | Size = DL.getTypeAllocSize(CB.getParamByValType(i)); | ||||
| 4183 | if (ArgOffset + Size > kParamTLSSize) | ||||
| 4184 | break; | ||||
| 4185 | const MaybeAlign ParamAlignment(CB.getParamAlign(i)); | ||||
| 4186 | MaybeAlign Alignment = std::nullopt; | ||||
| 4187 | if (ParamAlignment) | ||||
| 4188 | Alignment = std::min(*ParamAlignment, kShadowTLSAlignment); | ||||
| 4189 | Value *AShadowPtr, *AOriginPtr; | ||||
| 4190 | std::tie(AShadowPtr, AOriginPtr) = | ||||
| 4191 | getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), Alignment, | ||||
| 4192 | /*isStore*/ false); | ||||
| 4193 | if (!PropagateShadow) { | ||||
| 4194 | Store = IRB.CreateMemSet(ArgShadowBase, | ||||
| 4195 | Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 4196 | Size, Alignment); | ||||
| 4197 | } else { | ||||
| 4198 | Store = IRB.CreateMemCpy(ArgShadowBase, Alignment, AShadowPtr, | ||||
| 4199 | Alignment, Size); | ||||
| 4200 | if (MS.TrackOrigins) { | ||||
| 4201 | Value *ArgOriginBase = getOriginPtrForArgument(A, IRB, ArgOffset); | ||||
| 4202 | // FIXME: OriginSize should be: | ||||
| 4203 | // alignTo(A % kMinOriginAlignment + Size, kMinOriginAlignment) | ||||
| 4204 | unsigned OriginSize = alignTo(Size, kMinOriginAlignment); | ||||
| 4205 | IRB.CreateMemCpy( | ||||
| 4206 | ArgOriginBase, | ||||
| 4207 | /* by origin_tls[ArgOffset] */ kMinOriginAlignment, | ||||
| 4208 | AOriginPtr, | ||||
| 4209 | /* by getShadowOriginPtr */ kMinOriginAlignment, OriginSize); | ||||
| 4210 | } | ||||
| 4211 | } | ||||
| 4212 | } else { | ||||
| 4213 | // Any other parameters mean we need bit-grained tracking of uninit | ||||
| 4214 | // data | ||||
| 4215 | Size = DL.getTypeAllocSize(A->getType()); | ||||
| 4216 | if (ArgOffset + Size > kParamTLSSize) | ||||
| 4217 | break; | ||||
| 4218 | Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase, | ||||
| 4219 | kShadowTLSAlignment); | ||||
| 4220 | Constant *Cst = dyn_cast<Constant>(ArgShadow); | ||||
| 4221 | if (MS.TrackOrigins && !(Cst && Cst->isNullValue())) { | ||||
| 4222 | IRB.CreateStore(getOrigin(A), | ||||
| 4223 | getOriginPtrForArgument(A, IRB, ArgOffset)); | ||||
| 4224 | } | ||||
| 4225 | } | ||||
| 4226 | (void)Store; | ||||
| 4227 | assert(Store != nullptr)(static_cast <bool> (Store != nullptr) ? void (0) : __assert_fail ("Store != nullptr", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 4227, __extension__ __PRETTY_FUNCTION__)); | ||||
| 4228 | LLVM_DEBUG(dbgs() << " Param:" << *Store << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " Param:" << *Store << "\n"; } } while (false); | ||||
| 4229 | } | ||||
| 4230 | assert(Size != 0)(static_cast <bool> (Size != 0) ? void (0) : __assert_fail ("Size != 0", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 4230, __extension__ __PRETTY_FUNCTION__)); | ||||
| 4231 | ArgOffset += alignTo(Size, kShadowTLSAlignment); | ||||
| 4232 | } | ||||
| 4233 | LLVM_DEBUG(dbgs() << " done with call args\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " done with call args\n"; } } while (false); | ||||
| 4234 | |||||
| 4235 | FunctionType *FT = CB.getFunctionType(); | ||||
| 4236 | if (FT->isVarArg()) { | ||||
| 4237 | VAHelper->visitCallBase(CB, IRB); | ||||
| 4238 | } | ||||
| 4239 | |||||
| 4240 | // Now, get the shadow for the RetVal. | ||||
| 4241 | if (!CB.getType()->isSized()) | ||||
| 4242 | return; | ||||
| 4243 | // Don't emit the epilogue for musttail call returns. | ||||
| 4244 | if (isa<CallInst>(CB) && cast<CallInst>(CB).isMustTailCall()) | ||||
| 4245 | return; | ||||
| 4246 | |||||
| 4247 | if (MayCheckCall && CB.hasRetAttr(Attribute::NoUndef)) { | ||||
| 4248 | setShadow(&CB, getCleanShadow(&CB)); | ||||
| 4249 | setOrigin(&CB, getCleanOrigin()); | ||||
| 4250 | return; | ||||
| 4251 | } | ||||
| 4252 | |||||
| 4253 | IRBuilder<> IRBBefore(&CB); | ||||
| 4254 | // Until we have full dynamic coverage, make sure the retval shadow is 0. | ||||
| 4255 | Value *Base = getShadowPtrForRetval(&CB, IRBBefore); | ||||
| 4256 | IRBBefore.CreateAlignedStore(getCleanShadow(&CB), Base, | ||||
| 4257 | kShadowTLSAlignment); | ||||
| 4258 | BasicBlock::iterator NextInsn; | ||||
| 4259 | if (isa<CallInst>(CB)) { | ||||
| 4260 | NextInsn = ++CB.getIterator(); | ||||
| 4261 | assert(NextInsn != CB.getParent()->end())(static_cast <bool> (NextInsn != CB.getParent()->end ()) ? void (0) : __assert_fail ("NextInsn != CB.getParent()->end()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4261 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4262 | } else { | ||||
| 4263 | BasicBlock *NormalDest = cast<InvokeInst>(CB).getNormalDest(); | ||||
| 4264 | if (!NormalDest->getSinglePredecessor()) { | ||||
| 4265 | // FIXME: this case is tricky, so we are just conservative here. | ||||
| 4266 | // Perhaps we need to split the edge between this BB and NormalDest, | ||||
| 4267 | // but a naive attempt to use SplitEdge leads to a crash. | ||||
| 4268 | setShadow(&CB, getCleanShadow(&CB)); | ||||
| 4269 | setOrigin(&CB, getCleanOrigin()); | ||||
| 4270 | return; | ||||
| 4271 | } | ||||
| 4272 | // FIXME: NextInsn is likely in a basic block that has not been visited | ||||
| 4273 | // yet. Anything inserted there will be instrumented by MSan later! | ||||
| 4274 | NextInsn = NormalDest->getFirstInsertionPt(); | ||||
| 4275 | assert(NextInsn != NormalDest->end() &&(static_cast <bool> (NextInsn != NormalDest->end() && "Could not find insertion point for retval shadow load") ? void (0) : __assert_fail ("NextInsn != NormalDest->end() && \"Could not find insertion point for retval shadow load\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4276 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 4276 | "Could not find insertion point for retval shadow load")(static_cast <bool> (NextInsn != NormalDest->end() && "Could not find insertion point for retval shadow load") ? void (0) : __assert_fail ("NextInsn != NormalDest->end() && \"Could not find insertion point for retval shadow load\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4276 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4277 | } | ||||
| 4278 | IRBuilder<> IRBAfter(&*NextInsn); | ||||
| 4279 | Value *RetvalShadow = IRBAfter.CreateAlignedLoad( | ||||
| 4280 | getShadowTy(&CB), getShadowPtrForRetval(&CB, IRBAfter), | ||||
| 4281 | kShadowTLSAlignment, "_msret"); | ||||
| 4282 | setShadow(&CB, RetvalShadow); | ||||
| 4283 | if (MS.TrackOrigins) | ||||
| 4284 | setOrigin(&CB, IRBAfter.CreateLoad(MS.OriginTy, | ||||
| 4285 | getOriginPtrForRetval(IRBAfter))); | ||||
| 4286 | } | ||||
| 4287 | |||||
| 4288 | bool isAMustTailRetVal(Value *RetVal) { | ||||
| 4289 | if (auto *I = dyn_cast<BitCastInst>(RetVal)) { | ||||
| 4290 | RetVal = I->getOperand(0); | ||||
| 4291 | } | ||||
| 4292 | if (auto *I = dyn_cast<CallInst>(RetVal)) { | ||||
| 4293 | return I->isMustTailCall(); | ||||
| 4294 | } | ||||
| 4295 | return false; | ||||
| 4296 | } | ||||
| 4297 | |||||
| 4298 | void visitReturnInst(ReturnInst &I) { | ||||
| 4299 | IRBuilder<> IRB(&I); | ||||
| 4300 | Value *RetVal = I.getReturnValue(); | ||||
| 4301 | if (!RetVal) | ||||
| 4302 | return; | ||||
| 4303 | // Don't emit the epilogue for musttail call returns. | ||||
| 4304 | if (isAMustTailRetVal(RetVal)) | ||||
| 4305 | return; | ||||
| 4306 | Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB); | ||||
| 4307 | bool HasNoUndef = F.hasRetAttribute(Attribute::NoUndef); | ||||
| 4308 | bool StoreShadow = !(MS.EagerChecks && HasNoUndef); | ||||
| 4309 | // FIXME: Consider using SpecialCaseList to specify a list of functions that | ||||
| 4310 | // must always return fully initialized values. For now, we hardcode "main". | ||||
| 4311 | bool EagerCheck = (MS.EagerChecks && HasNoUndef) || (F.getName() == "main"); | ||||
| 4312 | |||||
| 4313 | Value *Shadow = getShadow(RetVal); | ||||
| 4314 | bool StoreOrigin = true; | ||||
| 4315 | if (EagerCheck) { | ||||
| 4316 | insertShadowCheck(RetVal, &I); | ||||
| 4317 | Shadow = getCleanShadow(RetVal); | ||||
| 4318 | StoreOrigin = false; | ||||
| 4319 | } | ||||
| 4320 | |||||
| 4321 | // The caller may still expect information passed over TLS if we pass our | ||||
| 4322 | // check | ||||
| 4323 | if (StoreShadow) { | ||||
| 4324 | IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment); | ||||
| 4325 | if (MS.TrackOrigins && StoreOrigin) | ||||
| 4326 | IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB)); | ||||
| 4327 | } | ||||
| 4328 | } | ||||
| 4329 | |||||
| 4330 | void visitPHINode(PHINode &I) { | ||||
| 4331 | IRBuilder<> IRB(&I); | ||||
| 4332 | if (!PropagateShadow) { | ||||
| 4333 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4334 | setOrigin(&I, getCleanOrigin()); | ||||
| 4335 | return; | ||||
| 4336 | } | ||||
| 4337 | |||||
| 4338 | ShadowPHINodes.push_back(&I); | ||||
| 4339 | setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(), | ||||
| 4340 | "_msphi_s")); | ||||
| 4341 | if (MS.TrackOrigins) | ||||
| 4342 | setOrigin( | ||||
| 4343 | &I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(), "_msphi_o")); | ||||
| 4344 | } | ||||
| 4345 | |||||
| 4346 | Value *getLocalVarIdptr(AllocaInst &I) { | ||||
| 4347 | ConstantInt *IntConst = | ||||
| 4348 | ConstantInt::get(Type::getInt32Ty((*F.getParent()).getContext()), 0); | ||||
| 4349 | return new GlobalVariable(*F.getParent(), IntConst->getType(), | ||||
| 4350 | /*isConstant=*/false, GlobalValue::PrivateLinkage, | ||||
| 4351 | IntConst); | ||||
| 4352 | } | ||||
| 4353 | |||||
| 4354 | Value *getLocalVarDescription(AllocaInst &I) { | ||||
| 4355 | return createPrivateConstGlobalForString(*F.getParent(), I.getName()); | ||||
| 4356 | } | ||||
| 4357 | |||||
| 4358 | void poisonAllocaUserspace(AllocaInst &I, IRBuilder<> &IRB, Value *Len) { | ||||
| 4359 | if (PoisonStack && ClPoisonStackWithCall) { | ||||
| 4360 | IRB.CreateCall(MS.MsanPoisonStackFn, | ||||
| 4361 | {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len}); | ||||
| 4362 | } else { | ||||
| 4363 | Value *ShadowBase, *OriginBase; | ||||
| 4364 | std::tie(ShadowBase, OriginBase) = getShadowOriginPtr( | ||||
| 4365 | &I, IRB, IRB.getInt8Ty(), Align(1), /*isStore*/ true); | ||||
| 4366 | |||||
| 4367 | Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0); | ||||
| 4368 | IRB.CreateMemSet(ShadowBase, PoisonValue, Len, I.getAlign()); | ||||
| 4369 | } | ||||
| 4370 | |||||
| 4371 | if (PoisonStack && MS.TrackOrigins) { | ||||
| 4372 | Value *Idptr = getLocalVarIdptr(I); | ||||
| 4373 | if (ClPrintStackNames) { | ||||
| 4374 | Value *Descr = getLocalVarDescription(I); | ||||
| 4375 | IRB.CreateCall(MS.MsanSetAllocaOriginWithDescriptionFn, | ||||
| 4376 | {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len, | ||||
| 4377 | IRB.CreatePointerCast(Idptr, IRB.getInt8PtrTy()), | ||||
| 4378 | IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())}); | ||||
| 4379 | } else { | ||||
| 4380 | IRB.CreateCall(MS.MsanSetAllocaOriginNoDescriptionFn, | ||||
| 4381 | {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len, | ||||
| 4382 | IRB.CreatePointerCast(Idptr, IRB.getInt8PtrTy())}); | ||||
| 4383 | } | ||||
| 4384 | } | ||||
| 4385 | } | ||||
| 4386 | |||||
| 4387 | void poisonAllocaKmsan(AllocaInst &I, IRBuilder<> &IRB, Value *Len) { | ||||
| 4388 | Value *Descr = getLocalVarDescription(I); | ||||
| 4389 | if (PoisonStack) { | ||||
| 4390 | IRB.CreateCall(MS.MsanPoisonAllocaFn, | ||||
| 4391 | {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len, | ||||
| 4392 | IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy())}); | ||||
| 4393 | } else { | ||||
| 4394 | IRB.CreateCall(MS.MsanUnpoisonAllocaFn, | ||||
| 4395 | {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len}); | ||||
| 4396 | } | ||||
| 4397 | } | ||||
| 4398 | |||||
| 4399 | void instrumentAlloca(AllocaInst &I, Instruction *InsPoint = nullptr) { | ||||
| 4400 | if (!InsPoint) | ||||
| 4401 | InsPoint = &I; | ||||
| 4402 | NextNodeIRBuilder IRB(InsPoint); | ||||
| 4403 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 4404 | uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType()); | ||||
| 4405 | Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize); | ||||
| 4406 | if (I.isArrayAllocation()) | ||||
| 4407 | Len = IRB.CreateMul(Len, | ||||
| 4408 | IRB.CreateZExtOrTrunc(I.getArraySize(), MS.IntptrTy)); | ||||
| 4409 | |||||
| 4410 | if (MS.CompileKernel) | ||||
| 4411 | poisonAllocaKmsan(I, IRB, Len); | ||||
| 4412 | else | ||||
| 4413 | poisonAllocaUserspace(I, IRB, Len); | ||||
| 4414 | } | ||||
| 4415 | |||||
| 4416 | void visitAllocaInst(AllocaInst &I) { | ||||
| 4417 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4418 | setOrigin(&I, getCleanOrigin()); | ||||
| 4419 | // We'll get to this alloca later unless it's poisoned at the corresponding | ||||
| 4420 | // llvm.lifetime.start. | ||||
| 4421 | AllocaSet.insert(&I); | ||||
| 4422 | } | ||||
| 4423 | |||||
| 4424 | void visitSelectInst(SelectInst &I) { | ||||
| 4425 | IRBuilder<> IRB(&I); | ||||
| 4426 | // a = select b, c, d | ||||
| 4427 | Value *B = I.getCondition(); | ||||
| 4428 | Value *C = I.getTrueValue(); | ||||
| 4429 | Value *D = I.getFalseValue(); | ||||
| 4430 | Value *Sb = getShadow(B); | ||||
| 4431 | Value *Sc = getShadow(C); | ||||
| 4432 | Value *Sd = getShadow(D); | ||||
| 4433 | |||||
| 4434 | // Result shadow if condition shadow is 0. | ||||
| 4435 | Value *Sa0 = IRB.CreateSelect(B, Sc, Sd); | ||||
| 4436 | Value *Sa1; | ||||
| 4437 | if (I.getType()->isAggregateType()) { | ||||
| 4438 | // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do | ||||
| 4439 | // an extra "select". This results in much more compact IR. | ||||
| 4440 | // Sa = select Sb, poisoned, (select b, Sc, Sd) | ||||
| 4441 | Sa1 = getPoisonedShadow(getShadowTy(I.getType())); | ||||
| 4442 | } else { | ||||
| 4443 | // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ] | ||||
| 4444 | // If Sb (condition is poisoned), look for bits in c and d that are equal | ||||
| 4445 | // and both unpoisoned. | ||||
| 4446 | // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd. | ||||
| 4447 | |||||
| 4448 | // Cast arguments to shadow-compatible type. | ||||
| 4449 | C = CreateAppToShadowCast(IRB, C); | ||||
| 4450 | D = CreateAppToShadowCast(IRB, D); | ||||
| 4451 | |||||
| 4452 | // Result shadow if condition shadow is 1. | ||||
| 4453 | Sa1 = IRB.CreateOr({IRB.CreateXor(C, D), Sc, Sd}); | ||||
| 4454 | } | ||||
| 4455 | Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select"); | ||||
| 4456 | setShadow(&I, Sa); | ||||
| 4457 | if (MS.TrackOrigins) { | ||||
| 4458 | // Origins are always i32, so any vector conditions must be flattened. | ||||
| 4459 | // FIXME: consider tracking vector origins for app vectors? | ||||
| 4460 | if (B->getType()->isVectorTy()) { | ||||
| 4461 | B = convertToBool(B, IRB); | ||||
| 4462 | Sb = convertToBool(Sb, IRB); | ||||
| 4463 | } | ||||
| 4464 | // a = select b, c, d | ||||
| 4465 | // Oa = Sb ? Ob : (b ? Oc : Od) | ||||
| 4466 | setOrigin( | ||||
| 4467 | &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()), | ||||
| 4468 | IRB.CreateSelect(B, getOrigin(I.getTrueValue()), | ||||
| 4469 | getOrigin(I.getFalseValue())))); | ||||
| 4470 | } | ||||
| 4471 | } | ||||
| 4472 | |||||
| 4473 | void visitLandingPadInst(LandingPadInst &I) { | ||||
| 4474 | // Do nothing. | ||||
| 4475 | // See https://github.com/google/sanitizers/issues/504 | ||||
| 4476 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4477 | setOrigin(&I, getCleanOrigin()); | ||||
| 4478 | } | ||||
| 4479 | |||||
| 4480 | void visitCatchSwitchInst(CatchSwitchInst &I) { | ||||
| 4481 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4482 | setOrigin(&I, getCleanOrigin()); | ||||
| 4483 | } | ||||
| 4484 | |||||
| 4485 | void visitFuncletPadInst(FuncletPadInst &I) { | ||||
| 4486 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4487 | setOrigin(&I, getCleanOrigin()); | ||||
| 4488 | } | ||||
| 4489 | |||||
| 4490 | void visitGetElementPtrInst(GetElementPtrInst &I) { handleShadowOr(I); } | ||||
| 4491 | |||||
| 4492 | void visitExtractValueInst(ExtractValueInst &I) { | ||||
| 4493 | IRBuilder<> IRB(&I); | ||||
| 4494 | Value *Agg = I.getAggregateOperand(); | ||||
| 4495 | LLVM_DEBUG(dbgs() << "ExtractValue: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "ExtractValue: " << I << "\n"; } } while (false); | ||||
| 4496 | Value *AggShadow = getShadow(Agg); | ||||
| 4497 | LLVM_DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " AggShadow: " << *AggShadow << "\n"; } } while (false); | ||||
| 4498 | Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices()); | ||||
| 4499 | LLVM_DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " ResShadow: " << *ResShadow << "\n"; } } while (false); | ||||
| 4500 | setShadow(&I, ResShadow); | ||||
| 4501 | setOriginForNaryOp(I); | ||||
| 4502 | } | ||||
| 4503 | |||||
| 4504 | void visitInsertValueInst(InsertValueInst &I) { | ||||
| 4505 | IRBuilder<> IRB(&I); | ||||
| 4506 | LLVM_DEBUG(dbgs() << "InsertValue: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "InsertValue: " << I << "\n"; } } while (false); | ||||
| 4507 | Value *AggShadow = getShadow(I.getAggregateOperand()); | ||||
| 4508 | Value *InsShadow = getShadow(I.getInsertedValueOperand()); | ||||
| 4509 | LLVM_DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " AggShadow: " << *AggShadow << "\n"; } } while (false); | ||||
| 4510 | LLVM_DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " InsShadow: " << *InsShadow << "\n"; } } while (false); | ||||
| 4511 | Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices()); | ||||
| 4512 | LLVM_DEBUG(dbgs() << " Res: " << *Res << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << " Res: " << *Res << "\n"; } } while (false); | ||||
| 4513 | setShadow(&I, Res); | ||||
| 4514 | setOriginForNaryOp(I); | ||||
| 4515 | } | ||||
| 4516 | |||||
| 4517 | void dumpInst(Instruction &I) { | ||||
| 4518 | if (CallInst *CI = dyn_cast<CallInst>(&I)) { | ||||
| 4519 | errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n"; | ||||
| 4520 | } else { | ||||
| 4521 | errs() << "ZZZ " << I.getOpcodeName() << "\n"; | ||||
| 4522 | } | ||||
| 4523 | errs() << "QQQ " << I << "\n"; | ||||
| 4524 | } | ||||
| 4525 | |||||
| 4526 | void visitResumeInst(ResumeInst &I) { | ||||
| 4527 | LLVM_DEBUG(dbgs() << "Resume: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "Resume: " << I << "\n" ; } } while (false); | ||||
| 4528 | // Nothing to do here. | ||||
| 4529 | } | ||||
| 4530 | |||||
| 4531 | void visitCleanupReturnInst(CleanupReturnInst &CRI) { | ||||
| 4532 | LLVM_DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "CleanupReturn: " << CRI << "\n"; } } while (false); | ||||
| 4533 | // Nothing to do here. | ||||
| 4534 | } | ||||
| 4535 | |||||
| 4536 | void visitCatchReturnInst(CatchReturnInst &CRI) { | ||||
| 4537 | LLVM_DEBUG(dbgs() << "CatchReturn: " << CRI << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "CatchReturn: " << CRI << "\n"; } } while (false); | ||||
| 4538 | // Nothing to do here. | ||||
| 4539 | } | ||||
| 4540 | |||||
| 4541 | void instrumentAsmArgument(Value *Operand, Type *ElemTy, Instruction &I, | ||||
| 4542 | IRBuilder<> &IRB, const DataLayout &DL, | ||||
| 4543 | bool isOutput) { | ||||
| 4544 | // For each assembly argument, we check its value for being initialized. | ||||
| 4545 | // If the argument is a pointer, we assume it points to a single element | ||||
| 4546 | // of the corresponding type (or to a 8-byte word, if the type is unsized). | ||||
| 4547 | // Each such pointer is instrumented with a call to the runtime library. | ||||
| 4548 | Type *OpType = Operand->getType(); | ||||
| 4549 | // Check the operand value itself. | ||||
| 4550 | insertShadowCheck(Operand, &I); | ||||
| 4551 | if (!OpType->isPointerTy() || !isOutput) { | ||||
| 4552 | assert(!isOutput)(static_cast <bool> (!isOutput) ? void (0) : __assert_fail ("!isOutput", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 4552, __extension__ __PRETTY_FUNCTION__)); | ||||
| 4553 | return; | ||||
| 4554 | } | ||||
| 4555 | if (!ElemTy->isSized()) | ||||
| 4556 | return; | ||||
| 4557 | Value *Ptr = IRB.CreatePointerCast(Operand, IRB.getInt8PtrTy()); | ||||
| 4558 | Value *SizeVal = | ||||
| 4559 | IRB.CreateTypeSize(MS.IntptrTy, DL.getTypeStoreSize(ElemTy)); | ||||
| 4560 | IRB.CreateCall(MS.MsanInstrumentAsmStoreFn, {Ptr, SizeVal}); | ||||
| 4561 | } | ||||
| 4562 | |||||
| 4563 | /// Get the number of output arguments returned by pointers. | ||||
| 4564 | int getNumOutputArgs(InlineAsm *IA, CallBase *CB) { | ||||
| 4565 | int NumRetOutputs = 0; | ||||
| 4566 | int NumOutputs = 0; | ||||
| 4567 | Type *RetTy = cast<Value>(CB)->getType(); | ||||
| 4568 | if (!RetTy->isVoidTy()) { | ||||
| 4569 | // Register outputs are returned via the CallInst return value. | ||||
| 4570 | auto *ST = dyn_cast<StructType>(RetTy); | ||||
| 4571 | if (ST) | ||||
| 4572 | NumRetOutputs = ST->getNumElements(); | ||||
| 4573 | else | ||||
| 4574 | NumRetOutputs = 1; | ||||
| 4575 | } | ||||
| 4576 | InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints(); | ||||
| 4577 | for (const InlineAsm::ConstraintInfo &Info : Constraints) { | ||||
| 4578 | switch (Info.Type) { | ||||
| 4579 | case InlineAsm::isOutput: | ||||
| 4580 | NumOutputs++; | ||||
| 4581 | break; | ||||
| 4582 | default: | ||||
| 4583 | break; | ||||
| 4584 | } | ||||
| 4585 | } | ||||
| 4586 | return NumOutputs - NumRetOutputs; | ||||
| 4587 | } | ||||
| 4588 | |||||
| 4589 | void visitAsmInstruction(Instruction &I) { | ||||
| 4590 | // Conservative inline assembly handling: check for poisoned shadow of | ||||
| 4591 | // asm() arguments, then unpoison the result and all the memory locations | ||||
| 4592 | // pointed to by those arguments. | ||||
| 4593 | // An inline asm() statement in C++ contains lists of input and output | ||||
| 4594 | // arguments used by the assembly code. These are mapped to operands of the | ||||
| 4595 | // CallInst as follows: | ||||
| 4596 | // - nR register outputs ("=r) are returned by value in a single structure | ||||
| 4597 | // (SSA value of the CallInst); | ||||
| 4598 | // - nO other outputs ("=m" and others) are returned by pointer as first | ||||
| 4599 | // nO operands of the CallInst; | ||||
| 4600 | // - nI inputs ("r", "m" and others) are passed to CallInst as the | ||||
| 4601 | // remaining nI operands. | ||||
| 4602 | // The total number of asm() arguments in the source is nR+nO+nI, and the | ||||
| 4603 | // corresponding CallInst has nO+nI+1 operands (the last operand is the | ||||
| 4604 | // function to be called). | ||||
| 4605 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 4606 | CallBase *CB = cast<CallBase>(&I); | ||||
| 4607 | IRBuilder<> IRB(&I); | ||||
| 4608 | InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand()); | ||||
| 4609 | int OutputArgs = getNumOutputArgs(IA, CB); | ||||
| 4610 | // The last operand of a CallInst is the function itself. | ||||
| 4611 | int NumOperands = CB->getNumOperands() - 1; | ||||
| 4612 | |||||
| 4613 | // Check input arguments. Doing so before unpoisoning output arguments, so | ||||
| 4614 | // that we won't overwrite uninit values before checking them. | ||||
| 4615 | for (int i = OutputArgs; i < NumOperands; i++) { | ||||
| 4616 | Value *Operand = CB->getOperand(i); | ||||
| 4617 | instrumentAsmArgument(Operand, CB->getParamElementType(i), I, IRB, DL, | ||||
| 4618 | /*isOutput*/ false); | ||||
| 4619 | } | ||||
| 4620 | // Unpoison output arguments. This must happen before the actual InlineAsm | ||||
| 4621 | // call, so that the shadow for memory published in the asm() statement | ||||
| 4622 | // remains valid. | ||||
| 4623 | for (int i = 0; i < OutputArgs; i++) { | ||||
| 4624 | Value *Operand = CB->getOperand(i); | ||||
| 4625 | instrumentAsmArgument(Operand, CB->getParamElementType(i), I, IRB, DL, | ||||
| 4626 | /*isOutput*/ true); | ||||
| 4627 | } | ||||
| 4628 | |||||
| 4629 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4630 | setOrigin(&I, getCleanOrigin()); | ||||
| 4631 | } | ||||
| 4632 | |||||
| 4633 | void visitFreezeInst(FreezeInst &I) { | ||||
| 4634 | // Freeze always returns a fully defined value. | ||||
| 4635 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4636 | setOrigin(&I, getCleanOrigin()); | ||||
| 4637 | } | ||||
| 4638 | |||||
| 4639 | void visitInstruction(Instruction &I) { | ||||
| 4640 | // Everything else: stop propagating and check for poisoned shadow. | ||||
| 4641 | if (ClDumpStrictInstructions) | ||||
| 4642 | dumpInst(I); | ||||
| 4643 | LLVM_DEBUG(dbgs() << "DEFAULT: " << I << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("msan")) { dbgs() << "DEFAULT: " << I << "\n" ; } } while (false); | ||||
| 4644 | for (size_t i = 0, n = I.getNumOperands(); i < n; i++) { | ||||
| 4645 | Value *Operand = I.getOperand(i); | ||||
| 4646 | if (Operand->getType()->isSized()) | ||||
| 4647 | insertShadowCheck(Operand, &I); | ||||
| 4648 | } | ||||
| 4649 | setShadow(&I, getCleanShadow(&I)); | ||||
| 4650 | setOrigin(&I, getCleanOrigin()); | ||||
| 4651 | } | ||||
| 4652 | }; | ||||
| 4653 | |||||
| 4654 | /// AMD64-specific implementation of VarArgHelper. | ||||
| 4655 | struct VarArgAMD64Helper : public VarArgHelper { | ||||
| 4656 | // An unfortunate workaround for asymmetric lowering of va_arg stuff. | ||||
| 4657 | // See a comment in visitCallBase for more details. | ||||
| 4658 | static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7 | ||||
| 4659 | static const unsigned AMD64FpEndOffsetSSE = 176; | ||||
| 4660 | // If SSE is disabled, fp_offset in va_list is zero. | ||||
| 4661 | static const unsigned AMD64FpEndOffsetNoSSE = AMD64GpEndOffset; | ||||
| 4662 | |||||
| 4663 | unsigned AMD64FpEndOffset; | ||||
| 4664 | Function &F; | ||||
| 4665 | MemorySanitizer &MS; | ||||
| 4666 | MemorySanitizerVisitor &MSV; | ||||
| 4667 | AllocaInst *VAArgTLSCopy = nullptr; | ||||
| 4668 | AllocaInst *VAArgTLSOriginCopy = nullptr; | ||||
| 4669 | Value *VAArgOverflowSize = nullptr; | ||||
| 4670 | |||||
| 4671 | SmallVector<CallInst *, 16> VAStartInstrumentationList; | ||||
| 4672 | |||||
| 4673 | enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory }; | ||||
| 4674 | |||||
| 4675 | VarArgAMD64Helper(Function &F, MemorySanitizer &MS, | ||||
| 4676 | MemorySanitizerVisitor &MSV) | ||||
| 4677 | : F(F), MS(MS), MSV(MSV) { | ||||
| 4678 | AMD64FpEndOffset = AMD64FpEndOffsetSSE; | ||||
| 4679 | for (const auto &Attr : F.getAttributes().getFnAttrs()) { | ||||
| 4680 | if (Attr.isStringAttribute() && | ||||
| 4681 | (Attr.getKindAsString() == "target-features")) { | ||||
| 4682 | if (Attr.getValueAsString().contains("-sse")) | ||||
| 4683 | AMD64FpEndOffset = AMD64FpEndOffsetNoSSE; | ||||
| 4684 | break; | ||||
| 4685 | } | ||||
| 4686 | } | ||||
| 4687 | } | ||||
| 4688 | |||||
| 4689 | ArgKind classifyArgument(Value *arg) { | ||||
| 4690 | // A very rough approximation of X86_64 argument classification rules. | ||||
| 4691 | Type *T = arg->getType(); | ||||
| 4692 | if (T->isFPOrFPVectorTy() || T->isX86_MMXTy()) | ||||
| 4693 | return AK_FloatingPoint; | ||||
| 4694 | if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64) | ||||
| 4695 | return AK_GeneralPurpose; | ||||
| 4696 | if (T->isPointerTy()) | ||||
| 4697 | return AK_GeneralPurpose; | ||||
| 4698 | return AK_Memory; | ||||
| 4699 | } | ||||
| 4700 | |||||
| 4701 | // For VarArg functions, store the argument shadow in an ABI-specific format | ||||
| 4702 | // that corresponds to va_list layout. | ||||
| 4703 | // We do this because Clang lowers va_arg in the frontend, and this pass | ||||
| 4704 | // only sees the low level code that deals with va_list internals. | ||||
| 4705 | // A much easier alternative (provided that Clang emits va_arg instructions) | ||||
| 4706 | // would have been to associate each live instance of va_list with a copy of | ||||
| 4707 | // MSanParamTLS, and extract shadow on va_arg() call in the argument list | ||||
| 4708 | // order. | ||||
| 4709 | void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { | ||||
| 4710 | unsigned GpOffset = 0; | ||||
| 4711 | unsigned FpOffset = AMD64GpEndOffset; | ||||
| 4712 | unsigned OverflowOffset = AMD64FpEndOffset; | ||||
| 4713 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 4714 | for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) { | ||||
| 4715 | bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); | ||||
| 4716 | bool IsByVal = CB.paramHasAttr(ArgNo, Attribute::ByVal); | ||||
| 4717 | if (IsByVal) { | ||||
| 4718 | // ByVal arguments always go to the overflow area. | ||||
| 4719 | // Fixed arguments passed through the overflow area will be stepped | ||||
| 4720 | // over by va_start, so don't count them towards the offset. | ||||
| 4721 | if (IsFixed) | ||||
| 4722 | continue; | ||||
| 4723 | assert(A->getType()->isPointerTy())(static_cast <bool> (A->getType()->isPointerTy()) ? void (0) : __assert_fail ("A->getType()->isPointerTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4723 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4724 | Type *RealTy = CB.getParamByValType(ArgNo); | ||||
| 4725 | uint64_t ArgSize = DL.getTypeAllocSize(RealTy); | ||||
| 4726 | Value *ShadowBase = getShadowPtrForVAArgument( | ||||
| 4727 | RealTy, IRB, OverflowOffset, alignTo(ArgSize, 8)); | ||||
| 4728 | Value *OriginBase = nullptr; | ||||
| 4729 | if (MS.TrackOrigins) | ||||
| 4730 | OriginBase = getOriginPtrForVAArgument(RealTy, IRB, OverflowOffset); | ||||
| 4731 | OverflowOffset += alignTo(ArgSize, 8); | ||||
| 4732 | if (!ShadowBase) | ||||
| 4733 | continue; | ||||
| 4734 | Value *ShadowPtr, *OriginPtr; | ||||
| 4735 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 4736 | MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), kShadowTLSAlignment, | ||||
| 4737 | /*isStore*/ false); | ||||
| 4738 | |||||
| 4739 | IRB.CreateMemCpy(ShadowBase, kShadowTLSAlignment, ShadowPtr, | ||||
| 4740 | kShadowTLSAlignment, ArgSize); | ||||
| 4741 | if (MS.TrackOrigins) | ||||
| 4742 | IRB.CreateMemCpy(OriginBase, kShadowTLSAlignment, OriginPtr, | ||||
| 4743 | kShadowTLSAlignment, ArgSize); | ||||
| 4744 | } else { | ||||
| 4745 | ArgKind AK = classifyArgument(A); | ||||
| 4746 | if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset) | ||||
| 4747 | AK = AK_Memory; | ||||
| 4748 | if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset) | ||||
| 4749 | AK = AK_Memory; | ||||
| 4750 | Value *ShadowBase, *OriginBase = nullptr; | ||||
| 4751 | switch (AK) { | ||||
| 4752 | case AK_GeneralPurpose: | ||||
| 4753 | ShadowBase = | ||||
| 4754 | getShadowPtrForVAArgument(A->getType(), IRB, GpOffset, 8); | ||||
| 4755 | if (MS.TrackOrigins) | ||||
| 4756 | OriginBase = getOriginPtrForVAArgument(A->getType(), IRB, GpOffset); | ||||
| 4757 | GpOffset += 8; | ||||
| 4758 | break; | ||||
| 4759 | case AK_FloatingPoint: | ||||
| 4760 | ShadowBase = | ||||
| 4761 | getShadowPtrForVAArgument(A->getType(), IRB, FpOffset, 16); | ||||
| 4762 | if (MS.TrackOrigins) | ||||
| 4763 | OriginBase = getOriginPtrForVAArgument(A->getType(), IRB, FpOffset); | ||||
| 4764 | FpOffset += 16; | ||||
| 4765 | break; | ||||
| 4766 | case AK_Memory: | ||||
| 4767 | if (IsFixed) | ||||
| 4768 | continue; | ||||
| 4769 | uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); | ||||
| 4770 | ShadowBase = | ||||
| 4771 | getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, 8); | ||||
| 4772 | if (MS.TrackOrigins) | ||||
| 4773 | OriginBase = | ||||
| 4774 | getOriginPtrForVAArgument(A->getType(), IRB, OverflowOffset); | ||||
| 4775 | OverflowOffset += alignTo(ArgSize, 8); | ||||
| 4776 | } | ||||
| 4777 | // Take fixed arguments into account for GpOffset and FpOffset, | ||||
| 4778 | // but don't actually store shadows for them. | ||||
| 4779 | // TODO(glider): don't call get*PtrForVAArgument() for them. | ||||
| 4780 | if (IsFixed) | ||||
| 4781 | continue; | ||||
| 4782 | if (!ShadowBase) | ||||
| 4783 | continue; | ||||
| 4784 | Value *Shadow = MSV.getShadow(A); | ||||
| 4785 | IRB.CreateAlignedStore(Shadow, ShadowBase, kShadowTLSAlignment); | ||||
| 4786 | if (MS.TrackOrigins) { | ||||
| 4787 | Value *Origin = MSV.getOrigin(A); | ||||
| 4788 | TypeSize StoreSize = DL.getTypeStoreSize(Shadow->getType()); | ||||
| 4789 | MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize, | ||||
| 4790 | std::max(kShadowTLSAlignment, kMinOriginAlignment)); | ||||
| 4791 | } | ||||
| 4792 | } | ||||
| 4793 | } | ||||
| 4794 | Constant *OverflowSize = | ||||
| 4795 | ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset); | ||||
| 4796 | IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); | ||||
| 4797 | } | ||||
| 4798 | |||||
| 4799 | /// Compute the shadow address for a given va_arg. | ||||
| 4800 | Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, | ||||
| 4801 | unsigned ArgOffset, unsigned ArgSize) { | ||||
| 4802 | // Make sure we don't overflow __msan_va_arg_tls. | ||||
| 4803 | if (ArgOffset + ArgSize > kParamTLSSize) | ||||
| 4804 | return nullptr; | ||||
| 4805 | Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); | ||||
| 4806 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 4807 | return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), | ||||
| 4808 | "_msarg_va_s"); | ||||
| 4809 | } | ||||
| 4810 | |||||
| 4811 | /// Compute the origin address for a given va_arg. | ||||
| 4812 | Value *getOriginPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, int ArgOffset) { | ||||
| 4813 | Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy); | ||||
| 4814 | // getOriginPtrForVAArgument() is always called after | ||||
| 4815 | // getShadowPtrForVAArgument(), so __msan_va_arg_origin_tls can never | ||||
| 4816 | // overflow. | ||||
| 4817 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 4818 | return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), | ||||
| 4819 | "_msarg_va_o"); | ||||
| 4820 | } | ||||
| 4821 | |||||
| 4822 | void unpoisonVAListTagForInst(IntrinsicInst &I) { | ||||
| 4823 | IRBuilder<> IRB(&I); | ||||
| 4824 | Value *VAListTag = I.getArgOperand(0); | ||||
| 4825 | Value *ShadowPtr, *OriginPtr; | ||||
| 4826 | const Align Alignment = Align(8); | ||||
| 4827 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 4828 | MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment, | ||||
| 4829 | /*isStore*/ true); | ||||
| 4830 | |||||
| 4831 | // Unpoison the whole __va_list_tag. | ||||
| 4832 | // FIXME: magic ABI constants. | ||||
| 4833 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 4834 | /* size */ 24, Alignment, false); | ||||
| 4835 | // We shouldn't need to zero out the origins, as they're only checked for | ||||
| 4836 | // nonzero shadow. | ||||
| 4837 | } | ||||
| 4838 | |||||
| 4839 | void visitVAStartInst(VAStartInst &I) override { | ||||
| 4840 | if (F.getCallingConv() == CallingConv::Win64) | ||||
| 4841 | return; | ||||
| 4842 | VAStartInstrumentationList.push_back(&I); | ||||
| 4843 | unpoisonVAListTagForInst(I); | ||||
| 4844 | } | ||||
| 4845 | |||||
| 4846 | void visitVACopyInst(VACopyInst &I) override { | ||||
| 4847 | if (F.getCallingConv() == CallingConv::Win64) | ||||
| 4848 | return; | ||||
| 4849 | unpoisonVAListTagForInst(I); | ||||
| 4850 | } | ||||
| 4851 | |||||
| 4852 | void finalizeInstrumentation() override { | ||||
| 4853 | assert(!VAArgOverflowSize && !VAArgTLSCopy &&(static_cast <bool> (!VAArgOverflowSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgOverflowSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4854 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 4854 | "finalizeInstrumentation called twice")(static_cast <bool> (!VAArgOverflowSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgOverflowSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 4854 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 4855 | if (!VAStartInstrumentationList.empty()) { | ||||
| 4856 | // If there is a va_start in this function, make a backup copy of | ||||
| 4857 | // va_arg_tls somewhere in the function entry block. | ||||
| 4858 | IRBuilder<> IRB(MSV.FnPrologueEnd); | ||||
| 4859 | VAArgOverflowSize = | ||||
| 4860 | IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); | ||||
| 4861 | Value *CopySize = IRB.CreateAdd( | ||||
| 4862 | ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset), VAArgOverflowSize); | ||||
| 4863 | VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 4864 | VAArgTLSCopy->setAlignment(kShadowTLSAlignment); | ||||
| 4865 | IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 4866 | CopySize, kShadowTLSAlignment, false); | ||||
| 4867 | |||||
| 4868 | Value *SrcSize = IRB.CreateBinaryIntrinsic( | ||||
| 4869 | Intrinsic::umin, CopySize, | ||||
| 4870 | ConstantInt::get(MS.IntptrTy, kParamTLSSize)); | ||||
| 4871 | IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS, | ||||
| 4872 | kShadowTLSAlignment, SrcSize); | ||||
| 4873 | if (MS.TrackOrigins) { | ||||
| 4874 | VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 4875 | VAArgTLSOriginCopy->setAlignment(kShadowTLSAlignment); | ||||
| 4876 | IRB.CreateMemCpy(VAArgTLSOriginCopy, kShadowTLSAlignment, | ||||
| 4877 | MS.VAArgOriginTLS, kShadowTLSAlignment, SrcSize); | ||||
| 4878 | } | ||||
| 4879 | } | ||||
| 4880 | |||||
| 4881 | // Instrument va_start. | ||||
| 4882 | // Copy va_list shadow from the backup copy of the TLS contents. | ||||
| 4883 | for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { | ||||
| 4884 | CallInst *OrigInst = VAStartInstrumentationList[i]; | ||||
| 4885 | NextNodeIRBuilder IRB(OrigInst); | ||||
| 4886 | Value *VAListTag = OrigInst->getArgOperand(0); | ||||
| 4887 | |||||
| 4888 | Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); | ||||
| 4889 | Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr( | ||||
| 4890 | IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 4891 | ConstantInt::get(MS.IntptrTy, 16)), | ||||
| 4892 | PointerType::get(RegSaveAreaPtrTy, 0)); | ||||
| 4893 | Value *RegSaveAreaPtr = | ||||
| 4894 | IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); | ||||
| 4895 | Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; | ||||
| 4896 | const Align Alignment = Align(16); | ||||
| 4897 | std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = | ||||
| 4898 | MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 4899 | Alignment, /*isStore*/ true); | ||||
| 4900 | IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, | ||||
| 4901 | AMD64FpEndOffset); | ||||
| 4902 | if (MS.TrackOrigins) | ||||
| 4903 | IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy, | ||||
| 4904 | Alignment, AMD64FpEndOffset); | ||||
| 4905 | Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C); | ||||
| 4906 | Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr( | ||||
| 4907 | IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 4908 | ConstantInt::get(MS.IntptrTy, 8)), | ||||
| 4909 | PointerType::get(OverflowArgAreaPtrTy, 0)); | ||||
| 4910 | Value *OverflowArgAreaPtr = | ||||
| 4911 | IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr); | ||||
| 4912 | Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr; | ||||
| 4913 | std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) = | ||||
| 4914 | MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 4915 | Alignment, /*isStore*/ true); | ||||
| 4916 | Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy, | ||||
| 4917 | AMD64FpEndOffset); | ||||
| 4918 | IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment, | ||||
| 4919 | VAArgOverflowSize); | ||||
| 4920 | if (MS.TrackOrigins) { | ||||
| 4921 | SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy, | ||||
| 4922 | AMD64FpEndOffset); | ||||
| 4923 | IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment, | ||||
| 4924 | VAArgOverflowSize); | ||||
| 4925 | } | ||||
| 4926 | } | ||||
| 4927 | } | ||||
| 4928 | }; | ||||
| 4929 | |||||
| 4930 | /// MIPS64-specific implementation of VarArgHelper. | ||||
| 4931 | struct VarArgMIPS64Helper : public VarArgHelper { | ||||
| 4932 | Function &F; | ||||
| 4933 | MemorySanitizer &MS; | ||||
| 4934 | MemorySanitizerVisitor &MSV; | ||||
| 4935 | AllocaInst *VAArgTLSCopy = nullptr; | ||||
| 4936 | Value *VAArgSize = nullptr; | ||||
| 4937 | |||||
| 4938 | SmallVector<CallInst *, 16> VAStartInstrumentationList; | ||||
| 4939 | |||||
| 4940 | VarArgMIPS64Helper(Function &F, MemorySanitizer &MS, | ||||
| 4941 | MemorySanitizerVisitor &MSV) | ||||
| 4942 | : F(F), MS(MS), MSV(MSV) {} | ||||
| 4943 | |||||
| 4944 | void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { | ||||
| 4945 | unsigned VAArgOffset = 0; | ||||
| 4946 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 4947 | for (Value *A : | ||||
| 4948 | llvm::drop_begin(CB.args(), CB.getFunctionType()->getNumParams())) { | ||||
| 4949 | Triple TargetTriple(F.getParent()->getTargetTriple()); | ||||
| 4950 | Value *Base; | ||||
| 4951 | uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); | ||||
| 4952 | if (TargetTriple.getArch() == Triple::mips64) { | ||||
| 4953 | // Adjusting the shadow for argument with size < 8 to match the | ||||
| 4954 | // placement of bits in big endian system | ||||
| 4955 | if (ArgSize < 8) | ||||
| 4956 | VAArgOffset += (8 - ArgSize); | ||||
| 4957 | } | ||||
| 4958 | Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset, ArgSize); | ||||
| 4959 | VAArgOffset += ArgSize; | ||||
| 4960 | VAArgOffset = alignTo(VAArgOffset, 8); | ||||
| 4961 | if (!Base) | ||||
| 4962 | continue; | ||||
| 4963 | IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); | ||||
| 4964 | } | ||||
| 4965 | |||||
| 4966 | Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset); | ||||
| 4967 | // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of | ||||
| 4968 | // a new class member i.e. it is the total size of all VarArgs. | ||||
| 4969 | IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS); | ||||
| 4970 | } | ||||
| 4971 | |||||
| 4972 | /// Compute the shadow address for a given va_arg. | ||||
| 4973 | Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, | ||||
| 4974 | unsigned ArgOffset, unsigned ArgSize) { | ||||
| 4975 | // Make sure we don't overflow __msan_va_arg_tls. | ||||
| 4976 | if (ArgOffset + ArgSize > kParamTLSSize) | ||||
| 4977 | return nullptr; | ||||
| 4978 | Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); | ||||
| 4979 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 4980 | return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), | ||||
| 4981 | "_msarg"); | ||||
| 4982 | } | ||||
| 4983 | |||||
| 4984 | void visitVAStartInst(VAStartInst &I) override { | ||||
| 4985 | IRBuilder<> IRB(&I); | ||||
| 4986 | VAStartInstrumentationList.push_back(&I); | ||||
| 4987 | Value *VAListTag = I.getArgOperand(0); | ||||
| 4988 | Value *ShadowPtr, *OriginPtr; | ||||
| 4989 | const Align Alignment = Align(8); | ||||
| 4990 | std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( | ||||
| 4991 | VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); | ||||
| 4992 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 4993 | /* size */ 8, Alignment, false); | ||||
| 4994 | } | ||||
| 4995 | |||||
| 4996 | void visitVACopyInst(VACopyInst &I) override { | ||||
| 4997 | IRBuilder<> IRB(&I); | ||||
| 4998 | VAStartInstrumentationList.push_back(&I); | ||||
| 4999 | Value *VAListTag = I.getArgOperand(0); | ||||
| 5000 | Value *ShadowPtr, *OriginPtr; | ||||
| 5001 | const Align Alignment = Align(8); | ||||
| 5002 | std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( | ||||
| 5003 | VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); | ||||
| 5004 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5005 | /* size */ 8, Alignment, false); | ||||
| 5006 | } | ||||
| 5007 | |||||
| 5008 | void finalizeInstrumentation() override { | ||||
| 5009 | assert(!VAArgSize && !VAArgTLSCopy &&(static_cast <bool> (!VAArgSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5010 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 5010 | "finalizeInstrumentation called twice")(static_cast <bool> (!VAArgSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5010 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 5011 | IRBuilder<> IRB(MSV.FnPrologueEnd); | ||||
| 5012 | VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); | ||||
| 5013 | Value *CopySize = | ||||
| 5014 | IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0), VAArgSize); | ||||
| 5015 | |||||
| 5016 | if (!VAStartInstrumentationList.empty()) { | ||||
| 5017 | // If there is a va_start in this function, make a backup copy of | ||||
| 5018 | // va_arg_tls somewhere in the function entry block. | ||||
| 5019 | VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 5020 | VAArgTLSCopy->setAlignment(kShadowTLSAlignment); | ||||
| 5021 | IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5022 | CopySize, kShadowTLSAlignment, false); | ||||
| 5023 | |||||
| 5024 | Value *SrcSize = IRB.CreateBinaryIntrinsic( | ||||
| 5025 | Intrinsic::umin, CopySize, | ||||
| 5026 | ConstantInt::get(MS.IntptrTy, kParamTLSSize)); | ||||
| 5027 | IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS, | ||||
| 5028 | kShadowTLSAlignment, SrcSize); | ||||
| 5029 | } | ||||
| 5030 | |||||
| 5031 | // Instrument va_start. | ||||
| 5032 | // Copy va_list shadow from the backup copy of the TLS contents. | ||||
| 5033 | for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { | ||||
| 5034 | CallInst *OrigInst = VAStartInstrumentationList[i]; | ||||
| 5035 | NextNodeIRBuilder IRB(OrigInst); | ||||
| 5036 | Value *VAListTag = OrigInst->getArgOperand(0); | ||||
| 5037 | Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); | ||||
| 5038 | Value *RegSaveAreaPtrPtr = | ||||
| 5039 | IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 5040 | PointerType::get(RegSaveAreaPtrTy, 0)); | ||||
| 5041 | Value *RegSaveAreaPtr = | ||||
| 5042 | IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); | ||||
| 5043 | Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; | ||||
| 5044 | const Align Alignment = Align(8); | ||||
| 5045 | std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = | ||||
| 5046 | MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 5047 | Alignment, /*isStore*/ true); | ||||
| 5048 | IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, | ||||
| 5049 | CopySize); | ||||
| 5050 | } | ||||
| 5051 | } | ||||
| 5052 | }; | ||||
| 5053 | |||||
| 5054 | /// AArch64-specific implementation of VarArgHelper. | ||||
| 5055 | struct VarArgAArch64Helper : public VarArgHelper { | ||||
| 5056 | static const unsigned kAArch64GrArgSize = 64; | ||||
| 5057 | static const unsigned kAArch64VrArgSize = 128; | ||||
| 5058 | |||||
| 5059 | static const unsigned AArch64GrBegOffset = 0; | ||||
| 5060 | static const unsigned AArch64GrEndOffset = kAArch64GrArgSize; | ||||
| 5061 | // Make VR space aligned to 16 bytes. | ||||
| 5062 | static const unsigned AArch64VrBegOffset = AArch64GrEndOffset; | ||||
| 5063 | static const unsigned AArch64VrEndOffset = | ||||
| 5064 | AArch64VrBegOffset + kAArch64VrArgSize; | ||||
| 5065 | static const unsigned AArch64VAEndOffset = AArch64VrEndOffset; | ||||
| 5066 | |||||
| 5067 | Function &F; | ||||
| 5068 | MemorySanitizer &MS; | ||||
| 5069 | MemorySanitizerVisitor &MSV; | ||||
| 5070 | AllocaInst *VAArgTLSCopy = nullptr; | ||||
| 5071 | Value *VAArgOverflowSize = nullptr; | ||||
| 5072 | |||||
| 5073 | SmallVector<CallInst *, 16> VAStartInstrumentationList; | ||||
| 5074 | |||||
| 5075 | enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory }; | ||||
| 5076 | |||||
| 5077 | VarArgAArch64Helper(Function &F, MemorySanitizer &MS, | ||||
| 5078 | MemorySanitizerVisitor &MSV) | ||||
| 5079 | : F(F), MS(MS), MSV(MSV) {} | ||||
| 5080 | |||||
| 5081 | ArgKind classifyArgument(Value *arg) { | ||||
| 5082 | Type *T = arg->getType(); | ||||
| 5083 | if (T->isFPOrFPVectorTy()) | ||||
| 5084 | return AK_FloatingPoint; | ||||
| 5085 | if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64) || | ||||
| 5086 | (T->isPointerTy())) | ||||
| 5087 | return AK_GeneralPurpose; | ||||
| 5088 | return AK_Memory; | ||||
| 5089 | } | ||||
| 5090 | |||||
| 5091 | // The instrumentation stores the argument shadow in a non ABI-specific | ||||
| 5092 | // format because it does not know which argument is named (since Clang, | ||||
| 5093 | // like x86_64 case, lowers the va_args in the frontend and this pass only | ||||
| 5094 | // sees the low level code that deals with va_list internals). | ||||
| 5095 | // The first seven GR registers are saved in the first 56 bytes of the | ||||
| 5096 | // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then | ||||
| 5097 | // the remaining arguments. | ||||
| 5098 | // Using constant offset within the va_arg TLS array allows fast copy | ||||
| 5099 | // in the finalize instrumentation. | ||||
| 5100 | void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { | ||||
| 5101 | unsigned GrOffset = AArch64GrBegOffset; | ||||
| 5102 | unsigned VrOffset = AArch64VrBegOffset; | ||||
| 5103 | unsigned OverflowOffset = AArch64VAEndOffset; | ||||
| 5104 | |||||
| 5105 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 5106 | for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) { | ||||
| 5107 | bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); | ||||
| |||||
| 5108 | ArgKind AK = classifyArgument(A); | ||||
| 5109 | if (AK
| ||||
| 5110 | AK = AK_Memory; | ||||
| 5111 | if (AK
| ||||
| 5112 | AK = AK_Memory; | ||||
| 5113 | Value *Base; | ||||
| 5114 | switch (AK) { | ||||
| 5115 | case AK_GeneralPurpose: | ||||
| 5116 | Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset, 8); | ||||
| 5117 | GrOffset += 8; | ||||
| 5118 | break; | ||||
| 5119 | case AK_FloatingPoint: | ||||
| 5120 | Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset, 8); | ||||
| 5121 | VrOffset += 16; | ||||
| 5122 | break; | ||||
| 5123 | case AK_Memory: | ||||
| 5124 | // Don't count fixed arguments in the overflow area - va_start will | ||||
| 5125 | // skip right over them. | ||||
| 5126 | if (IsFixed) | ||||
| 5127 | continue; | ||||
| 5128 | uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); | ||||
| 5129 | Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset, | ||||
| 5130 | alignTo(ArgSize, 8)); | ||||
| 5131 | OverflowOffset += alignTo(ArgSize, 8); | ||||
| 5132 | break; | ||||
| 5133 | } | ||||
| 5134 | // Count Gp/Vr fixed arguments to their respective offsets, but don't | ||||
| 5135 | // bother to actually store a shadow. | ||||
| 5136 | if (IsFixed
| ||||
| 5137 | continue; | ||||
| 5138 | if (!Base) | ||||
| 5139 | continue; | ||||
| 5140 | IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); | ||||
| 5141 | } | ||||
| 5142 | Constant *OverflowSize = | ||||
| 5143 | ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset); | ||||
| 5144 | IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); | ||||
| 5145 | } | ||||
| 5146 | |||||
| 5147 | /// Compute the shadow address for a given va_arg. | ||||
| 5148 | Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, | ||||
| 5149 | unsigned ArgOffset, unsigned ArgSize) { | ||||
| 5150 | // Make sure we don't overflow __msan_va_arg_tls. | ||||
| 5151 | if (ArgOffset + ArgSize > kParamTLSSize) | ||||
| 5152 | return nullptr; | ||||
| 5153 | Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); | ||||
| 5154 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 5155 | return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), | ||||
| 5156 | "_msarg"); | ||||
| 5157 | } | ||||
| 5158 | |||||
| 5159 | void visitVAStartInst(VAStartInst &I) override { | ||||
| 5160 | IRBuilder<> IRB(&I); | ||||
| 5161 | VAStartInstrumentationList.push_back(&I); | ||||
| 5162 | Value *VAListTag = I.getArgOperand(0); | ||||
| 5163 | Value *ShadowPtr, *OriginPtr; | ||||
| 5164 | const Align Alignment = Align(8); | ||||
| 5165 | std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( | ||||
| 5166 | VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); | ||||
| 5167 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5168 | /* size */ 32, Alignment, false); | ||||
| 5169 | } | ||||
| 5170 | |||||
| 5171 | void visitVACopyInst(VACopyInst &I) override { | ||||
| 5172 | IRBuilder<> IRB(&I); | ||||
| 5173 | VAStartInstrumentationList.push_back(&I); | ||||
| 5174 | Value *VAListTag = I.getArgOperand(0); | ||||
| 5175 | Value *ShadowPtr, *OriginPtr; | ||||
| 5176 | const Align Alignment = Align(8); | ||||
| 5177 | std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( | ||||
| 5178 | VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); | ||||
| 5179 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5180 | /* size */ 32, Alignment, false); | ||||
| 5181 | } | ||||
| 5182 | |||||
| 5183 | // Retrieve a va_list field of 'void*' size. | ||||
| 5184 | Value *getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) { | ||||
| 5185 | Value *SaveAreaPtrPtr = IRB.CreateIntToPtr( | ||||
| 5186 | IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 5187 | ConstantInt::get(MS.IntptrTy, offset)), | ||||
| 5188 | Type::getInt64PtrTy(*MS.C)); | ||||
| 5189 | return IRB.CreateLoad(Type::getInt64Ty(*MS.C), SaveAreaPtrPtr); | ||||
| 5190 | } | ||||
| 5191 | |||||
| 5192 | // Retrieve a va_list field of 'int' size. | ||||
| 5193 | Value *getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) { | ||||
| 5194 | Value *SaveAreaPtr = IRB.CreateIntToPtr( | ||||
| 5195 | IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 5196 | ConstantInt::get(MS.IntptrTy, offset)), | ||||
| 5197 | Type::getInt32PtrTy(*MS.C)); | ||||
| 5198 | Value *SaveArea32 = IRB.CreateLoad(IRB.getInt32Ty(), SaveAreaPtr); | ||||
| 5199 | return IRB.CreateSExt(SaveArea32, MS.IntptrTy); | ||||
| 5200 | } | ||||
| 5201 | |||||
| 5202 | void finalizeInstrumentation() override { | ||||
| 5203 | assert(!VAArgOverflowSize && !VAArgTLSCopy &&(static_cast <bool> (!VAArgOverflowSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgOverflowSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5204 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 5204 | "finalizeInstrumentation called twice")(static_cast <bool> (!VAArgOverflowSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgOverflowSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5204 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 5205 | if (!VAStartInstrumentationList.empty()) { | ||||
| 5206 | // If there is a va_start in this function, make a backup copy of | ||||
| 5207 | // va_arg_tls somewhere in the function entry block. | ||||
| 5208 | IRBuilder<> IRB(MSV.FnPrologueEnd); | ||||
| 5209 | VAArgOverflowSize = | ||||
| 5210 | IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); | ||||
| 5211 | Value *CopySize = IRB.CreateAdd( | ||||
| 5212 | ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset), VAArgOverflowSize); | ||||
| 5213 | VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 5214 | VAArgTLSCopy->setAlignment(kShadowTLSAlignment); | ||||
| 5215 | IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5216 | CopySize, kShadowTLSAlignment, false); | ||||
| 5217 | |||||
| 5218 | Value *SrcSize = IRB.CreateBinaryIntrinsic( | ||||
| 5219 | Intrinsic::umin, CopySize, | ||||
| 5220 | ConstantInt::get(MS.IntptrTy, kParamTLSSize)); | ||||
| 5221 | IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS, | ||||
| 5222 | kShadowTLSAlignment, SrcSize); | ||||
| 5223 | } | ||||
| 5224 | |||||
| 5225 | Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize); | ||||
| 5226 | Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize); | ||||
| 5227 | |||||
| 5228 | // Instrument va_start, copy va_list shadow from the backup copy of | ||||
| 5229 | // the TLS contents. | ||||
| 5230 | for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { | ||||
| 5231 | CallInst *OrigInst = VAStartInstrumentationList[i]; | ||||
| 5232 | NextNodeIRBuilder IRB(OrigInst); | ||||
| 5233 | |||||
| 5234 | Value *VAListTag = OrigInst->getArgOperand(0); | ||||
| 5235 | |||||
| 5236 | // The variadic ABI for AArch64 creates two areas to save the incoming | ||||
| 5237 | // argument registers (one for 64-bit general register xn-x7 and another | ||||
| 5238 | // for 128-bit FP/SIMD vn-v7). | ||||
| 5239 | // We need then to propagate the shadow arguments on both regions | ||||
| 5240 | // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'. | ||||
| 5241 | // The remaining arguments are saved on shadow for 'va::stack'. | ||||
| 5242 | // One caveat is it requires only to propagate the non-named arguments, | ||||
| 5243 | // however on the call site instrumentation 'all' the arguments are | ||||
| 5244 | // saved. So to copy the shadow values from the va_arg TLS array | ||||
| 5245 | // we need to adjust the offset for both GR and VR fields based on | ||||
| 5246 | // the __{gr,vr}_offs value (since they are stores based on incoming | ||||
| 5247 | // named arguments). | ||||
| 5248 | |||||
| 5249 | // Read the stack pointer from the va_list. | ||||
| 5250 | Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0); | ||||
| 5251 | |||||
| 5252 | // Read both the __gr_top and __gr_off and add them up. | ||||
| 5253 | Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8); | ||||
| 5254 | Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24); | ||||
| 5255 | |||||
| 5256 | Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea); | ||||
| 5257 | |||||
| 5258 | // Read both the __vr_top and __vr_off and add them up. | ||||
| 5259 | Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16); | ||||
| 5260 | Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28); | ||||
| 5261 | |||||
| 5262 | Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea); | ||||
| 5263 | |||||
| 5264 | // It does not know how many named arguments is being used and, on the | ||||
| 5265 | // callsite all the arguments were saved. Since __gr_off is defined as | ||||
| 5266 | // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic | ||||
| 5267 | // argument by ignoring the bytes of shadow from named arguments. | ||||
| 5268 | Value *GrRegSaveAreaShadowPtrOff = | ||||
| 5269 | IRB.CreateAdd(GrArgSize, GrOffSaveArea); | ||||
| 5270 | |||||
| 5271 | Value *GrRegSaveAreaShadowPtr = | ||||
| 5272 | MSV.getShadowOriginPtr(GrRegSaveAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 5273 | Align(8), /*isStore*/ true) | ||||
| 5274 | .first; | ||||
| 5275 | |||||
| 5276 | Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy, | ||||
| 5277 | GrRegSaveAreaShadowPtrOff); | ||||
| 5278 | Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff); | ||||
| 5279 | |||||
| 5280 | IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, Align(8), GrSrcPtr, Align(8), | ||||
| 5281 | GrCopySize); | ||||
| 5282 | |||||
| 5283 | // Again, but for FP/SIMD values. | ||||
| 5284 | Value *VrRegSaveAreaShadowPtrOff = | ||||
| 5285 | IRB.CreateAdd(VrArgSize, VrOffSaveArea); | ||||
| 5286 | |||||
| 5287 | Value *VrRegSaveAreaShadowPtr = | ||||
| 5288 | MSV.getShadowOriginPtr(VrRegSaveAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 5289 | Align(8), /*isStore*/ true) | ||||
| 5290 | .first; | ||||
| 5291 | |||||
| 5292 | Value *VrSrcPtr = IRB.CreateInBoundsGEP( | ||||
| 5293 | IRB.getInt8Ty(), | ||||
| 5294 | IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy, | ||||
| 5295 | IRB.getInt32(AArch64VrBegOffset)), | ||||
| 5296 | VrRegSaveAreaShadowPtrOff); | ||||
| 5297 | Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff); | ||||
| 5298 | |||||
| 5299 | IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, Align(8), VrSrcPtr, Align(8), | ||||
| 5300 | VrCopySize); | ||||
| 5301 | |||||
| 5302 | // And finally for remaining arguments. | ||||
| 5303 | Value *StackSaveAreaShadowPtr = | ||||
| 5304 | MSV.getShadowOriginPtr(StackSaveAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 5305 | Align(16), /*isStore*/ true) | ||||
| 5306 | .first; | ||||
| 5307 | |||||
| 5308 | Value *StackSrcPtr = IRB.CreateInBoundsGEP( | ||||
| 5309 | IRB.getInt8Ty(), VAArgTLSCopy, IRB.getInt32(AArch64VAEndOffset)); | ||||
| 5310 | |||||
| 5311 | IRB.CreateMemCpy(StackSaveAreaShadowPtr, Align(16), StackSrcPtr, | ||||
| 5312 | Align(16), VAArgOverflowSize); | ||||
| 5313 | } | ||||
| 5314 | } | ||||
| 5315 | }; | ||||
| 5316 | |||||
| 5317 | /// PowerPC64-specific implementation of VarArgHelper. | ||||
| 5318 | struct VarArgPowerPC64Helper : public VarArgHelper { | ||||
| 5319 | Function &F; | ||||
| 5320 | MemorySanitizer &MS; | ||||
| 5321 | MemorySanitizerVisitor &MSV; | ||||
| 5322 | AllocaInst *VAArgTLSCopy = nullptr; | ||||
| 5323 | Value *VAArgSize = nullptr; | ||||
| 5324 | |||||
| 5325 | SmallVector<CallInst *, 16> VAStartInstrumentationList; | ||||
| 5326 | |||||
| 5327 | VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS, | ||||
| 5328 | MemorySanitizerVisitor &MSV) | ||||
| 5329 | : F(F), MS(MS), MSV(MSV) {} | ||||
| 5330 | |||||
| 5331 | void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { | ||||
| 5332 | // For PowerPC, we need to deal with alignment of stack arguments - | ||||
| 5333 | // they are mostly aligned to 8 bytes, but vectors and i128 arrays | ||||
| 5334 | // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes, | ||||
| 5335 | // For that reason, we compute current offset from stack pointer (which is | ||||
| 5336 | // always properly aligned), and offset for the first vararg, then subtract | ||||
| 5337 | // them. | ||||
| 5338 | unsigned VAArgBase; | ||||
| 5339 | Triple TargetTriple(F.getParent()->getTargetTriple()); | ||||
| 5340 | // Parameter save area starts at 48 bytes from frame pointer for ABIv1, | ||||
| 5341 | // and 32 bytes for ABIv2. This is usually determined by target | ||||
| 5342 | // endianness, but in theory could be overridden by function attribute. | ||||
| 5343 | if (TargetTriple.getArch() == Triple::ppc64) | ||||
| 5344 | VAArgBase = 48; | ||||
| 5345 | else | ||||
| 5346 | VAArgBase = 32; | ||||
| 5347 | unsigned VAArgOffset = VAArgBase; | ||||
| 5348 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 5349 | for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) { | ||||
| 5350 | bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); | ||||
| 5351 | bool IsByVal = CB.paramHasAttr(ArgNo, Attribute::ByVal); | ||||
| 5352 | if (IsByVal) { | ||||
| 5353 | assert(A->getType()->isPointerTy())(static_cast <bool> (A->getType()->isPointerTy()) ? void (0) : __assert_fail ("A->getType()->isPointerTy()" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5353 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 5354 | Type *RealTy = CB.getParamByValType(ArgNo); | ||||
| 5355 | uint64_t ArgSize = DL.getTypeAllocSize(RealTy); | ||||
| 5356 | Align ArgAlign = CB.getParamAlign(ArgNo).value_or(Align(8)); | ||||
| 5357 | if (ArgAlign < 8) | ||||
| 5358 | ArgAlign = Align(8); | ||||
| 5359 | VAArgOffset = alignTo(VAArgOffset, ArgAlign); | ||||
| 5360 | if (!IsFixed) { | ||||
| 5361 | Value *Base = getShadowPtrForVAArgument( | ||||
| 5362 | RealTy, IRB, VAArgOffset - VAArgBase, ArgSize); | ||||
| 5363 | if (Base) { | ||||
| 5364 | Value *AShadowPtr, *AOriginPtr; | ||||
| 5365 | std::tie(AShadowPtr, AOriginPtr) = | ||||
| 5366 | MSV.getShadowOriginPtr(A, IRB, IRB.getInt8Ty(), | ||||
| 5367 | kShadowTLSAlignment, /*isStore*/ false); | ||||
| 5368 | |||||
| 5369 | IRB.CreateMemCpy(Base, kShadowTLSAlignment, AShadowPtr, | ||||
| 5370 | kShadowTLSAlignment, ArgSize); | ||||
| 5371 | } | ||||
| 5372 | } | ||||
| 5373 | VAArgOffset += alignTo(ArgSize, Align(8)); | ||||
| 5374 | } else { | ||||
| 5375 | Value *Base; | ||||
| 5376 | uint64_t ArgSize = DL.getTypeAllocSize(A->getType()); | ||||
| 5377 | Align ArgAlign = Align(8); | ||||
| 5378 | if (A->getType()->isArrayTy()) { | ||||
| 5379 | // Arrays are aligned to element size, except for long double | ||||
| 5380 | // arrays, which are aligned to 8 bytes. | ||||
| 5381 | Type *ElementTy = A->getType()->getArrayElementType(); | ||||
| 5382 | if (!ElementTy->isPPC_FP128Ty()) | ||||
| 5383 | ArgAlign = Align(DL.getTypeAllocSize(ElementTy)); | ||||
| 5384 | } else if (A->getType()->isVectorTy()) { | ||||
| 5385 | // Vectors are naturally aligned. | ||||
| 5386 | ArgAlign = Align(ArgSize); | ||||
| 5387 | } | ||||
| 5388 | if (ArgAlign < 8) | ||||
| 5389 | ArgAlign = Align(8); | ||||
| 5390 | VAArgOffset = alignTo(VAArgOffset, ArgAlign); | ||||
| 5391 | if (DL.isBigEndian()) { | ||||
| 5392 | // Adjusting the shadow for argument with size < 8 to match the | ||||
| 5393 | // placement of bits in big endian system | ||||
| 5394 | if (ArgSize < 8) | ||||
| 5395 | VAArgOffset += (8 - ArgSize); | ||||
| 5396 | } | ||||
| 5397 | if (!IsFixed) { | ||||
| 5398 | Base = getShadowPtrForVAArgument(A->getType(), IRB, | ||||
| 5399 | VAArgOffset - VAArgBase, ArgSize); | ||||
| 5400 | if (Base) | ||||
| 5401 | IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment); | ||||
| 5402 | } | ||||
| 5403 | VAArgOffset += ArgSize; | ||||
| 5404 | VAArgOffset = alignTo(VAArgOffset, Align(8)); | ||||
| 5405 | } | ||||
| 5406 | if (IsFixed) | ||||
| 5407 | VAArgBase = VAArgOffset; | ||||
| 5408 | } | ||||
| 5409 | |||||
| 5410 | Constant *TotalVAArgSize = | ||||
| 5411 | ConstantInt::get(IRB.getInt64Ty(), VAArgOffset - VAArgBase); | ||||
| 5412 | // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of | ||||
| 5413 | // a new class member i.e. it is the total size of all VarArgs. | ||||
| 5414 | IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS); | ||||
| 5415 | } | ||||
| 5416 | |||||
| 5417 | /// Compute the shadow address for a given va_arg. | ||||
| 5418 | Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB, | ||||
| 5419 | unsigned ArgOffset, unsigned ArgSize) { | ||||
| 5420 | // Make sure we don't overflow __msan_va_arg_tls. | ||||
| 5421 | if (ArgOffset + ArgSize > kParamTLSSize) | ||||
| 5422 | return nullptr; | ||||
| 5423 | Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); | ||||
| 5424 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 5425 | return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0), | ||||
| 5426 | "_msarg"); | ||||
| 5427 | } | ||||
| 5428 | |||||
| 5429 | void visitVAStartInst(VAStartInst &I) override { | ||||
| 5430 | IRBuilder<> IRB(&I); | ||||
| 5431 | VAStartInstrumentationList.push_back(&I); | ||||
| 5432 | Value *VAListTag = I.getArgOperand(0); | ||||
| 5433 | Value *ShadowPtr, *OriginPtr; | ||||
| 5434 | const Align Alignment = Align(8); | ||||
| 5435 | std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( | ||||
| 5436 | VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); | ||||
| 5437 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5438 | /* size */ 8, Alignment, false); | ||||
| 5439 | } | ||||
| 5440 | |||||
| 5441 | void visitVACopyInst(VACopyInst &I) override { | ||||
| 5442 | IRBuilder<> IRB(&I); | ||||
| 5443 | Value *VAListTag = I.getArgOperand(0); | ||||
| 5444 | Value *ShadowPtr, *OriginPtr; | ||||
| 5445 | const Align Alignment = Align(8); | ||||
| 5446 | std::tie(ShadowPtr, OriginPtr) = MSV.getShadowOriginPtr( | ||||
| 5447 | VAListTag, IRB, IRB.getInt8Ty(), Alignment, /*isStore*/ true); | ||||
| 5448 | // Unpoison the whole __va_list_tag. | ||||
| 5449 | // FIXME: magic ABI constants. | ||||
| 5450 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5451 | /* size */ 8, Alignment, false); | ||||
| 5452 | } | ||||
| 5453 | |||||
| 5454 | void finalizeInstrumentation() override { | ||||
| 5455 | assert(!VAArgSize && !VAArgTLSCopy &&(static_cast <bool> (!VAArgSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5456 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 5456 | "finalizeInstrumentation called twice")(static_cast <bool> (!VAArgSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5456 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 5457 | IRBuilder<> IRB(MSV.FnPrologueEnd); | ||||
| 5458 | VAArgSize = IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); | ||||
| 5459 | Value *CopySize = | ||||
| 5460 | IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0), VAArgSize); | ||||
| 5461 | |||||
| 5462 | if (!VAStartInstrumentationList.empty()) { | ||||
| 5463 | // If there is a va_start in this function, make a backup copy of | ||||
| 5464 | // va_arg_tls somewhere in the function entry block. | ||||
| 5465 | |||||
| 5466 | VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 5467 | VAArgTLSCopy->setAlignment(kShadowTLSAlignment); | ||||
| 5468 | IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5469 | CopySize, kShadowTLSAlignment, false); | ||||
| 5470 | |||||
| 5471 | Value *SrcSize = IRB.CreateBinaryIntrinsic( | ||||
| 5472 | Intrinsic::umin, CopySize, | ||||
| 5473 | ConstantInt::get(MS.IntptrTy, kParamTLSSize)); | ||||
| 5474 | IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS, | ||||
| 5475 | kShadowTLSAlignment, SrcSize); | ||||
| 5476 | } | ||||
| 5477 | |||||
| 5478 | // Instrument va_start. | ||||
| 5479 | // Copy va_list shadow from the backup copy of the TLS contents. | ||||
| 5480 | for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) { | ||||
| 5481 | CallInst *OrigInst = VAStartInstrumentationList[i]; | ||||
| 5482 | NextNodeIRBuilder IRB(OrigInst); | ||||
| 5483 | Value *VAListTag = OrigInst->getArgOperand(0); | ||||
| 5484 | Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); | ||||
| 5485 | Value *RegSaveAreaPtrPtr = | ||||
| 5486 | IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 5487 | PointerType::get(RegSaveAreaPtrTy, 0)); | ||||
| 5488 | Value *RegSaveAreaPtr = | ||||
| 5489 | IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); | ||||
| 5490 | Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; | ||||
| 5491 | const Align Alignment = Align(8); | ||||
| 5492 | std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = | ||||
| 5493 | MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 5494 | Alignment, /*isStore*/ true); | ||||
| 5495 | IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, | ||||
| 5496 | CopySize); | ||||
| 5497 | } | ||||
| 5498 | } | ||||
| 5499 | }; | ||||
| 5500 | |||||
| 5501 | /// SystemZ-specific implementation of VarArgHelper. | ||||
| 5502 | struct VarArgSystemZHelper : public VarArgHelper { | ||||
| 5503 | static const unsigned SystemZGpOffset = 16; | ||||
| 5504 | static const unsigned SystemZGpEndOffset = 56; | ||||
| 5505 | static const unsigned SystemZFpOffset = 128; | ||||
| 5506 | static const unsigned SystemZFpEndOffset = 160; | ||||
| 5507 | static const unsigned SystemZMaxVrArgs = 8; | ||||
| 5508 | static const unsigned SystemZRegSaveAreaSize = 160; | ||||
| 5509 | static const unsigned SystemZOverflowOffset = 160; | ||||
| 5510 | static const unsigned SystemZVAListTagSize = 32; | ||||
| 5511 | static const unsigned SystemZOverflowArgAreaPtrOffset = 16; | ||||
| 5512 | static const unsigned SystemZRegSaveAreaPtrOffset = 24; | ||||
| 5513 | |||||
| 5514 | Function &F; | ||||
| 5515 | MemorySanitizer &MS; | ||||
| 5516 | MemorySanitizerVisitor &MSV; | ||||
| 5517 | bool IsSoftFloatABI; | ||||
| 5518 | AllocaInst *VAArgTLSCopy = nullptr; | ||||
| 5519 | AllocaInst *VAArgTLSOriginCopy = nullptr; | ||||
| 5520 | Value *VAArgOverflowSize = nullptr; | ||||
| 5521 | |||||
| 5522 | SmallVector<CallInst *, 16> VAStartInstrumentationList; | ||||
| 5523 | |||||
| 5524 | enum class ArgKind { | ||||
| 5525 | GeneralPurpose, | ||||
| 5526 | FloatingPoint, | ||||
| 5527 | Vector, | ||||
| 5528 | Memory, | ||||
| 5529 | Indirect, | ||||
| 5530 | }; | ||||
| 5531 | |||||
| 5532 | enum class ShadowExtension { None, Zero, Sign }; | ||||
| 5533 | |||||
| 5534 | VarArgSystemZHelper(Function &F, MemorySanitizer &MS, | ||||
| 5535 | MemorySanitizerVisitor &MSV) | ||||
| 5536 | : F(F), MS(MS), MSV(MSV), | ||||
| 5537 | IsSoftFloatABI(F.getFnAttribute("use-soft-float").getValueAsBool()) {} | ||||
| 5538 | |||||
| 5539 | ArgKind classifyArgument(Type *T) { | ||||
| 5540 | // T is a SystemZABIInfo::classifyArgumentType() output, and there are | ||||
| 5541 | // only a few possibilities of what it can be. In particular, enums, single | ||||
| 5542 | // element structs and large types have already been taken care of. | ||||
| 5543 | |||||
| 5544 | // Some i128 and fp128 arguments are converted to pointers only in the | ||||
| 5545 | // back end. | ||||
| 5546 | if (T->isIntegerTy(128) || T->isFP128Ty()) | ||||
| 5547 | return ArgKind::Indirect; | ||||
| 5548 | if (T->isFloatingPointTy()) | ||||
| 5549 | return IsSoftFloatABI ? ArgKind::GeneralPurpose : ArgKind::FloatingPoint; | ||||
| 5550 | if (T->isIntegerTy() || T->isPointerTy()) | ||||
| 5551 | return ArgKind::GeneralPurpose; | ||||
| 5552 | if (T->isVectorTy()) | ||||
| 5553 | return ArgKind::Vector; | ||||
| 5554 | return ArgKind::Memory; | ||||
| 5555 | } | ||||
| 5556 | |||||
| 5557 | ShadowExtension getShadowExtension(const CallBase &CB, unsigned ArgNo) { | ||||
| 5558 | // ABI says: "One of the simple integer types no more than 64 bits wide. | ||||
| 5559 | // ... If such an argument is shorter than 64 bits, replace it by a full | ||||
| 5560 | // 64-bit integer representing the same number, using sign or zero | ||||
| 5561 | // extension". Shadow for an integer argument has the same type as the | ||||
| 5562 | // argument itself, so it can be sign or zero extended as well. | ||||
| 5563 | bool ZExt = CB.paramHasAttr(ArgNo, Attribute::ZExt); | ||||
| 5564 | bool SExt = CB.paramHasAttr(ArgNo, Attribute::SExt); | ||||
| 5565 | if (ZExt) { | ||||
| 5566 | assert(!SExt)(static_cast <bool> (!SExt) ? void (0) : __assert_fail ( "!SExt", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 5566, __extension__ __PRETTY_FUNCTION__)); | ||||
| 5567 | return ShadowExtension::Zero; | ||||
| 5568 | } | ||||
| 5569 | if (SExt) { | ||||
| 5570 | assert(!ZExt)(static_cast <bool> (!ZExt) ? void (0) : __assert_fail ( "!ZExt", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 5570, __extension__ __PRETTY_FUNCTION__)); | ||||
| 5571 | return ShadowExtension::Sign; | ||||
| 5572 | } | ||||
| 5573 | return ShadowExtension::None; | ||||
| 5574 | } | ||||
| 5575 | |||||
| 5576 | void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override { | ||||
| 5577 | unsigned GpOffset = SystemZGpOffset; | ||||
| 5578 | unsigned FpOffset = SystemZFpOffset; | ||||
| 5579 | unsigned VrIndex = 0; | ||||
| 5580 | unsigned OverflowOffset = SystemZOverflowOffset; | ||||
| 5581 | const DataLayout &DL = F.getParent()->getDataLayout(); | ||||
| 5582 | for (const auto &[ArgNo, A] : llvm::enumerate(CB.args())) { | ||||
| 5583 | bool IsFixed = ArgNo < CB.getFunctionType()->getNumParams(); | ||||
| 5584 | // SystemZABIInfo does not produce ByVal parameters. | ||||
| 5585 | assert(!CB.paramHasAttr(ArgNo, Attribute::ByVal))(static_cast <bool> (!CB.paramHasAttr(ArgNo, Attribute:: ByVal)) ? void (0) : __assert_fail ("!CB.paramHasAttr(ArgNo, Attribute::ByVal)" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5585 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 5586 | Type *T = A->getType(); | ||||
| 5587 | ArgKind AK = classifyArgument(T); | ||||
| 5588 | if (AK == ArgKind::Indirect) { | ||||
| 5589 | T = PointerType::get(T, 0); | ||||
| 5590 | AK = ArgKind::GeneralPurpose; | ||||
| 5591 | } | ||||
| 5592 | if (AK == ArgKind::GeneralPurpose && GpOffset >= SystemZGpEndOffset) | ||||
| 5593 | AK = ArgKind::Memory; | ||||
| 5594 | if (AK == ArgKind::FloatingPoint && FpOffset >= SystemZFpEndOffset) | ||||
| 5595 | AK = ArgKind::Memory; | ||||
| 5596 | if (AK == ArgKind::Vector && (VrIndex >= SystemZMaxVrArgs || !IsFixed)) | ||||
| 5597 | AK = ArgKind::Memory; | ||||
| 5598 | Value *ShadowBase = nullptr; | ||||
| 5599 | Value *OriginBase = nullptr; | ||||
| 5600 | ShadowExtension SE = ShadowExtension::None; | ||||
| 5601 | switch (AK) { | ||||
| 5602 | case ArgKind::GeneralPurpose: { | ||||
| 5603 | // Always keep track of GpOffset, but store shadow only for varargs. | ||||
| 5604 | uint64_t ArgSize = 8; | ||||
| 5605 | if (GpOffset + ArgSize <= kParamTLSSize) { | ||||
| 5606 | if (!IsFixed) { | ||||
| 5607 | SE = getShadowExtension(CB, ArgNo); | ||||
| 5608 | uint64_t GapSize = 0; | ||||
| 5609 | if (SE == ShadowExtension::None) { | ||||
| 5610 | uint64_t ArgAllocSize = DL.getTypeAllocSize(T); | ||||
| 5611 | assert(ArgAllocSize <= ArgSize)(static_cast <bool> (ArgAllocSize <= ArgSize) ? void (0) : __assert_fail ("ArgAllocSize <= ArgSize", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 5611, __extension__ __PRETTY_FUNCTION__)); | ||||
| 5612 | GapSize = ArgSize - ArgAllocSize; | ||||
| 5613 | } | ||||
| 5614 | ShadowBase = getShadowAddrForVAArgument(IRB, GpOffset + GapSize); | ||||
| 5615 | if (MS.TrackOrigins) | ||||
| 5616 | OriginBase = getOriginPtrForVAArgument(IRB, GpOffset + GapSize); | ||||
| 5617 | } | ||||
| 5618 | GpOffset += ArgSize; | ||||
| 5619 | } else { | ||||
| 5620 | GpOffset = kParamTLSSize; | ||||
| 5621 | } | ||||
| 5622 | break; | ||||
| 5623 | } | ||||
| 5624 | case ArgKind::FloatingPoint: { | ||||
| 5625 | // Always keep track of FpOffset, but store shadow only for varargs. | ||||
| 5626 | uint64_t ArgSize = 8; | ||||
| 5627 | if (FpOffset + ArgSize <= kParamTLSSize) { | ||||
| 5628 | if (!IsFixed) { | ||||
| 5629 | // PoP says: "A short floating-point datum requires only the | ||||
| 5630 | // left-most 32 bit positions of a floating-point register". | ||||
| 5631 | // Therefore, in contrast to AK_GeneralPurpose and AK_Memory, | ||||
| 5632 | // don't extend shadow and don't mind the gap. | ||||
| 5633 | ShadowBase = getShadowAddrForVAArgument(IRB, FpOffset); | ||||
| 5634 | if (MS.TrackOrigins) | ||||
| 5635 | OriginBase = getOriginPtrForVAArgument(IRB, FpOffset); | ||||
| 5636 | } | ||||
| 5637 | FpOffset += ArgSize; | ||||
| 5638 | } else { | ||||
| 5639 | FpOffset = kParamTLSSize; | ||||
| 5640 | } | ||||
| 5641 | break; | ||||
| 5642 | } | ||||
| 5643 | case ArgKind::Vector: { | ||||
| 5644 | // Keep track of VrIndex. No need to store shadow, since vector varargs | ||||
| 5645 | // go through AK_Memory. | ||||
| 5646 | assert(IsFixed)(static_cast <bool> (IsFixed) ? void (0) : __assert_fail ("IsFixed", "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp" , 5646, __extension__ __PRETTY_FUNCTION__)); | ||||
| 5647 | VrIndex++; | ||||
| 5648 | break; | ||||
| 5649 | } | ||||
| 5650 | case ArgKind::Memory: { | ||||
| 5651 | // Keep track of OverflowOffset and store shadow only for varargs. | ||||
| 5652 | // Ignore fixed args, since we need to copy only the vararg portion of | ||||
| 5653 | // the overflow area shadow. | ||||
| 5654 | if (!IsFixed) { | ||||
| 5655 | uint64_t ArgAllocSize = DL.getTypeAllocSize(T); | ||||
| 5656 | uint64_t ArgSize = alignTo(ArgAllocSize, 8); | ||||
| 5657 | if (OverflowOffset + ArgSize <= kParamTLSSize) { | ||||
| 5658 | SE = getShadowExtension(CB, ArgNo); | ||||
| 5659 | uint64_t GapSize = | ||||
| 5660 | SE == ShadowExtension::None ? ArgSize - ArgAllocSize : 0; | ||||
| 5661 | ShadowBase = | ||||
| 5662 | getShadowAddrForVAArgument(IRB, OverflowOffset + GapSize); | ||||
| 5663 | if (MS.TrackOrigins) | ||||
| 5664 | OriginBase = | ||||
| 5665 | getOriginPtrForVAArgument(IRB, OverflowOffset + GapSize); | ||||
| 5666 | OverflowOffset += ArgSize; | ||||
| 5667 | } else { | ||||
| 5668 | OverflowOffset = kParamTLSSize; | ||||
| 5669 | } | ||||
| 5670 | } | ||||
| 5671 | break; | ||||
| 5672 | } | ||||
| 5673 | case ArgKind::Indirect: | ||||
| 5674 | llvm_unreachable("Indirect must be converted to GeneralPurpose")::llvm::llvm_unreachable_internal("Indirect must be converted to GeneralPurpose" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5674 ); | ||||
| 5675 | } | ||||
| 5676 | if (ShadowBase == nullptr) | ||||
| 5677 | continue; | ||||
| 5678 | Value *Shadow = MSV.getShadow(A); | ||||
| 5679 | if (SE != ShadowExtension::None) | ||||
| 5680 | Shadow = MSV.CreateShadowCast(IRB, Shadow, IRB.getInt64Ty(), | ||||
| 5681 | /*Signed*/ SE == ShadowExtension::Sign); | ||||
| 5682 | ShadowBase = IRB.CreateIntToPtr( | ||||
| 5683 | ShadowBase, PointerType::get(Shadow->getType(), 0), "_msarg_va_s"); | ||||
| 5684 | IRB.CreateStore(Shadow, ShadowBase); | ||||
| 5685 | if (MS.TrackOrigins) { | ||||
| 5686 | Value *Origin = MSV.getOrigin(A); | ||||
| 5687 | TypeSize StoreSize = DL.getTypeStoreSize(Shadow->getType()); | ||||
| 5688 | MSV.paintOrigin(IRB, Origin, OriginBase, StoreSize, | ||||
| 5689 | kMinOriginAlignment); | ||||
| 5690 | } | ||||
| 5691 | } | ||||
| 5692 | Constant *OverflowSize = ConstantInt::get( | ||||
| 5693 | IRB.getInt64Ty(), OverflowOffset - SystemZOverflowOffset); | ||||
| 5694 | IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS); | ||||
| 5695 | } | ||||
| 5696 | |||||
| 5697 | Value *getShadowAddrForVAArgument(IRBuilder<> &IRB, unsigned ArgOffset) { | ||||
| 5698 | Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy); | ||||
| 5699 | return IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 5700 | } | ||||
| 5701 | |||||
| 5702 | Value *getOriginPtrForVAArgument(IRBuilder<> &IRB, int ArgOffset) { | ||||
| 5703 | Value *Base = IRB.CreatePointerCast(MS.VAArgOriginTLS, MS.IntptrTy); | ||||
| 5704 | Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset)); | ||||
| 5705 | return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0), | ||||
| 5706 | "_msarg_va_o"); | ||||
| 5707 | } | ||||
| 5708 | |||||
| 5709 | void unpoisonVAListTagForInst(IntrinsicInst &I) { | ||||
| 5710 | IRBuilder<> IRB(&I); | ||||
| 5711 | Value *VAListTag = I.getArgOperand(0); | ||||
| 5712 | Value *ShadowPtr, *OriginPtr; | ||||
| 5713 | const Align Alignment = Align(8); | ||||
| 5714 | std::tie(ShadowPtr, OriginPtr) = | ||||
| 5715 | MSV.getShadowOriginPtr(VAListTag, IRB, IRB.getInt8Ty(), Alignment, | ||||
| 5716 | /*isStore*/ true); | ||||
| 5717 | IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5718 | SystemZVAListTagSize, Alignment, false); | ||||
| 5719 | } | ||||
| 5720 | |||||
| 5721 | void visitVAStartInst(VAStartInst &I) override { | ||||
| 5722 | VAStartInstrumentationList.push_back(&I); | ||||
| 5723 | unpoisonVAListTagForInst(I); | ||||
| 5724 | } | ||||
| 5725 | |||||
| 5726 | void visitVACopyInst(VACopyInst &I) override { unpoisonVAListTagForInst(I); } | ||||
| 5727 | |||||
| 5728 | void copyRegSaveArea(IRBuilder<> &IRB, Value *VAListTag) { | ||||
| 5729 | Type *RegSaveAreaPtrTy = Type::getInt64PtrTy(*MS.C); | ||||
| 5730 | Value *RegSaveAreaPtrPtr = IRB.CreateIntToPtr( | ||||
| 5731 | IRB.CreateAdd( | ||||
| 5732 | IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 5733 | ConstantInt::get(MS.IntptrTy, SystemZRegSaveAreaPtrOffset)), | ||||
| 5734 | PointerType::get(RegSaveAreaPtrTy, 0)); | ||||
| 5735 | Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrTy, RegSaveAreaPtrPtr); | ||||
| 5736 | Value *RegSaveAreaShadowPtr, *RegSaveAreaOriginPtr; | ||||
| 5737 | const Align Alignment = Align(8); | ||||
| 5738 | std::tie(RegSaveAreaShadowPtr, RegSaveAreaOriginPtr) = | ||||
| 5739 | MSV.getShadowOriginPtr(RegSaveAreaPtr, IRB, IRB.getInt8Ty(), Alignment, | ||||
| 5740 | /*isStore*/ true); | ||||
| 5741 | // TODO(iii): copy only fragments filled by visitCallBase() | ||||
| 5742 | // TODO(iii): support packed-stack && !use-soft-float | ||||
| 5743 | // For use-soft-float functions, it is enough to copy just the GPRs. | ||||
| 5744 | unsigned RegSaveAreaSize = | ||||
| 5745 | IsSoftFloatABI ? SystemZGpEndOffset : SystemZRegSaveAreaSize; | ||||
| 5746 | IRB.CreateMemCpy(RegSaveAreaShadowPtr, Alignment, VAArgTLSCopy, Alignment, | ||||
| 5747 | RegSaveAreaSize); | ||||
| 5748 | if (MS.TrackOrigins) | ||||
| 5749 | IRB.CreateMemCpy(RegSaveAreaOriginPtr, Alignment, VAArgTLSOriginCopy, | ||||
| 5750 | Alignment, RegSaveAreaSize); | ||||
| 5751 | } | ||||
| 5752 | |||||
| 5753 | void copyOverflowArea(IRBuilder<> &IRB, Value *VAListTag) { | ||||
| 5754 | Type *OverflowArgAreaPtrTy = Type::getInt64PtrTy(*MS.C); | ||||
| 5755 | Value *OverflowArgAreaPtrPtr = IRB.CreateIntToPtr( | ||||
| 5756 | IRB.CreateAdd( | ||||
| 5757 | IRB.CreatePtrToInt(VAListTag, MS.IntptrTy), | ||||
| 5758 | ConstantInt::get(MS.IntptrTy, SystemZOverflowArgAreaPtrOffset)), | ||||
| 5759 | PointerType::get(OverflowArgAreaPtrTy, 0)); | ||||
| 5760 | Value *OverflowArgAreaPtr = | ||||
| 5761 | IRB.CreateLoad(OverflowArgAreaPtrTy, OverflowArgAreaPtrPtr); | ||||
| 5762 | Value *OverflowArgAreaShadowPtr, *OverflowArgAreaOriginPtr; | ||||
| 5763 | const Align Alignment = Align(8); | ||||
| 5764 | std::tie(OverflowArgAreaShadowPtr, OverflowArgAreaOriginPtr) = | ||||
| 5765 | MSV.getShadowOriginPtr(OverflowArgAreaPtr, IRB, IRB.getInt8Ty(), | ||||
| 5766 | Alignment, /*isStore*/ true); | ||||
| 5767 | Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy, | ||||
| 5768 | SystemZOverflowOffset); | ||||
| 5769 | IRB.CreateMemCpy(OverflowArgAreaShadowPtr, Alignment, SrcPtr, Alignment, | ||||
| 5770 | VAArgOverflowSize); | ||||
| 5771 | if (MS.TrackOrigins) { | ||||
| 5772 | SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSOriginCopy, | ||||
| 5773 | SystemZOverflowOffset); | ||||
| 5774 | IRB.CreateMemCpy(OverflowArgAreaOriginPtr, Alignment, SrcPtr, Alignment, | ||||
| 5775 | VAArgOverflowSize); | ||||
| 5776 | } | ||||
| 5777 | } | ||||
| 5778 | |||||
| 5779 | void finalizeInstrumentation() override { | ||||
| 5780 | assert(!VAArgOverflowSize && !VAArgTLSCopy &&(static_cast <bool> (!VAArgOverflowSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgOverflowSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5781 , __extension__ __PRETTY_FUNCTION__)) | ||||
| 5781 | "finalizeInstrumentation called twice")(static_cast <bool> (!VAArgOverflowSize && !VAArgTLSCopy && "finalizeInstrumentation called twice") ? void (0 ) : __assert_fail ("!VAArgOverflowSize && !VAArgTLSCopy && \"finalizeInstrumentation called twice\"" , "llvm/lib/Transforms/Instrumentation/MemorySanitizer.cpp", 5781 , __extension__ __PRETTY_FUNCTION__)); | ||||
| 5782 | if (!VAStartInstrumentationList.empty()) { | ||||
| 5783 | // If there is a va_start in this function, make a backup copy of | ||||
| 5784 | // va_arg_tls somewhere in the function entry block. | ||||
| 5785 | IRBuilder<> IRB(MSV.FnPrologueEnd); | ||||
| 5786 | VAArgOverflowSize = | ||||
| 5787 | IRB.CreateLoad(IRB.getInt64Ty(), MS.VAArgOverflowSizeTLS); | ||||
| 5788 | Value *CopySize = | ||||
| 5789 | IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, SystemZOverflowOffset), | ||||
| 5790 | VAArgOverflowSize); | ||||
| 5791 | VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 5792 | VAArgTLSCopy->setAlignment(kShadowTLSAlignment); | ||||
| 5793 | IRB.CreateMemSet(VAArgTLSCopy, Constant::getNullValue(IRB.getInt8Ty()), | ||||
| 5794 | CopySize, kShadowTLSAlignment, false); | ||||
| 5795 | |||||
| 5796 | Value *SrcSize = IRB.CreateBinaryIntrinsic( | ||||
| 5797 | Intrinsic::umin, CopySize, | ||||
| 5798 | ConstantInt::get(MS.IntptrTy, kParamTLSSize)); | ||||
| 5799 | IRB.CreateMemCpy(VAArgTLSCopy, kShadowTLSAlignment, MS.VAArgTLS, | ||||
| 5800 | kShadowTLSAlignment, SrcSize); | ||||
| 5801 | if (MS.TrackOrigins) { | ||||
| 5802 | VAArgTLSOriginCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize); | ||||
| 5803 | VAArgTLSOriginCopy->setAlignment(kShadowTLSAlignment); | ||||
| 5804 | IRB.CreateMemCpy(VAArgTLSOriginCopy, kShadowTLSAlignment, | ||||
| 5805 | MS.VAArgOriginTLS, kShadowTLSAlignment, SrcSize); | ||||
| 5806 | } | ||||
| 5807 | } | ||||
| 5808 | |||||
| 5809 | // Instrument va_start. | ||||
| 5810 | // Copy va_list shadow from the backup copy of the TLS contents. | ||||
| 5811 | for (size_t VaStartNo = 0, VaStartNum = VAStartInstrumentationList.size(); | ||||
| 5812 | VaStartNo < VaStartNum; VaStartNo++) { | ||||
| 5813 | CallInst *OrigInst = VAStartInstrumentationList[VaStartNo]; | ||||
| 5814 | NextNodeIRBuilder IRB(OrigInst); | ||||
| 5815 | Value *VAListTag = OrigInst->getArgOperand(0); | ||||
| 5816 | copyRegSaveArea(IRB, VAListTag); | ||||
| 5817 | copyOverflowArea(IRB, VAListTag); | ||||
| 5818 | } | ||||
| 5819 | } | ||||
| 5820 | }; | ||||
| 5821 | |||||
| 5822 | /// A no-op implementation of VarArgHelper. | ||||
| 5823 | struct VarArgNoOpHelper : public VarArgHelper { | ||||
| 5824 | VarArgNoOpHelper(Function &F, MemorySanitizer &MS, | ||||
| 5825 | MemorySanitizerVisitor &MSV) {} | ||||
| 5826 | |||||
| 5827 | void visitCallBase(CallBase &CB, IRBuilder<> &IRB) override {} | ||||
| 5828 | |||||
| 5829 | void visitVAStartInst(VAStartInst &I) override {} | ||||
| 5830 | |||||
| 5831 | void visitVACopyInst(VACopyInst &I) override {} | ||||
| 5832 | |||||
| 5833 | void finalizeInstrumentation() override {} | ||||
| 5834 | }; | ||||
| 5835 | |||||
| 5836 | } // end anonymous namespace | ||||
| 5837 | |||||
| 5838 | static VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan, | ||||
| 5839 | MemorySanitizerVisitor &Visitor) { | ||||
| 5840 | // VarArg handling is only implemented on AMD64. False positives are possible | ||||
| 5841 | // on other platforms. | ||||
| 5842 | Triple TargetTriple(Func.getParent()->getTargetTriple()); | ||||
| 5843 | if (TargetTriple.getArch() == Triple::x86_64) | ||||
| 5844 | return new VarArgAMD64Helper(Func, Msan, Visitor); | ||||
| 5845 | else if (TargetTriple.isMIPS64()) | ||||
| 5846 | return new VarArgMIPS64Helper(Func, Msan, Visitor); | ||||
| 5847 | else if (TargetTriple.getArch() == Triple::aarch64) | ||||
| 5848 | return new VarArgAArch64Helper(Func, Msan, Visitor); | ||||
| 5849 | else if (TargetTriple.getArch() == Triple::ppc64 || | ||||
| 5850 | TargetTriple.getArch() == Triple::ppc64le) | ||||
| 5851 | return new VarArgPowerPC64Helper(Func, Msan, Visitor); | ||||
| 5852 | else if (TargetTriple.getArch() == Triple::systemz) | ||||
| 5853 | return new VarArgSystemZHelper(Func, Msan, Visitor); | ||||
| 5854 | else | ||||
| 5855 | return new VarArgNoOpHelper(Func, Msan, Visitor); | ||||
| 5856 | } | ||||
| 5857 | |||||
| 5858 | bool MemorySanitizer::sanitizeFunction(Function &F, TargetLibraryInfo &TLI) { | ||||
| 5859 | if (!CompileKernel && F.getName() == kMsanModuleCtorName) | ||||
| 5860 | return false; | ||||
| 5861 | |||||
| 5862 | if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation)) | ||||
| 5863 | return false; | ||||
| 5864 | |||||
| 5865 | MemorySanitizerVisitor Visitor(F, *this, TLI); | ||||
| 5866 | |||||
| 5867 | // Clear out memory attributes. | ||||
| 5868 | AttributeMask B; | ||||
| 5869 | B.addAttribute(Attribute::Memory).addAttribute(Attribute::Speculatable); | ||||
| 5870 | F.removeFnAttrs(B); | ||||
| 5871 | |||||
| 5872 | return Visitor.runOnFunction(); | ||||
| 5873 | } |