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