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