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