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