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