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