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