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 AAcrh64 branch target pass"),
162                         cl::init(true));
163 
164 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAArch64Target() {
165   // Register the target.
166   RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
167   RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
168   RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
169   RegisterTargetMachine<AArch64leTargetMachine> W(getTheARM64_32Target());
170   RegisterTargetMachine<AArch64leTargetMachine> V(getTheAArch64_32Target());
171   auto PR = PassRegistry::getPassRegistry();
172   initializeGlobalISel(*PR);
173   initializeAArch64A53Fix835769Pass(*PR);
174   initializeAArch64A57FPLoadBalancingPass(*PR);
175   initializeAArch64AdvSIMDScalarPass(*PR);
176   initializeAArch64BranchTargetsPass(*PR);
177   initializeAArch64CollectLOHPass(*PR);
178   initializeAArch64CompressJumpTablesPass(*PR);
179   initializeAArch64ConditionalComparesPass(*PR);
180   initializeAArch64ConditionOptimizerPass(*PR);
181   initializeAArch64DeadRegisterDefinitionsPass(*PR);
182   initializeAArch64ExpandPseudoPass(*PR);
183   initializeAArch64LoadStoreOptPass(*PR);
184   initializeAArch64SIMDInstrOptPass(*PR);
185   initializeAArch64PreLegalizerCombinerPass(*PR);
186   initializeAArch64PostLegalizerCombinerPass(*PR);
187   initializeAArch64PostLegalizerLoweringPass(*PR);
188   initializeAArch64PostSelectOptimizePass(*PR);
189   initializeAArch64PromoteConstantPass(*PR);
190   initializeAArch64RedundantCopyEliminationPass(*PR);
191   initializeAArch64StorePairSuppressPass(*PR);
192   initializeFalkorHWPFFixPass(*PR);
193   initializeFalkorMarkStridedAccessesLegacyPass(*PR);
194   initializeLDTLSCleanupPass(*PR);
195   initializeSVEIntrinsicOptsPass(*PR);
196   initializeAArch64SpeculationHardeningPass(*PR);
197   initializeAArch64SLSHardeningPass(*PR);
198   initializeAArch64StackTaggingPass(*PR);
199   initializeAArch64StackTaggingPreRAPass(*PR);
200 }
201 
202 //===----------------------------------------------------------------------===//
203 // AArch64 Lowering public interface.
204 //===----------------------------------------------------------------------===//
205 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
206   if (TT.isOSBinFormatMachO())
207     return std::make_unique<AArch64_MachoTargetObjectFile>();
208   if (TT.isOSBinFormatCOFF())
209     return std::make_unique<AArch64_COFFTargetObjectFile>();
210 
211   return std::make_unique<AArch64_ELFTargetObjectFile>();
212 }
213 
214 // Helper function to build a DataLayout string
215 static std::string computeDataLayout(const Triple &TT,
216                                      const MCTargetOptions &Options,
217                                      bool LittleEndian) {
218   if (Options.getABIName() == "ilp32")
219     return "e-m:e-p:32:32-i8:8-i16:16-i64:64-S128";
220   if (TT.isOSBinFormatMachO()) {
221     if (TT.getArch() == Triple::aarch64_32)
222       return "e-m:o-p:32:32-i64:64-i128:128-n32:64-S128";
223     return "e-m:o-i64:64-i128:128-n32:64-S128";
224   }
225   if (TT.isOSBinFormatCOFF())
226     return "e-m:w-p:64:64-i32:32-i64:64-i128:128-n32:64-S128";
227   if (LittleEndian)
228     return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
229   return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
230 }
231 
232 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
233                                            Optional<Reloc::Model> RM) {
234   // AArch64 Darwin and Windows are always PIC.
235   if (TT.isOSDarwin() || TT.isOSWindows())
236     return Reloc::PIC_;
237   // On ELF platforms the default static relocation model has a smart enough
238   // linker to cope with referencing external symbols defined in a shared
239   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
240   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
241     return Reloc::Static;
242   return *RM;
243 }
244 
245 static CodeModel::Model
246 getEffectiveAArch64CodeModel(const Triple &TT, Optional<CodeModel::Model> CM,
247                              bool JIT) {
248   if (CM) {
249     if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
250         *CM != CodeModel::Large) {
251       report_fatal_error(
252           "Only small, tiny and large code models are allowed on AArch64");
253     } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF())
254       report_fatal_error("tiny code model is only supported on ELF");
255     return *CM;
256   }
257   // The default MCJIT memory managers make no guarantees about where they can
258   // find an executable page; JITed code needs to be able to refer to globals
259   // no matter how far away they are.
260   // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
261   // since with large code model LLVM generating 4 MOV instructions, and
262   // Windows doesn't support relocating these long branch (4 MOVs).
263   if (JIT && !TT.isOSWindows())
264     return CodeModel::Large;
265   return CodeModel::Small;
266 }
267 
268 /// Create an AArch64 architecture model.
269 ///
270 AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
271                                            StringRef CPU, StringRef FS,
272                                            const TargetOptions &Options,
273                                            Optional<Reloc::Model> RM,
274                                            Optional<CodeModel::Model> CM,
275                                            CodeGenOpt::Level OL, bool JIT,
276                                            bool LittleEndian)
277     : LLVMTargetMachine(T,
278                         computeDataLayout(TT, Options.MCOptions, LittleEndian),
279                         TT, CPU, FS, Options, getEffectiveRelocModel(TT, RM),
280                         getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
281       TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
282   initAsmInfo();
283 
284   if (TT.isOSBinFormatMachO()) {
285     this->Options.TrapUnreachable = true;
286     this->Options.NoTrapAfterNoreturn = true;
287   }
288 
289   if (getMCAsmInfo()->usesWindowsCFI()) {
290     // Unwinding can get confused if the last instruction in an
291     // exception-handling region (function, funclet, try block, etc.)
292     // is a call.
293     //
294     // FIXME: We could elide the trap if the next instruction would be in
295     // the same region anyway.
296     this->Options.TrapUnreachable = true;
297   }
298 
299   if (this->Options.TLSSize == 0) // default
300     this->Options.TLSSize = 24;
301   if ((getCodeModel() == CodeModel::Small ||
302        getCodeModel() == CodeModel::Kernel) &&
303       this->Options.TLSSize > 32)
304     // for the small (and kernel) code model, the maximum TLS size is 4GiB
305     this->Options.TLSSize = 32;
306   else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
307     // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
308     this->Options.TLSSize = 24;
309 
310   // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
311   // MachO/CodeModel::Large, which GlobalISel does not support.
312   if (getOptLevel() <= EnableGlobalISelAtO &&
313       TT.getArch() != Triple::aarch64_32 &&
314       !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO())) {
315     setGlobalISel(true);
316     setGlobalISelAbort(GlobalISelAbortMode::Disable);
317   }
318 
319   // AArch64 supports the MachineOutliner.
320   setMachineOutliner(true);
321 
322   // AArch64 supports default outlining behaviour.
323   setSupportsDefaultOutlining(true);
324 
325   // AArch64 supports the debug entry values.
326   setSupportsDebugEntryValues(true);
327 }
328 
329 AArch64TargetMachine::~AArch64TargetMachine() = default;
330 
331 const AArch64Subtarget *
332 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
333   Attribute CPUAttr = F.getFnAttribute("target-cpu");
334   Attribute FSAttr = F.getFnAttribute("target-features");
335 
336   std::string CPU =
337       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
338   std::string FS =
339       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
340 
341   auto &I = SubtargetMap[CPU + FS];
342   if (!I) {
343     // This needs to be done before we create a new subtarget since any
344     // creation will depend on the TM and the code generation flags on the
345     // function that reside in TargetOptions.
346     resetTargetOptions(F);
347     I = std::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
348                                             isLittle);
349   }
350   return I.get();
351 }
352 
353 void AArch64leTargetMachine::anchor() { }
354 
355 AArch64leTargetMachine::AArch64leTargetMachine(
356     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
357     const TargetOptions &Options, Optional<Reloc::Model> RM,
358     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
359     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
360 
361 void AArch64beTargetMachine::anchor() { }
362 
363 AArch64beTargetMachine::AArch64beTargetMachine(
364     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
365     const TargetOptions &Options, Optional<Reloc::Model> RM,
366     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
367     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
368 
369 namespace {
370 
371 /// AArch64 Code Generator Pass Configuration Options.
372 class AArch64PassConfig : public TargetPassConfig {
373 public:
374   AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
375       : TargetPassConfig(TM, PM) {
376     if (TM.getOptLevel() != CodeGenOpt::None)
377       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
378   }
379 
380   AArch64TargetMachine &getAArch64TargetMachine() const {
381     return getTM<AArch64TargetMachine>();
382   }
383 
384   ScheduleDAGInstrs *
385   createMachineScheduler(MachineSchedContext *C) const override {
386     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
387     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
388     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
389     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
390     if (ST.hasFusion())
391       DAG->addMutation(createAArch64MacroFusionDAGMutation());
392     return DAG;
393   }
394 
395   ScheduleDAGInstrs *
396   createPostMachineScheduler(MachineSchedContext *C) const override {
397     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
398     if (ST.hasFusion()) {
399       // Run the Macro Fusion after RA again since literals are expanded from
400       // pseudos then (v. addPreSched2()).
401       ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
402       DAG->addMutation(createAArch64MacroFusionDAGMutation());
403       return DAG;
404     }
405 
406     return nullptr;
407   }
408 
409   void addIRPasses()  override;
410   bool addPreISel() override;
411   bool addInstSelector() override;
412   bool addIRTranslator() override;
413   void addPreLegalizeMachineIR() override;
414   bool addLegalizeMachineIR() override;
415   void addPreRegBankSelect() override;
416   bool addRegBankSelect() override;
417   void addPreGlobalInstructionSelect() override;
418   bool addGlobalInstructionSelect() override;
419   bool addILPOpts() override;
420   void addPreRegAlloc() override;
421   void addPostRegAlloc() override;
422   void addPreSched2() override;
423   void addPreEmitPass() override;
424 
425   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
426 };
427 
428 } // end anonymous namespace
429 
430 TargetTransformInfo
431 AArch64TargetMachine::getTargetTransformInfo(const Function &F) {
432   return TargetTransformInfo(AArch64TTIImpl(this, F));
433 }
434 
435 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
436   return new AArch64PassConfig(*this, PM);
437 }
438 
439 std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
440   return getStandardCSEConfigForOpt(TM->getOptLevel());
441 }
442 
443 void AArch64PassConfig::addIRPasses() {
444   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
445   // ourselves.
446   addPass(createAtomicExpandPass());
447 
448   // Expand any SVE vector library calls that we can't code generate directly.
449   if (EnableSVEIntrinsicOpts && TM->getOptLevel() == CodeGenOpt::Aggressive)
450     addPass(createSVEIntrinsicOptsPass());
451 
452   // Cmpxchg instructions are often used with a subsequent comparison to
453   // determine whether it succeeded. We can exploit existing control-flow in
454   // ldrex/strex loops to simplify this, but it needs tidying up.
455   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
456     addPass(createCFGSimplificationPass(SimplifyCFGOptions()
457                                             .forwardSwitchCondToPhi(true)
458                                             .convertSwitchToLookupTable(true)
459                                             .needCanonicalLoops(false)
460                                             .hoistCommonInsts(true)
461                                             .sinkCommonInsts(true)));
462 
463   // Run LoopDataPrefetch
464   //
465   // Run this before LSR to remove the multiplies involved in computing the
466   // pointer values N iterations ahead.
467   if (TM->getOptLevel() != CodeGenOpt::None) {
468     if (EnableLoopDataPrefetch)
469       addPass(createLoopDataPrefetchPass());
470     if (EnableFalkorHWPFFix)
471       addPass(createFalkorMarkStridedAccessesPass());
472   }
473 
474   TargetPassConfig::addIRPasses();
475 
476   addPass(createAArch64StackTaggingPass(
477       /*IsOptNone=*/TM->getOptLevel() == CodeGenOpt::None));
478 
479   // Match interleaved memory accesses to ldN/stN intrinsics.
480   if (TM->getOptLevel() != CodeGenOpt::None) {
481     addPass(createInterleavedLoadCombinePass());
482     addPass(createInterleavedAccessPass());
483   }
484 
485   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
486     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
487     // and lower a GEP with multiple indices to either arithmetic operations or
488     // multiple GEPs with single index.
489     addPass(createSeparateConstOffsetFromGEPPass(true));
490     // Call EarlyCSE pass to find and remove subexpressions in the lowered
491     // result.
492     addPass(createEarlyCSEPass());
493     // Do loop invariant code motion in case part of the lowered result is
494     // invariant.
495     addPass(createLICMPass());
496   }
497 
498   // Add Control Flow Guard checks.
499   if (TM->getTargetTriple().isOSWindows())
500     addPass(createCFGuardCheckPass());
501 }
502 
503 // Pass Pipeline Configuration
504 bool AArch64PassConfig::addPreISel() {
505   // Run promote constant before global merge, so that the promoted constants
506   // get a chance to be merged
507   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
508     addPass(createAArch64PromoteConstantPass());
509   // FIXME: On AArch64, this depends on the type.
510   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
511   // and the offset has to be a multiple of the related size in bytes.
512   if ((TM->getOptLevel() != CodeGenOpt::None &&
513        EnableGlobalMerge == cl::BOU_UNSET) ||
514       EnableGlobalMerge == cl::BOU_TRUE) {
515     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
516                                (EnableGlobalMerge == cl::BOU_UNSET);
517 
518     // Merging of extern globals is enabled by default on non-Mach-O as we
519     // expect it to be generally either beneficial or harmless. On Mach-O it
520     // is disabled as we emit the .subsections_via_symbols directive which
521     // means that merging extern globals is not safe.
522     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
523 
524     // FIXME: extern global merging is only enabled when we optimise for size
525     // because there are some regressions with it also enabled for performance.
526     if (!OnlyOptimizeForSize)
527       MergeExternalByDefault = false;
528 
529     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize,
530                                   MergeExternalByDefault));
531   }
532 
533   return false;
534 }
535 
536 bool AArch64PassConfig::addInstSelector() {
537   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
538 
539   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
540   // references to _TLS_MODULE_BASE_ as possible.
541   if (TM->getTargetTriple().isOSBinFormatELF() &&
542       getOptLevel() != CodeGenOpt::None)
543     addPass(createAArch64CleanupLocalDynamicTLSPass());
544 
545   return false;
546 }
547 
548 bool AArch64PassConfig::addIRTranslator() {
549   addPass(new IRTranslator(getOptLevel()));
550   return false;
551 }
552 
553 void AArch64PassConfig::addPreLegalizeMachineIR() {
554   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
555   addPass(createAArch64PreLegalizerCombiner(IsOptNone));
556 }
557 
558 bool AArch64PassConfig::addLegalizeMachineIR() {
559   addPass(new Legalizer());
560   return false;
561 }
562 
563 void AArch64PassConfig::addPreRegBankSelect() {
564   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
565   if (!IsOptNone)
566     addPass(createAArch64PostLegalizerCombiner(IsOptNone));
567   addPass(createAArch64PostLegalizerLowering());
568 }
569 
570 bool AArch64PassConfig::addRegBankSelect() {
571   addPass(new RegBankSelect());
572   return false;
573 }
574 
575 void AArch64PassConfig::addPreGlobalInstructionSelect() {
576   addPass(new Localizer());
577 }
578 
579 bool AArch64PassConfig::addGlobalInstructionSelect() {
580   addPass(new InstructionSelect());
581   if (getOptLevel() != CodeGenOpt::None)
582     addPass(createAArch64PostSelectOptimize());
583   return false;
584 }
585 
586 bool AArch64PassConfig::addILPOpts() {
587   if (EnableCondOpt)
588     addPass(createAArch64ConditionOptimizerPass());
589   if (EnableCCMP)
590     addPass(createAArch64ConditionalCompares());
591   if (EnableMCR)
592     addPass(&MachineCombinerID);
593   if (EnableCondBrTuning)
594     addPass(createAArch64CondBrTuning());
595   if (EnableEarlyIfConversion)
596     addPass(&EarlyIfConverterID);
597   if (EnableStPairSuppress)
598     addPass(createAArch64StorePairSuppressPass());
599   addPass(createAArch64SIMDInstrOptPass());
600   if (TM->getOptLevel() != CodeGenOpt::None)
601     addPass(createAArch64StackTaggingPreRAPass());
602   return true;
603 }
604 
605 void AArch64PassConfig::addPreRegAlloc() {
606   // Change dead register definitions to refer to the zero register.
607   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
608     addPass(createAArch64DeadRegisterDefinitions());
609 
610   // Use AdvSIMD scalar instructions whenever profitable.
611   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
612     addPass(createAArch64AdvSIMDScalar());
613     // The AdvSIMD pass may produce copies that can be rewritten to
614     // be register coalescer friendly.
615     addPass(&PeepholeOptimizerID);
616   }
617 }
618 
619 void AArch64PassConfig::addPostRegAlloc() {
620   // Remove redundant copy instructions.
621   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
622     addPass(createAArch64RedundantCopyEliminationPass());
623 
624   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
625     // Improve performance for some FP/SIMD code for A57.
626     addPass(createAArch64A57FPLoadBalancing());
627 }
628 
629 void AArch64PassConfig::addPreSched2() {
630   // Expand some pseudo instructions to allow proper scheduling.
631   addPass(createAArch64ExpandPseudoPass());
632   // Use load/store pair instructions when possible.
633   if (TM->getOptLevel() != CodeGenOpt::None) {
634     if (EnableLoadStoreOpt)
635       addPass(createAArch64LoadStoreOptimizationPass());
636   }
637 
638   // The AArch64SpeculationHardeningPass destroys dominator tree and natural
639   // loop info, which is needed for the FalkorHWPFFixPass and also later on.
640   // Therefore, run the AArch64SpeculationHardeningPass before the
641   // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
642   // info.
643   addPass(createAArch64SpeculationHardeningPass());
644 
645   addPass(createAArch64IndirectThunks());
646   addPass(createAArch64SLSHardeningPass());
647 
648   if (TM->getOptLevel() != CodeGenOpt::None) {
649     if (EnableFalkorHWPFFix)
650       addPass(createFalkorHWPFFixPass());
651   }
652 }
653 
654 void AArch64PassConfig::addPreEmitPass() {
655   // Machine Block Placement might have created new opportunities when run
656   // at O3, where the Tail Duplication Threshold is set to 4 instructions.
657   // Run the load/store optimizer once more.
658   if (TM->getOptLevel() >= CodeGenOpt::Aggressive && EnableLoadStoreOpt)
659     addPass(createAArch64LoadStoreOptimizationPass());
660 
661   if (EnableA53Fix835769)
662     addPass(createAArch64A53Fix835769());
663 
664   if (EnableBranchTargets)
665     addPass(createAArch64BranchTargetsPass());
666 
667   // Relax conditional branch instructions if they're otherwise out of
668   // range of their destination.
669   if (BranchRelaxation)
670     addPass(&BranchRelaxationPassID);
671 
672   // Identify valid longjmp targets for Windows Control Flow Guard.
673   if (TM->getTargetTriple().isOSWindows())
674     addPass(createCFGuardLongjmpPass());
675 
676   if (TM->getOptLevel() != CodeGenOpt::None && EnableCompressJumpTables)
677     addPass(createAArch64CompressJumpTablesPass());
678 
679   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
680       TM->getTargetTriple().isOSBinFormatMachO())
681     addPass(createAArch64CollectLOHPass());
682 
683   // SVE bundles move prefixes with destructive operations.
684   addPass(createUnpackMachineBundles(nullptr));
685 }
686 
687 yaml::MachineFunctionInfo *
688 AArch64TargetMachine::createDefaultFuncInfoYAML() const {
689   return new yaml::AArch64FunctionInfo();
690 }
691 
692 yaml::MachineFunctionInfo *
693 AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
694   const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
695   return new yaml::AArch64FunctionInfo(*MFI);
696 }
697 
698 bool AArch64TargetMachine::parseMachineFunctionInfo(
699     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
700     SMDiagnostic &Error, SMRange &SourceRange) const {
701   const auto &YamlMFI =
702       reinterpret_cast<const yaml::AArch64FunctionInfo &>(MFI);
703   MachineFunction &MF = PFS.MF;
704   MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
705   return false;
706 }
707