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