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/ADT/Triple.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/CodeGen/CFIFixup.h"
26 #include "llvm/CodeGen/CSEConfigBase.h"
27 #include "llvm/CodeGen/GlobalISel/CSEInfo.h"
28 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
29 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
30 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
31 #include "llvm/CodeGen/GlobalISel/LoadStoreOpt.h"
32 #include "llvm/CodeGen/GlobalISel/Localizer.h"
33 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
34 #include "llvm/CodeGen/MIRParser/MIParser.h"
35 #include "llvm/CodeGen/MachineScheduler.h"
36 #include "llvm/CodeGen/Passes.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/InitializePasses.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCTargetOptions.h"
44 #include "llvm/MC/TargetRegistry.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CodeGen.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetOptions.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
LLVMInitializeAArch64Target()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 initializeAArch64KCFIPass(*PR);
219 initializeAArch64LoadStoreOptPass(*PR);
220 initializeAArch64MIPeepholeOptPass(*PR);
221 initializeAArch64SIMDInstrOptPass(*PR);
222 initializeAArch64O0PreLegalizerCombinerPass(*PR);
223 initializeAArch64PreLegalizerCombinerPass(*PR);
224 initializeAArch64PostLegalizerCombinerPass(*PR);
225 initializeAArch64PostLegalizerLoweringPass(*PR);
226 initializeAArch64PostSelectOptimizePass(*PR);
227 initializeAArch64PromoteConstantPass(*PR);
228 initializeAArch64RedundantCopyEliminationPass(*PR);
229 initializeAArch64StorePairSuppressPass(*PR);
230 initializeFalkorHWPFFixPass(*PR);
231 initializeFalkorMarkStridedAccessesLegacyPass(*PR);
232 initializeLDTLSCleanupPass(*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 }
242
243 //===----------------------------------------------------------------------===//
244 // AArch64 Lowering public interface.
245 //===----------------------------------------------------------------------===//
createTLOF(const Triple & TT)246 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
247 if (TT.isOSBinFormatMachO())
248 return std::make_unique<AArch64_MachoTargetObjectFile>();
249 if (TT.isOSBinFormatCOFF())
250 return std::make_unique<AArch64_COFFTargetObjectFile>();
251
252 return std::make_unique<AArch64_ELFTargetObjectFile>();
253 }
254
255 // Helper function to build a DataLayout string
computeDataLayout(const Triple & TT,const MCTargetOptions & Options,bool LittleEndian)256 static std::string computeDataLayout(const Triple &TT,
257 const MCTargetOptions &Options,
258 bool LittleEndian) {
259 if (TT.isOSBinFormatMachO()) {
260 if (TT.getArch() == Triple::aarch64_32)
261 return "e-m:o-p:32:32-i64:64-i128:128-n32:64-S128";
262 return "e-m:o-i64:64-i128:128-n32:64-S128";
263 }
264 if (TT.isOSBinFormatCOFF())
265 return "e-m:w-p:64:64-i32:32-i64:64-i128:128-n32:64-S128";
266 std::string Endian = LittleEndian ? "e" : "E";
267 std::string Ptr32 = TT.getEnvironment() == Triple::GNUILP32 ? "-p:32:32" : "";
268 return Endian + "-m:e" + Ptr32 +
269 "-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
270 }
271
computeDefaultCPU(const Triple & TT,StringRef CPU)272 static StringRef computeDefaultCPU(const Triple &TT, StringRef CPU) {
273 if (CPU.empty() && TT.isArm64e())
274 return "apple-a12";
275 return CPU;
276 }
277
getEffectiveRelocModel(const Triple & TT,std::optional<Reloc::Model> RM)278 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
279 std::optional<Reloc::Model> RM) {
280 // AArch64 Darwin and Windows are always PIC.
281 if (TT.isOSDarwin() || TT.isOSWindows())
282 return Reloc::PIC_;
283 // On ELF platforms the default static relocation model has a smart enough
284 // linker to cope with referencing external symbols defined in a shared
285 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
286 if (!RM || *RM == Reloc::DynamicNoPIC)
287 return Reloc::Static;
288 return *RM;
289 }
290
291 static CodeModel::Model
getEffectiveAArch64CodeModel(const Triple & TT,std::optional<CodeModel::Model> CM,bool JIT)292 getEffectiveAArch64CodeModel(const Triple &TT,
293 std::optional<CodeModel::Model> CM, bool JIT) {
294 if (CM) {
295 if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
296 *CM != CodeModel::Large) {
297 report_fatal_error(
298 "Only small, tiny and large code models are allowed on AArch64");
299 } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF())
300 report_fatal_error("tiny code model is only supported on ELF");
301 return *CM;
302 }
303 // The default MCJIT memory managers make no guarantees about where they can
304 // find an executable page; JITed code needs to be able to refer to globals
305 // no matter how far away they are.
306 // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
307 // since with large code model LLVM generating 4 MOV instructions, and
308 // Windows doesn't support relocating these long branch (4 MOVs).
309 if (JIT && !TT.isOSWindows())
310 return CodeModel::Large;
311 return CodeModel::Small;
312 }
313
314 /// Create an AArch64 architecture model.
315 ///
AArch64TargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,std::optional<Reloc::Model> RM,std::optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT,bool LittleEndian)316 AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
317 StringRef CPU, StringRef FS,
318 const TargetOptions &Options,
319 std::optional<Reloc::Model> RM,
320 std::optional<CodeModel::Model> CM,
321 CodeGenOpt::Level OL, bool JIT,
322 bool LittleEndian)
323 : LLVMTargetMachine(T,
324 computeDataLayout(TT, Options.MCOptions, LittleEndian),
325 TT, computeDefaultCPU(TT, CPU), FS, Options,
326 getEffectiveRelocModel(TT, RM),
327 getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
328 TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
329 initAsmInfo();
330
331 if (TT.isOSBinFormatMachO()) {
332 this->Options.TrapUnreachable = true;
333 this->Options.NoTrapAfterNoreturn = true;
334 }
335
336 if (getMCAsmInfo()->usesWindowsCFI()) {
337 // Unwinding can get confused if the last instruction in an
338 // exception-handling region (function, funclet, try block, etc.)
339 // is a call.
340 //
341 // FIXME: We could elide the trap if the next instruction would be in
342 // the same region anyway.
343 this->Options.TrapUnreachable = true;
344 }
345
346 if (this->Options.TLSSize == 0) // default
347 this->Options.TLSSize = 24;
348 if ((getCodeModel() == CodeModel::Small ||
349 getCodeModel() == CodeModel::Kernel) &&
350 this->Options.TLSSize > 32)
351 // for the small (and kernel) code model, the maximum TLS size is 4GiB
352 this->Options.TLSSize = 32;
353 else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
354 // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
355 this->Options.TLSSize = 24;
356
357 // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
358 // MachO/CodeModel::Large, which GlobalISel does not support.
359 if (getOptLevel() <= EnableGlobalISelAtO &&
360 !getTargetTriple().isOSOpenBSD() &&
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 *
getSubtargetImpl(const Function & F) const385 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 StreamingSVEModeDisabled =
395 !F.hasFnAttribute("aarch64_pstate_sm_enabled") &&
396 !F.hasFnAttribute("aarch64_pstate_sm_compatible") &&
397 !F.hasFnAttribute("aarch64_pstate_sm_body");
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 << "StreamingSVEModeDisabled="
431 << StreamingSVEModeDisabled << CPU << TuneCPU << FS;
432
433 auto &I = SubtargetMap[Key];
434 if (!I) {
435 // This needs to be done before we create a new subtarget since any
436 // creation will depend on the TM and the code generation flags on the
437 // function that reside in TargetOptions.
438 resetTargetOptions(F);
439 I = std::make_unique<AArch64Subtarget>(
440 TargetTriple, CPU, TuneCPU, FS, *this, isLittle, MinSVEVectorSize,
441 MaxSVEVectorSize, StreamingSVEModeDisabled);
442 }
443 return I.get();
444 }
445
anchor()446 void AArch64leTargetMachine::anchor() { }
447
AArch64leTargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,std::optional<Reloc::Model> RM,std::optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)448 AArch64leTargetMachine::AArch64leTargetMachine(
449 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
450 const TargetOptions &Options, std::optional<Reloc::Model> RM,
451 std::optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
452 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
453
anchor()454 void AArch64beTargetMachine::anchor() { }
455
AArch64beTargetMachine(const Target & T,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,std::optional<Reloc::Model> RM,std::optional<CodeModel::Model> CM,CodeGenOpt::Level OL,bool JIT)456 AArch64beTargetMachine::AArch64beTargetMachine(
457 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
458 const TargetOptions &Options, std::optional<Reloc::Model> RM,
459 std::optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
460 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
461
462 namespace {
463
464 /// AArch64 Code Generator Pass Configuration Options.
465 class AArch64PassConfig : public TargetPassConfig {
466 public:
AArch64PassConfig(AArch64TargetMachine & TM,PassManagerBase & PM)467 AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
468 : TargetPassConfig(TM, PM) {
469 if (TM.getOptLevel() != CodeGenOpt::None)
470 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
471 }
472
getAArch64TargetMachine() const473 AArch64TargetMachine &getAArch64TargetMachine() const {
474 return getTM<AArch64TargetMachine>();
475 }
476
477 ScheduleDAGInstrs *
createMachineScheduler(MachineSchedContext * C) const478 createMachineScheduler(MachineSchedContext *C) const override {
479 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
480 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
481 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
482 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
483 if (ST.hasFusion())
484 DAG->addMutation(createAArch64MacroFusionDAGMutation());
485 return DAG;
486 }
487
488 ScheduleDAGInstrs *
createPostMachineScheduler(MachineSchedContext * C) const489 createPostMachineScheduler(MachineSchedContext *C) const override {
490 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
491 ScheduleDAGMI *DAG =
492 new ScheduleDAGMI(C, std::make_unique<AArch64PostRASchedStrategy>(C),
493 /* RemoveKillFlags=*/true);
494 if (ST.hasFusion()) {
495 // Run the Macro Fusion after RA again since literals are expanded from
496 // pseudos then (v. addPreSched2()).
497 DAG->addMutation(createAArch64MacroFusionDAGMutation());
498 return DAG;
499 }
500
501 return DAG;
502 }
503
504 void addIRPasses() override;
505 bool addPreISel() override;
506 void addCodeGenPrepare() override;
507 bool addInstSelector() override;
508 bool addIRTranslator() override;
509 void addPreLegalizeMachineIR() override;
510 bool addLegalizeMachineIR() override;
511 void addPreRegBankSelect() override;
512 bool addRegBankSelect() override;
513 void addPreGlobalInstructionSelect() override;
514 bool addGlobalInstructionSelect() override;
515 void addMachineSSAOptimization() override;
516 bool addILPOpts() override;
517 void addPreRegAlloc() override;
518 void addPostRegAlloc() override;
519 void addPreSched2() override;
520 void addPreEmitPass() override;
521 void addPreEmitPass2() override;
522
523 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
524 };
525
526 } // end anonymous namespace
527
528 TargetTransformInfo
getTargetTransformInfo(const Function & F) const529 AArch64TargetMachine::getTargetTransformInfo(const Function &F) const {
530 return TargetTransformInfo(AArch64TTIImpl(this, F));
531 }
532
createPassConfig(PassManagerBase & PM)533 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
534 return new AArch64PassConfig(*this, PM);
535 }
536
getCSEConfig() const537 std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
538 return getStandardCSEConfigForOpt(TM->getOptLevel());
539 }
540
addIRPasses()541 void AArch64PassConfig::addIRPasses() {
542 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
543 // ourselves.
544 addPass(createAtomicExpandPass());
545
546 // Expand any SVE vector library calls that we can't code generate directly.
547 if (EnableSVEIntrinsicOpts && TM->getOptLevel() == CodeGenOpt::Aggressive)
548 addPass(createSVEIntrinsicOptsPass());
549
550 // Cmpxchg instructions are often used with a subsequent comparison to
551 // determine whether it succeeded. We can exploit existing control-flow in
552 // ldrex/strex loops to simplify this, but it needs tidying up.
553 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
554 addPass(createCFGSimplificationPass(SimplifyCFGOptions()
555 .forwardSwitchCondToPhi(true)
556 .convertSwitchRangeToICmp(true)
557 .convertSwitchToLookupTable(true)
558 .needCanonicalLoops(false)
559 .hoistCommonInsts(true)
560 .sinkCommonInsts(true)));
561
562 // Run LoopDataPrefetch
563 //
564 // Run this before LSR to remove the multiplies involved in computing the
565 // pointer values N iterations ahead.
566 if (TM->getOptLevel() != CodeGenOpt::None) {
567 if (EnableLoopDataPrefetch)
568 addPass(createLoopDataPrefetchPass());
569 if (EnableFalkorHWPFFix)
570 addPass(createFalkorMarkStridedAccessesPass());
571 }
572
573 if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
574 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
575 // and lower a GEP with multiple indices to either arithmetic operations or
576 // multiple GEPs with single index.
577 addPass(createSeparateConstOffsetFromGEPPass(true));
578 // Call EarlyCSE pass to find and remove subexpressions in the lowered
579 // result.
580 addPass(createEarlyCSEPass());
581 // Do loop invariant code motion in case part of the lowered result is
582 // invariant.
583 addPass(createLICMPass());
584 }
585
586 TargetPassConfig::addIRPasses();
587
588 if (getOptLevel() == CodeGenOpt::Aggressive && EnableSelectOpt)
589 addPass(createSelectOptimizePass());
590
591 addPass(createAArch64StackTaggingPass(
592 /*IsOptNone=*/TM->getOptLevel() == CodeGenOpt::None));
593
594 // Match complex arithmetic patterns
595 if (TM->getOptLevel() >= CodeGenOpt::Default)
596 addPass(createComplexDeinterleavingPass(TM));
597
598 // Match interleaved memory accesses to ldN/stN intrinsics.
599 if (TM->getOptLevel() != CodeGenOpt::None) {
600 addPass(createInterleavedLoadCombinePass());
601 addPass(createInterleavedAccessPass());
602 }
603
604 // Expand any functions marked with SME attributes which require special
605 // changes for the calling convention or that require the lazy-saving
606 // mechanism specified in the SME ABI.
607 addPass(createSMEABIPass());
608
609 // Add Control Flow Guard checks.
610 if (TM->getTargetTriple().isOSWindows())
611 addPass(createCFGuardCheckPass());
612
613 if (TM->Options.JMCInstrument)
614 addPass(createJMCInstrumenterPass());
615 }
616
617 // Pass Pipeline Configuration
addPreISel()618 bool AArch64PassConfig::addPreISel() {
619 // Run promote constant before global merge, so that the promoted constants
620 // get a chance to be merged
621 if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
622 addPass(createAArch64PromoteConstantPass());
623 // FIXME: On AArch64, this depends on the type.
624 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
625 // and the offset has to be a multiple of the related size in bytes.
626 if ((TM->getOptLevel() != CodeGenOpt::None &&
627 EnableGlobalMerge == cl::BOU_UNSET) ||
628 EnableGlobalMerge == cl::BOU_TRUE) {
629 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
630 (EnableGlobalMerge == cl::BOU_UNSET);
631
632 // Merging of extern globals is enabled by default on non-Mach-O as we
633 // expect it to be generally either beneficial or harmless. On Mach-O it
634 // is disabled as we emit the .subsections_via_symbols directive which
635 // means that merging extern globals is not safe.
636 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
637
638 // FIXME: extern global merging is only enabled when we optimise for size
639 // because there are some regressions with it also enabled for performance.
640 if (!OnlyOptimizeForSize)
641 MergeExternalByDefault = false;
642
643 addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize,
644 MergeExternalByDefault));
645 }
646
647 return false;
648 }
649
addCodeGenPrepare()650 void AArch64PassConfig::addCodeGenPrepare() {
651 if (getOptLevel() != CodeGenOpt::None)
652 addPass(createTypePromotionLegacyPass());
653 TargetPassConfig::addCodeGenPrepare();
654 }
655
addInstSelector()656 bool AArch64PassConfig::addInstSelector() {
657 addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
658
659 // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
660 // references to _TLS_MODULE_BASE_ as possible.
661 if (TM->getTargetTriple().isOSBinFormatELF() &&
662 getOptLevel() != CodeGenOpt::None)
663 addPass(createAArch64CleanupLocalDynamicTLSPass());
664
665 return false;
666 }
667
addIRTranslator()668 bool AArch64PassConfig::addIRTranslator() {
669 addPass(new IRTranslator(getOptLevel()));
670 return false;
671 }
672
addPreLegalizeMachineIR()673 void AArch64PassConfig::addPreLegalizeMachineIR() {
674 if (getOptLevel() == CodeGenOpt::None)
675 addPass(createAArch64O0PreLegalizerCombiner());
676 else {
677 addPass(createAArch64PreLegalizerCombiner());
678 if (EnableGISelLoadStoreOptPreLegal)
679 addPass(new LoadStoreOpt());
680 }
681 }
682
addLegalizeMachineIR()683 bool AArch64PassConfig::addLegalizeMachineIR() {
684 addPass(new Legalizer());
685 return false;
686 }
687
addPreRegBankSelect()688 void AArch64PassConfig::addPreRegBankSelect() {
689 bool IsOptNone = getOptLevel() == CodeGenOpt::None;
690 if (!IsOptNone) {
691 addPass(createAArch64PostLegalizerCombiner(IsOptNone));
692 if (EnableGISelLoadStoreOptPostLegal)
693 addPass(new LoadStoreOpt());
694 }
695 addPass(createAArch64PostLegalizerLowering());
696 }
697
addRegBankSelect()698 bool AArch64PassConfig::addRegBankSelect() {
699 addPass(new RegBankSelect());
700 return false;
701 }
702
addPreGlobalInstructionSelect()703 void AArch64PassConfig::addPreGlobalInstructionSelect() {
704 addPass(new Localizer());
705 }
706
addGlobalInstructionSelect()707 bool AArch64PassConfig::addGlobalInstructionSelect() {
708 addPass(new InstructionSelect(getOptLevel()));
709 if (getOptLevel() != CodeGenOpt::None)
710 addPass(createAArch64PostSelectOptimize());
711 return false;
712 }
713
addMachineSSAOptimization()714 void AArch64PassConfig::addMachineSSAOptimization() {
715 // Run default MachineSSAOptimization first.
716 TargetPassConfig::addMachineSSAOptimization();
717
718 if (TM->getOptLevel() != CodeGenOpt::None)
719 addPass(createAArch64MIPeepholeOptPass());
720 }
721
addILPOpts()722 bool AArch64PassConfig::addILPOpts() {
723 if (EnableCondOpt)
724 addPass(createAArch64ConditionOptimizerPass());
725 if (EnableCCMP)
726 addPass(createAArch64ConditionalCompares());
727 if (EnableMCR)
728 addPass(&MachineCombinerID);
729 if (EnableCondBrTuning)
730 addPass(createAArch64CondBrTuning());
731 if (EnableEarlyIfConversion)
732 addPass(&EarlyIfConverterID);
733 if (EnableStPairSuppress)
734 addPass(createAArch64StorePairSuppressPass());
735 addPass(createAArch64SIMDInstrOptPass());
736 if (TM->getOptLevel() != CodeGenOpt::None)
737 addPass(createAArch64StackTaggingPreRAPass());
738 return true;
739 }
740
addPreRegAlloc()741 void AArch64PassConfig::addPreRegAlloc() {
742 // Change dead register definitions to refer to the zero register.
743 if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
744 addPass(createAArch64DeadRegisterDefinitions());
745
746 // Use AdvSIMD scalar instructions whenever profitable.
747 if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
748 addPass(createAArch64AdvSIMDScalar());
749 // The AdvSIMD pass may produce copies that can be rewritten to
750 // be register coalescer friendly.
751 addPass(&PeepholeOptimizerID);
752 }
753 }
754
addPostRegAlloc()755 void AArch64PassConfig::addPostRegAlloc() {
756 // Remove redundant copy instructions.
757 if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
758 addPass(createAArch64RedundantCopyEliminationPass());
759
760 if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
761 // Improve performance for some FP/SIMD code for A57.
762 addPass(createAArch64A57FPLoadBalancing());
763 }
764
addPreSched2()765 void AArch64PassConfig::addPreSched2() {
766 // Lower homogeneous frame instructions
767 if (EnableHomogeneousPrologEpilog)
768 addPass(createAArch64LowerHomogeneousPrologEpilogPass());
769 // Expand some pseudo instructions to allow proper scheduling.
770 addPass(createAArch64ExpandPseudoPass());
771 // Use load/store pair instructions when possible.
772 if (TM->getOptLevel() != CodeGenOpt::None) {
773 if (EnableLoadStoreOpt)
774 addPass(createAArch64LoadStoreOptimizationPass());
775 }
776 // Emit KCFI checks for indirect calls.
777 addPass(createAArch64KCFIPass());
778
779 // The AArch64SpeculationHardeningPass destroys dominator tree and natural
780 // loop info, which is needed for the FalkorHWPFFixPass and also later on.
781 // Therefore, run the AArch64SpeculationHardeningPass before the
782 // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
783 // info.
784 addPass(createAArch64SpeculationHardeningPass());
785
786 addPass(createAArch64IndirectThunks());
787 addPass(createAArch64SLSHardeningPass());
788
789 if (TM->getOptLevel() != CodeGenOpt::None) {
790 if (EnableFalkorHWPFFix)
791 addPass(createFalkorHWPFFixPass());
792 }
793 }
794
addPreEmitPass()795 void AArch64PassConfig::addPreEmitPass() {
796 // Machine Block Placement might have created new opportunities when run
797 // at O3, where the Tail Duplication Threshold is set to 4 instructions.
798 // Run the load/store optimizer once more.
799 if (TM->getOptLevel() >= CodeGenOpt::Aggressive && EnableLoadStoreOpt)
800 addPass(createAArch64LoadStoreOptimizationPass());
801
802 if (TM->getOptLevel() >= CodeGenOpt::Aggressive &&
803 EnableAArch64CopyPropagation)
804 addPass(createMachineCopyPropagationPass(true));
805
806 addPass(createAArch64A53Fix835769());
807
808 if (EnableBranchTargets)
809 addPass(createAArch64BranchTargetsPass());
810
811 // Relax conditional branch instructions if they're otherwise out of
812 // range of their destination.
813 if (BranchRelaxation)
814 addPass(&BranchRelaxationPassID);
815
816 if (TM->getTargetTriple().isOSWindows()) {
817 // Identify valid longjmp targets for Windows Control Flow Guard.
818 addPass(createCFGuardLongjmpPass());
819 // Identify valid eh continuation targets for Windows EHCont Guard.
820 addPass(createEHContGuardCatchretPass());
821 }
822
823 if (TM->getOptLevel() != CodeGenOpt::None && EnableCompressJumpTables)
824 addPass(createAArch64CompressJumpTablesPass());
825
826 if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
827 TM->getTargetTriple().isOSBinFormatMachO())
828 addPass(createAArch64CollectLOHPass());
829 }
830
addPreEmitPass2()831 void AArch64PassConfig::addPreEmitPass2() {
832 // SVE bundles move prefixes with destructive operations. BLR_RVMARKER pseudo
833 // instructions are lowered to bundles as well.
834 addPass(createUnpackMachineBundles(nullptr));
835 }
836
createMachineFunctionInfo(BumpPtrAllocator & Allocator,const Function & F,const TargetSubtargetInfo * STI) const837 MachineFunctionInfo *AArch64TargetMachine::createMachineFunctionInfo(
838 BumpPtrAllocator &Allocator, const Function &F,
839 const TargetSubtargetInfo *STI) const {
840 return AArch64FunctionInfo::create<AArch64FunctionInfo>(
841 Allocator, F, static_cast<const AArch64Subtarget *>(STI));
842 }
843
844 yaml::MachineFunctionInfo *
createDefaultFuncInfoYAML() const845 AArch64TargetMachine::createDefaultFuncInfoYAML() const {
846 return new yaml::AArch64FunctionInfo();
847 }
848
849 yaml::MachineFunctionInfo *
convertFuncInfoToYAML(const MachineFunction & MF) const850 AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
851 const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
852 return new yaml::AArch64FunctionInfo(*MFI);
853 }
854
parseMachineFunctionInfo(const yaml::MachineFunctionInfo & MFI,PerFunctionMIParsingState & PFS,SMDiagnostic & Error,SMRange & SourceRange) const855 bool AArch64TargetMachine::parseMachineFunctionInfo(
856 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
857 SMDiagnostic &Error, SMRange &SourceRange) const {
858 const auto &YamlMFI = static_cast<const yaml::AArch64FunctionInfo &>(MFI);
859 MachineFunction &MF = PFS.MF;
860 MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
861 return false;
862 }
863