LLVM 19.0.0git
AddressSanitizer.cpp
Go to the documentation of this file.
1//===- AddressSanitizer.cpp - memory error detector -----------------------===//
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// This file is a part of AddressSanitizer, an address basic correctness
10// checker.
11// Details of the algorithm:
12// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
13//
14// FIXME: This sanitizer does not yet handle scalable vectors
15//
16//===----------------------------------------------------------------------===//
17
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
35#include "llvm/IR/Argument.h"
36#include "llvm/IR/Attributes.h"
37#include "llvm/IR/BasicBlock.h"
38#include "llvm/IR/Comdat.h"
39#include "llvm/IR/Constant.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DIBuilder.h"
42#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DebugLoc.h"
47#include "llvm/IR/Function.h"
48#include "llvm/IR/GlobalAlias.h"
49#include "llvm/IR/GlobalValue.h"
51#include "llvm/IR/IRBuilder.h"
52#include "llvm/IR/InlineAsm.h"
53#include "llvm/IR/InstVisitor.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/LLVMContext.h"
60#include "llvm/IR/MDBuilder.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Module.h"
63#include "llvm/IR/Type.h"
64#include "llvm/IR/Use.h"
65#include "llvm/IR/Value.h"
69#include "llvm/Support/Debug.h"
82#include <algorithm>
83#include <cassert>
84#include <cstddef>
85#include <cstdint>
86#include <iomanip>
87#include <limits>
88#include <sstream>
89#include <string>
90#include <tuple>
91
92using namespace llvm;
93
94#define DEBUG_TYPE "asan"
95
97static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
98static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
100 std::numeric_limits<uint64_t>::max();
101static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
103static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
104static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
105static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
106static const uint64_t kMIPS_ShadowOffsetN32 = 1ULL << 29;
107static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
108static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
109static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
110static const uint64_t kLoongArch64_ShadowOffset64 = 1ULL << 46;
111static const uint64_t kRISCV64_ShadowOffset64 = 0xd55550000;
112static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
113static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
114static const uint64_t kFreeBSDAArch64_ShadowOffset64 = 1ULL << 47;
115static const uint64_t kFreeBSDKasan_ShadowOffset64 = 0xdffff7c000000000;
116static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
117static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
118static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
119static const uint64_t kPS_ShadowOffset64 = 1ULL << 40;
120static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
122
123// The shadow memory space is dynamically allocated.
125
126static const size_t kMinStackMallocSize = 1 << 6; // 64B
127static const size_t kMaxStackMallocSize = 1 << 16; // 64K
128static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
129static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
130
131const char kAsanModuleCtorName[] = "asan.module_ctor";
132const char kAsanModuleDtorName[] = "asan.module_dtor";
134// On Emscripten, the system needs more than one priorities for constructors.
136const char kAsanReportErrorTemplate[] = "__asan_report_";
137const char kAsanRegisterGlobalsName[] = "__asan_register_globals";
138const char kAsanUnregisterGlobalsName[] = "__asan_unregister_globals";
139const char kAsanRegisterImageGlobalsName[] = "__asan_register_image_globals";
141 "__asan_unregister_image_globals";
142const char kAsanRegisterElfGlobalsName[] = "__asan_register_elf_globals";
143const char kAsanUnregisterElfGlobalsName[] = "__asan_unregister_elf_globals";
144const char kAsanPoisonGlobalsName[] = "__asan_before_dynamic_init";
145const char kAsanUnpoisonGlobalsName[] = "__asan_after_dynamic_init";
146const char kAsanInitName[] = "__asan_init";
147const char kAsanVersionCheckNamePrefix[] = "__asan_version_mismatch_check_v";
148const char kAsanPtrCmp[] = "__sanitizer_ptr_cmp";
149const char kAsanPtrSub[] = "__sanitizer_ptr_sub";
150const char kAsanHandleNoReturnName[] = "__asan_handle_no_return";
151static const int kMaxAsanStackMallocSizeClass = 10;
152const char kAsanStackMallocNameTemplate[] = "__asan_stack_malloc_";
154 "__asan_stack_malloc_always_";
155const char kAsanStackFreeNameTemplate[] = "__asan_stack_free_";
156const char kAsanGenPrefix[] = "___asan_gen_";
157const char kODRGenPrefix[] = "__odr_asan_gen_";
158const char kSanCovGenPrefix[] = "__sancov_gen_";
159const char kAsanSetShadowPrefix[] = "__asan_set_shadow_";
160const char kAsanPoisonStackMemoryName[] = "__asan_poison_stack_memory";
161const char kAsanUnpoisonStackMemoryName[] = "__asan_unpoison_stack_memory";
162
163// ASan version script has __asan_* wildcard. Triple underscore prevents a
164// linker (gold) warning about attempting to export a local symbol.
165const char kAsanGlobalsRegisteredFlagName[] = "___asan_globals_registered";
166
168 "__asan_option_detect_stack_use_after_return";
169
171 "__asan_shadow_memory_dynamic_address";
172
173const char kAsanAllocaPoison[] = "__asan_alloca_poison";
174const char kAsanAllocasUnpoison[] = "__asan_allocas_unpoison";
175
176const char kAMDGPUAddressSharedName[] = "llvm.amdgcn.is.shared";
177const char kAMDGPUAddressPrivateName[] = "llvm.amdgcn.is.private";
178const char kAMDGPUBallotName[] = "llvm.amdgcn.ballot.i64";
179const char kAMDGPUUnreachableName[] = "llvm.amdgcn.unreachable";
180
181// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
182static const size_t kNumberOfAccessSizes = 5;
183
184static const uint64_t kAllocaRzSize = 32;
185
186// ASanAccessInfo implementation constants.
187constexpr size_t kCompileKernelShift = 0;
188constexpr size_t kCompileKernelMask = 0x1;
189constexpr size_t kAccessSizeIndexShift = 1;
190constexpr size_t kAccessSizeIndexMask = 0xf;
191constexpr size_t kIsWriteShift = 5;
192constexpr size_t kIsWriteMask = 0x1;
193
194// Command-line flags.
195
197 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
198 cl::Hidden, cl::init(false));
199
201 "asan-recover",
202 cl::desc("Enable recovery mode (continue-after-error)."),
203 cl::Hidden, cl::init(false));
204
206 "asan-guard-against-version-mismatch",
207 cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden,
208 cl::init(true));
209
210// This flag may need to be replaced with -f[no-]asan-reads.
211static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
212 cl::desc("instrument read instructions"),
213 cl::Hidden, cl::init(true));
214
216 "asan-instrument-writes", cl::desc("instrument write instructions"),
217 cl::Hidden, cl::init(true));
218
219static cl::opt<bool>
220 ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(true),
221 cl::Hidden, cl::desc("Use Stack Safety analysis results"),
223
225 "asan-instrument-atomics",
226 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
227 cl::init(true));
228
229static cl::opt<bool>
230 ClInstrumentByval("asan-instrument-byval",
231 cl::desc("instrument byval call arguments"), cl::Hidden,
232 cl::init(true));
233
235 "asan-always-slow-path",
236 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
237 cl::init(false));
238
240 "asan-force-dynamic-shadow",
241 cl::desc("Load shadow address into a local variable for each function"),
242 cl::Hidden, cl::init(false));
243
244static cl::opt<bool>
245 ClWithIfunc("asan-with-ifunc",
246 cl::desc("Access dynamic shadow through an ifunc global on "
247 "platforms that support this"),
248 cl::Hidden, cl::init(true));
249
251 "asan-with-ifunc-suppress-remat",
252 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
253 "it through inline asm in prologue."),
254 cl::Hidden, cl::init(true));
255
256// This flag limits the number of instructions to be instrumented
257// in any given BB. Normally, this should be set to unlimited (INT_MAX),
258// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
259// set it to 10000.
261 "asan-max-ins-per-bb", cl::init(10000),
262 cl::desc("maximal number of instructions to instrument in any given BB"),
263 cl::Hidden);
264
265// This flag may need to be replaced with -f[no]asan-stack.
266static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
267 cl::Hidden, cl::init(true));
269 "asan-max-inline-poisoning-size",
270 cl::desc(
271 "Inline shadow poisoning for blocks up to the given size in bytes."),
272 cl::Hidden, cl::init(64));
273
275 "asan-use-after-return",
276 cl::desc("Sets the mode of detection for stack-use-after-return."),
278 clEnumValN(AsanDetectStackUseAfterReturnMode::Never, "never",
279 "Never detect stack use after return."),
281 AsanDetectStackUseAfterReturnMode::Runtime, "runtime",
282 "Detect stack use after return if "
283 "binary flag 'ASAN_OPTIONS=detect_stack_use_after_return' is set."),
284 clEnumValN(AsanDetectStackUseAfterReturnMode::Always, "always",
285 "Always detect stack use after return.")),
286 cl::Hidden, cl::init(AsanDetectStackUseAfterReturnMode::Runtime));
287
288static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
289 cl::desc("Create redzones for byval "
290 "arguments (extra copy "
291 "required)"), cl::Hidden,
292 cl::init(true));
293
294static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
295 cl::desc("Check stack-use-after-scope"),
296 cl::Hidden, cl::init(false));
297
298// This flag may need to be replaced with -f[no]asan-globals.
299static cl::opt<bool> ClGlobals("asan-globals",
300 cl::desc("Handle global objects"), cl::Hidden,
301 cl::init(true));
302
303static cl::opt<bool> ClInitializers("asan-initialization-order",
304 cl::desc("Handle C++ initializer order"),
305 cl::Hidden, cl::init(true));
306
308 "asan-detect-invalid-pointer-pair",
309 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
310 cl::init(false));
311
313 "asan-detect-invalid-pointer-cmp",
314 cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden,
315 cl::init(false));
316
318 "asan-detect-invalid-pointer-sub",
319 cl::desc("Instrument - operations with pointer operands"), cl::Hidden,
320 cl::init(false));
321
323 "asan-realign-stack",
324 cl::desc("Realign stack to the value of this flag (power of two)"),
325 cl::Hidden, cl::init(32));
326
328 "asan-instrumentation-with-call-threshold",
329 cl::desc("If the function being instrumented contains more than "
330 "this number of memory accesses, use callbacks instead of "
331 "inline checks (-1 means never use callbacks)."),
332 cl::Hidden, cl::init(7000));
333
335 "asan-memory-access-callback-prefix",
336 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
337 cl::init("__asan_"));
338
340 "asan-kernel-mem-intrinsic-prefix",
341 cl::desc("Use prefix for memory intrinsics in KASAN mode"), cl::Hidden,
342 cl::init(false));
343
344static cl::opt<bool>
345 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
346 cl::desc("instrument dynamic allocas"),
347 cl::Hidden, cl::init(true));
348
350 "asan-skip-promotable-allocas",
351 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
352 cl::init(true));
353
355 "asan-constructor-kind",
356 cl::desc("Sets the ASan constructor kind"),
357 cl::values(clEnumValN(AsanCtorKind::None, "none", "No constructors"),
358 clEnumValN(AsanCtorKind::Global, "global",
359 "Use global constructors")),
360 cl::init(AsanCtorKind::Global), cl::Hidden);
361// These flags allow to change the shadow mapping.
362// The shadow mapping looks like
363// Shadow = (Mem >> scale) + offset
364
365static cl::opt<int> ClMappingScale("asan-mapping-scale",
366 cl::desc("scale of asan shadow mapping"),
367 cl::Hidden, cl::init(0));
368
370 ClMappingOffset("asan-mapping-offset",
371 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),
372 cl::Hidden, cl::init(0));
373
374// Optimization flags. Not user visible, used mostly for testing
375// and benchmarking the tool.
376
377static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
378 cl::Hidden, cl::init(true));
379
380static cl::opt<bool> ClOptimizeCallbacks("asan-optimize-callbacks",
381 cl::desc("Optimize callbacks"),
382 cl::Hidden, cl::init(false));
383
385 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
386 cl::Hidden, cl::init(true));
387
388static cl::opt<bool> ClOptGlobals("asan-opt-globals",
389 cl::desc("Don't instrument scalar globals"),
390 cl::Hidden, cl::init(true));
391
393 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
394 cl::Hidden, cl::init(false));
395
397 "asan-stack-dynamic-alloca",
398 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
399 cl::init(true));
400
402 "asan-force-experiment",
403 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
404 cl::init(0));
405
406static cl::opt<bool>
407 ClUsePrivateAlias("asan-use-private-alias",
408 cl::desc("Use private aliases for global variables"),
409 cl::Hidden, cl::init(true));
410
411static cl::opt<bool>
412 ClUseOdrIndicator("asan-use-odr-indicator",
413 cl::desc("Use odr indicators to improve ODR reporting"),
414 cl::Hidden, cl::init(true));
415
416static cl::opt<bool>
417 ClUseGlobalsGC("asan-globals-live-support",
418 cl::desc("Use linker features to support dead "
419 "code stripping of globals"),
420 cl::Hidden, cl::init(true));
421
422// This is on by default even though there is a bug in gold:
423// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
424static cl::opt<bool>
425 ClWithComdat("asan-with-comdat",
426 cl::desc("Place ASan constructors in comdat sections"),
427 cl::Hidden, cl::init(true));
428
430 "asan-destructor-kind",
431 cl::desc("Sets the ASan destructor kind. The default is to use the value "
432 "provided to the pass constructor"),
433 cl::values(clEnumValN(AsanDtorKind::None, "none", "No destructors"),
434 clEnumValN(AsanDtorKind::Global, "global",
435 "Use global destructors")),
436 cl::init(AsanDtorKind::Invalid), cl::Hidden);
437
438// Debug flags.
439
440static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
441 cl::init(0));
442
443static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
444 cl::Hidden, cl::init(0));
445
447 cl::desc("Debug func"));
448
449static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
450 cl::Hidden, cl::init(-1));
451
452static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
453 cl::Hidden, cl::init(-1));
454
455STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
456STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
457STATISTIC(NumOptimizedAccessesToGlobalVar,
458 "Number of optimized accesses to global vars");
459STATISTIC(NumOptimizedAccessesToStackVar,
460 "Number of optimized accesses to stack vars");
461
462namespace {
463
464/// This struct defines the shadow mapping using the rule:
465/// shadow = (mem >> Scale) ADD-or-OR Offset.
466/// If InGlobal is true, then
467/// extern char __asan_shadow[];
468/// shadow = (mem >> Scale) + &__asan_shadow
469struct ShadowMapping {
470 int Scale;
471 uint64_t Offset;
472 bool OrShadowOffset;
473 bool InGlobal;
474};
475
476} // end anonymous namespace
477
478static ShadowMapping getShadowMapping(const Triple &TargetTriple, int LongSize,
479 bool IsKasan) {
480 bool IsAndroid = TargetTriple.isAndroid();
481 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS() ||
482 TargetTriple.isDriverKit();
483 bool IsMacOS = TargetTriple.isMacOSX();
484 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
485 bool IsNetBSD = TargetTriple.isOSNetBSD();
486 bool IsPS = TargetTriple.isPS();
487 bool IsLinux = TargetTriple.isOSLinux();
488 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
489 TargetTriple.getArch() == Triple::ppc64le;
490 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
491 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
492 bool IsMIPSN32ABI = TargetTriple.getEnvironment() == Triple::GNUABIN32;
493 bool IsMIPS32 = TargetTriple.isMIPS32();
494 bool IsMIPS64 = TargetTriple.isMIPS64();
495 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
496 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64 ||
497 TargetTriple.getArch() == Triple::aarch64_be;
498 bool IsLoongArch64 = TargetTriple.isLoongArch64();
499 bool IsRISCV64 = TargetTriple.getArch() == Triple::riscv64;
500 bool IsWindows = TargetTriple.isOSWindows();
501 bool IsFuchsia = TargetTriple.isOSFuchsia();
502 bool IsEmscripten = TargetTriple.isOSEmscripten();
503 bool IsAMDGPU = TargetTriple.isAMDGPU();
504
505 ShadowMapping Mapping;
506
507 Mapping.Scale = kDefaultShadowScale;
508 if (ClMappingScale.getNumOccurrences() > 0) {
509 Mapping.Scale = ClMappingScale;
510 }
511
512 if (LongSize == 32) {
513 if (IsAndroid)
514 Mapping.Offset = kDynamicShadowSentinel;
515 else if (IsMIPSN32ABI)
516 Mapping.Offset = kMIPS_ShadowOffsetN32;
517 else if (IsMIPS32)
518 Mapping.Offset = kMIPS32_ShadowOffset32;
519 else if (IsFreeBSD)
520 Mapping.Offset = kFreeBSD_ShadowOffset32;
521 else if (IsNetBSD)
522 Mapping.Offset = kNetBSD_ShadowOffset32;
523 else if (IsIOS)
524 Mapping.Offset = kDynamicShadowSentinel;
525 else if (IsWindows)
526 Mapping.Offset = kWindowsShadowOffset32;
527 else if (IsEmscripten)
528 Mapping.Offset = kEmscriptenShadowOffset;
529 else
530 Mapping.Offset = kDefaultShadowOffset32;
531 } else { // LongSize == 64
532 // Fuchsia is always PIE, which means that the beginning of the address
533 // space is always available.
534 if (IsFuchsia)
535 Mapping.Offset = 0;
536 else if (IsPPC64)
537 Mapping.Offset = kPPC64_ShadowOffset64;
538 else if (IsSystemZ)
539 Mapping.Offset = kSystemZ_ShadowOffset64;
540 else if (IsFreeBSD && IsAArch64)
541 Mapping.Offset = kFreeBSDAArch64_ShadowOffset64;
542 else if (IsFreeBSD && !IsMIPS64) {
543 if (IsKasan)
544 Mapping.Offset = kFreeBSDKasan_ShadowOffset64;
545 else
546 Mapping.Offset = kFreeBSD_ShadowOffset64;
547 } else if (IsNetBSD) {
548 if (IsKasan)
549 Mapping.Offset = kNetBSDKasan_ShadowOffset64;
550 else
551 Mapping.Offset = kNetBSD_ShadowOffset64;
552 } else if (IsPS)
553 Mapping.Offset = kPS_ShadowOffset64;
554 else if (IsLinux && IsX86_64) {
555 if (IsKasan)
556 Mapping.Offset = kLinuxKasan_ShadowOffset64;
557 else
558 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
559 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
560 } else if (IsWindows && IsX86_64) {
561 Mapping.Offset = kWindowsShadowOffset64;
562 } else if (IsMIPS64)
563 Mapping.Offset = kMIPS64_ShadowOffset64;
564 else if (IsIOS)
565 Mapping.Offset = kDynamicShadowSentinel;
566 else if (IsMacOS && IsAArch64)
567 Mapping.Offset = kDynamicShadowSentinel;
568 else if (IsAArch64)
569 Mapping.Offset = kAArch64_ShadowOffset64;
570 else if (IsLoongArch64)
571 Mapping.Offset = kLoongArch64_ShadowOffset64;
572 else if (IsRISCV64)
573 Mapping.Offset = kRISCV64_ShadowOffset64;
574 else if (IsAMDGPU)
575 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
576 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
577 else
578 Mapping.Offset = kDefaultShadowOffset64;
579 }
580
582 Mapping.Offset = kDynamicShadowSentinel;
583 }
584
585 if (ClMappingOffset.getNumOccurrences() > 0) {
586 Mapping.Offset = ClMappingOffset;
587 }
588
589 // OR-ing shadow offset if more efficient (at least on x86) if the offset
590 // is a power of two, but on ppc64 and loongarch64 we have to use add since
591 // the shadow offset is not necessarily 1/8-th of the address space. On
592 // SystemZ, we could OR the constant in a single instruction, but it's more
593 // efficient to load it once and use indexed addressing.
594 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS &&
595 !IsRISCV64 && !IsLoongArch64 &&
596 !(Mapping.Offset & (Mapping.Offset - 1)) &&
597 Mapping.Offset != kDynamicShadowSentinel;
598 bool IsAndroidWithIfuncSupport =
599 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
600 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
601
602 return Mapping;
603}
604
605namespace llvm {
606void getAddressSanitizerParams(const Triple &TargetTriple, int LongSize,
607 bool IsKasan, uint64_t *ShadowBase,
608 int *MappingScale, bool *OrShadowOffset) {
609 auto Mapping = getShadowMapping(TargetTriple, LongSize, IsKasan);
610 *ShadowBase = Mapping.Offset;
611 *MappingScale = Mapping.Scale;
612 *OrShadowOffset = Mapping.OrShadowOffset;
613}
614
616 : Packed(Packed),
617 AccessSizeIndex((Packed >> kAccessSizeIndexShift) & kAccessSizeIndexMask),
618 IsWrite((Packed >> kIsWriteShift) & kIsWriteMask),
619 CompileKernel((Packed >> kCompileKernelShift) & kCompileKernelMask) {}
620
621ASanAccessInfo::ASanAccessInfo(bool IsWrite, bool CompileKernel,
622 uint8_t AccessSizeIndex)
623 : Packed((IsWrite << kIsWriteShift) +
624 (CompileKernel << kCompileKernelShift) +
625 (AccessSizeIndex << kAccessSizeIndexShift)),
626 AccessSizeIndex(AccessSizeIndex), IsWrite(IsWrite),
627 CompileKernel(CompileKernel) {}
628
629} // namespace llvm
630
631static uint64_t getRedzoneSizeForScale(int MappingScale) {
632 // Redzone used for stack and globals is at least 32 bytes.
633 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
634 return std::max(32U, 1U << MappingScale);
635}
636
638 if (TargetTriple.isOSEmscripten()) {
640 } else {
642 }
643}
644
645namespace {
646/// Helper RAII class to post-process inserted asan runtime calls during a
647/// pass on a single Function. Upon end of scope, detects and applies the
648/// required funclet OpBundle.
649class RuntimeCallInserter {
650 Function *OwnerFn = nullptr;
651 bool TrackInsertedCalls = false;
652 SmallVector<CallInst *> InsertedCalls;
653
654public:
655 RuntimeCallInserter(Function &Fn) : OwnerFn(&Fn) {
656 if (Fn.hasPersonalityFn()) {
657 auto Personality = classifyEHPersonality(Fn.getPersonalityFn());
658 if (isScopedEHPersonality(Personality))
659 TrackInsertedCalls = true;
660 }
661 }
662
663 ~RuntimeCallInserter() {
664 if (InsertedCalls.empty())
665 return;
666 assert(TrackInsertedCalls && "Calls were wrongly tracked");
667
669 for (CallInst *CI : InsertedCalls) {
670 BasicBlock *BB = CI->getParent();
671 assert(BB && "Instruction doesn't belong to a BasicBlock");
672 assert(BB->getParent() == OwnerFn &&
673 "Instruction doesn't belong to the expected Function!");
674
675 ColorVector &Colors = BlockColors[BB];
676 // funclet opbundles are only valid in monochromatic BBs.
677 // Note that unreachable BBs are seen as colorless by colorEHFunclets()
678 // and will be DCE'ed later.
679 if (Colors.empty())
680 continue;
681 if (Colors.size() != 1) {
682 OwnerFn->getContext().emitError(
683 "Instruction's BasicBlock is not monochromatic");
684 continue;
685 }
686
687 BasicBlock *Color = Colors.front();
688 Instruction *EHPad = Color->getFirstNonPHI();
689
690 if (EHPad && EHPad->isEHPad()) {
691 // Replace CI with a clone with an added funclet OperandBundle
692 OperandBundleDef OB("funclet", EHPad);
693 auto *NewCall =
695 NewCall->copyMetadata(*CI);
696 CI->replaceAllUsesWith(NewCall);
697 CI->eraseFromParent();
698 }
699 }
700 }
701
702 CallInst *createRuntimeCall(IRBuilder<> &IRB, FunctionCallee Callee,
703 ArrayRef<Value *> Args = {},
704 const Twine &Name = "") {
705 assert(IRB.GetInsertBlock()->getParent() == OwnerFn);
706
707 CallInst *Inst = IRB.CreateCall(Callee, Args, Name, nullptr);
708 if (TrackInsertedCalls)
709 InsertedCalls.push_back(Inst);
710 return Inst;
711 }
712};
713
714/// AddressSanitizer: instrument the code in module to find memory bugs.
715struct AddressSanitizer {
716 AddressSanitizer(Module &M, const StackSafetyGlobalInfo *SSGI,
717 int InstrumentationWithCallsThreshold,
718 uint32_t MaxInlinePoisoningSize, bool CompileKernel = false,
719 bool Recover = false, bool UseAfterScope = false,
720 AsanDetectStackUseAfterReturnMode UseAfterReturn =
721 AsanDetectStackUseAfterReturnMode::Runtime)
722 : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
723 : CompileKernel),
724 Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
725 UseAfterScope(UseAfterScope || ClUseAfterScope),
726 UseAfterReturn(ClUseAfterReturn.getNumOccurrences() ? ClUseAfterReturn
727 : UseAfterReturn),
728 SSGI(SSGI),
729 InstrumentationWithCallsThreshold(
730 ClInstrumentationWithCallsThreshold.getNumOccurrences() > 0
732 : InstrumentationWithCallsThreshold),
733 MaxInlinePoisoningSize(ClMaxInlinePoisoningSize.getNumOccurrences() > 0
735 : MaxInlinePoisoningSize) {
736 C = &(M.getContext());
737 DL = &M.getDataLayout();
738 LongSize = M.getDataLayout().getPointerSizeInBits();
739 IntptrTy = Type::getIntNTy(*C, LongSize);
740 PtrTy = PointerType::getUnqual(*C);
742 TargetTriple = Triple(M.getTargetTriple());
743
744 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
745
746 assert(this->UseAfterReturn != AsanDetectStackUseAfterReturnMode::Invalid);
747 }
748
749 TypeSize getAllocaSizeInBytes(const AllocaInst &AI) const {
750 return *AI.getAllocationSize(AI.getModule()->getDataLayout());
751 }
752
753 /// Check if we want (and can) handle this alloca.
754 bool isInterestingAlloca(const AllocaInst &AI);
755
756 bool ignoreAccess(Instruction *Inst, Value *Ptr);
757 void getInterestingMemoryOperands(
759
760 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
761 InterestingMemoryOperand &O, bool UseCalls,
762 const DataLayout &DL, RuntimeCallInserter &RTCI);
763 void instrumentPointerComparisonOrSubtraction(Instruction *I,
764 RuntimeCallInserter &RTCI);
765 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
766 Value *Addr, MaybeAlign Alignment,
767 uint32_t TypeStoreSize, bool IsWrite,
768 Value *SizeArgument, bool UseCalls, uint32_t Exp,
769 RuntimeCallInserter &RTCI);
770 Instruction *instrumentAMDGPUAddress(Instruction *OrigIns,
771 Instruction *InsertBefore, Value *Addr,
772 uint32_t TypeStoreSize, bool IsWrite,
773 Value *SizeArgument);
774 Instruction *genAMDGPUReportBlock(IRBuilder<> &IRB, Value *Cond,
775 bool Recover);
776 void instrumentUnusualSizeOrAlignment(Instruction *I,
777 Instruction *InsertBefore, Value *Addr,
778 TypeSize TypeStoreSize, bool IsWrite,
779 Value *SizeArgument, bool UseCalls,
780 uint32_t Exp,
781 RuntimeCallInserter &RTCI);
782 void instrumentMaskedLoadOrStore(AddressSanitizer *Pass, const DataLayout &DL,
783 Type *IntptrTy, Value *Mask, Value *EVL,
784 Value *Stride, Instruction *I, Value *Addr,
785 MaybeAlign Alignment, unsigned Granularity,
786 Type *OpType, bool IsWrite,
787 Value *SizeArgument, bool UseCalls,
788 uint32_t Exp, RuntimeCallInserter &RTCI);
789 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
790 Value *ShadowValue, uint32_t TypeStoreSize);
791 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
792 bool IsWrite, size_t AccessSizeIndex,
793 Value *SizeArgument, uint32_t Exp,
794 RuntimeCallInserter &RTCI);
795 void instrumentMemIntrinsic(MemIntrinsic *MI, RuntimeCallInserter &RTCI);
796 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
797 bool suppressInstrumentationSiteForDebug(int &Instrumented);
798 bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);
799 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
800 bool maybeInsertDynamicShadowAtFunctionEntry(Function &F);
801 void markEscapedLocalAllocas(Function &F);
802
803private:
804 friend struct FunctionStackPoisoner;
805
806 void initializeCallbacks(Module &M, const TargetLibraryInfo *TLI);
807
808 bool LooksLikeCodeInBug11395(Instruction *I);
809 bool GlobalIsLinkerInitialized(GlobalVariable *G);
810 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
811 TypeSize TypeStoreSize) const;
812
813 /// Helper to cleanup per-function state.
814 struct FunctionStateRAII {
815 AddressSanitizer *Pass;
816
817 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
818 assert(Pass->ProcessedAllocas.empty() &&
819 "last pass forgot to clear cache");
820 assert(!Pass->LocalDynamicShadow);
821 }
822
823 ~FunctionStateRAII() {
824 Pass->LocalDynamicShadow = nullptr;
825 Pass->ProcessedAllocas.clear();
826 }
827 };
828
829 LLVMContext *C;
830 const DataLayout *DL;
831 Triple TargetTriple;
832 int LongSize;
833 bool CompileKernel;
834 bool Recover;
835 bool UseAfterScope;
837 Type *IntptrTy;
838 Type *Int32Ty;
839 PointerType *PtrTy;
840 ShadowMapping Mapping;
841 FunctionCallee AsanHandleNoReturnFunc;
842 FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
843 Constant *AsanShadowGlobal;
844
845 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
846 FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];
847 FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
848
849 // These arrays is indexed by AccessIsWrite and Experiment.
850 FunctionCallee AsanErrorCallbackSized[2][2];
851 FunctionCallee AsanMemoryAccessCallbackSized[2][2];
852
853 FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;
854 Value *LocalDynamicShadow = nullptr;
855 const StackSafetyGlobalInfo *SSGI;
856 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
857
858 FunctionCallee AMDGPUAddressShared;
859 FunctionCallee AMDGPUAddressPrivate;
860 int InstrumentationWithCallsThreshold;
861 uint32_t MaxInlinePoisoningSize;
862};
863
864class ModuleAddressSanitizer {
865public:
866 ModuleAddressSanitizer(Module &M, bool InsertVersionCheck,
867 bool CompileKernel = false, bool Recover = false,
868 bool UseGlobalsGC = true, bool UseOdrIndicator = true,
869 AsanDtorKind DestructorKind = AsanDtorKind::Global,
870 AsanCtorKind ConstructorKind = AsanCtorKind::Global)
871 : CompileKernel(ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan
872 : CompileKernel),
873 InsertVersionCheck(ClInsertVersionCheck.getNumOccurrences() > 0
875 : InsertVersionCheck),
876 Recover(ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover),
877 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC && !this->CompileKernel),
878 // Enable aliases as they should have no downside with ODR indicators.
879 UsePrivateAlias(ClUsePrivateAlias.getNumOccurrences() > 0
881 : UseOdrIndicator),
882 UseOdrIndicator(ClUseOdrIndicator.getNumOccurrences() > 0
884 : UseOdrIndicator),
885 // Not a typo: ClWithComdat is almost completely pointless without
886 // ClUseGlobalsGC (because then it only works on modules without
887 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
888 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
889 // argument is designed as workaround. Therefore, disable both
890 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
891 // do globals-gc.
892 UseCtorComdat(UseGlobalsGC && ClWithComdat && !this->CompileKernel),
893 DestructorKind(DestructorKind),
894 ConstructorKind(ClConstructorKind.getNumOccurrences() > 0
896 : ConstructorKind) {
897 C = &(M.getContext());
898 int LongSize = M.getDataLayout().getPointerSizeInBits();
899 IntptrTy = Type::getIntNTy(*C, LongSize);
900 PtrTy = PointerType::getUnqual(*C);
901 TargetTriple = Triple(M.getTargetTriple());
902 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
903
904 if (ClOverrideDestructorKind != AsanDtorKind::Invalid)
905 this->DestructorKind = ClOverrideDestructorKind;
906 assert(this->DestructorKind != AsanDtorKind::Invalid);
907 }
908
909 bool instrumentModule(Module &);
910
911private:
912 void initializeCallbacks(Module &M);
913
914 void instrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
915 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
916 ArrayRef<GlobalVariable *> ExtendedGlobals,
917 ArrayRef<Constant *> MetadataInitializers);
918 void instrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
919 ArrayRef<GlobalVariable *> ExtendedGlobals,
920 ArrayRef<Constant *> MetadataInitializers,
921 const std::string &UniqueModuleId);
922 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
923 ArrayRef<GlobalVariable *> ExtendedGlobals,
924 ArrayRef<Constant *> MetadataInitializers);
925 void
926 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
927 ArrayRef<GlobalVariable *> ExtendedGlobals,
928 ArrayRef<Constant *> MetadataInitializers);
929
930 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
931 StringRef OriginalName);
932 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
933 StringRef InternalSuffix);
934 Instruction *CreateAsanModuleDtor(Module &M);
935
936 const GlobalVariable *getExcludedAliasedGlobal(const GlobalAlias &GA) const;
937 bool shouldInstrumentGlobal(GlobalVariable *G) const;
938 bool ShouldUseMachOGlobalsSection() const;
939 StringRef getGlobalMetadataSection() const;
940 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
941 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
942 uint64_t getMinRedzoneSizeForGlobal() const {
943 return getRedzoneSizeForScale(Mapping.Scale);
944 }
945 uint64_t getRedzoneSizeForGlobal(uint64_t SizeInBytes) const;
946 int GetAsanVersion(const Module &M) const;
947
948 bool CompileKernel;
949 bool InsertVersionCheck;
950 bool Recover;
951 bool UseGlobalsGC;
952 bool UsePrivateAlias;
953 bool UseOdrIndicator;
954 bool UseCtorComdat;
955 AsanDtorKind DestructorKind;
956 AsanCtorKind ConstructorKind;
957 Type *IntptrTy;
958 PointerType *PtrTy;
959 LLVMContext *C;
960 Triple TargetTriple;
961 ShadowMapping Mapping;
962 FunctionCallee AsanPoisonGlobals;
963 FunctionCallee AsanUnpoisonGlobals;
964 FunctionCallee AsanRegisterGlobals;
965 FunctionCallee AsanUnregisterGlobals;
966 FunctionCallee AsanRegisterImageGlobals;
967 FunctionCallee AsanUnregisterImageGlobals;
968 FunctionCallee AsanRegisterElfGlobals;
969 FunctionCallee AsanUnregisterElfGlobals;
970
971 Function *AsanCtorFunction = nullptr;
972 Function *AsanDtorFunction = nullptr;
973};
974
975// Stack poisoning does not play well with exception handling.
976// When an exception is thrown, we essentially bypass the code
977// that unpoisones the stack. This is why the run-time library has
978// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
979// stack in the interceptor. This however does not work inside the
980// actual function which catches the exception. Most likely because the
981// compiler hoists the load of the shadow value somewhere too high.
982// This causes asan to report a non-existing bug on 453.povray.
983// It sounds like an LLVM bug.
984struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
985 Function &F;
986 AddressSanitizer &ASan;
987 RuntimeCallInserter &RTCI;
988 DIBuilder DIB;
989 LLVMContext *C;
990 Type *IntptrTy;
991 Type *IntptrPtrTy;
992 ShadowMapping Mapping;
993
995 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
997
998 FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
999 AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
1000 FunctionCallee AsanSetShadowFunc[0x100] = {};
1001 FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
1002 FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;
1003
1004 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
1005 struct AllocaPoisonCall {
1006 IntrinsicInst *InsBefore;
1007 AllocaInst *AI;
1008 uint64_t Size;
1009 bool DoPoison;
1010 };
1011 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
1012 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
1013 bool HasUntracedLifetimeIntrinsic = false;
1014
1015 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
1016 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
1017 AllocaInst *DynamicAllocaLayout = nullptr;
1018 IntrinsicInst *LocalEscapeCall = nullptr;
1019
1020 bool HasInlineAsm = false;
1021 bool HasReturnsTwiceCall = false;
1022 bool PoisonStack;
1023
1024 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan,
1025 RuntimeCallInserter &RTCI)
1026 : F(F), ASan(ASan), RTCI(RTCI),
1027 DIB(*F.getParent(), /*AllowUnresolved*/ false), C(ASan.C),
1028 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
1029 Mapping(ASan.Mapping),
1030 PoisonStack(ClStack &&
1031 !Triple(F.getParent()->getTargetTriple()).isAMDGPU()) {}
1032
1033 bool runOnFunction() {
1034 if (!PoisonStack)
1035 return false;
1036
1038 copyArgsPassedByValToAllocas();
1039
1040 // Collect alloca, ret, lifetime instructions etc.
1041 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
1042
1043 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
1044
1045 initializeCallbacks(*F.getParent());
1046
1047 if (HasUntracedLifetimeIntrinsic) {
1048 // If there are lifetime intrinsics which couldn't be traced back to an
1049 // alloca, we may not know exactly when a variable enters scope, and
1050 // therefore should "fail safe" by not poisoning them.
1051 StaticAllocaPoisonCallVec.clear();
1052 DynamicAllocaPoisonCallVec.clear();
1053 }
1054
1055 processDynamicAllocas();
1056 processStaticAllocas();
1057
1058 if (ClDebugStack) {
1059 LLVM_DEBUG(dbgs() << F);
1060 }
1061 return true;
1062 }
1063
1064 // Arguments marked with the "byval" attribute are implicitly copied without
1065 // using an alloca instruction. To produce redzones for those arguments, we
1066 // copy them a second time into memory allocated with an alloca instruction.
1067 void copyArgsPassedByValToAllocas();
1068
1069 // Finds all Alloca instructions and puts
1070 // poisoned red zones around all of them.
1071 // Then unpoison everything back before the function returns.
1072 void processStaticAllocas();
1073 void processDynamicAllocas();
1074
1075 void createDynamicAllocasInitStorage();
1076
1077 // ----------------------- Visitors.
1078 /// Collect all Ret instructions, or the musttail call instruction if it
1079 /// precedes the return instruction.
1080 void visitReturnInst(ReturnInst &RI) {
1082 RetVec.push_back(CI);
1083 else
1084 RetVec.push_back(&RI);
1085 }
1086
1087 /// Collect all Resume instructions.
1088 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
1089
1090 /// Collect all CatchReturnInst instructions.
1091 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
1092
1093 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
1094 Value *SavedStack) {
1095 IRBuilder<> IRB(InstBefore);
1096 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
1097 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
1098 // need to adjust extracted SP to compute the address of the most recent
1099 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
1100 // this purpose.
1101 if (!isa<ReturnInst>(InstBefore)) {
1102 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
1103 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
1104 {IntptrTy});
1105
1106 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
1107
1108 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
1109 DynamicAreaOffset);
1110 }
1111
1112 RTCI.createRuntimeCall(
1113 IRB, AsanAllocasUnpoisonFunc,
1114 {IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
1115 }
1116
1117 // Unpoison dynamic allocas redzones.
1118 void unpoisonDynamicAllocas() {
1119 for (Instruction *Ret : RetVec)
1120 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
1121
1122 for (Instruction *StackRestoreInst : StackRestoreVec)
1123 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
1124 StackRestoreInst->getOperand(0));
1125 }
1126
1127 // Deploy and poison redzones around dynamic alloca call. To do this, we
1128 // should replace this call with another one with changed parameters and
1129 // replace all its uses with new address, so
1130 // addr = alloca type, old_size, align
1131 // is replaced by
1132 // new_size = (old_size + additional_size) * sizeof(type)
1133 // tmp = alloca i8, new_size, max(align, 32)
1134 // addr = tmp + 32 (first 32 bytes are for the left redzone).
1135 // Additional_size is added to make new memory allocation contain not only
1136 // requested memory, but also left, partial and right redzones.
1137 void handleDynamicAllocaCall(AllocaInst *AI);
1138
1139 /// Collect Alloca instructions we want (and can) handle.
1140 void visitAllocaInst(AllocaInst &AI) {
1141 // FIXME: Handle scalable vectors instead of ignoring them.
1142 if (!ASan.isInterestingAlloca(AI) ||
1143 isa<ScalableVectorType>(AI.getAllocatedType())) {
1144 if (AI.isStaticAlloca()) {
1145 // Skip over allocas that are present *before* the first instrumented
1146 // alloca, we don't want to move those around.
1147 if (AllocaVec.empty())
1148 return;
1149
1150 StaticAllocasToMoveUp.push_back(&AI);
1151 }
1152 return;
1153 }
1154
1155 if (!AI.isStaticAlloca())
1156 DynamicAllocaVec.push_back(&AI);
1157 else
1158 AllocaVec.push_back(&AI);
1159 }
1160
1161 /// Collect lifetime intrinsic calls to check for use-after-scope
1162 /// errors.
1165 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
1166 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
1167 if (!ASan.UseAfterScope)
1168 return;
1169 if (!II.isLifetimeStartOrEnd())
1170 return;
1171 // Found lifetime intrinsic, add ASan instrumentation if necessary.
1172 auto *Size = cast<ConstantInt>(II.getArgOperand(0));
1173 // If size argument is undefined, don't do anything.
1174 if (Size->isMinusOne()) return;
1175 // Check that size doesn't saturate uint64_t and can
1176 // be stored in IntptrTy.
1177 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1178 if (SizeValue == ~0ULL ||
1179 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1180 return;
1181 // Find alloca instruction that corresponds to llvm.lifetime argument.
1182 // Currently we can only handle lifetime markers pointing to the
1183 // beginning of the alloca.
1184 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1), true);
1185 if (!AI) {
1186 HasUntracedLifetimeIntrinsic = true;
1187 return;
1188 }
1189 // We're interested only in allocas we can handle.
1190 if (!ASan.isInterestingAlloca(*AI))
1191 return;
1192 bool DoPoison = (ID == Intrinsic::lifetime_end);
1193 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
1194 if (AI->isStaticAlloca())
1195 StaticAllocaPoisonCallVec.push_back(APC);
1197 DynamicAllocaPoisonCallVec.push_back(APC);
1198 }
1199
1200 void visitCallBase(CallBase &CB) {
1201 if (CallInst *CI = dyn_cast<CallInst>(&CB)) {
1202 HasInlineAsm |= CI->isInlineAsm() && &CB != ASan.LocalDynamicShadow;
1203 HasReturnsTwiceCall |= CI->canReturnTwice();
1204 }
1205 }
1206
1207 // ---------------------- Helpers.
1208 void initializeCallbacks(Module &M);
1209
1210 // Copies bytes from ShadowBytes into shadow memory for indexes where
1211 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1212 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1213 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1214 IRBuilder<> &IRB, Value *ShadowBase);
1215 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1216 size_t Begin, size_t End, IRBuilder<> &IRB,
1217 Value *ShadowBase);
1218 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1219 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1220 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1221
1222 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
1223
1224 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1225 bool Dynamic);
1226 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1227 Instruction *ThenTerm, Value *ValueIfFalse);
1228};
1229
1230} // end anonymous namespace
1231
1233 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1235 OS, MapClassName2PassName);
1236 OS << '<';
1237 if (Options.CompileKernel)
1238 OS << "kernel";
1239 OS << '>';
1240}
1241
1243 const AddressSanitizerOptions &Options, bool UseGlobalGC,
1244 bool UseOdrIndicator, AsanDtorKind DestructorKind,
1245 AsanCtorKind ConstructorKind)
1246 : Options(Options), UseGlobalGC(UseGlobalGC),
1247 UseOdrIndicator(UseOdrIndicator), DestructorKind(DestructorKind),
1248 ConstructorKind(ConstructorKind) {}
1249
1252 ModuleAddressSanitizer ModuleSanitizer(
1253 M, Options.InsertVersionCheck, Options.CompileKernel, Options.Recover,
1254 UseGlobalGC, UseOdrIndicator, DestructorKind, ConstructorKind);
1255 bool Modified = false;
1256 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1257 const StackSafetyGlobalInfo *const SSGI =
1259 for (Function &F : M) {
1260 AddressSanitizer FunctionSanitizer(
1261 M, SSGI, Options.InstrumentationWithCallsThreshold,
1262 Options.MaxInlinePoisoningSize, Options.CompileKernel, Options.Recover,
1263 Options.UseAfterScope, Options.UseAfterReturn);
1265 Modified |= FunctionSanitizer.instrumentFunction(F, &TLI);
1266 }
1267 Modified |= ModuleSanitizer.instrumentModule(M);
1268 if (!Modified)
1269 return PreservedAnalyses::all();
1270
1272 // GlobalsAA is considered stateless and does not get invalidated unless
1273 // explicitly invalidated; PreservedAnalyses::none() is not enough. Sanitizers
1274 // make changes that require GlobalsAA to be invalidated.
1275 PA.abandon<GlobalsAA>();
1276 return PA;
1277}
1278
1280 size_t Res = llvm::countr_zero(TypeSize / 8);
1282 return Res;
1283}
1284
1285/// Check if \p G has been created by a trusted compiler pass.
1287 // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1288 if (G->getName().starts_with("llvm.") ||
1289 // Do not instrument gcov counter arrays.
1290 G->getName().starts_with("__llvm_gcov_ctr") ||
1291 // Do not instrument rtti proxy symbols for function sanitizer.
1292 G->getName().starts_with("__llvm_rtti_proxy"))
1293 return true;
1294
1295 // Do not instrument asan globals.
1296 if (G->getName().starts_with(kAsanGenPrefix) ||
1297 G->getName().starts_with(kSanCovGenPrefix) ||
1298 G->getName().starts_with(kODRGenPrefix))
1299 return true;
1300
1301 return false;
1302}
1303
1305 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
1306 unsigned int AddrSpace = PtrTy->getPointerAddressSpace();
1307 if (AddrSpace == 3 || AddrSpace == 5)
1308 return true;
1309 return false;
1310}
1311
1312Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1313 // Shadow >> scale
1314 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
1315 if (Mapping.Offset == 0) return Shadow;
1316 // (Shadow >> scale) | offset
1317 Value *ShadowBase;
1318 if (LocalDynamicShadow)
1319 ShadowBase = LocalDynamicShadow;
1320 else
1321 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1322 if (Mapping.OrShadowOffset)
1323 return IRB.CreateOr(Shadow, ShadowBase);
1324 else
1325 return IRB.CreateAdd(Shadow, ShadowBase);
1326}
1327
1328// Instrument memset/memmove/memcpy
1329void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI,
1330 RuntimeCallInserter &RTCI) {
1332 if (isa<MemTransferInst>(MI)) {
1333 RTCI.createRuntimeCall(
1334 IRB, isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
1335 {IRB.CreateAddrSpaceCast(MI->getOperand(0), PtrTy),
1336 IRB.CreateAddrSpaceCast(MI->getOperand(1), PtrTy),
1337 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1338 } else if (isa<MemSetInst>(MI)) {
1339 RTCI.createRuntimeCall(
1340 IRB, AsanMemset,
1341 {IRB.CreateAddrSpaceCast(MI->getOperand(0), PtrTy),
1342 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1343 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1344 }
1345 MI->eraseFromParent();
1346}
1347
1348/// Check if we want (and can) handle this alloca.
1349bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1350 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1351
1352 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1353 return PreviouslySeenAllocaInfo->getSecond();
1354
1355 bool IsInteresting =
1356 (AI.getAllocatedType()->isSized() &&
1357 // alloca() may be called with 0 size, ignore it.
1358 ((!AI.isStaticAlloca()) || !getAllocaSizeInBytes(AI).isZero()) &&
1359 // We are only interested in allocas not promotable to registers.
1360 // Promotable allocas are common under -O0.
1362 // inalloca allocas are not treated as static, and we don't want
1363 // dynamic alloca instrumentation for them as well.
1364 !AI.isUsedWithInAlloca() &&
1365 // swifterror allocas are register promoted by ISel
1366 !AI.isSwiftError() &&
1367 // safe allocas are not interesting
1368 !(SSGI && SSGI->isSafe(AI)));
1369
1370 ProcessedAllocas[&AI] = IsInteresting;
1371 return IsInteresting;
1372}
1373
1374bool AddressSanitizer::ignoreAccess(Instruction *Inst, Value *Ptr) {
1375 // Instrument accesses from different address spaces only for AMDGPU.
1376 Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
1377 if (PtrTy->getPointerAddressSpace() != 0 &&
1378 !(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(Ptr)))
1379 return true;
1380
1381 // Ignore swifterror addresses.
1382 // swifterror memory addresses are mem2reg promoted by instruction
1383 // selection. As such they cannot have regular uses like an instrumentation
1384 // function and it makes no sense to track them as memory.
1385 if (Ptr->isSwiftError())
1386 return true;
1387
1388 // Treat memory accesses to promotable allocas as non-interesting since they
1389 // will not cause memory violations. This greatly speeds up the instrumented
1390 // executable at -O0.
1391 if (auto AI = dyn_cast_or_null<AllocaInst>(Ptr))
1392 if (ClSkipPromotableAllocas && !isInterestingAlloca(*AI))
1393 return true;
1394
1395 if (SSGI != nullptr && SSGI->stackAccessIsSafe(*Inst) &&
1397 return true;
1398
1399 return false;
1400}
1401
1402void AddressSanitizer::getInterestingMemoryOperands(
1404 // Do not instrument the load fetching the dynamic shadow address.
1405 if (LocalDynamicShadow == I)
1406 return;
1407
1408 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1409 if (!ClInstrumentReads || ignoreAccess(I, LI->getPointerOperand()))
1410 return;
1411 Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
1412 LI->getType(), LI->getAlign());
1413 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1414 if (!ClInstrumentWrites || ignoreAccess(I, SI->getPointerOperand()))
1415 return;
1416 Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
1417 SI->getValueOperand()->getType(), SI->getAlign());
1418 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1419 if (!ClInstrumentAtomics || ignoreAccess(I, RMW->getPointerOperand()))
1420 return;
1421 Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
1422 RMW->getValOperand()->getType(), std::nullopt);
1423 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1424 if (!ClInstrumentAtomics || ignoreAccess(I, XCHG->getPointerOperand()))
1425 return;
1426 Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
1427 XCHG->getCompareOperand()->getType(),
1428 std::nullopt);
1429 } else if (auto CI = dyn_cast<CallInst>(I)) {
1430 switch (CI->getIntrinsicID()) {
1431 case Intrinsic::masked_load:
1432 case Intrinsic::masked_store:
1433 case Intrinsic::masked_gather:
1434 case Intrinsic::masked_scatter: {
1435 bool IsWrite = CI->getType()->isVoidTy();
1436 // Masked store has an initial operand for the value.
1437 unsigned OpOffset = IsWrite ? 1 : 0;
1438 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1439 return;
1440
1441 auto BasePtr = CI->getOperand(OpOffset);
1442 if (ignoreAccess(I, BasePtr))
1443 return;
1444 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1445 MaybeAlign Alignment = Align(1);
1446 // Otherwise no alignment guarantees. We probably got Undef.
1447 if (auto *Op = dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1448 Alignment = Op->getMaybeAlignValue();
1449 Value *Mask = CI->getOperand(2 + OpOffset);
1450 Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, Mask);
1451 break;
1452 }
1453 case Intrinsic::masked_expandload:
1454 case Intrinsic::masked_compressstore: {
1455 bool IsWrite = CI->getIntrinsicID() == Intrinsic::masked_compressstore;
1456 unsigned OpOffset = IsWrite ? 1 : 0;
1457 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1458 return;
1459 auto BasePtr = CI->getOperand(OpOffset);
1460 if (ignoreAccess(I, BasePtr))
1461 return;
1462 MaybeAlign Alignment = BasePtr->getPointerAlignment(*DL);
1463 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1464
1465 IRBuilder IB(I);
1466 Value *Mask = CI->getOperand(1 + OpOffset);
1467 // Use the popcount of Mask as the effective vector length.
1468 Type *ExtTy = VectorType::get(IntptrTy, cast<VectorType>(Ty));
1469 Value *ExtMask = IB.CreateZExt(Mask, ExtTy);
1470 Value *EVL = IB.CreateAddReduce(ExtMask);
1471 Value *TrueMask = ConstantInt::get(Mask->getType(), 1);
1472 Interesting.emplace_back(I, OpOffset, IsWrite, Ty, Alignment, TrueMask,
1473 EVL);
1474 break;
1475 }
1476 case Intrinsic::vp_load:
1477 case Intrinsic::vp_store:
1478 case Intrinsic::experimental_vp_strided_load:
1479 case Intrinsic::experimental_vp_strided_store: {
1480 auto *VPI = cast<VPIntrinsic>(CI);
1481 unsigned IID = CI->getIntrinsicID();
1482 bool IsWrite = CI->getType()->isVoidTy();
1483 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1484 return;
1485 unsigned PtrOpNo = *VPI->getMemoryPointerParamPos(IID);
1486 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1487 MaybeAlign Alignment = VPI->getOperand(PtrOpNo)->getPointerAlignment(*DL);
1488 Value *Stride = nullptr;
1489 if (IID == Intrinsic::experimental_vp_strided_store ||
1490 IID == Intrinsic::experimental_vp_strided_load) {
1491 Stride = VPI->getOperand(PtrOpNo + 1);
1492 // Use the pointer alignment as the element alignment if the stride is a
1493 // mutiple of the pointer alignment. Otherwise, the element alignment
1494 // should be Align(1).
1495 unsigned PointerAlign = Alignment.valueOrOne().value();
1496 if (!isa<ConstantInt>(Stride) ||
1497 cast<ConstantInt>(Stride)->getZExtValue() % PointerAlign != 0)
1498 Alignment = Align(1);
1499 }
1500 Interesting.emplace_back(I, PtrOpNo, IsWrite, Ty, Alignment,
1501 VPI->getMaskParam(), VPI->getVectorLengthParam(),
1502 Stride);
1503 break;
1504 }
1505 case Intrinsic::vp_gather:
1506 case Intrinsic::vp_scatter: {
1507 auto *VPI = cast<VPIntrinsic>(CI);
1508 unsigned IID = CI->getIntrinsicID();
1509 bool IsWrite = IID == Intrinsic::vp_scatter;
1510 if (IsWrite ? !ClInstrumentWrites : !ClInstrumentReads)
1511 return;
1512 unsigned PtrOpNo = *VPI->getMemoryPointerParamPos(IID);
1513 Type *Ty = IsWrite ? CI->getArgOperand(0)->getType() : CI->getType();
1514 MaybeAlign Alignment = VPI->getPointerAlignment();
1515 Interesting.emplace_back(I, PtrOpNo, IsWrite, Ty, Alignment,
1516 VPI->getMaskParam(),
1517 VPI->getVectorLengthParam());
1518 break;
1519 }
1520 default:
1521 for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ArgNo++) {
1522 if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
1523 ignoreAccess(I, CI->getArgOperand(ArgNo)))
1524 continue;
1525 Type *Ty = CI->getParamByValType(ArgNo);
1526 Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));
1527 }
1528 }
1529 }
1530}
1531
1532static bool isPointerOperand(Value *V) {
1533 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1534}
1535
1536// This is a rough heuristic; it may cause both false positives and
1537// false negatives. The proper implementation requires cooperation with
1538// the frontend.
1540 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1541 if (!Cmp->isRelational())
1542 return false;
1543 } else {
1544 return false;
1545 }
1546 return isPointerOperand(I->getOperand(0)) &&
1547 isPointerOperand(I->getOperand(1));
1548}
1549
1550// This is a rough heuristic; it may cause both false positives and
1551// false negatives. The proper implementation requires cooperation with
1552// the frontend.
1554 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1555 if (BO->getOpcode() != Instruction::Sub)
1556 return false;
1557 } else {
1558 return false;
1559 }
1560 return isPointerOperand(I->getOperand(0)) &&
1561 isPointerOperand(I->getOperand(1));
1562}
1563
1564bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1565 // If a global variable does not have dynamic initialization we don't
1566 // have to instrument it. However, if a global does not have initializer
1567 // at all, we assume it has dynamic initializer (in other TU).
1568 if (!G->hasInitializer())
1569 return false;
1570
1571 if (G->hasSanitizerMetadata() && G->getSanitizerMetadata().IsDynInit)
1572 return false;
1573
1574 return true;
1575}
1576
1577void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1578 Instruction *I, RuntimeCallInserter &RTCI) {
1579 IRBuilder<> IRB(I);
1580 FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1581 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1582 for (Value *&i : Param) {
1583 if (i->getType()->isPointerTy())
1584 i = IRB.CreatePointerCast(i, IntptrTy);
1585 }
1586 RTCI.createRuntimeCall(IRB, F, Param);
1587}
1588
1589static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1590 Instruction *InsertBefore, Value *Addr,
1591 MaybeAlign Alignment, unsigned Granularity,
1592 TypeSize TypeStoreSize, bool IsWrite,
1593 Value *SizeArgument, bool UseCalls,
1594 uint32_t Exp, RuntimeCallInserter &RTCI) {
1595 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1596 // if the data is properly aligned.
1597 if (!TypeStoreSize.isScalable()) {
1598 const auto FixedSize = TypeStoreSize.getFixedValue();
1599 switch (FixedSize) {
1600 case 8:
1601 case 16:
1602 case 32:
1603 case 64:
1604 case 128:
1605 if (!Alignment || *Alignment >= Granularity ||
1606 *Alignment >= FixedSize / 8)
1607 return Pass->instrumentAddress(I, InsertBefore, Addr, Alignment,
1608 FixedSize, IsWrite, nullptr, UseCalls,
1609 Exp, RTCI);
1610 }
1611 }
1612 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeStoreSize,
1613 IsWrite, nullptr, UseCalls, Exp, RTCI);
1614}
1615
1616void AddressSanitizer::instrumentMaskedLoadOrStore(
1617 AddressSanitizer *Pass, const DataLayout &DL, Type *IntptrTy, Value *Mask,
1618 Value *EVL, Value *Stride, Instruction *I, Value *Addr,
1619 MaybeAlign Alignment, unsigned Granularity, Type *OpType, bool IsWrite,
1620 Value *SizeArgument, bool UseCalls, uint32_t Exp,
1621 RuntimeCallInserter &RTCI) {
1622 auto *VTy = cast<VectorType>(OpType);
1623 TypeSize ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1624 auto Zero = ConstantInt::get(IntptrTy, 0);
1625
1626 IRBuilder IB(I);
1627 Instruction *LoopInsertBefore = I;
1628 if (EVL) {
1629 // The end argument of SplitBlockAndInsertForLane is assumed bigger
1630 // than zero, so we should check whether EVL is zero here.
1631 Type *EVLType = EVL->getType();
1632 Value *IsEVLZero = IB.CreateICmpNE(EVL, ConstantInt::get(EVLType, 0));
1633 LoopInsertBefore = SplitBlockAndInsertIfThen(IsEVLZero, I, false);
1634 IB.SetInsertPoint(LoopInsertBefore);
1635 // Cast EVL to IntptrTy.
1636 EVL = IB.CreateZExtOrTrunc(EVL, IntptrTy);
1637 // To avoid undefined behavior for extracting with out of range index, use
1638 // the minimum of evl and element count as trip count.
1639 Value *EC = IB.CreateElementCount(IntptrTy, VTy->getElementCount());
1640 EVL = IB.CreateBinaryIntrinsic(Intrinsic::umin, EVL, EC);
1641 } else {
1642 EVL = IB.CreateElementCount(IntptrTy, VTy->getElementCount());
1643 }
1644
1645 // Cast Stride to IntptrTy.
1646 if (Stride)
1647 Stride = IB.CreateZExtOrTrunc(Stride, IntptrTy);
1648
1649 SplitBlockAndInsertForEachLane(EVL, LoopInsertBefore,
1650 [&](IRBuilderBase &IRB, Value *Index) {
1651 Value *MaskElem = IRB.CreateExtractElement(Mask, Index);
1652 if (auto *MaskElemC = dyn_cast<ConstantInt>(MaskElem)) {
1653 if (MaskElemC->isZero())
1654 // No check
1655 return;
1656 // Unconditional check
1657 } else {
1658 // Conditional check
1660 MaskElem, &*IRB.GetInsertPoint(), false);
1661 IRB.SetInsertPoint(ThenTerm);
1662 }
1663
1664 Value *InstrumentedAddress;
1665 if (isa<VectorType>(Addr->getType())) {
1666 assert(
1667 cast<VectorType>(Addr->getType())->getElementType()->isPointerTy() &&
1668 "Expected vector of pointer.");
1669 InstrumentedAddress = IRB.CreateExtractElement(Addr, Index);
1670 } else if (Stride) {
1671 Index = IRB.CreateMul(Index, Stride);
1672 InstrumentedAddress = IRB.CreatePtrAdd(Addr, Index);
1673 } else {
1674 InstrumentedAddress = IRB.CreateGEP(VTy, Addr, {Zero, Index});
1675 }
1676 doInstrumentAddress(Pass, I, &*IRB.GetInsertPoint(), InstrumentedAddress,
1677 Alignment, Granularity, ElemTypeSize, IsWrite,
1678 SizeArgument, UseCalls, Exp, RTCI);
1679 });
1680}
1681
1682void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1683 InterestingMemoryOperand &O, bool UseCalls,
1684 const DataLayout &DL,
1685 RuntimeCallInserter &RTCI) {
1686 Value *Addr = O.getPtr();
1687
1688 // Optimization experiments.
1689 // The experiments can be used to evaluate potential optimizations that remove
1690 // instrumentation (assess false negatives). Instead of completely removing
1691 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1692 // experiments that want to remove instrumentation of this instruction).
1693 // If Exp is non-zero, this pass will emit special calls into runtime
1694 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1695 // make runtime terminate the program in a special way (with a different
1696 // exit status). Then you run the new compiler on a buggy corpus, collect
1697 // the special terminations (ideally, you don't see them at all -- no false
1698 // negatives) and make the decision on the optimization.
1700
1701 if (ClOpt && ClOptGlobals) {
1702 // If initialization order checking is disabled, a simple access to a
1703 // dynamically initialized global is always valid.
1704 GlobalVariable *G = dyn_cast<GlobalVariable>(getUnderlyingObject(Addr));
1705 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1706 isSafeAccess(ObjSizeVis, Addr, O.TypeStoreSize)) {
1707 NumOptimizedAccessesToGlobalVar++;
1708 return;
1709 }
1710 }
1711
1712 if (ClOpt && ClOptStack) {
1713 // A direct inbounds access to a stack variable is always valid.
1714 if (isa<AllocaInst>(getUnderlyingObject(Addr)) &&
1715 isSafeAccess(ObjSizeVis, Addr, O.TypeStoreSize)) {
1716 NumOptimizedAccessesToStackVar++;
1717 return;
1718 }
1719 }
1720
1721 if (O.IsWrite)
1722 NumInstrumentedWrites++;
1723 else
1724 NumInstrumentedReads++;
1725
1726 unsigned Granularity = 1 << Mapping.Scale;
1727 if (O.MaybeMask) {
1728 instrumentMaskedLoadOrStore(this, DL, IntptrTy, O.MaybeMask, O.MaybeEVL,
1729 O.MaybeStride, O.getInsn(), Addr, O.Alignment,
1730 Granularity, O.OpType, O.IsWrite, nullptr,
1731 UseCalls, Exp, RTCI);
1732 } else {
1733 doInstrumentAddress(this, O.getInsn(), O.getInsn(), Addr, O.Alignment,
1734 Granularity, O.TypeStoreSize, O.IsWrite, nullptr,
1735 UseCalls, Exp, RTCI);
1736 }
1737}
1738
1739Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1740 Value *Addr, bool IsWrite,
1741 size_t AccessSizeIndex,
1742 Value *SizeArgument,
1743 uint32_t Exp,
1744 RuntimeCallInserter &RTCI) {
1745 InstrumentationIRBuilder IRB(InsertBefore);
1746 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1747 CallInst *Call = nullptr;
1748 if (SizeArgument) {
1749 if (Exp == 0)
1750 Call = RTCI.createRuntimeCall(IRB, AsanErrorCallbackSized[IsWrite][0],
1751 {Addr, SizeArgument});
1752 else
1753 Call = RTCI.createRuntimeCall(IRB, AsanErrorCallbackSized[IsWrite][1],
1754 {Addr, SizeArgument, ExpVal});
1755 } else {
1756 if (Exp == 0)
1757 Call = RTCI.createRuntimeCall(
1758 IRB, AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1759 else
1760 Call = RTCI.createRuntimeCall(
1761 IRB, AsanErrorCallback[IsWrite][1][AccessSizeIndex], {Addr, ExpVal});
1762 }
1763
1764 Call->setCannotMerge();
1765 return Call;
1766}
1767
1768Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1769 Value *ShadowValue,
1770 uint32_t TypeStoreSize) {
1771 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1772 // Addr & (Granularity - 1)
1773 Value *LastAccessedByte =
1774 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1775 // (Addr & (Granularity - 1)) + size - 1
1776 if (TypeStoreSize / 8 > 1)
1777 LastAccessedByte = IRB.CreateAdd(
1778 LastAccessedByte, ConstantInt::get(IntptrTy, TypeStoreSize / 8 - 1));
1779 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1780 LastAccessedByte =
1781 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1782 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1783 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1784}
1785
1786Instruction *AddressSanitizer::instrumentAMDGPUAddress(
1787 Instruction *OrigIns, Instruction *InsertBefore, Value *Addr,
1788 uint32_t TypeStoreSize, bool IsWrite, Value *SizeArgument) {
1789 // Do not instrument unsupported addrspaces.
1791 return nullptr;
1792 Type *PtrTy = cast<PointerType>(Addr->getType()->getScalarType());
1793 // Follow host instrumentation for global and constant addresses.
1794 if (PtrTy->getPointerAddressSpace() != 0)
1795 return InsertBefore;
1796 // Instrument generic addresses in supported addressspaces.
1797 IRBuilder<> IRB(InsertBefore);
1798 Value *IsShared = IRB.CreateCall(AMDGPUAddressShared, {Addr});
1799 Value *IsPrivate = IRB.CreateCall(AMDGPUAddressPrivate, {Addr});
1800 Value *IsSharedOrPrivate = IRB.CreateOr(IsShared, IsPrivate);
1801 Value *Cmp = IRB.CreateNot(IsSharedOrPrivate);
1802 Value *AddrSpaceZeroLanding =
1803 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
1804 InsertBefore = cast<Instruction>(AddrSpaceZeroLanding);
1805 return InsertBefore;
1806}
1807
1808Instruction *AddressSanitizer::genAMDGPUReportBlock(IRBuilder<> &IRB,
1809 Value *Cond, bool Recover) {
1810 Module &M = *IRB.GetInsertBlock()->getModule();
1811 Value *ReportCond = Cond;
1812 if (!Recover) {
1813 auto Ballot = M.getOrInsertFunction(kAMDGPUBallotName, IRB.getInt64Ty(),
1814 IRB.getInt1Ty());
1815 ReportCond = IRB.CreateIsNotNull(IRB.CreateCall(Ballot, {Cond}));
1816 }
1817
1818 auto *Trm =
1819 SplitBlockAndInsertIfThen(ReportCond, &*IRB.GetInsertPoint(), false,
1820 MDBuilder(*C).createBranchWeights(1, 100000));
1821 Trm->getParent()->setName("asan.report");
1822
1823 if (Recover)
1824 return Trm;
1825
1826 Trm = SplitBlockAndInsertIfThen(Cond, Trm, false);
1827 IRB.SetInsertPoint(Trm);
1828 return IRB.CreateCall(
1829 M.getOrInsertFunction(kAMDGPUUnreachableName, IRB.getVoidTy()), {});
1830}
1831
1832void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1833 Instruction *InsertBefore, Value *Addr,
1834 MaybeAlign Alignment,
1835 uint32_t TypeStoreSize, bool IsWrite,
1836 Value *SizeArgument, bool UseCalls,
1837 uint32_t Exp,
1838 RuntimeCallInserter &RTCI) {
1839 if (TargetTriple.isAMDGPU()) {
1840 InsertBefore = instrumentAMDGPUAddress(OrigIns, InsertBefore, Addr,
1841 TypeStoreSize, IsWrite, SizeArgument);
1842 if (!InsertBefore)
1843 return;
1844 }
1845
1846 InstrumentationIRBuilder IRB(InsertBefore);
1847 size_t AccessSizeIndex = TypeStoreSizeToSizeIndex(TypeStoreSize);
1848 const ASanAccessInfo AccessInfo(IsWrite, CompileKernel, AccessSizeIndex);
1849
1850 if (UseCalls && ClOptimizeCallbacks) {
1851 const ASanAccessInfo AccessInfo(IsWrite, CompileKernel, AccessSizeIndex);
1852 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1853 IRB.CreateCall(
1854 Intrinsic::getDeclaration(M, Intrinsic::asan_check_memaccess),
1855 {IRB.CreatePointerCast(Addr, PtrTy),
1856 ConstantInt::get(Int32Ty, AccessInfo.Packed)});
1857 return;
1858 }
1859
1860 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1861 if (UseCalls) {
1862 if (Exp == 0)
1863 RTCI.createRuntimeCall(
1864 IRB, AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex], AddrLong);
1865 else
1866 RTCI.createRuntimeCall(
1867 IRB, AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1868 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1869 return;
1870 }
1871
1872 Type *ShadowTy =
1873 IntegerType::get(*C, std::max(8U, TypeStoreSize >> Mapping.Scale));
1874 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1875 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1876 const uint64_t ShadowAlign =
1877 std::max<uint64_t>(Alignment.valueOrOne().value() >> Mapping.Scale, 1);
1878 Value *ShadowValue = IRB.CreateAlignedLoad(
1879 ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy), Align(ShadowAlign));
1880
1881 Value *Cmp = IRB.CreateIsNotNull(ShadowValue);
1882 size_t Granularity = 1ULL << Mapping.Scale;
1883 Instruction *CrashTerm = nullptr;
1884
1885 bool GenSlowPath = (ClAlwaysSlowPath || (TypeStoreSize < 8 * Granularity));
1886
1887 if (TargetTriple.isAMDGCN()) {
1888 if (GenSlowPath) {
1889 auto *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeStoreSize);
1890 Cmp = IRB.CreateAnd(Cmp, Cmp2);
1891 }
1892 CrashTerm = genAMDGPUReportBlock(IRB, Cmp, Recover);
1893 } else if (GenSlowPath) {
1894 // We use branch weights for the slow path check, to indicate that the slow
1895 // path is rarely taken. This seems to be the case for SPEC benchmarks.
1897 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1898 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1899 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1900 IRB.SetInsertPoint(CheckTerm);
1901 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeStoreSize);
1902 if (Recover) {
1903 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1904 } else {
1905 BasicBlock *CrashBlock =
1906 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1907 CrashTerm = new UnreachableInst(*C, CrashBlock);
1908 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1909 ReplaceInstWithInst(CheckTerm, NewTerm);
1910 }
1911 } else {
1912 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1913 }
1914
1915 Instruction *Crash = generateCrashCode(
1916 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument, Exp, RTCI);
1917 if (OrigIns->getDebugLoc())
1918 Crash->setDebugLoc(OrigIns->getDebugLoc());
1919}
1920
1921// Instrument unusual size or unusual alignment.
1922// We can not do it with a single check, so we do 1-byte check for the first
1923// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1924// to report the actual access size.
1925void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1926 Instruction *I, Instruction *InsertBefore, Value *Addr,
1927 TypeSize TypeStoreSize, bool IsWrite, Value *SizeArgument, bool UseCalls,
1928 uint32_t Exp, RuntimeCallInserter &RTCI) {
1929 InstrumentationIRBuilder IRB(InsertBefore);
1930 Value *NumBits = IRB.CreateTypeSize(IntptrTy, TypeStoreSize);
1931 Value *Size = IRB.CreateLShr(NumBits, ConstantInt::get(IntptrTy, 3));
1932
1933 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1934 if (UseCalls) {
1935 if (Exp == 0)
1936 RTCI.createRuntimeCall(IRB, AsanMemoryAccessCallbackSized[IsWrite][0],
1937 {AddrLong, Size});
1938 else
1939 RTCI.createRuntimeCall(
1940 IRB, AsanMemoryAccessCallbackSized[IsWrite][1],
1941 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1942 } else {
1943 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
1944 Value *LastByte = IRB.CreateIntToPtr(
1945 IRB.CreateAdd(AddrLong, SizeMinusOne),
1946 Addr->getType());
1947 instrumentAddress(I, InsertBefore, Addr, {}, 8, IsWrite, Size, false, Exp,
1948 RTCI);
1949 instrumentAddress(I, InsertBefore, LastByte, {}, 8, IsWrite, Size, false,
1950 Exp, RTCI);
1951 }
1952}
1953
1954void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,
1956 // Set up the arguments to our poison/unpoison functions.
1957 IRBuilder<> IRB(&GlobalInit.front(),
1958 GlobalInit.front().getFirstInsertionPt());
1959
1960 // Add a call to poison all external globals before the given function starts.
1961 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1962 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1963
1964 // Add calls to unpoison all globals before each return instruction.
1965 for (auto &BB : GlobalInit)
1966 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1967 CallInst::Create(AsanUnpoisonGlobals, "", RI->getIterator());
1968}
1969
1970void ModuleAddressSanitizer::createInitializerPoisonCalls(
1972 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1973 if (!GV)
1974 return;
1975
1976 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1977 if (!CA)
1978 return;
1979
1980 for (Use &OP : CA->operands()) {
1981 if (isa<ConstantAggregateZero>(OP)) continue;
1982 ConstantStruct *CS = cast<ConstantStruct>(OP);
1983
1984 // Must have a function or null ptr.
1985 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1986 if (F->getName() == kAsanModuleCtorName) continue;
1987 auto *Priority = cast<ConstantInt>(CS->getOperand(0));
1988 // Don't instrument CTORs that will run before asan.module_ctor.
1989 if (Priority->getLimitedValue() <= GetCtorAndDtorPriority(TargetTriple))
1990 continue;
1991 poisonOneInitializer(*F, ModuleName);
1992 }
1993 }
1994}
1995
1996const GlobalVariable *
1997ModuleAddressSanitizer::getExcludedAliasedGlobal(const GlobalAlias &GA) const {
1998 // In case this function should be expanded to include rules that do not just
1999 // apply when CompileKernel is true, either guard all existing rules with an
2000 // 'if (CompileKernel) { ... }' or be absolutely sure that all these rules
2001 // should also apply to user space.
2002 assert(CompileKernel && "Only expecting to be called when compiling kernel");
2003
2004 const Constant *C = GA.getAliasee();
2005
2006 // When compiling the kernel, globals that are aliased by symbols prefixed
2007 // by "__" are special and cannot be padded with a redzone.
2008 if (GA.getName().starts_with("__"))
2009 return dyn_cast<GlobalVariable>(C->stripPointerCastsAndAliases());
2010
2011 return nullptr;
2012}
2013
2014bool ModuleAddressSanitizer::shouldInstrumentGlobal(GlobalVariable *G) const {
2015 Type *Ty = G->getValueType();
2016 LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
2017
2018 if (G->hasSanitizerMetadata() && G->getSanitizerMetadata().NoAddress)
2019 return false;
2020 if (!Ty->isSized()) return false;
2021 if (!G->hasInitializer()) return false;
2022 // Globals in address space 1 and 4 are supported for AMDGPU.
2023 if (G->getAddressSpace() &&
2024 !(TargetTriple.isAMDGPU() && !isUnsupportedAMDGPUAddrspace(G)))
2025 return false;
2026 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
2027 // Two problems with thread-locals:
2028 // - The address of the main thread's copy can't be computed at link-time.
2029 // - Need to poison all copies, not just the main thread's one.
2030 if (G->isThreadLocal()) return false;
2031 // For now, just ignore this Global if the alignment is large.
2032 if (G->getAlign() && *G->getAlign() > getMinRedzoneSizeForGlobal()) return false;
2033
2034 // For non-COFF targets, only instrument globals known to be defined by this
2035 // TU.
2036 // FIXME: We can instrument comdat globals on ELF if we are using the
2037 // GC-friendly metadata scheme.
2038 if (!TargetTriple.isOSBinFormatCOFF()) {
2039 if (!G->hasExactDefinition() || G->hasComdat())
2040 return false;
2041 } else {
2042 // On COFF, don't instrument non-ODR linkages.
2043 if (G->isInterposable())
2044 return false;
2045 // If the global has AvailableExternally linkage, then it is not in this
2046 // module, which means it does not need to be instrumented.
2047 if (G->hasAvailableExternallyLinkage())
2048 return false;
2049 }
2050
2051 // If a comdat is present, it must have a selection kind that implies ODR
2052 // semantics: no duplicates, any, or exact match.
2053 if (Comdat *C = G->getComdat()) {
2054 switch (C->getSelectionKind()) {
2055 case Comdat::Any:
2056 case Comdat::ExactMatch:
2058 break;
2059 case Comdat::Largest:
2060 case Comdat::SameSize:
2061 return false;
2062 }
2063 }
2064
2065 if (G->hasSection()) {
2066 // The kernel uses explicit sections for mostly special global variables
2067 // that we should not instrument. E.g. the kernel may rely on their layout
2068 // without redzones, or remove them at link time ("discard.*"), etc.
2069 if (CompileKernel)
2070 return false;
2071
2072 StringRef Section = G->getSection();
2073
2074 // Globals from llvm.metadata aren't emitted, do not instrument them.
2075 if (Section == "llvm.metadata") return false;
2076 // Do not instrument globals from special LLVM sections.
2077 if (Section.contains("__llvm") || Section.contains("__LLVM"))
2078 return false;
2079
2080 // Do not instrument function pointers to initialization and termination
2081 // routines: dynamic linker will not properly handle redzones.
2082 if (Section.starts_with(".preinit_array") ||
2083 Section.starts_with(".init_array") ||
2084 Section.starts_with(".fini_array")) {
2085 return false;
2086 }
2087
2088 // Do not instrument user-defined sections (with names resembling
2089 // valid C identifiers)
2090 if (TargetTriple.isOSBinFormatELF()) {
2091 if (llvm::all_of(Section,
2092 [](char c) { return llvm::isAlnum(c) || c == '_'; }))
2093 return false;
2094 }
2095
2096 // On COFF, if the section name contains '$', it is highly likely that the
2097 // user is using section sorting to create an array of globals similar to
2098 // the way initialization callbacks are registered in .init_array and
2099 // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
2100 // to such globals is counterproductive, because the intent is that they
2101 // will form an array, and out-of-bounds accesses are expected.
2102 // See https://github.com/google/sanitizers/issues/305
2103 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
2104 if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
2105 LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
2106 << *G << "\n");
2107 return false;
2108 }
2109
2110 if (TargetTriple.isOSBinFormatMachO()) {
2111 StringRef ParsedSegment, ParsedSection;
2112 unsigned TAA = 0, StubSize = 0;
2113 bool TAAParsed;
2115 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize));
2116
2117 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
2118 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
2119 // them.
2120 if (ParsedSegment == "__OBJC" ||
2121 (ParsedSegment == "__DATA" && ParsedSection.starts_with("__objc_"))) {
2122 LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
2123 return false;
2124 }
2125 // See https://github.com/google/sanitizers/issues/32
2126 // Constant CFString instances are compiled in the following way:
2127 // -- the string buffer is emitted into
2128 // __TEXT,__cstring,cstring_literals
2129 // -- the constant NSConstantString structure referencing that buffer
2130 // is placed into __DATA,__cfstring
2131 // Therefore there's no point in placing redzones into __DATA,__cfstring.
2132 // Moreover, it causes the linker to crash on OS X 10.7
2133 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
2134 LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
2135 return false;
2136 }
2137 // The linker merges the contents of cstring_literals and removes the
2138 // trailing zeroes.
2139 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
2140 LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
2141 return false;
2142 }
2143 }
2144 }
2145
2146 if (CompileKernel) {
2147 // Globals that prefixed by "__" are special and cannot be padded with a
2148 // redzone.
2149 if (G->getName().starts_with("__"))
2150 return false;
2151 }
2152
2153 return true;
2154}
2155
2156// On Mach-O platforms, we emit global metadata in a separate section of the
2157// binary in order to allow the linker to properly dead strip. This is only
2158// supported on recent versions of ld64.
2159bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
2160 if (!TargetTriple.isOSBinFormatMachO())
2161 return false;
2162
2163 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
2164 return true;
2165 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
2166 return true;
2167 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
2168 return true;
2169 if (TargetTriple.isDriverKit())
2170 return true;
2171 if (TargetTriple.isXROS())
2172 return true;
2173
2174 return false;
2175}
2176
2177StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
2178 switch (TargetTriple.getObjectFormat()) {
2179 case Triple::COFF: return ".ASAN$GL";
2180 case Triple::ELF: return "asan_globals";
2181 case Triple::MachO: return "__DATA,__asan_globals,regular";
2182 case Triple::Wasm:
2183 case Triple::GOFF:
2184 case Triple::SPIRV:
2185 case Triple::XCOFF:
2188 "ModuleAddressSanitizer not implemented for object file format");
2190 break;
2191 }
2192 llvm_unreachable("unsupported object format");
2193}
2194
2195void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
2196 IRBuilder<> IRB(*C);
2197
2198 // Declare our poisoning and unpoisoning functions.
2199 AsanPoisonGlobals =
2200 M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
2201 AsanUnpoisonGlobals =
2202 M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
2203
2204 // Declare functions that register/unregister globals.
2205 AsanRegisterGlobals = M.getOrInsertFunction(
2206 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2207 AsanUnregisterGlobals = M.getOrInsertFunction(
2208 kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2209
2210 // Declare the functions that find globals in a shared object and then invoke
2211 // the (un)register function on them.
2212 AsanRegisterImageGlobals = M.getOrInsertFunction(
2213 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
2214 AsanUnregisterImageGlobals = M.getOrInsertFunction(
2216
2217 AsanRegisterElfGlobals =
2218 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
2219 IntptrTy, IntptrTy, IntptrTy);
2220 AsanUnregisterElfGlobals =
2221 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
2222 IntptrTy, IntptrTy, IntptrTy);
2223}
2224
2225// Put the metadata and the instrumented global in the same group. This ensures
2226// that the metadata is discarded if the instrumented global is discarded.
2227void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
2228 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
2229 Module &M = *G->getParent();
2230 Comdat *C = G->getComdat();
2231 if (!C) {
2232 if (!G->hasName()) {
2233 // If G is unnamed, it must be internal. Give it an artificial name
2234 // so we can put it in a comdat.
2235 assert(G->hasLocalLinkage());
2236 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
2237 }
2238
2239 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
2240 std::string Name = std::string(G->getName());
2241 Name += InternalSuffix;
2242 C = M.getOrInsertComdat(Name);
2243 } else {
2244 C = M.getOrInsertComdat(G->getName());
2245 }
2246
2247 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
2248 // linkage to internal linkage so that a symbol table entry is emitted. This
2249 // is necessary in order to create the comdat group.
2250 if (TargetTriple.isOSBinFormatCOFF()) {
2251 C->setSelectionKind(Comdat::NoDeduplicate);
2252 if (G->hasPrivateLinkage())
2253 G->setLinkage(GlobalValue::InternalLinkage);
2254 }
2255 G->setComdat(C);
2256 }
2257
2258 assert(G->hasComdat());
2259 Metadata->setComdat(G->getComdat());
2260}
2261
2262// Create a separate metadata global and put it in the appropriate ASan
2263// global registration section.
2265ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
2266 StringRef OriginalName) {
2267 auto Linkage = TargetTriple.isOSBinFormatMachO()
2271 M, Initializer->getType(), false, Linkage, Initializer,
2272 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
2273 Metadata->setSection(getGlobalMetadataSection());
2274 // Place metadata in a large section for x86-64 ELF binaries to mitigate
2275 // relocation pressure.
2277 return Metadata;
2278}
2279
2280Instruction *ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
2281 AsanDtorFunction = Function::createWithDefaultAttr(
2284 AsanDtorFunction->addFnAttr(Attribute::NoUnwind);
2285 // Ensure Dtor cannot be discarded, even if in a comdat.
2286 appendToUsed(M, {AsanDtorFunction});
2287 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
2288
2289 return ReturnInst::Create(*C, AsanDtorBB);
2290}
2291
2292void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
2293 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2294 ArrayRef<Constant *> MetadataInitializers) {
2295 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2296 auto &DL = M.getDataLayout();
2297
2298 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2299 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2300 Constant *Initializer = MetadataInitializers[i];
2301 GlobalVariable *G = ExtendedGlobals[i];
2303 CreateMetadataGlobal(M, Initializer, G->getName());
2304 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2305 Metadata->setMetadata(LLVMContext::MD_associated, MD);
2306 MetadataGlobals[i] = Metadata;
2307
2308 // The MSVC linker always inserts padding when linking incrementally. We
2309 // cope with that by aligning each struct to its size, which must be a power
2310 // of two.
2311 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2312 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2313 "global metadata will not be padded appropriately");
2314 Metadata->setAlignment(assumeAligned(SizeOfGlobalStruct));
2315
2316 SetComdatForGlobalMetadata(G, Metadata, "");
2317 }
2318
2319 // Update llvm.compiler.used, adding the new metadata globals. This is
2320 // needed so that during LTO these variables stay alive.
2321 if (!MetadataGlobals.empty())
2322 appendToCompilerUsed(M, MetadataGlobals);
2323}
2324
2325void ModuleAddressSanitizer::instrumentGlobalsELF(
2326 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2327 ArrayRef<Constant *> MetadataInitializers,
2328 const std::string &UniqueModuleId) {
2329 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2330
2331 // Putting globals in a comdat changes the semantic and potentially cause
2332 // false negative odr violations at link time. If odr indicators are used, we
2333 // keep the comdat sections, as link time odr violations will be dectected on
2334 // the odr indicator symbols.
2335 bool UseComdatForGlobalsGC = UseOdrIndicator && !UniqueModuleId.empty();
2336
2337 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2338 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2339 GlobalVariable *G = ExtendedGlobals[i];
2341 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2342 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2343 Metadata->setMetadata(LLVMContext::MD_associated, MD);
2344 MetadataGlobals[i] = Metadata;
2345
2346 if (UseComdatForGlobalsGC)
2347 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2348 }
2349
2350 // Update llvm.compiler.used, adding the new metadata globals. This is
2351 // needed so that during LTO these variables stay alive.
2352 if (!MetadataGlobals.empty())
2353 appendToCompilerUsed(M, MetadataGlobals);
2354
2355 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2356 // to look up the loaded image that contains it. Second, we can store in it
2357 // whether registration has already occurred, to prevent duplicate
2358 // registration.
2359 //
2360 // Common linkage ensures that there is only one global per shared library.
2361 GlobalVariable *RegisteredFlag = new GlobalVariable(
2362 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2363 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2365
2366 // Create start and stop symbols.
2367 GlobalVariable *StartELFMetadata = new GlobalVariable(
2368 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2369 "__start_" + getGlobalMetadataSection());
2371 GlobalVariable *StopELFMetadata = new GlobalVariable(
2372 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2373 "__stop_" + getGlobalMetadataSection());
2375
2376 // Create a call to register the globals with the runtime.
2377 if (ConstructorKind == AsanCtorKind::Global)
2378 IRB.CreateCall(AsanRegisterElfGlobals,
2379 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2380 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2381 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2382
2383 // We also need to unregister globals at the end, e.g., when a shared library
2384 // gets closed.
2385 if (DestructorKind != AsanDtorKind::None && !MetadataGlobals.empty()) {
2386 IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2387 IrbDtor.CreateCall(AsanUnregisterElfGlobals,
2388 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2389 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2390 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2391 }
2392}
2393
2394void ModuleAddressSanitizer::InstrumentGlobalsMachO(
2395 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2396 ArrayRef<Constant *> MetadataInitializers) {
2397 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2398
2399 // On recent Mach-O platforms, use a structure which binds the liveness of
2400 // the global variable to the metadata struct. Keep the list of "Liveness" GV
2401 // created to be added to llvm.compiler.used
2402 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
2403 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2404
2405 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2406 Constant *Initializer = MetadataInitializers[i];
2407 GlobalVariable *G = ExtendedGlobals[i];
2409 CreateMetadataGlobal(M, Initializer, G->getName());
2410
2411 // On recent Mach-O platforms, we emit the global metadata in a way that
2412 // allows the linker to properly strip dead globals.
2413 auto LivenessBinder =
2414 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2416 GlobalVariable *Liveness = new GlobalVariable(
2417 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2418 Twine("__asan_binder_") + G->getName());
2419 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2420 LivenessGlobals[i] = Liveness;
2421 }
2422
2423 // Update llvm.compiler.used, adding the new liveness globals. This is
2424 // needed so that during LTO these variables stay alive. The alternative
2425 // would be to have the linker handling the LTO symbols, but libLTO
2426 // current API does not expose access to the section for each symbol.
2427 if (!LivenessGlobals.empty())
2428 appendToCompilerUsed(M, LivenessGlobals);
2429
2430 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2431 // to look up the loaded image that contains it. Second, we can store in it
2432 // whether registration has already occurred, to prevent duplicate
2433 // registration.
2434 //
2435 // common linkage ensures that there is only one global per shared library.
2436 GlobalVariable *RegisteredFlag = new GlobalVariable(
2437 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2438 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2440
2441 if (ConstructorKind == AsanCtorKind::Global)
2442 IRB.CreateCall(AsanRegisterImageGlobals,
2443 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2444
2445 // We also need to unregister globals at the end, e.g., when a shared library
2446 // gets closed.
2447 if (DestructorKind != AsanDtorKind::None) {
2448 IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2449 IrbDtor.CreateCall(AsanUnregisterImageGlobals,
2450 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2451 }
2452}
2453
2454void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
2455 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2456 ArrayRef<Constant *> MetadataInitializers) {
2457 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2458 unsigned N = ExtendedGlobals.size();
2459 assert(N > 0);
2460
2461 // On platforms that don't have a custom metadata section, we emit an array
2462 // of global metadata structures.
2463 ArrayType *ArrayOfGlobalStructTy =
2464 ArrayType::get(MetadataInitializers[0]->getType(), N);
2465 auto AllGlobals = new GlobalVariable(
2466 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2467 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
2468 if (Mapping.Scale > 3)
2469 AllGlobals->setAlignment(Align(1ULL << Mapping.Scale));
2470
2471 if (ConstructorKind == AsanCtorKind::Global)
2472 IRB.CreateCall(AsanRegisterGlobals,
2473 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2474 ConstantInt::get(IntptrTy, N)});
2475
2476 // We also need to unregister globals at the end, e.g., when a shared library
2477 // gets closed.
2478 if (DestructorKind != AsanDtorKind::None) {
2479 IRBuilder<> IrbDtor(CreateAsanModuleDtor(M));
2480 IrbDtor.CreateCall(AsanUnregisterGlobals,
2481 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2482 ConstantInt::get(IntptrTy, N)});
2483 }
2484}
2485
2486// This function replaces all global variables with new variables that have
2487// trailing redzones. It also creates a function that poisons
2488// redzones and inserts this function into llvm.global_ctors.
2489// Sets *CtorComdat to true if the global registration code emitted into the
2490// asan constructor is comdat-compatible.
2491void ModuleAddressSanitizer::instrumentGlobals(IRBuilder<> &IRB, Module &M,
2492 bool *CtorComdat) {
2493 // Build set of globals that are aliased by some GA, where
2494 // getExcludedAliasedGlobal(GA) returns the relevant GlobalVariable.
2495 SmallPtrSet<const GlobalVariable *, 16> AliasedGlobalExclusions;
2496 if (CompileKernel) {
2497 for (auto &GA : M.aliases()) {
2498 if (const GlobalVariable *GV = getExcludedAliasedGlobal(GA))
2499 AliasedGlobalExclusions.insert(GV);
2500 }
2501 }
2502
2503 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2504 for (auto &G : M.globals()) {
2505 if (!AliasedGlobalExclusions.count(&G) && shouldInstrumentGlobal(&G))
2506 GlobalsToChange.push_back(&G);
2507 }
2508
2509 size_t n = GlobalsToChange.size();
2510 auto &DL = M.getDataLayout();
2511
2512 // A global is described by a structure
2513 // size_t beg;
2514 // size_t size;
2515 // size_t size_with_redzone;
2516 // const char *name;
2517 // const char *module_name;
2518 // size_t has_dynamic_init;
2519 // size_t padding_for_windows_msvc_incremental_link;
2520 // size_t odr_indicator;
2521 // We initialize an array of such structures and pass it to a run-time call.
2522 StructType *GlobalStructTy =
2523 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
2524 IntptrTy, IntptrTy, IntptrTy);
2526 SmallVector<Constant *, 16> Initializers(n);
2527
2528 bool HasDynamicallyInitializedGlobals = false;
2529
2530 // We shouldn't merge same module names, as this string serves as unique
2531 // module ID in runtime.
2533 n != 0
2534 ? createPrivateGlobalForString(M, M.getModuleIdentifier(),
2535 /*AllowMerging*/ false, kAsanGenPrefix)
2536 : nullptr;
2537
2538 for (size_t i = 0; i < n; i++) {
2539 GlobalVariable *G = GlobalsToChange[i];
2540
2542 if (G->hasSanitizerMetadata())
2543 MD = G->getSanitizerMetadata();
2544
2545 // The runtime library tries demangling symbol names in the descriptor but
2546 // functionality like __cxa_demangle may be unavailable (e.g.
2547 // -static-libstdc++). So we demangle the symbol names here.
2548 std::string NameForGlobal = G->getName().str();
2551 /*AllowMerging*/ true, kAsanGenPrefix);
2552
2553 Type *Ty = G->getValueType();
2554 const uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
2555 const uint64_t RightRedzoneSize = getRedzoneSizeForGlobal(SizeInBytes);
2556 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2557
2558 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2559 Constant *NewInitializer = ConstantStruct::get(
2560 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
2561
2562 // Create a new global variable with enough space for a redzone.
2563 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2564 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2566 GlobalVariable *NewGlobal = new GlobalVariable(
2567 M, NewTy, G->isConstant(), Linkage, NewInitializer, "", G,
2568 G->getThreadLocalMode(), G->getAddressSpace());
2569 NewGlobal->copyAttributesFrom(G);
2570 NewGlobal->setComdat(G->getComdat());
2571 NewGlobal->setAlignment(Align(getMinRedzoneSizeForGlobal()));
2572 // Don't fold globals with redzones. ODR violation detector and redzone
2573 // poisoning implicitly creates a dependence on the global's address, so it
2574 // is no longer valid for it to be marked unnamed_addr.
2576
2577 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2578 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2579 G->isConstant()) {
2580 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2581 if (Seq && Seq->isCString())
2582 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2583 }
2584
2585 // Transfer the debug info and type metadata. The payload starts at offset
2586 // zero so we can copy the metadata over as is.
2587 NewGlobal->copyMetadata(G, 0);
2588
2589 Value *Indices2[2];
2590 Indices2[0] = IRB.getInt32(0);
2591 Indices2[1] = IRB.getInt32(0);
2592
2593 G->replaceAllUsesWith(
2594 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
2595 NewGlobal->takeName(G);
2596 G->eraseFromParent();
2597 NewGlobals[i] = NewGlobal;
2598
2599 Constant *ODRIndicator = ConstantPointerNull::get(PtrTy);
2600 GlobalValue *InstrumentedGlobal = NewGlobal;
2601
2602 bool CanUsePrivateAliases =
2603 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2604 TargetTriple.isOSBinFormatWasm();
2605 if (CanUsePrivateAliases && UsePrivateAlias) {
2606 // Create local alias for NewGlobal to avoid crash on ODR between
2607 // instrumented and non-instrumented libraries.
2608 InstrumentedGlobal =
2610 }
2611
2612 // ODR should not happen for local linkage.
2613 if (NewGlobal->hasLocalLinkage()) {
2614 ODRIndicator =
2615 ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1), PtrTy);
2616 } else if (UseOdrIndicator) {
2617 // With local aliases, we need to provide another externally visible
2618 // symbol __odr_asan_XXX to detect ODR violation.
2619 auto *ODRIndicatorSym =
2620 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2622 kODRGenPrefix + NameForGlobal, nullptr,
2623 NewGlobal->getThreadLocalMode());
2624
2625 // Set meaningful attributes for indicator symbol.
2626 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2627 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2628 ODRIndicatorSym->setAlignment(Align(1));
2629 ODRIndicator = ODRIndicatorSym;
2630 }
2631
2632 Constant *Initializer = ConstantStruct::get(
2633 GlobalStructTy,
2634 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
2635 ConstantInt::get(IntptrTy, SizeInBytes),
2636 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2639 ConstantInt::get(IntptrTy, MD.IsDynInit),
2640 Constant::getNullValue(IntptrTy),
2641 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
2642
2643 if (ClInitializers && MD.IsDynInit)
2644 HasDynamicallyInitializedGlobals = true;
2645
2646 LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
2647
2648 Initializers[i] = Initializer;
2649 }
2650
2651 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2652 // ConstantMerge'ing them.
2653 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2654 for (size_t i = 0; i < n; i++) {
2655 GlobalVariable *G = NewGlobals[i];
2656 if (G->getName().empty()) continue;
2657 GlobalsToAddToUsedList.push_back(G);
2658 }
2659 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2660
2661 if (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) {
2662 // Use COMDAT and register globals even if n == 0 to ensure that (a) the
2663 // linkage unit will only have one module constructor, and (b) the register
2664 // function will be called. The module destructor is not created when n ==
2665 // 0.
2666 *CtorComdat = true;
2667 instrumentGlobalsELF(IRB, M, NewGlobals, Initializers,
2668 getUniqueModuleId(&M));
2669 } else if (n == 0) {
2670 // When UseGlobalsGC is false, COMDAT can still be used if n == 0, because
2671 // all compile units will have identical module constructor/destructor.
2672 *CtorComdat = TargetTriple.isOSBinFormatELF();
2673 } else {
2674 *CtorComdat = false;
2675 if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
2676 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2677 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
2678 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2679 } else {
2680 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
2681 }
2682 }
2683
2684 // Create calls for poisoning before initializers run and unpoisoning after.
2685 if (HasDynamicallyInitializedGlobals)
2686 createInitializerPoisonCalls(M, ModuleName);
2687
2688 LLVM_DEBUG(dbgs() << M);
2689}
2690
2692ModuleAddressSanitizer::getRedzoneSizeForGlobal(uint64_t SizeInBytes) const {
2693 constexpr uint64_t kMaxRZ = 1 << 18;
2694 const uint64_t MinRZ = getMinRedzoneSizeForGlobal();
2695
2696 uint64_t RZ = 0;
2697 if (SizeInBytes <= MinRZ / 2) {
2698 // Reduce redzone size for small size objects, e.g. int, char[1]. MinRZ is
2699 // at least 32 bytes, optimize when SizeInBytes is less than or equal to
2700 // half of MinRZ.
2701 RZ = MinRZ - SizeInBytes;
2702 } else {
2703 // Calculate RZ, where MinRZ <= RZ <= MaxRZ, and RZ ~ 1/4 * SizeInBytes.
2704 RZ = std::clamp((SizeInBytes / MinRZ / 4) * MinRZ, MinRZ, kMaxRZ);
2705
2706 // Round up to multiple of MinRZ.
2707 if (SizeInBytes % MinRZ)
2708 RZ += MinRZ - (SizeInBytes % MinRZ);
2709 }
2710
2711 assert((RZ + SizeInBytes) % MinRZ == 0);
2712
2713 return RZ;
2714}
2715
2716int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
2717 int LongSize = M.getDataLayout().getPointerSizeInBits();
2718 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2719 int Version = 8;
2720 // 32-bit Android is one version ahead because of the switch to dynamic
2721 // shadow.
2722 Version += (LongSize == 32 && isAndroid);
2723 return Version;
2724}
2725
2726bool ModuleAddressSanitizer::instrumentModule(Module &M) {
2727 initializeCallbacks(M);
2728
2729 // Create a module constructor. A destructor is created lazily because not all
2730 // platforms, and not all modules need it.
2731 if (ConstructorKind == AsanCtorKind::Global) {
2732 if (CompileKernel) {
2733 // The kernel always builds with its own runtime, and therefore does not
2734 // need the init and version check calls.
2735 AsanCtorFunction = createSanitizerCtor(M, kAsanModuleCtorName);
2736 } else {
2737 std::string AsanVersion = std::to_string(GetAsanVersion(M));
2738 std::string VersionCheckName =
2739 InsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
2740 std::tie(AsanCtorFunction, std::ignore) =
2742 kAsanInitName, /*InitArgTypes=*/{},
2743 /*InitArgs=*/{}, VersionCheckName);
2744 }
2745 }
2746
2747 bool CtorComdat = true;
2748 if (ClGlobals) {
2749 assert(AsanCtorFunction || ConstructorKind == AsanCtorKind::None);
2750 if (AsanCtorFunction) {
2751 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
2752 instrumentGlobals(IRB, M, &CtorComdat);
2753 } else {
2754 IRBuilder<> IRB(*C);
2755 instrumentGlobals(IRB, M, &CtorComdat);
2756 }
2757 }
2758
2759 const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2760
2761 // Put the constructor and destructor in comdat if both
2762 // (1) global instrumentation is not TU-specific
2763 // (2) target is ELF.
2764 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2765 if (AsanCtorFunction) {
2766 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2767 appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
2768 }
2769 if (AsanDtorFunction) {
2770 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2771 appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
2772 }
2773 } else {
2774 if (AsanCtorFunction)
2775 appendToGlobalCtors(M, AsanCtorFunction, Priority);
2776 if (AsanDtorFunction)
2777 appendToGlobalDtors(M, AsanDtorFunction, Priority);
2778 }
2779
2780 return true;
2781}
2782
2783void AddressSanitizer::initializeCallbacks(Module &M, const TargetLibraryInfo *TLI) {
2784 IRBuilder<> IRB(*C);
2785 // Create __asan_report* callbacks.
2786 // IsWrite, TypeSize and Exp are encoded in the function name.
2787 for (int Exp = 0; Exp < 2; Exp++) {
2788 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2789 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2790 const std::string ExpStr = Exp ? "exp_" : "";
2791 const std::string EndingStr = Recover ? "_noabort" : "";
2792
2793 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2794 SmallVector<Type *, 2> Args1{1, IntptrTy};
2795 AttributeList AL2;
2796 AttributeList AL1;
2797 if (Exp) {
2798 Type *ExpType = Type::getInt32Ty(*C);
2799 Args2.push_back(ExpType);
2800 Args1.push_back(ExpType);
2801 if (auto AK = TLI->getExtAttrForI32Param(false)) {
2802 AL2 = AL2.addParamAttribute(*C, 2, AK);
2803 AL1 = AL1.addParamAttribute(*C, 1, AK);
2804 }
2805 }
2806 AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2807 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2808 FunctionType::get(IRB.getVoidTy(), Args2, false), AL2);
2809
2810 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2811 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2812 FunctionType::get(IRB.getVoidTy(), Args2, false), AL2);
2813
2814 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2815 AccessSizeIndex++) {
2816 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2817 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2818 M.getOrInsertFunction(
2819 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2820 FunctionType::get(IRB.getVoidTy(), Args1, false), AL1);
2821
2822 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2823 M.getOrInsertFunction(
2824 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2825 FunctionType::get(IRB.getVoidTy(), Args1, false), AL1);
2826 }
2827 }
2828 }
2829
2830 const std::string MemIntrinCallbackPrefix =
2831 (CompileKernel && !ClKasanMemIntrinCallbackPrefix)
2832 ? std::string("")
2834 AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2835 PtrTy, PtrTy, PtrTy, IntptrTy);
2836 AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy", PtrTy,
2837 PtrTy, PtrTy, IntptrTy);
2838 AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2839 TLI->getAttrList(C, {1}, /*Signed=*/false),
2840 PtrTy, PtrTy, IRB.getInt32Ty(), IntptrTy);
2841
2842 AsanHandleNoReturnFunc =
2843 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
2844
2845 AsanPtrCmpFunction =
2846 M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2847 AsanPtrSubFunction =
2848 M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
2849 if (Mapping.InGlobal)
2850 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2851 ArrayType::get(IRB.getInt8Ty(), 0));
2852
2853 AMDGPUAddressShared =
2854 M.getOrInsertFunction(kAMDGPUAddressSharedName, IRB.getInt1Ty(), PtrTy);
2855 AMDGPUAddressPrivate =
2856 M.getOrInsertFunction(kAMDGPUAddressPrivateName, IRB.getInt1Ty(), PtrTy);
2857}
2858
2859bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2860 // For each NSObject descendant having a +load method, this method is invoked
2861 // by the ObjC runtime before any of the static constructors is called.
2862 // Therefore we need to instrument such methods with a call to __asan_init
2863 // at the beginning in order to initialize our runtime before any access to
2864 // the shadow memory.
2865 // We cannot just ignore these methods, because they may call other
2866 // instrumented functions.
2867 if (F.getName().contains(" load]")) {
2868 FunctionCallee AsanInitFunction =
2869 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
2870 IRBuilder<> IRB(&F.front(), F.front().begin());
2871 IRB.CreateCall(AsanInitFunction, {});
2872 return true;
2873 }
2874 return false;
2875}
2876
2877bool AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2878 // Generate code only when dynamic addressing is needed.
2879 if (Mapping.Offset != kDynamicShadowSentinel)
2880 return false;
2881
2882 IRBuilder<> IRB(&F.front().front());
2883 if (Mapping.InGlobal) {
2885 // An empty inline asm with input reg == output reg.
2886 // An opaque pointer-to-int cast, basically.
2888 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2889 StringRef(""), StringRef("=r,0"),
2890 /*hasSideEffects=*/false);
2891 LocalDynamicShadow =
2892 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2893 } else {
2894 LocalDynamicShadow =
2895 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2896 }
2897 } else {
2898 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2900 LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
2901 }
2902 return true;
2903}
2904
2905void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2906 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2907 // to it as uninteresting. This assumes we haven't started processing allocas
2908 // yet. This check is done up front because iterating the use list in
2909 // isInterestingAlloca would be algorithmically slower.
2910 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2911
2912 // Try to get the declaration of llvm.localescape. If it's not in the module,
2913 // we can exit early.
2914 if (!F.getParent()->getFunction("llvm.localescape")) return;
2915
2916 // Look for a call to llvm.localescape call in the entry block. It can't be in
2917 // any other block.
2918 for (Instruction &I : F.getEntryBlock()) {
2919 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2920 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2921 // We found a call. Mark all the allocas passed in as uninteresting.
2922 for (Value *Arg : II->args()) {
2923 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2924 assert(AI && AI->isStaticAlloca() &&
2925 "non-static alloca arg to localescape");
2926 ProcessedAllocas[AI] = false;
2927 }
2928 break;
2929 }
2930 }
2931}
2932
2933bool AddressSanitizer::suppressInstrumentationSiteForDebug(int &Instrumented) {
2934 bool ShouldInstrument =
2935 ClDebugMin < 0 || ClDebugMax < 0 ||
2936 (Instrumented >= ClDebugMin && Instrumented <= ClDebugMax);
2937 Instrumented++;
2938 return !ShouldInstrument;
2939}
2940
2941bool AddressSanitizer::instrumentFunction(Function &F,
2942 const TargetLibraryInfo *TLI) {
2943 if (F.empty())
2944 return false;
2945 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2946 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2947 if (F.getName().starts_with("__asan_")) return false;
2948
2949 bool FunctionModified = false;
2950
2951 // If needed, insert __asan_init before checking for SanitizeAddress attr.
2952 // This function needs to be called even if the function body is not
2953 // instrumented.
2954 if (maybeInsertAsanInitAtFunctionEntry(F))
2955 FunctionModified = true;
2956
2957 // Leave if the function doesn't need instrumentation.
2958 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2959
2960 if (F.hasFnAttribute(Attribute::DisableSanitizerInstrumentation))
2961 return FunctionModified;
2962
2963 LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2964
2965 initializeCallbacks(*F.getParent(), TLI);
2966
2967 FunctionStateRAII CleanupObj(this);
2968
2969 RuntimeCallInserter RTCI(F);
2970
2971 FunctionModified |= maybeInsertDynamicShadowAtFunctionEntry(F);
2972
2973 // We can't instrument allocas used with llvm.localescape. Only static allocas
2974 // can be passed to that intrinsic.
2975 markEscapedLocalAllocas(F);
2976
2977 // We want to instrument every address only once per basic block (unless there
2978 // are calls between uses).
2979 SmallPtrSet<Value *, 16> TempsToInstrument;
2980 SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
2981 SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
2982 SmallVector<Instruction *, 8> NoReturnCalls;
2984 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2985
2986 // Fill the set of memory operations to instrument.
2987 for (auto &BB : F) {
2988 AllBlocks.push_back(&BB);
2989 TempsToInstrument.clear();
2990 int NumInsnsPerBB = 0;
2991 for (auto &Inst : BB) {
2992 if (LooksLikeCodeInBug11395(&Inst)) return false;
2993 // Skip instructions inserted by another instrumentation.
2994 if (Inst.hasMetadata(LLVMContext::MD_nosanitize))
2995 continue;
2996 SmallVector<InterestingMemoryOperand, 1> InterestingOperands;
2997 getInterestingMemoryOperands(&Inst, InterestingOperands);
2998
2999 if (!InterestingOperands.empty()) {
3000 for (auto &Operand : InterestingOperands) {
3001 if (ClOpt && ClOptSameTemp) {
3002 Value *Ptr = Operand.getPtr();
3003 // If we have a mask, skip instrumentation if we've already
3004 // instrumented the full object. But don't add to TempsToInstrument
3005 // because we might get another load/store with a different mask.
3006 if (Operand.MaybeMask) {
3007 if (TempsToInstrument.count(Ptr))
3008 continue; // We've seen this (whole) temp in the current BB.
3009 } else {
3010 if (!TempsToInstrument.insert(Ptr).second)
3011 continue; // We've seen this temp in the current BB.
3012 }
3013 }
3014 OperandsToInstrument.push_back(Operand);
3015 NumInsnsPerBB++;
3016 }
3017 } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
3021 PointerComparisonsOrSubtracts.push_back(&Inst);
3022 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst)) {
3023 // ok, take it.
3024 IntrinToInstrument.push_back(MI);
3025 NumInsnsPerBB++;
3026 } else {
3027 if (auto *CB = dyn_cast<CallBase>(&Inst)) {
3028 // A call inside BB.
3029 TempsToInstrument.clear();
3030 if (CB->doesNotReturn())
3031 NoReturnCalls.push_back(CB);
3032 }
3033 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
3035 }
3036 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
3037 }
3038 }
3039
3040 bool UseCalls = (InstrumentationWithCallsThreshold >= 0 &&
3041 OperandsToInstrument.size() + IntrinToInstrument.size() >
3042 (unsigned)InstrumentationWithCallsThreshold);
3043 const DataLayout &DL = F.getParent()->getDataLayout();
3044 ObjectSizeOpts ObjSizeOpts;
3045 ObjSizeOpts.RoundToAlign = true;
3046 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
3047
3048 // Instrument.
3049 int NumInstrumented = 0;
3050 for (auto &Operand : OperandsToInstrument) {
3051 if (!suppressInstrumentationSiteForDebug(NumInstrumented))
3052 instrumentMop(ObjSizeVis, Operand, UseCalls,
3053 F.getParent()->getDataLayout(), RTCI);
3054 FunctionModified = true;
3055 }
3056 for (auto *Inst : IntrinToInstrument) {
3057 if (!suppressInstrumentationSiteForDebug(NumInstrumented))
3058 instrumentMemIntrinsic(Inst, RTCI);
3059 FunctionModified = true;
3060 }
3061
3062 FunctionStackPoisoner FSP(F, *this, RTCI);
3063 bool ChangedStack = FSP.runOnFunction();
3064
3065 // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
3066 // See e.g. https://github.com/google/sanitizers/issues/37
3067 for (auto *CI : NoReturnCalls) {
3068 IRBuilder<> IRB(CI);
3069 RTCI.createRuntimeCall(IRB, AsanHandleNoReturnFunc, {});
3070 }
3071
3072 for (auto *Inst : PointerComparisonsOrSubtracts) {
3073 instrumentPointerComparisonOrSubtraction(Inst, RTCI);
3074 FunctionModified = true;
3075 }
3076
3077 if (ChangedStack || !NoReturnCalls.empty())
3078 FunctionModified = true;
3079
3080 LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
3081 << F << "\n");
3082
3083 return FunctionModified;
3084}
3085
3086// Workaround for bug 11395: we don't want to instrument stack in functions
3087// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
3088// FIXME: remove once the bug 11395 is fixed.
3089bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
3090 if (LongSize != 32) return false;
3091 CallInst *CI = dyn_cast<CallInst>(I);
3092 if (!CI || !CI->isInlineAsm()) return false;
3093 if (CI->arg_size() <= 5)
3094 return false;
3095 // We have inline assembly with quite a few arguments.
3096 return true;
3097}
3098
3099void FunctionStackPoisoner::initializeCallbacks(Module &M) {
3100 IRBuilder<> IRB(*C);
3101 if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always ||
3102 ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
3103 const char *MallocNameTemplate =
3104 ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Always
3107 for (int Index = 0; Index <= kMaxAsanStackMallocSizeClass; Index++) {
3108 std::string Suffix = itostr(Index);
3109 AsanStackMallocFunc[Index] = M.getOrInsertFunction(
3110 MallocNameTemplate + Suffix, IntptrTy, IntptrTy);
3111 AsanStackFreeFunc[Index] =
3112 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
3113 IRB.getVoidTy(), IntptrTy, IntptrTy);
3114 }
3115 }
3116 if (ASan.UseAfterScope) {
3117 AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
3118 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
3119 AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
3120 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
3121 }
3122
3123 for (size_t Val : {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0xf1, 0xf2,
3124 0xf3, 0xf5, 0xf8}) {
3125 std::ostringstream Name;
3127 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
3128 AsanSetShadowFunc[Val] =
3129 M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
3130 }
3131
3132 AsanAllocaPoisonFunc = M.getOrInsertFunction(
3133 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
3134 AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
3135 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
3136}
3137
3138void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
3139 ArrayRef<uint8_t> ShadowBytes,
3140 size_t Begin, size_t End,
3141 IRBuilder<> &IRB,
3142 Value *ShadowBase) {
3143 if (Begin >= End)
3144 return;
3145
3146 const size_t LargestStoreSizeInBytes =
3147 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
3148
3149 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
3150
3151 // Poison given range in shadow using larges store size with out leading and
3152 // trailing zeros in ShadowMask. Zeros never change, so they need neither
3153 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
3154 // middle of a store.
3155 for (size_t i = Begin; i < End;) {
3156 if (!ShadowMask[i]) {
3157 assert(!ShadowBytes[i]);
3158 ++i;
3159 continue;
3160 }
3161
3162 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
3163 // Fit store size into the range.
3164 while (StoreSizeInBytes > End - i)
3165 StoreSizeInBytes /= 2;
3166
3167 // Minimize store size by trimming trailing zeros.
3168 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
3169 while (j <= StoreSizeInBytes / 2)
3170 StoreSizeInBytes /= 2;
3171 }
3172
3173 uint64_t Val = 0;
3174 for (size_t j = 0; j < StoreSizeInBytes; j++) {
3175 if (IsLittleEndian)
3176 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
3177 else
3178 Val = (Val << 8) | ShadowBytes[i + j];
3179 }
3180
3181 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
3182 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
3184 Poison, IRB.CreateIntToPtr(Ptr, PointerType::getUnqual(Poison->getContext())),
3185 Align(1));
3186
3187 i += StoreSizeInBytes;
3188 }
3189}
3190
3191void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3192 ArrayRef<uint8_t> ShadowBytes,
3193 IRBuilder<> &IRB, Value *ShadowBase) {
3194 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
3195}
3196
3197void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
3198 ArrayRef<uint8_t> ShadowBytes,
3199 size_t Begin, size_t End,
3200 IRBuilder<> &IRB, Value *ShadowBase) {
3201 assert(ShadowMask.size() == ShadowBytes.size());
3202 size_t Done = Begin;
3203 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
3204 if (!ShadowMask[i]) {
3205 assert(!ShadowBytes[i]);
3206 continue;
3207 }
3208 uint8_t Val = ShadowBytes[i];
3209 if (!AsanSetShadowFunc[Val])
3210 continue;
3211
3212 // Skip same values.
3213 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
3214 }
3215
3216 if (j - i >= ASan.MaxInlinePoisoningSize) {
3217 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
3218 RTCI.createRuntimeCall(
3219 IRB, AsanSetShadowFunc[Val],
3220 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
3221 ConstantInt::get(IntptrTy, j - i)});
3222 Done = j;
3223 }
3224 }
3225
3226 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
3227}
3228
3229// Fake stack allocator (asan_fake_stack.h) has 11 size classes
3230// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
3231static int StackMallocSizeClass(uint64_t LocalStackSize) {
3232 assert(LocalStackSize <= kMaxStackMallocSize);
3233 uint64_t MaxSize = kMinStackMallocSize;
3234 for (int i = 0;; i++, MaxSize *= 2)
3235 if (LocalStackSize <= MaxSize) return i;
3236 llvm_unreachable("impossible LocalStackSize");
3237}
3238
3239void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
3240 Instruction *CopyInsertPoint = &F.front().front();
3241 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
3242 // Insert after the dynamic shadow location is determined
3243 CopyInsertPoint = CopyInsertPoint->getNextNode();
3244 assert(CopyInsertPoint);
3245 }
3246 IRBuilder<> IRB(CopyInsertPoint);
3247 const DataLayout &DL = F.getParent()->getDataLayout();
3248 for (Argument &Arg : F.args()) {
3249 if (Arg.hasByValAttr()) {
3250 Type *Ty = Arg.getParamByValType();
3251 const Align Alignment =
3252 DL.getValueOrABITypeAlignment(Arg.getParamAlign(), Ty);
3253
3254 AllocaInst *AI = IRB.CreateAlloca(
3255 Ty, nullptr,
3256 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
3257 ".byval");
3258 AI->setAlignment(Alignment);
3259 Arg.replaceAllUsesWith(AI);
3260
3261 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
3262 IRB.CreateMemCpy(AI, Alignment, &Arg, Alignment, AllocSize);
3263 }
3264 }
3265}
3266
3267PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
3268 Value *ValueIfTrue,
3269 Instruction *ThenTerm,
3270 Value *ValueIfFalse) {
3271 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
3272 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
3273 PHI->addIncoming(ValueIfFalse, CondBlock);
3274 BasicBlock *ThenBlock = ThenTerm->getParent();
3275 PHI->addIncoming(ValueIfTrue, ThenBlock);
3276 return PHI;
3277}
3278
3279Value *FunctionStackPoisoner::createAllocaForLayout(
3280 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
3281 AllocaInst *Alloca;
3282 if (Dynamic) {
3283 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
3284 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
3285 "MyAlloca");
3286 } else {
3287 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
3288 nullptr, "MyAlloca");
3289 assert(Alloca->isStaticAlloca());
3290 }
3291 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
3292 uint64_t FrameAlignment = std::max(L.FrameAlignment, uint64_t(ClRealignStack));
3293 Alloca->setAlignment(Align(FrameAlignment));
3294 return IRB.CreatePointerCast(Alloca, IntptrTy);
3295}
3296
3297void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
3298 BasicBlock &FirstBB = *F.begin();
3299 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
3300 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
3301 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
3302 DynamicAllocaLayout->setAlignment(Align(32));
3303}
3304
3305void FunctionStackPoisoner::processDynamicAllocas() {
3306 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
3307 assert(DynamicAllocaPoisonCallVec.empty());
3308 return;
3309 }
3310
3311 // Insert poison calls for lifetime intrinsics for dynamic allocas.
3312 for (const auto &APC : DynamicAllocaPoisonCallVec) {
3313 assert(APC.InsBefore);
3314 assert(APC.AI);
3315 assert(ASan.isInterestingAlloca(*APC.AI));
3316 assert(!APC.AI->isStaticAlloca());
3317
3318 IRBuilder<> IRB(APC.InsBefore);
3319 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
3320 // Dynamic allocas will be unpoisoned unconditionally below in
3321 // unpoisonDynamicAllocas.
3322 // Flag that we need unpoison static allocas.
3323 }
3324
3325 // Handle dynamic allocas.
3326 createDynamicAllocasInitStorage();
3327 for (auto &AI : DynamicAllocaVec)
3328 handleDynamicAllocaCall(AI);
3329 unpoisonDynamicAllocas();
3330}
3331
3332/// Collect instructions in the entry block after \p InsBefore which initialize
3333/// permanent storage for a function argument. These instructions must remain in
3334/// the entry block so that uninitialized values do not appear in backtraces. An
3335/// added benefit is that this conserves spill slots. This does not move stores
3336/// before instrumented / "interesting" allocas.
3338 AddressSanitizer &ASan, Instruction &InsBefore,
3339 SmallVectorImpl<Instruction *> &InitInsts) {
3340 Instruction *Start = InsBefore.getNextNonDebugInstruction();
3341 for (Instruction *It = Start; It; It = It->getNextNonDebugInstruction()) {
3342 // Argument initialization looks like:
3343 // 1) store <Argument>, <Alloca> OR
3344 // 2) <CastArgument> = cast <Argument> to ...
3345 // store <CastArgument> to <Alloca>
3346 // Do not consider any other kind of instruction.
3347 //
3348 // Note: This covers all known cases, but may not be exhaustive. An
3349 // alternative to pattern-matching stores is to DFS over all Argument uses:
3350 // this might be more general, but is probably much more complicated.
3351 if (isa<AllocaInst>(It) || isa<CastInst>(It))
3352 continue;
3353 if (auto *Store = dyn_cast<StoreInst>(It)) {
3354 // The store destination must be an alloca that isn't interesting for
3355 // ASan to instrument. These are moved up before InsBefore, and they're
3356 // not interesting because allocas for arguments can be mem2reg'd.
3357 auto *Alloca = dyn_cast<AllocaInst>(Store->getPointerOperand());
3358 if (!Alloca || ASan.isInterestingAlloca(*Alloca))
3359 continue;
3360
3361 Value *Val = Store->getValueOperand();
3362 bool IsDirectArgInit = isa<Argument>(Val);
3363 bool IsArgInitViaCast =
3364 isa<CastInst>(Val) &&
3365 isa<Argument>(cast<CastInst>(Val)->getOperand(0)) &&
3366 // Check that the cast appears directly before the store. Otherwise
3367 // moving the cast before InsBefore may break the IR.
3368 Val == It->getPrevNonDebugInstruction();
3369 bool IsArgInit = IsDirectArgInit || IsArgInitViaCast;
3370 if (!IsArgInit)
3371 continue;
3372
3373 if (IsArgInitViaCast)
3374 InitInsts.push_back(cast<Instruction>(Val));
3375 InitInsts.push_back(Store);
3376 continue;
3377 }
3378
3379 // Do not reorder past unknown instructions: argument initialization should
3380 // only involve casts and stores.
3381 return;
3382 }
3383}
3384
3385void FunctionStackPoisoner::processStaticAllocas() {
3386 if (AllocaVec.empty()) {
3387 assert(StaticAllocaPoisonCallVec.empty());
3388 return;
3389 }
3390
3391 int StackMallocIdx = -1;
3392 DebugLoc EntryDebugLocation;
3393 if (auto SP = F.getSubprogram())
3394 EntryDebugLocation =
3395 DILocation::get(SP->getContext(), SP->getScopeLine(), 0, SP);
3396
3397 Instruction *InsBefore = AllocaVec[0];
3398 IRBuilder<> IRB(InsBefore);
3399
3400 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
3401 // debug info is broken, because only entry-block allocas are treated as
3402 // regular stack slots.
3403 auto InsBeforeB = InsBefore->getParent();
3404 assert(InsBeforeB == &F.getEntryBlock());
3405 for (auto *AI : StaticAllocasToMoveUp)
3406 if (AI->getParent() == InsBeforeB)
3407 AI->moveBefore(InsBefore);
3408
3409 // Move stores of arguments into entry-block allocas as well. This prevents
3410 // extra stack slots from being generated (to house the argument values until
3411 // they can be stored into the allocas). This also prevents uninitialized
3412 // values from being shown in backtraces.
3413 SmallVector<Instruction *, 8> ArgInitInsts;
3414 findStoresToUninstrumentedArgAllocas(ASan, *InsBefore, ArgInitInsts);
3415 for (Instruction *ArgInitInst : ArgInitInsts)
3416 ArgInitInst->moveBefore(InsBefore);
3417
3418 // If we have a call to llvm.localescape, keep it in the entry block.
3419 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3420
3422 SVD.reserve(AllocaVec.size());
3423 for (AllocaInst *AI : AllocaVec) {
3425 ASan.getAllocaSizeInBytes(*AI),
3426 0,
3427 AI->getAlign().value(),
3428 AI,
3429 0,
3430 0};
3431 SVD.push_back(D);
3432 }
3433
3434 // Minimal header size (left redzone) is 4 pointers,
3435 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
3436 uint64_t Granularity = 1ULL << Mapping.Scale;
3437 uint64_t MinHeaderSize = std::max((uint64_t)ASan.LongSize / 2, Granularity);
3438 const ASanStackFrameLayout &L =
3439 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
3440
3441 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3443 for (auto &Desc : SVD)
3444 AllocaToSVDMap[Desc.AI] = &Desc;
3445
3446 // Update SVD with information from lifetime intrinsics.
3447 for (const auto &APC : StaticAllocaPoisonCallVec) {
3448 assert(APC.InsBefore);
3449 assert(APC.AI);
3450 assert(ASan.isInterestingAlloca(*APC.AI));
3451 assert(APC.AI->isStaticAlloca());
3452
3453 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3454 Desc.LifetimeSize = Desc.Size;
3455 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3456 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3457 if (LifetimeLoc->getFile() == FnLoc->getFile())
3458 if (unsigned Line = LifetimeLoc->getLine())
3459 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3460 }
3461 }
3462 }
3463
3464 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
3465 LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
3466 uint64_t LocalStackSize = L.FrameSize;
3467 bool DoStackMalloc =
3468 ASan.UseAfterReturn != AsanDetectStackUseAfterReturnMode::Never &&
3469 !ASan.CompileKernel && LocalStackSize <= kMaxStackMallocSize;
3470 bool DoDynamicAlloca = ClDynamicAllocaStack;
3471 // Don't do dynamic alloca or stack malloc if:
3472 // 1) There is inline asm: too often it makes assumptions on which registers
3473 // are available.
3474 // 2) There is a returns_twice call (typically setjmp), which is
3475 // optimization-hostile, and doesn't play well with introduced indirect
3476 // register-relative calculation of local variable addresses.
3477 DoDynamicAlloca &= !HasInlineAsm && !HasReturnsTwiceCall;
3478 DoStackMalloc &= !HasInlineAsm && !HasReturnsTwiceCall;
3479
3480 Value *StaticAlloca =
3481 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3482
3483 Value *FakeStack;
3484 Value *LocalStackBase;
3485 Value *LocalStackBaseAlloca;
3486 uint8_t DIExprFlags = DIExpression::ApplyOffset;
3487
3488 if (DoStackMalloc) {
3489 LocalStackBaseAlloca =
3490 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
3491 if (ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode::Runtime) {
3492 // void *FakeStack = __asan_option_detect_stack_use_after_return
3493 // ? __asan_stack_malloc_N(LocalStackSize)
3494 // : nullptr;
3495 // void *LocalStackBase = (FakeStack) ? FakeStack :
3496 // alloca(LocalStackSize);
3497 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3499 Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3500 IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3502 Instruction *Term =
3503 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
3504 IRBuilder<> IRBIf(Term);
3505 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3506 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3507 Value *FakeStackValue =
3508 RTCI.createRuntimeCall(IRBIf, AsanStackMallocFunc[StackMallocIdx],
3509 ConstantInt::get(IntptrTy, LocalStackSize));
3510 IRB.SetInsertPoint(InsBefore);
3511 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
3512 ConstantInt::get(IntptrTy, 0));
3513 } else {
3514 // assert(ASan.UseAfterReturn == AsanDetectStackUseAfterReturnMode:Always)
3515 // void *FakeStack = __asan_stack_malloc_N(LocalStackSize);
3516 // void *LocalStackBase = (FakeStack) ? FakeStack :
3517 // alloca(LocalStackSize);
3518 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3519 FakeStack =
3520 RTCI.createRuntimeCall(IRB, AsanStackMallocFunc[StackMallocIdx],
3521 ConstantInt::get(IntptrTy, LocalStackSize));
3522 }
3523 Value *NoFakeStack =
3524 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3525 Instruction *Term =
3526 SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3527 IRBuilder<> IRBIf(Term);
3528 Value *AllocaValue =
3529 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
3530
3531 IRB.SetInsertPoint(InsBefore);
3532 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
3533 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3534 DIExprFlags |= DIExpression::DerefBefore;
3535 } else {
3536 // void *FakeStack = nullptr;
3537 // void *LocalStackBase = alloca(LocalStackSize);
3538 FakeStack = ConstantInt::get(IntptrTy, 0);
3539 LocalStackBase =
3540 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
3541 LocalStackBaseAlloca = LocalStackBase;
3542 }
3543
3544 // It shouldn't matter whether we pass an `alloca` or a `ptrtoint` as the
3545 // dbg.declare address opereand, but passing a `ptrtoint` seems to confuse
3546 // later passes and can result in dropped variable coverage in debug info.
3547 Value *LocalStackBaseAllocaPtr =
3548 isa<PtrToIntInst>(LocalStackBaseAlloca)
3549 ? cast<PtrToIntInst>(LocalStackBaseAlloca)->getPointerOperand()
3550 : LocalStackBaseAlloca;
3551 assert(isa<AllocaInst>(LocalStackBaseAllocaPtr) &&
3552 "Variable descriptions relative to ASan stack base will be dropped");
3553
3554 // Replace Alloca instructions with base+offset.
3555 for (const auto &Desc : SVD) {
3556 AllocaInst *AI = Desc.AI;
3557 replaceDbgDeclare(AI, LocalStackBaseAllocaPtr, DIB, DIExprFlags,
3558 Desc.Offset);
3559 Value *NewAllocaPtr = IRB.CreateIntToPtr(
3560 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
3561 AI->getType());
3562 AI->replaceAllUsesWith(NewAllocaPtr);
3563 }
3564
3565 // The left-most redzone has enough space for at least 4 pointers.
3566 // Write the Magic value to redzone[0].
3567 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3568 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3569 BasePlus0);
3570 // Write the frame description constant to redzone[1].
3571 Value *BasePlus1 = IRB.CreateIntToPtr(
3572 IRB.CreateAdd(LocalStackBase,
3573 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3574 IntptrPtrTy);
3575 GlobalVariable *StackDescriptionGlobal =
3576 createPrivateGlobalForString(*F.getParent(), DescriptionString,
3577 /*AllowMerging*/ true, kAsanGenPrefix);
3578 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
3579 IRB.CreateStore(Description, BasePlus1);
3580 // Write the PC to redzone[2].
3581 Value *BasePlus2 = IRB.CreateIntToPtr(
3582 IRB.CreateAdd(LocalStackBase,
3583 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3584 IntptrPtrTy);
3585 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
3586
3587 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3588
3589 // Poison the stack red zones at the entry.
3590 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
3591 // As mask we must use most poisoned case: red zones and after scope.
3592 // As bytes we can use either the same or just red zones only.
3593 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3594
3595 if (!StaticAllocaPoisonCallVec.empty()) {
3596 const auto &ShadowInScope = GetShadowBytes(SVD, L);
3597
3598 // Poison static allocas near lifetime intrinsics.
3599 for (const auto &APC : StaticAllocaPoisonCallVec) {
3600 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3601 assert(Desc.Offset % L.Granularity == 0);
3602 size_t Begin = Desc.Offset / L.Granularity;
3603 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3604
3605 IRBuilder<> IRB(APC.InsBefore);
3606 copyToShadow(ShadowAfterScope,
3607 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3608 IRB, ShadowBase);
3609 }
3610 }
3611
3612 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
3613 SmallVector<uint8_t, 64> ShadowAfterReturn;
3614
3615 // (Un)poison the stack before all ret instructions.
3616 for (Instruction *Ret : RetVec) {
3617 IRBuilder<> IRBRet(Ret);
3618 // Mark the current frame as retired.
3619 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3620 BasePlus0);
3621 if (DoStackMalloc) {
3622 assert(StackMallocIdx >= 0);
3623 // if FakeStack != 0 // LocalStackBase == FakeStack
3624 // // In use-after-return mode, poison the whole stack frame.
3625 // if StackMallocIdx <= 4
3626 // // For small sizes inline the whole thing:
3627 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
3628 // **SavedFlagPtr(FakeStack) = 0
3629 // else
3630 // __asan_stack_free_N(FakeStack, LocalStackSize)
3631 // else
3632 // <This is not a fake stack; unpoison the redzones>
3633 Value *Cmp =
3634 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
3635 Instruction *ThenTerm, *ElseTerm;
3636 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3637
3638 IRBuilder<> IRBPoison(ThenTerm);
3639 if (ASan.MaxInlinePoisoningSize != 0 && StackMallocIdx <= 4) {
3640 int ClassSize = kMinStackMallocSize << StackMallocIdx;
3641 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3643 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3644 ShadowBase);
3645 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
3646 FakeStack,
3647 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3648 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3649 IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3650 IRBPoison.CreateStore(
3651 Constant::getNullValue(IRBPoison.getInt8Ty()),
3652 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getPtrTy()));
3653 } else {
3654 // For larger frames call __asan_stack_free_*.
3655 RTCI.createRuntimeCall(
3656 IRBPoison, AsanStackFreeFunc[StackMallocIdx],
3657 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
3658 }
3659
3660 IRBuilder<> IRBElse(ElseTerm);
3661 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
3662 } else {
3663 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
3664 }
3665 }
3666
3667 // We are done. Remove the old unused alloca instructions.
3668 for (auto *AI : AllocaVec)
3669 AI->eraseFromParent();
3670}
3671
3672void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
3673 IRBuilder<> &IRB, bool DoPoison) {
3674 // For now just insert the call to ASan runtime.
3675 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3676 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
3677 RTCI.createRuntimeCall(
3678 IRB, DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3679 {AddrArg, SizeArg});
3680}
3681
3682// Handling llvm.lifetime intrinsics for a given %alloca:
3683// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3684// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3685// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3686// could be poisoned by previous llvm.lifetime.end instruction, as the
3687// variable may go in and out of scope several times, e.g. in loops).
3688// (3) if we poisoned at least one %alloca in a function,
3689// unpoison the whole stack frame at function exit.
3690void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
3691 IRBuilder<> IRB(AI);
3692
3693 const Align Alignment = std::max(Align(kAllocaRzSize), AI->getAlign());
3694 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3695
3696 Value *Zero = Constant::getNullValue(IntptrTy);
3697 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3698 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
3699
3700 // Since we need to extend alloca with additional memory to locate
3701 // redzones, and OldSize is number of allocated blocks with
3702 // ElementSize size, get allocated memory size in bytes by
3703 // OldSize * ElementSize.
3704 const unsigned ElementSize =
3705 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
3706 Value *OldSize =
3707 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3708 ConstantInt::get(IntptrTy, ElementSize));
3709
3710 // PartialSize = OldSize % 32
3711 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3712
3713 // Misalign = kAllocaRzSize - PartialSize;
3714 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3715
3716 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3717 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3718 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3719
3720 // AdditionalChunkSize = Alignment + PartialPadding + kAllocaRzSize
3721 // Alignment is added to locate left redzone, PartialPadding for possible
3722 // partial redzone and kAllocaRzSize for right redzone respectively.
3723 Value *AdditionalChunkSize = IRB.CreateAdd(
3724 ConstantInt::get(IntptrTy, Alignment.value() + kAllocaRzSize),
3725 PartialPadding);
3726
3727 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3728
3729 // Insert new alloca with new NewSize and Alignment params.
3730 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3731 NewAlloca->setAlignment(Alignment);
3732
3733 // NewAddress = Address + Alignment
3734 Value *NewAddress =
3735 IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3736 ConstantInt::get(IntptrTy, Alignment.value()));
3737
3738 // Insert __asan_alloca_poison call for new created alloca.
3739 RTCI.createRuntimeCall(IRB, AsanAllocaPoisonFunc, {NewAddress, OldSize});
3740
3741 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3742 // for unpoisoning stuff.
3743 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3744
3745 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3746
3747 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
3748 AI->replaceAllUsesWith(NewAddressPtr);
3749
3750 // We are done. Erase old alloca from parent.
3751 AI->eraseFromParent();
3752}
3753
3754// isSafeAccess returns true if Addr is always inbounds with respect to its
3755// base object. For example, it is a field access or an array access with
3756// constant inbounds index.
3757bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3758 Value *Addr, TypeSize TypeStoreSize) const {
3759 if (TypeStoreSize.isScalable())
3760 // TODO: We can use vscale_range to convert a scalable value to an
3761 // upper bound on the access size.
3762 return false;
3763
3764 SizeOffsetAPInt SizeOffset = ObjSizeVis.compute(Addr);
3765 if (!SizeOffset.bothKnown())
3766 return false;
3767
3768 uint64_t Size = SizeOffset.Size.getZExtValue();
3769 int64_t Offset = SizeOffset.Offset.getSExtValue();
3770
3771 // Three checks are required to ensure safety:
3772 // . Offset >= 0 (since the offset is given from the base ptr)
3773 // . Size >= Offset (unsigned)
3774 // . Size - Offset >= NeededSize (unsigned)
3775 return Offset >= 0 && Size >= uint64_t(Offset) &&
3776 Size - uint64_t(Offset) >= TypeStoreSize / 8;
3777}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< bool > ClUseStackSafety("stack-tagging-use-stack-safety", cl::Hidden, cl::init(true), cl::desc("Use Stack Safety analysis results"))
Rewrite undef for PHI
static void findStoresToUninstrumentedArgAllocas(AddressSanitizer &ASan, Instruction &InsBefore, SmallVectorImpl< Instruction * > &InitInsts)
Collect instructions in the entry block after InsBefore which initialize permanent storage for a func...
static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I, Instruction *InsertBefore, Value *Addr, MaybeAlign Alignment, unsigned Granularity, TypeSize TypeStoreSize, bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp, RuntimeCallInserter &RTCI)
static const uint64_t kDefaultShadowScale
const char kAMDGPUUnreachableName[]
constexpr size_t kAccessSizeIndexMask
static cl::opt< int > ClDebugMin("asan-debug-min", cl::desc("Debug min inst"), cl::Hidden, cl::init(-1))
static cl::opt< bool > ClUsePrivateAlias("asan-use-private-alias", cl::desc("Use private aliases for global variables"), cl::Hidden, cl::init(true))
static const uint64_t kPS_ShadowOffset64
static const uint64_t kFreeBSD_ShadowOffset32
constexpr size_t kIsWriteShift
static const uint64_t kSmallX86_64ShadowOffsetAlignMask
static bool isInterestingPointerSubtraction(Instruction *I)
const char kAMDGPUAddressSharedName[]
const char kAsanStackFreeNameTemplate[]
constexpr size_t kCompileKernelMask
static cl::opt< bool > ClForceDynamicShadow("asan-force-dynamic-shadow", cl::desc("Load shadow address into a local variable for each function"), cl::Hidden, cl::init(false))
const char kAsanOptionDetectUseAfterReturn[]
static cl::opt< std::string > ClMemoryAccessCallbackPrefix("asan-memory-access-callback-prefix", cl::desc("Prefix for memory access callbacks"), cl::Hidden, cl::init("__asan_"))
static const uint64_t kRISCV64_ShadowOffset64
static cl::opt< bool > ClInsertVersionCheck("asan-guard-against-version-mismatch", cl::desc("Guard against compiler/runtime version mismatch."), cl::Hidden, cl::init(true))
const char kAsanSetShadowPrefix[]
static cl::opt< AsanDtorKind > ClOverrideDestructorKind("asan-destructor-kind", cl::desc("Sets the ASan destructor kind. The default is to use the value " "provided to the pass constructor"), cl::values(clEnumValN(AsanDtorKind::None, "none", "No destructors"), clEnumValN(AsanDtorKind::Global, "global", "Use global destructors")), cl::init(AsanDtorKind::Invalid), cl::Hidden)
static cl::opt< bool > ClInstrumentWrites("asan-instrument-writes", cl::desc("instrument write instructions"), cl::Hidden, cl::init(true))
const char kAsanPtrCmp[]
static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple)
const char kAsanStackMallocNameTemplate[]
static cl::opt< bool > ClInstrumentByval("asan-instrument-byval", cl::desc("instrument byval call arguments"), cl::Hidden, cl::init(true))
const char kAsanInitName[]
static cl::opt< bool > ClGlobals("asan-globals", cl::desc("Handle global objects"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClRedzoneByvalArgs("asan-redzone-byval-args", cl::desc("Create redzones for byval " "arguments (extra copy " "required)"), cl::Hidden, cl::init(true))
static const uint64_t kWindowsShadowOffset64
static const uint64_t kEmscriptenShadowOffset
const char kAsanGenPrefix[]
constexpr size_t kIsWriteMask
static uint64_t getRedzoneSizeForScale(int MappingScale)
static const uint64_t kDefaultShadowOffset64
static cl::opt< bool > ClOptimizeCallbacks("asan-optimize-callbacks", cl::desc("Optimize callbacks"), cl::Hidden, cl::init(false))
const char kAsanUnregisterGlobalsName[]
static const uint64_t kAsanCtorAndDtorPriority
const char kAsanUnpoisonGlobalsName[]
static cl::opt< bool > ClWithIfuncSuppressRemat("asan-with-ifunc-suppress-remat", cl::desc("Suppress rematerialization of dynamic shadow address by passing " "it through inline asm in prologue."), cl::Hidden, cl::init(true))
static cl::opt< int > ClDebugStack("asan-debug-stack", cl::desc("debug stack"), cl::Hidden, cl::init(0))
const char kAsanUnregisterElfGlobalsName[]
static bool isUnsupportedAMDGPUAddrspace(Value *Addr)
const char kAsanRegisterImageGlobalsName[]
static cl::opt< bool > ClOpt("asan-opt", cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true))
static const uint64_t kAllocaRzSize
const char kODRGenPrefix[]
static const uint64_t kSystemZ_ShadowOffset64
static const uint64_t kDefaultShadowOffset32
const char kAsanShadowMemoryDynamicAddress[]
static cl::opt< bool > ClUseOdrIndicator("asan-use-odr-indicator", cl::desc("Use odr indicators to improve ODR reporting"), cl::Hidden, cl::init(true))
static bool GlobalWasGeneratedByCompiler(GlobalVariable *G)
Check if G has been created by a trusted compiler pass.
const char kAsanStackMallocAlwaysNameTemplate[]
static cl::opt< bool > ClInvalidPointerCmp("asan-detect-invalid-pointer-cmp", cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden, cl::init(false))
static const uint64_t kAsanEmscriptenCtorAndDtorPriority
static cl::opt< int > ClInstrumentationWithCallsThreshold("asan-instrumentation-with-call-threshold", cl::desc("If the function being instrumented contains more than " "this number of memory accesses, use callbacks instead of " "inline checks (-1 means never use callbacks)."), cl::Hidden, cl::init(7000))
static cl::opt< int > ClDebugMax("asan-debug-max", cl::desc("Debug max inst"), cl::Hidden, cl::init(-1))
static cl::opt< bool > ClInvalidPointerSub("asan-detect-invalid-pointer-sub", cl::desc("Instrument - operations with pointer operands"), cl::Hidden, cl::init(false))
static const uint64_t kFreeBSD_ShadowOffset64
static cl::opt< uint32_t > ClForceExperiment("asan-force-experiment", cl::desc("Force optimization experiment (for testing)"), cl::Hidden, cl::init(0))
const char kSanCovGenPrefix[]
static const uint64_t kFreeBSDKasan_ShadowOffset64
const char kAsanModuleDtorName[]
static const uint64_t kDynamicShadowSentinel
static bool isInterestingPointerComparison(Instruction *I)
static cl::opt< bool > ClStack("asan-stack", cl::desc("Handle stack memory"), cl::Hidden, cl::init(true))
static const uint64_t kMIPS64_ShadowOffset64
static const uint64_t kLinuxKasan_ShadowOffset64
static int StackMallocSizeClass(uint64_t LocalStackSize)
static cl::opt< uint32_t > ClMaxInlinePoisoningSize("asan-max-inline-poisoning-size", cl::desc("Inline shadow poisoning for blocks up to the given size in bytes."), cl::Hidden, cl::init(64))
static cl::opt< bool > ClInstrumentAtomics("asan-instrument-atomics", cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClUseAfterScope("asan-use-after-scope", cl::desc("Check stack-use-after-scope"), cl::Hidden, cl::init(false))
constexpr size_t kAccessSizeIndexShift
static cl::opt< int > ClMappingScale("asan-mapping-scale", cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0))
const char kAsanPoisonStackMemoryName[]
static cl::opt< bool > ClEnableKasan("asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"), cl::Hidden, cl::init(false))
static cl::opt< std::string > ClDebugFunc("asan-debug-func", cl::Hidden, cl::desc("Debug func"))
static cl::opt< bool > ClUseGlobalsGC("asan-globals-live-support", cl::desc("Use linker features to support dead " "code stripping of globals"), cl::Hidden, cl::init(true))
static const size_t kNumberOfAccessSizes
const char kAsanUnpoisonStackMemoryName[]
static const uint64_t kLoongArch64_ShadowOffset64
const char kAsanRegisterGlobalsName[]
static cl::opt< bool > ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas", cl::desc("instrument dynamic allocas"), cl::Hidden, cl::init(true))
const char kAsanModuleCtorName[]
const char kAsanGlobalsRegisteredFlagName[]
static const size_t kMaxStackMallocSize
static cl::opt< bool > ClRecover("asan-recover", cl::desc("Enable recovery mode (continue-after-error)."), cl::Hidden, cl::init(false))
static cl::opt< bool > ClOptSameTemp("asan-opt-same-temp", cl::desc("Instrument the same temp just once"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClDynamicAllocaStack("asan-stack-dynamic-alloca", cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClOptStack("asan-opt-stack", cl::desc("Don't instrument scalar stack variables"), cl::Hidden, cl::init(false))
static const uint64_t kMIPS_ShadowOffsetN32
const char kAsanUnregisterImageGlobalsName[]
static cl::opt< AsanDetectStackUseAfterReturnMode > ClUseAfterReturn("asan-use-after-return", cl::desc("Sets the mode of detection for stack-use-after-return."), cl::values(clEnumValN(AsanDetectStackUseAfterReturnMode::Never, "never", "Never detect stack use after return."), clEnumValN(AsanDetectStackUseAfterReturnMode::Runtime, "runtime", "Detect stack use after return if " "binary flag 'ASAN_OPTIONS=detect_stack_use_after_return' is set."), clEnumValN(AsanDetectStackUseAfterReturnMode::Always, "always", "Always detect stack use after return.")), cl::Hidden, cl::init(AsanDetectStackUseAfterReturnMode::Runtime))
static cl::opt< bool > ClOptGlobals("asan-opt-globals", cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true))
static const uintptr_t kCurrentStackFrameMagic
static ShadowMapping getShadowMapping(const Triple &TargetTriple, int LongSize, bool IsKasan)
static const uint64_t kPPC64_ShadowOffset64
static cl::opt< AsanCtorKind > ClConstructorKind("asan-constructor-kind", cl::desc("Sets the ASan constructor kind"), cl::values(clEnumValN(AsanCtorKind::None, "none", "No constructors"), clEnumValN(AsanCtorKind::Global, "global", "Use global constructors")), cl::init(AsanCtorKind::Global), cl::Hidden)
static const int kMaxAsanStackMallocSizeClass
static const uint64_t kMIPS32_ShadowOffset32
static cl::opt< bool > ClAlwaysSlowPath("asan-always-slow-path", cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden, cl::init(false))
static const uint64_t kNetBSD_ShadowOffset32
static const uint64_t kFreeBSDAArch64_ShadowOffset64
static const uint64_t kSmallX86_64ShadowOffsetBase
static cl::opt< bool > ClInitializers("asan-initialization-order", cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(true))
static const uint64_t kNetBSD_ShadowOffset64
const char kAsanPtrSub[]
static cl::opt< unsigned > ClRealignStack("asan-realign-stack", cl::desc("Realign stack to the value of this flag (power of two)"), cl::Hidden, cl::init(32))
static const uint64_t kWindowsShadowOffset32
static cl::opt< bool > ClInstrumentReads("asan-instrument-reads", cl::desc("instrument read instructions"), cl::Hidden, cl::init(true))
static size_t TypeStoreSizeToSizeIndex(uint32_t TypeSize)
const char kAsanAllocaPoison[]
constexpr size_t kCompileKernelShift
static cl::opt< bool > ClWithIfunc("asan-with-ifunc", cl::desc("Access dynamic shadow through an ifunc global on " "platforms that support this"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClKasanMemIntrinCallbackPrefix("asan-kernel-mem-intrinsic-prefix", cl::desc("Use prefix for memory intrinsics in KASAN mode"), cl::Hidden, cl::init(false))
const char kAsanVersionCheckNamePrefix[]
const char kAMDGPUAddressPrivateName[]
static const uint64_t kNetBSDKasan_ShadowOffset64
const char kAMDGPUBallotName[]
const char kAsanRegisterElfGlobalsName[]
static cl::opt< uint64_t > ClMappingOffset("asan-mapping-offset", cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden, cl::init(0))
const char kAsanReportErrorTemplate[]
static cl::opt< bool > ClWithComdat("asan-with-comdat", cl::desc("Place ASan constructors in comdat sections"), cl::Hidden, cl::init(true))
static cl::opt< bool > ClSkipPromotableAllocas("asan-skip-promotable-allocas", cl::desc("Do not instrument promotable allocas"), cl::Hidden, cl::init(true))
static cl::opt< int > ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb", cl::init(10000), cl::desc("maximal number of instructions to instrument in any given BB"), cl::Hidden)
static const uintptr_t kRetiredStackFrameMagic
static cl::opt< bool > ClUseStackSafety("asan-use-stack-safety", cl::Hidden, cl::init(true), cl::Hidden, cl::desc("Use Stack Safety analysis results"), cl::Optional)
const char kAsanPoisonGlobalsName[]
const char kAsanHandleNoReturnName[]
static const size_t kMinStackMallocSize
static cl::opt< int > ClDebug("asan-debug", cl::desc("debug"), cl::Hidden, cl::init(0))
const char kAsanAllocasUnpoison[]
static const uint64_t kAArch64_ShadowOffset64
static cl::opt< bool > ClInvalidPointerPairs("asan-detect-invalid-pointer-pair", cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden, cl::init(false))
This file contains the simple types necessary to represent the attributes associated with functions a...
static bool isPointerOperand(Value *I, User *U)
static const Function * getParent(const Value *V)
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:693
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
static bool runOnFunction(Function &F, bool PostInlining)
This is the interface for a simple mod/ref and alias analysis over globals.
IRTranslator LLVM IR MI
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
This defines the Use class.
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1491
int64_t getSExtValue() const
Get sign extended value.
Definition: APInt.h:1513
AddressSanitizerPass(const AddressSanitizerOptions &Options, bool UseGlobalGC=true, bool UseOdrIndicator=true, AsanDtorKind DestructorKind=AsanDtorKind::Global, AsanCtorKind ConstructorKind=AsanCtorKind::Global)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
an instruction to allocate memory on the stack
Definition: Instructions.h:59
bool isSwiftError() const
Return true if this alloca is used as a swifterror argument to a call.
Definition: Instructions.h:157
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:132
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:107
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:125
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:147
std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
Definition: Instructions.h:136
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:103
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:348
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:500
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:647
An instruction that atomically checks whether a specified value is in a memory location,...
Definition: Instructions.h:539
an instruction that atomically reads a memory location, combines it with another value,...
Definition: Instructions.h:748
AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:589
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:429
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:396
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:198
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:205
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:220
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:280
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:276
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, BasicBlock::iterator InsertBefore)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1455
bool isInlineAsm() const
Check if this call is an inline asm statement.
Definition: InstrTypes.h:1770
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1648
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1639
bool doesNotReturn() const
Determine if the call cannot return.
Definition: InstrTypes.h:2222
unsigned arg_size() const
Definition: InstrTypes.h:1646
static CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, Instruction *InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr, BasicBlock::iterator InsertBefore)
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
ConstantArray - Constant Array Declarations.
Definition: Constants.h:422
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1291
static Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2126
static Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
Definition: Constants.cpp:2072
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< unsigned > InRangeIndex=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1201
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V.
Definition: Constants.cpp:1588
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1775
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Definition: Constants.cpp:1356
This is an important base class in LLVM.
Definition: Constant.h:41
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:432
Debug location.
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
A debug info location.
Definition: DebugLoc.h:33
DILocation * get() const
Get the underlying DILocation.
Definition: DebugLoc.cpp:20
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:168
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
const BasicBlock & front() const
Definition: Function.h:805
static Function * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags applied.
Definition: Function.cpp:359
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:850
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1874
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:342
const Constant * getAliasee() const
Definition: GlobalAlias.h:84
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:518
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:128
void copyMetadata(const GlobalObject *Src, unsigned Offset)
Copy metadata from Src, adjusting offsets by Offset.
Definition: Metadata.cpp:1753
void setComdat(Comdat *C)
Definition: Globals.cpp:197
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:251
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:231
bool hasLocalLinkage() const
Definition: GlobalValue.h:527
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1',...
Definition: GlobalValue.h:566
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:655
@ HiddenVisibility
The GV is hidden.
Definition: GlobalValue.h:68
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:254
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:51
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
DLLStorageClassTypes getDLLStorageClass() const
Definition: GlobalValue.h:275
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:482
Analysis pass providing a never-invalidated alias analysis result.
This instruction compares its operands according to the predicate given to the constructor.
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1772
IntegerType * getInt1Ty()
Fetch the type representing a single bit.
Definition: IRBuilder.h:505
Value * CreatePtrAdd(Value *Ptr, Value *Offset, const Twine &Name="", bool IsInBounds=false)
Definition: IRBuilder.h:1977
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2443
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1806
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2153
Value * CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2252
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1110
BasicBlock::iterator GetInsertPoint() const
Definition: IRBuilder.h:175
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2105
Value * CreateTypeSize(Type *DstType, TypeSize Size)
Create an expression which evaluates to the number of units in Size at runtime.
Definition: IRBuilder.cpp:104
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1431
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:520
BasicBlock * GetInsertBlock() const
Definition: IRBuilder.h:174
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:525
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2228
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:480
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2380
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1748
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2224
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1338
ConstantInt * getIntN(unsigned N, uint64_t C)
Get a constant N-bit value, zero extended or truncated from a 64-bit value.
Definition: IRBuilder.h:491
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1789
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1469
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1802
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1321
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2100
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg != 0.
Definition: IRBuilder.h:2532
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1491
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2179
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:558
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1825
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2395
Value * CreateGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="", bool IsInBounds=false)
Definition: IRBuilder.h:1865
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:510
CallInst * CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, uint64_t Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr)
Create and insert a memcpy between the specified pointers.
Definition: IRBuilder.h:653
Value * CreateAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2115
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1355
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2649
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT, bool canThrow=false)
InlineAsm::get - Return the specified uniqued inline asm string.
Definition: InlineAsm.cpp:43
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:658
Base class for instruction visitors.
Definition: InstVisitor.h:78
RetTy visitCallBase(CallBase &I)
Definition: InstVisitor.h:267
RetTy visitCleanupReturnInst(CleanupReturnInst &I)
Definition: InstVisitor.h:244
RetTy visitIntrinsicInst(IntrinsicInst &I)
Definition: InstVisitor.h:219
void visit(Iterator Start, Iterator End)
Definition: InstVisitor.h:87
RetTy visitReturnInst(ReturnInst &I)
Definition: InstVisitor.h:226
RetTy visitAllocaInst(AllocaInst &I)
Definition: InstVisitor.h:168
RetTy visitResumeInst(ResumeInst &I)
Definition: InstVisitor.h:238
bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:453
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:80
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
Definition: Instruction.h:340
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:801
const BasicBlock * getParent() const
Definition: Instruction.h:151
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
const Instruction * getNextNonDebugInstruction(bool SkipPseudoOp=false) const
Return a pointer to the next non-debug instruction in the same basic block as 'this',...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:450
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:278
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:47
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:54
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void emitError(uint64_t LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
An instruction for reading from memory.
Definition: Instructions.h:184
static Error ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight)
Return metadata containing two branch weights.
Definition: MDBuilder.cpp:37
Metadata node.
Definition: Metadata.h:1067
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1541
This is the common base class for memset/memcpy/memmove.
Root of the metadata hierarchy.
Definition: Metadata.h:62
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:287
Evaluate the size and offset of an object pointed to by a Value* statically.
SizeOffsetAPInt compute(Value *V)
A container for an operand bundle being viewed as a set of values rather than a set of uses.
Definition: InstrTypes.h:1408
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
Definition: DerivedTypes.h:662
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void abandon()
Mark an analysis as abandoned.
Definition: Analysis.h:162
Resume the propagation of an exception.
Return a value (possibly void), from a function.
static ReturnInst * Create(LLVMContext &C, Value *retVal, BasicBlock::iterator InsertBefore)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:360
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void reserve(size_type N)
Definition: SmallVector.h:676
void resize(size_type N)
Definition: SmallVector.h:651
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
This pass performs the global (interprocedural) stack safety analysis (new pass manager).
bool stackAccessIsSafe(const Instruction &I) const
bool isSafe(const AllocaInst &AI) const
An instruction for storing to memory.
Definition: Instructions.h:317
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Class to represent struct types.
Definition: DerivedTypes.h:216
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:373
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
AttributeList getAttrList(LLVMContext *C, ArrayRef< unsigned > ArgNos, bool Signed, bool Ret=false, AttributeList AL=AttributeList()) const
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:29
EltTy front() const
bool empty() const
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
bool isAndroidVersionLT(unsigned Major) const
Definition: Triple.h:755
bool isThumb() const
Tests whether the target is Thumb (little and big endian).
Definition: Triple.h:836
bool isDriverKit() const
Is this an Apple DriverKit triple.
Definition: Triple.h:537
bool isOSNetBSD() const
Definition: Triple.h:560
bool isAndroid() const
Tests whether the target is Android.
Definition: Triple.h:753
bool isMIPS64() const
Tests whether the target is MIPS 64-bit (little and big endian).
Definition: Triple.h:927
@ aarch64_be
Definition: Triple.h:52
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:361
bool isLoongArch64() const
Tests whether the target is 64-bit LoongArch.
Definition: Triple.h:916
EnvironmentType getEnvironment() const
Get the parsed environment type of this triple.
Definition: Triple.h:378
bool isMIPS32() const
Tests whether the target is MIPS 32-bit (little and big endian).
Definition: Triple.h:922
bool isOSWindows() const
Tests whether the OS is Windows.
Definition: Triple.h:608
@ DXContainer
Definition: Triple.h:289
@ UnknownObjectFormat
Definition: Triple.h:286
bool isARM() const
Tests whether the target is ARM (little and big endian).
Definition: Triple.h:841
bool isOSLinux() const
Tests whether the OS is Linux.
Definition: Triple.h:662
bool isAMDGPU() const
Definition: Triple.h:831
bool isMacOSX() const
Is this a Mac OS X triple.
Definition: Triple.h:506
bool isOSFreeBSD() const
Definition: Triple.h:568
bool isOSEmscripten() const
Tests whether the OS is Emscripten.
Definition: Triple.h:682
bool isWatchOS() const
Is this an Apple watchOS triple.
Definition: Triple.h:525
bool isiOS() const
Is this an iOS triple.
Definition: Triple.h:515
bool isPS() const
Tests whether the target is the PS4 or PS5 platform.
Definition: Triple.h:750
bool isOSFuchsia() const
Definition: Triple.h:572
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static Type * getVoidTy(LLVMContext &C)
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
static IntegerType * getInt32Ty(LLVMContext &C)
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
Value * getOperand(unsigned i) const
Definition: User.h:169
static ValueAsMetadata * get(Value *V)
Definition: Metadata.cpp:492
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1074
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
static VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Definition: Type.cpp:676
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:187
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
Definition: ilist_node.h:109
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:316
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
const uint64_t Version
Definition: InstrProf.h:1047
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=std::nullopt)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1451
@ S_CSTRING_LITERALS
S_CSTRING_LITERALS - Section with literal C strings.
Definition: MachO.h:131
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
Definition: X86BaseInfo.h:746
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:718
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
uint64_t getAllocaSizeInBytes(const AllocaInst &AI)
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
@ Offset
Definition: DWP.cpp:456
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1731
SmallVector< uint8_t, 64 > GetShadowBytesAfterScope(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
@ Done
Definition: Threading.h:61
Function * createSanitizerCtor(Module &M, StringRef CtorName)
Creates sanitizer constructor function.
AsanDetectStackUseAfterReturnMode
Mode of ASan detect stack use after return.
@ Always
Always detect stack use after return.
@ Never
Never detect stack use after return.
@ Runtime
Detect stack use after return if not disabled runtime with (ASAN_OPTIONS=detect_stack_use_after_retur...
GlobalVariable * createPrivateGlobalForString(Module &M, StringRef Str, bool AllowMerging, const char *NamePrefix="")
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value,...
Op::Description Desc
bool isAllocaPromotable(const AllocaInst *AI)
Return true if this alloca is legal for promotion.
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
SmallString< 64 > ComputeASanStackFrameDescription(const SmallVectorImpl< ASanStackVariableDescription > &Vars)
SmallVector< uint8_t, 64 > GetShadowBytes(const SmallVectorImpl< ASanStackVariableDescription > &Vars, const ASanStackFrameLayout &Layout)
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition: bit.h:215
FunctionCallee declareSanitizerInitFunction(Module &M, StringRef InitName, ArrayRef< Type * > InitArgTypes, bool Weak=false)
std::string getUniqueModuleId(Module *M)
Produce a unique identifier for this module by taking the MD5 sum of the names of the module's strong...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:264
std::pair< Function *, FunctionCallee > createSanitizerCtorAndInitFunctions(Module &M, StringRef CtorName, StringRef InitName, ArrayRef< Type * > InitArgTypes, ArrayRef< Value * > InitArgs, StringRef VersionCheckName=StringRef(), bool Weak=false)
Creates sanitizer constructor function, and calls sanitizer's init function from it.
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
void SplitBlockAndInsertForEachLane(ElementCount EC, Type *IndexTy, Instruction *InsertBefore, std::function< void(IRBuilderBase &, Value *)> Func)
Utility function for performing a given action on each lane of a vector with EC elements.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:156
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
AsanDtorKind
Types of ASan module destructors supported.
@ None
Do not emit any destructors for ASan.
ASanStackFrameLayout ComputeASanStackFrameLayout(SmallVectorImpl< ASanStackVariableDescription > &Vars, uint64_t Granularity, uint64_t MinHeaderSize)
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:749
void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
static const int kAsanStackUseAfterReturnMagic
void setGlobalVariableLargeSection(const Triple &TargetTriple, GlobalVariable &GV)
@ Dynamic
Denotes mode unknown at compile time.
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:73
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
Definition: Alignment.h:111
iterator_range< df_iterator< T > > depth_first(const T &G)
Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AsanCtorKind
Types of ASan module constructors supported.
void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition: Local.cpp:4021
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
void appendToGlobalDtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Same as appendToGlobalCtors(), but for global dtors.
Definition: ModuleUtils.cpp:77
void getAddressSanitizerParams(const Triple &TargetTriple, int LongSize, bool IsKasan, uint64_t *ShadowBase, int *MappingScale, bool *OrShadowOffset)
std::string demangle(std::string_view MangledName)
Attempt to demangle a string using different demangling schemes.
Definition: Demangle.cpp:20
bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces llvm.dbg.declare instruction when the address it describes is replaced with a new value.
Definition: Local.cpp:2116
#define N
#define OP(n)
Definition: regex2.h:73
ASanAccessInfo(int32_t Packed)
AsanDetectStackUseAfterReturnMode UseAfterReturn
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
Description of the encoding of one expression Op.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition: Alignment.h:117
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
Various options to control the behavior of getObjectSize.
bool RoundToAlign
Whether to round the result up to the alignment of allocas, byval arguments, and global variables.
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:91
SizeOffsetAPInt - Used by ObjectSizeOffsetVisitor, which works with APInts.
bool bothKnown() const