1 //===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
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 //
10 //===----------------------------------------------------------------------===//
11 
12 #include "AArch64TargetMachine.h"
13 #include "AArch64.h"
14 #include "AArch64MachineFunctionInfo.h"
15 #include "AArch64MacroFusion.h"
16 #include "AArch64Subtarget.h"
17 #include "AArch64TargetObjectFile.h"
18 #include "AArch64TargetTransformInfo.h"
19 #include "MCTargetDesc/AArch64MCTargetDesc.h"
20 #include "TargetInfo/AArch64TargetInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/CodeGen/CSEConfigBase.h"
25 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
26 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
27 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
28 #include "llvm/CodeGen/GlobalISel/Localizer.h"
29 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
30 #include "llvm/CodeGen/MIRParser/MIParser.h"
31 #include "llvm/CodeGen/MachineScheduler.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCTargetOptions.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CodeGen.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Transforms/CFGuard.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include <memory>
48 #include <string>
49 
50 using namespace llvm;
51 
52 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
53                                 cl::desc("Enable the CCMP formation pass"),
54                                 cl::init(true), cl::Hidden);
55 
56 static cl::opt<bool>
57     EnableCondBrTuning("aarch64-enable-cond-br-tune",
58                        cl::desc("Enable the conditional branch tuning pass"),
59                        cl::init(true), cl::Hidden);
60 
61 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
62                                cl::desc("Enable the machine combiner pass"),
63                                cl::init(true), cl::Hidden);
64 
65 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
66                                           cl::desc("Suppress STP for AArch64"),
67                                           cl::init(true), cl::Hidden);
68 
69 static cl::opt<bool> EnableAdvSIMDScalar(
70     "aarch64-enable-simd-scalar",
71     cl::desc("Enable use of AdvSIMD scalar integer instructions"),
72     cl::init(false), cl::Hidden);
73 
74 static cl::opt<bool>
75     EnablePromoteConstant("aarch64-enable-promote-const",
76                           cl::desc("Enable the promote constant pass"),
77                           cl::init(true), cl::Hidden);
78 
79 static cl::opt<bool> EnableCollectLOH(
80     "aarch64-enable-collect-loh",
81     cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
82     cl::init(true), cl::Hidden);
83 
84 static cl::opt<bool>
85     EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
86                                   cl::desc("Enable the pass that removes dead"
87                                            " definitons and replaces stores to"
88                                            " them with stores to the zero"
89                                            " register"),
90                                   cl::init(true));
91 
92 static cl::opt<bool> EnableRedundantCopyElimination(
93     "aarch64-enable-copyelim",
94     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
95     cl::Hidden);
96 
97 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
98                                         cl::desc("Enable the load/store pair"
99                                                  " optimization pass"),
100                                         cl::init(true), cl::Hidden);
101 
102 static cl::opt<bool> EnableAtomicTidy(
103     "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
104     cl::desc("Run SimplifyCFG after expanding atomic operations"
105              " to make use of cmpxchg flow-based information"),
106     cl::init(true));
107 
108 static cl::opt<bool>
109 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
110                         cl::desc("Run early if-conversion"),
111                         cl::init(true));
112 
113 static cl::opt<bool>
114     EnableCondOpt("aarch64-enable-condopt",
115                   cl::desc("Enable the condition optimizer pass"),
116                   cl::init(true), cl::Hidden);
117 
118 static cl::opt<bool>
119 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
120                 cl::desc("Work around Cortex-A53 erratum 835769"),
121                 cl::init(false));
122 
123 static cl::opt<bool>
124     EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
125                  cl::desc("Enable optimizations on complex GEPs"),
126                  cl::init(false));
127 
128 static cl::opt<bool>
129     BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
130                      cl::desc("Relax out of range conditional branches"));
131 
132 static cl::opt<bool> EnableCompressJumpTables(
133     "aarch64-enable-compress-jump-tables", cl::Hidden, cl::init(true),
134     cl::desc("Use smallest entry possible for jump tables"));
135 
136 // FIXME: Unify control over GlobalMerge.
137 static cl::opt<cl::boolOrDefault>
138     EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
139                       cl::desc("Enable the global merge pass"));
140 
141 static cl::opt<bool>
142     EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
143                            cl::desc("Enable the loop data prefetch pass"),
144                            cl::init(true));
145 
146 static cl::opt<int> EnableGlobalISelAtO(
147     "aarch64-enable-global-isel-at-O", cl::Hidden,
148     cl::desc("Enable GlobalISel at or below an opt level (-1 to disable)"),
149     cl::init(0));
150 
151 static cl::opt<bool>
152     EnableSVEIntrinsicOpts("aarch64-enable-sve-intrinsic-opts", cl::Hidden,
153                            cl::desc("Enable SVE intrinsic opts"),
154                            cl::init(true));
155 
156 static cl::opt<bool> EnableFalkorHWPFFix("aarch64-enable-falkor-hwpf-fix",
157                                          cl::init(true), cl::Hidden);
158 
159 static cl::opt<bool>
160     EnableBranchTargets("aarch64-enable-branch-targets", cl::Hidden,
161                         cl::desc("Enable the AArch64 branch target pass"),
162                         cl::init(true));
163 
164 static cl::opt<unsigned> SVEVectorBitsMaxOpt(
165     "aarch64-sve-vector-bits-max",
166     cl::desc("Assume SVE vector registers are at most this big, "
167              "with zero meaning no maximum size is assumed."),
168     cl::init(0), cl::Hidden);
169 
170 static cl::opt<unsigned> SVEVectorBitsMinOpt(
171     "aarch64-sve-vector-bits-min",
172     cl::desc("Assume SVE vector registers are at least this big, "
173              "with zero meaning no minimum size is assumed."),
174     cl::init(0), cl::Hidden);
175 
176 extern cl::opt<bool> EnableHomogeneousPrologEpilog;
177 
178 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAArch64Target() {
179   // Register the target.
180   RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
181   RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
182   RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
183   RegisterTargetMachine<AArch64leTargetMachine> W(getTheARM64_32Target());
184   RegisterTargetMachine<AArch64leTargetMachine> V(getTheAArch64_32Target());
185   auto PR = PassRegistry::getPassRegistry();
186   initializeGlobalISel(*PR);
187   initializeAArch64A53Fix835769Pass(*PR);
188   initializeAArch64A57FPLoadBalancingPass(*PR);
189   initializeAArch64AdvSIMDScalarPass(*PR);
190   initializeAArch64BranchTargetsPass(*PR);
191   initializeAArch64CollectLOHPass(*PR);
192   initializeAArch64CompressJumpTablesPass(*PR);
193   initializeAArch64ConditionalComparesPass(*PR);
194   initializeAArch64ConditionOptimizerPass(*PR);
195   initializeAArch64DeadRegisterDefinitionsPass(*PR);
196   initializeAArch64ExpandPseudoPass(*PR);
197   initializeAArch64LoadStoreOptPass(*PR);
198   initializeAArch64SIMDInstrOptPass(*PR);
199   initializeAArch64O0PreLegalizerCombinerPass(*PR);
200   initializeAArch64PreLegalizerCombinerPass(*PR);
201   initializeAArch64PostLegalizerCombinerPass(*PR);
202   initializeAArch64PostLegalizerLoweringPass(*PR);
203   initializeAArch64PostSelectOptimizePass(*PR);
204   initializeAArch64PromoteConstantPass(*PR);
205   initializeAArch64RedundantCopyEliminationPass(*PR);
206   initializeAArch64StorePairSuppressPass(*PR);
207   initializeFalkorHWPFFixPass(*PR);
208   initializeFalkorMarkStridedAccessesLegacyPass(*PR);
209   initializeLDTLSCleanupPass(*PR);
210   initializeSVEIntrinsicOptsPass(*PR);
211   initializeAArch64SpeculationHardeningPass(*PR);
212   initializeAArch64SLSHardeningPass(*PR);
213   initializeAArch64StackTaggingPass(*PR);
214   initializeAArch64StackTaggingPreRAPass(*PR);
215   initializeAArch64LowerHomogeneousPrologEpilogPass(*PR);
216 }
217 
218 //===----------------------------------------------------------------------===//
219 // AArch64 Lowering public interface.
220 //===----------------------------------------------------------------------===//
221 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
222   if (TT.isOSBinFormatMachO())
223     return std::make_unique<AArch64_MachoTargetObjectFile>();
224   if (TT.isOSBinFormatCOFF())
225     return std::make_unique<AArch64_COFFTargetObjectFile>();
226 
227   return std::make_unique<AArch64_ELFTargetObjectFile>();
228 }
229 
230 // Helper function to build a DataLayout string
231 static std::string computeDataLayout(const Triple &TT,
232                                      const MCTargetOptions &Options,
233                                      bool LittleEndian) {
234   if (TT.isOSBinFormatMachO()) {
235     if (TT.getArch() == Triple::aarch64_32)
236       return "e-m:o-p:32:32-i64:64-i128:128-n32:64-S128";
237     return "e-m:o-i64:64-i128:128-n32:64-S128";
238   }
239   if (TT.isOSBinFormatCOFF())
240     return "e-m:w-p:64:64-i32:32-i64:64-i128:128-n32:64-S128";
241   std::string Endian = LittleEndian ? "e" : "E";
242   std::string Ptr32 = TT.getEnvironment() == Triple::GNUILP32 ? "-p:32:32" : "";
243   return Endian + "-m:e" + Ptr32 +
244          "-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
245 }
246 
247 static StringRef computeDefaultCPU(const Triple &TT, StringRef CPU) {
248   if (CPU.empty() && TT.isArm64e())
249     return "apple-a12";
250   return CPU;
251 }
252 
253 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
254                                            Optional<Reloc::Model> RM) {
255   // AArch64 Darwin and Windows are always PIC.
256   if (TT.isOSDarwin() || TT.isOSWindows())
257     return Reloc::PIC_;
258   // On ELF platforms the default static relocation model has a smart enough
259   // linker to cope with referencing external symbols defined in a shared
260   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
261   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
262     return Reloc::Static;
263   return *RM;
264 }
265 
266 static CodeModel::Model
267 getEffectiveAArch64CodeModel(const Triple &TT, Optional<CodeModel::Model> CM,
268                              bool JIT) {
269   if (CM) {
270     if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
271         *CM != CodeModel::Large) {
272       report_fatal_error(
273           "Only small, tiny and large code models are allowed on AArch64");
274     } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF())
275       report_fatal_error("tiny code model is only supported on ELF");
276     return *CM;
277   }
278   // The default MCJIT memory managers make no guarantees about where they can
279   // find an executable page; JITed code needs to be able to refer to globals
280   // no matter how far away they are.
281   // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
282   // since with large code model LLVM generating 4 MOV instructions, and
283   // Windows doesn't support relocating these long branch (4 MOVs).
284   if (JIT && !TT.isOSWindows())
285     return CodeModel::Large;
286   return CodeModel::Small;
287 }
288 
289 /// Create an AArch64 architecture model.
290 ///
291 AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
292                                            StringRef CPU, StringRef FS,
293                                            const TargetOptions &Options,
294                                            Optional<Reloc::Model> RM,
295                                            Optional<CodeModel::Model> CM,
296                                            CodeGenOpt::Level OL, bool JIT,
297                                            bool LittleEndian)
298     : LLVMTargetMachine(T,
299                         computeDataLayout(TT, Options.MCOptions, LittleEndian),
300                         TT, computeDefaultCPU(TT, CPU), FS, Options,
301                         getEffectiveRelocModel(TT, RM),
302                         getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
303       TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
304   initAsmInfo();
305 
306   if (TT.isOSBinFormatMachO()) {
307     this->Options.TrapUnreachable = true;
308     this->Options.NoTrapAfterNoreturn = true;
309   }
310 
311   if (getMCAsmInfo()->usesWindowsCFI()) {
312     // Unwinding can get confused if the last instruction in an
313     // exception-handling region (function, funclet, try block, etc.)
314     // is a call.
315     //
316     // FIXME: We could elide the trap if the next instruction would be in
317     // the same region anyway.
318     this->Options.TrapUnreachable = true;
319   }
320 
321   if (this->Options.TLSSize == 0) // default
322     this->Options.TLSSize = 24;
323   if ((getCodeModel() == CodeModel::Small ||
324        getCodeModel() == CodeModel::Kernel) &&
325       this->Options.TLSSize > 32)
326     // for the small (and kernel) code model, the maximum TLS size is 4GiB
327     this->Options.TLSSize = 32;
328   else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
329     // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
330     this->Options.TLSSize = 24;
331 
332   // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
333   // MachO/CodeModel::Large, which GlobalISel does not support.
334   if (getOptLevel() <= EnableGlobalISelAtO &&
335       TT.getArch() != Triple::aarch64_32 &&
336       TT.getEnvironment() != Triple::GNUILP32 &&
337       !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO())) {
338     setGlobalISel(true);
339     setGlobalISelAbort(GlobalISelAbortMode::Disable);
340   }
341 
342   // AArch64 supports the MachineOutliner.
343   setMachineOutliner(true);
344 
345   // AArch64 supports default outlining behaviour.
346   setSupportsDefaultOutlining(true);
347 
348   // AArch64 supports the debug entry values.
349   setSupportsDebugEntryValues(true);
350 }
351 
352 AArch64TargetMachine::~AArch64TargetMachine() = default;
353 
354 const AArch64Subtarget *
355 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
356   Attribute CPUAttr = F.getFnAttribute("target-cpu");
357   Attribute FSAttr = F.getFnAttribute("target-features");
358 
359   std::string CPU =
360       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
361   std::string FS =
362       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
363 
364   SmallString<512> Key;
365 
366   unsigned MinSVEVectorSize = 0;
367   unsigned MaxSVEVectorSize = 0;
368   Attribute VScaleRangeAttr = F.getFnAttribute(Attribute::VScaleRange);
369   if (VScaleRangeAttr.isValid()) {
370     std::tie(MinSVEVectorSize, MaxSVEVectorSize) =
371         VScaleRangeAttr.getVScaleRangeArgs();
372     MinSVEVectorSize *= 128;
373     MaxSVEVectorSize *= 128;
374   } else {
375     MinSVEVectorSize = SVEVectorBitsMinOpt;
376     MaxSVEVectorSize = SVEVectorBitsMaxOpt;
377   }
378 
379   assert(MinSVEVectorSize % 128 == 0 &&
380          "SVE requires vector length in multiples of 128!");
381   assert(MaxSVEVectorSize % 128 == 0 &&
382          "SVE requires vector length in multiples of 128!");
383   assert((MaxSVEVectorSize >= MinSVEVectorSize || MaxSVEVectorSize == 0) &&
384          "Minimum SVE vector size should not be larger than its maximum!");
385 
386   // Sanitize user input in case of no asserts
387   if (MaxSVEVectorSize == 0)
388     MinSVEVectorSize = (MinSVEVectorSize / 128) * 128;
389   else {
390     MinSVEVectorSize =
391         (std::min(MinSVEVectorSize, MaxSVEVectorSize) / 128) * 128;
392     MaxSVEVectorSize =
393         (std::max(MinSVEVectorSize, MaxSVEVectorSize) / 128) * 128;
394   }
395 
396   Key += "SVEMin";
397   Key += std::to_string(MinSVEVectorSize);
398   Key += "SVEMax";
399   Key += std::to_string(MaxSVEVectorSize);
400   Key += CPU;
401   Key += FS;
402 
403   auto &I = SubtargetMap[Key];
404   if (!I) {
405     // This needs to be done before we create a new subtarget since any
406     // creation will depend on the TM and the code generation flags on the
407     // function that reside in TargetOptions.
408     resetTargetOptions(F);
409     I = std::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
410                                            isLittle, MinSVEVectorSize,
411                                            MaxSVEVectorSize);
412   }
413   return I.get();
414 }
415 
416 void AArch64leTargetMachine::anchor() { }
417 
418 AArch64leTargetMachine::AArch64leTargetMachine(
419     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
420     const TargetOptions &Options, Optional<Reloc::Model> RM,
421     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
422     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
423 
424 void AArch64beTargetMachine::anchor() { }
425 
426 AArch64beTargetMachine::AArch64beTargetMachine(
427     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
428     const TargetOptions &Options, Optional<Reloc::Model> RM,
429     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
430     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
431 
432 namespace {
433 
434 /// AArch64 Code Generator Pass Configuration Options.
435 class AArch64PassConfig : public TargetPassConfig {
436 public:
437   AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
438       : TargetPassConfig(TM, PM) {
439     if (TM.getOptLevel() != CodeGenOpt::None)
440       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
441   }
442 
443   AArch64TargetMachine &getAArch64TargetMachine() const {
444     return getTM<AArch64TargetMachine>();
445   }
446 
447   ScheduleDAGInstrs *
448   createMachineScheduler(MachineSchedContext *C) const override {
449     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
450     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
451     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
452     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
453     if (ST.hasFusion())
454       DAG->addMutation(createAArch64MacroFusionDAGMutation());
455     return DAG;
456   }
457 
458   ScheduleDAGInstrs *
459   createPostMachineScheduler(MachineSchedContext *C) const override {
460     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
461     if (ST.hasFusion()) {
462       // Run the Macro Fusion after RA again since literals are expanded from
463       // pseudos then (v. addPreSched2()).
464       ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
465       DAG->addMutation(createAArch64MacroFusionDAGMutation());
466       return DAG;
467     }
468 
469     return nullptr;
470   }
471 
472   void addIRPasses()  override;
473   bool addPreISel() override;
474   void addCodeGenPrepare() override;
475   bool addInstSelector() override;
476   bool addIRTranslator() override;
477   void addPreLegalizeMachineIR() override;
478   bool addLegalizeMachineIR() override;
479   void addPreRegBankSelect() override;
480   bool addRegBankSelect() override;
481   void addPreGlobalInstructionSelect() override;
482   bool addGlobalInstructionSelect() override;
483   bool addILPOpts() override;
484   void addPreRegAlloc() override;
485   void addPostRegAlloc() override;
486   void addPreSched2() override;
487   void addPreEmitPass() override;
488   void addPreEmitPass2() override;
489 
490   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
491 };
492 
493 } // end anonymous namespace
494 
495 TargetTransformInfo
496 AArch64TargetMachine::getTargetTransformInfo(const Function &F) {
497   return TargetTransformInfo(AArch64TTIImpl(this, F));
498 }
499 
500 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
501   return new AArch64PassConfig(*this, PM);
502 }
503 
504 std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
505   return getStandardCSEConfigForOpt(TM->getOptLevel());
506 }
507 
508 void AArch64PassConfig::addIRPasses() {
509   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
510   // ourselves.
511   addPass(createAtomicExpandPass());
512 
513   // Expand any SVE vector library calls that we can't code generate directly.
514   if (EnableSVEIntrinsicOpts && TM->getOptLevel() == CodeGenOpt::Aggressive)
515     addPass(createSVEIntrinsicOptsPass());
516 
517   // Cmpxchg instructions are often used with a subsequent comparison to
518   // determine whether it succeeded. We can exploit existing control-flow in
519   // ldrex/strex loops to simplify this, but it needs tidying up.
520   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
521     addPass(createCFGSimplificationPass(SimplifyCFGOptions()
522                                             .forwardSwitchCondToPhi(true)
523                                             .convertSwitchToLookupTable(true)
524                                             .needCanonicalLoops(false)
525                                             .hoistCommonInsts(true)
526                                             .sinkCommonInsts(true)));
527 
528   // Run LoopDataPrefetch
529   //
530   // Run this before LSR to remove the multiplies involved in computing the
531   // pointer values N iterations ahead.
532   if (TM->getOptLevel() != CodeGenOpt::None) {
533     if (EnableLoopDataPrefetch)
534       addPass(createLoopDataPrefetchPass());
535     if (EnableFalkorHWPFFix)
536       addPass(createFalkorMarkStridedAccessesPass());
537   }
538 
539   TargetPassConfig::addIRPasses();
540 
541   addPass(createAArch64StackTaggingPass(
542       /*IsOptNone=*/TM->getOptLevel() == CodeGenOpt::None));
543 
544   // Match interleaved memory accesses to ldN/stN intrinsics.
545   if (TM->getOptLevel() != CodeGenOpt::None) {
546     addPass(createInterleavedLoadCombinePass());
547     addPass(createInterleavedAccessPass());
548   }
549 
550   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
551     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
552     // and lower a GEP with multiple indices to either arithmetic operations or
553     // multiple GEPs with single index.
554     addPass(createSeparateConstOffsetFromGEPPass(true));
555     // Call EarlyCSE pass to find and remove subexpressions in the lowered
556     // result.
557     addPass(createEarlyCSEPass());
558     // Do loop invariant code motion in case part of the lowered result is
559     // invariant.
560     addPass(createLICMPass());
561   }
562 
563   // Add Control Flow Guard checks.
564   if (TM->getTargetTriple().isOSWindows())
565     addPass(createCFGuardCheckPass());
566 }
567 
568 // Pass Pipeline Configuration
569 bool AArch64PassConfig::addPreISel() {
570   // Run promote constant before global merge, so that the promoted constants
571   // get a chance to be merged
572   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
573     addPass(createAArch64PromoteConstantPass());
574   // FIXME: On AArch64, this depends on the type.
575   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
576   // and the offset has to be a multiple of the related size in bytes.
577   if ((TM->getOptLevel() != CodeGenOpt::None &&
578        EnableGlobalMerge == cl::BOU_UNSET) ||
579       EnableGlobalMerge == cl::BOU_TRUE) {
580     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
581                                (EnableGlobalMerge == cl::BOU_UNSET);
582 
583     // Merging of extern globals is enabled by default on non-Mach-O as we
584     // expect it to be generally either beneficial or harmless. On Mach-O it
585     // is disabled as we emit the .subsections_via_symbols directive which
586     // means that merging extern globals is not safe.
587     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
588 
589     // FIXME: extern global merging is only enabled when we optimise for size
590     // because there are some regressions with it also enabled for performance.
591     if (!OnlyOptimizeForSize)
592       MergeExternalByDefault = false;
593 
594     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize,
595                                   MergeExternalByDefault));
596   }
597 
598   return false;
599 }
600 
601 void AArch64PassConfig::addCodeGenPrepare() {
602   if (getOptLevel() != CodeGenOpt::None)
603     addPass(createTypePromotionPass());
604   TargetPassConfig::addCodeGenPrepare();
605 }
606 
607 bool AArch64PassConfig::addInstSelector() {
608   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
609 
610   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
611   // references to _TLS_MODULE_BASE_ as possible.
612   if (TM->getTargetTriple().isOSBinFormatELF() &&
613       getOptLevel() != CodeGenOpt::None)
614     addPass(createAArch64CleanupLocalDynamicTLSPass());
615 
616   return false;
617 }
618 
619 bool AArch64PassConfig::addIRTranslator() {
620   addPass(new IRTranslator(getOptLevel()));
621   return false;
622 }
623 
624 void AArch64PassConfig::addPreLegalizeMachineIR() {
625   if (getOptLevel() == CodeGenOpt::None)
626     addPass(createAArch64O0PreLegalizerCombiner());
627   else
628     addPass(createAArch64PreLegalizerCombiner());
629 }
630 
631 bool AArch64PassConfig::addLegalizeMachineIR() {
632   addPass(new Legalizer());
633   return false;
634 }
635 
636 void AArch64PassConfig::addPreRegBankSelect() {
637   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
638   if (!IsOptNone)
639     addPass(createAArch64PostLegalizerCombiner(IsOptNone));
640   addPass(createAArch64PostLegalizerLowering());
641 }
642 
643 bool AArch64PassConfig::addRegBankSelect() {
644   addPass(new RegBankSelect());
645   return false;
646 }
647 
648 void AArch64PassConfig::addPreGlobalInstructionSelect() {
649   addPass(new Localizer());
650 }
651 
652 bool AArch64PassConfig::addGlobalInstructionSelect() {
653   addPass(new InstructionSelect(getOptLevel()));
654   if (getOptLevel() != CodeGenOpt::None)
655     addPass(createAArch64PostSelectOptimize());
656   return false;
657 }
658 
659 bool AArch64PassConfig::addILPOpts() {
660   if (EnableCondOpt)
661     addPass(createAArch64ConditionOptimizerPass());
662   if (EnableCCMP)
663     addPass(createAArch64ConditionalCompares());
664   if (EnableMCR)
665     addPass(&MachineCombinerID);
666   if (EnableCondBrTuning)
667     addPass(createAArch64CondBrTuning());
668   if (EnableEarlyIfConversion)
669     addPass(&EarlyIfConverterID);
670   if (EnableStPairSuppress)
671     addPass(createAArch64StorePairSuppressPass());
672   addPass(createAArch64SIMDInstrOptPass());
673   if (TM->getOptLevel() != CodeGenOpt::None)
674     addPass(createAArch64StackTaggingPreRAPass());
675   return true;
676 }
677 
678 void AArch64PassConfig::addPreRegAlloc() {
679   // Change dead register definitions to refer to the zero register.
680   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
681     addPass(createAArch64DeadRegisterDefinitions());
682 
683   // Use AdvSIMD scalar instructions whenever profitable.
684   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
685     addPass(createAArch64AdvSIMDScalar());
686     // The AdvSIMD pass may produce copies that can be rewritten to
687     // be register coalescer friendly.
688     addPass(&PeepholeOptimizerID);
689   }
690 }
691 
692 void AArch64PassConfig::addPostRegAlloc() {
693   // Remove redundant copy instructions.
694   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
695     addPass(createAArch64RedundantCopyEliminationPass());
696 
697   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
698     // Improve performance for some FP/SIMD code for A57.
699     addPass(createAArch64A57FPLoadBalancing());
700 }
701 
702 void AArch64PassConfig::addPreSched2() {
703   // Lower homogeneous frame instructions
704   if (EnableHomogeneousPrologEpilog)
705     addPass(createAArch64LowerHomogeneousPrologEpilogPass());
706   // Expand some pseudo instructions to allow proper scheduling.
707   addPass(createAArch64ExpandPseudoPass());
708   // Use load/store pair instructions when possible.
709   if (TM->getOptLevel() != CodeGenOpt::None) {
710     if (EnableLoadStoreOpt)
711       addPass(createAArch64LoadStoreOptimizationPass());
712   }
713 
714   // The AArch64SpeculationHardeningPass destroys dominator tree and natural
715   // loop info, which is needed for the FalkorHWPFFixPass and also later on.
716   // Therefore, run the AArch64SpeculationHardeningPass before the
717   // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
718   // info.
719   addPass(createAArch64SpeculationHardeningPass());
720 
721   addPass(createAArch64IndirectThunks());
722   addPass(createAArch64SLSHardeningPass());
723 
724   if (TM->getOptLevel() != CodeGenOpt::None) {
725     if (EnableFalkorHWPFFix)
726       addPass(createFalkorHWPFFixPass());
727   }
728 }
729 
730 void AArch64PassConfig::addPreEmitPass() {
731   // Machine Block Placement might have created new opportunities when run
732   // at O3, where the Tail Duplication Threshold is set to 4 instructions.
733   // Run the load/store optimizer once more.
734   if (TM->getOptLevel() >= CodeGenOpt::Aggressive && EnableLoadStoreOpt)
735     addPass(createAArch64LoadStoreOptimizationPass());
736 
737   if (EnableA53Fix835769)
738     addPass(createAArch64A53Fix835769());
739 
740   if (EnableBranchTargets)
741     addPass(createAArch64BranchTargetsPass());
742 
743   // Relax conditional branch instructions if they're otherwise out of
744   // range of their destination.
745   if (BranchRelaxation)
746     addPass(&BranchRelaxationPassID);
747 
748   if (TM->getTargetTriple().isOSWindows()) {
749     // Identify valid longjmp targets for Windows Control Flow Guard.
750     addPass(createCFGuardLongjmpPass());
751     // Identify valid eh continuation targets for Windows EHCont Guard.
752     addPass(createEHContGuardCatchretPass());
753   }
754 
755   if (TM->getOptLevel() != CodeGenOpt::None && EnableCompressJumpTables)
756     addPass(createAArch64CompressJumpTablesPass());
757 
758   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
759       TM->getTargetTriple().isOSBinFormatMachO())
760     addPass(createAArch64CollectLOHPass());
761 }
762 
763 void AArch64PassConfig::addPreEmitPass2() {
764   // SVE bundles move prefixes with destructive operations. BLR_RVMARKER pseudo
765   // instructions are lowered to bundles as well.
766   addPass(createUnpackMachineBundles(nullptr));
767 }
768 
769 yaml::MachineFunctionInfo *
770 AArch64TargetMachine::createDefaultFuncInfoYAML() const {
771   return new yaml::AArch64FunctionInfo();
772 }
773 
774 yaml::MachineFunctionInfo *
775 AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
776   const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
777   return new yaml::AArch64FunctionInfo(*MFI);
778 }
779 
780 bool AArch64TargetMachine::parseMachineFunctionInfo(
781     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
782     SMDiagnostic &Error, SMRange &SourceRange) const {
783   const auto &YamlMFI =
784       reinterpret_cast<const yaml::AArch64FunctionInfo &>(MFI);
785   MachineFunction &MF = PFS.MF;
786   MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
787   return false;
788 }
789