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 initializeAArch64A53Fix835769LegacyPass(PR);
247 initializeAArch64A57FPLoadBalancingPass(PR);
248 initializeAArch64AdvSIMDScalarLegacyPass(PR);
249 initializeAArch64AsmPrinterPass(PR);
250 initializeAArch64BranchTargetsLegacyPass(PR);
251 initializeAArch64CollectLOHLegacyPass(PR);
252 initializeAArch64CompressJumpTablesLegacyPass(PR);
253 initializeAArch64ConditionalComparesPass(PR);
254 initializeAArch64ConditionOptimizerLegacyPass(PR);
255 initializeAArch64DeadRegisterDefinitionsPass(PR);
256 initializeAArch64ExpandPseudoPass(PR);
257 initializeAArch64LoadStoreOptLegacyPass(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 && EnableGlobalISelAtO != -1 &&
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#define GET_PASS_REGISTRY "AArch64PassRegistry.def"
590#include "llvm/Passes/TargetPassRegistry.inc"
591
592 PB.registerLateLoopOptimizationsEPCallback(
593 C: [=](LoopPassManager &LPM, OptimizationLevel Level) {
594 if (Level != OptimizationLevel::O0)
595 LPM.addPass(Pass: LoopIdiomVectorizePass());
596 });
597 if (getTargetTriple().isOSWindows())
598 PB.registerPipelineEarlySimplificationEPCallback(
599 C: [](ModulePassManager &PM, OptimizationLevel, ThinOrFullLTOPhase) {
600 PM.addPass(Pass: LowerIFuncPass());
601 });
602}
603
604TargetTransformInfo
605AArch64TargetMachine::getTargetTransformInfo(const Function &F) const {
606 return TargetTransformInfo(std::make_unique<AArch64TTIImpl>(args: this, args: F));
607}
608
609TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
610 return new AArch64PassConfig(*this, PM);
611}
612
613std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
614 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
615}
616
617// This function checks whether the opt level is explicitly set to none,
618// or whether GlobalISel was enabled due to SDAG encountering an optnone
619// function. If the opt level is greater than the level we automatically enable
620// globalisel at, and it wasn't enabled via CLI, we know that it must be because
621// of an optnone function.
622bool AArch64PassConfig::isGlobalISelOptNone() const {
623 const bool GlobalISelFlag =
624 getCGPassBuilderOption().EnableGlobalISelOption.value_or(u: false);
625
626 return getOptLevel() == CodeGenOptLevel::None ||
627 (static_cast<unsigned>(getOptLevel()) >
628 getAArch64TargetMachine().getEnableGlobalISelAtO() &&
629 !GlobalISelFlag);
630}
631
632void AArch64PassConfig::addIRPasses() {
633 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
634 // ourselves.
635 addPass(P: createAtomicExpandLegacyPass());
636
637 // Expand any SVE vector library calls that we can't code generate directly.
638 if (EnableSVEIntrinsicOpts &&
639 TM->getOptLevel() != CodeGenOptLevel::None)
640 addPass(P: createSVEIntrinsicOptsPass());
641
642 // Cmpxchg instructions are often used with a subsequent comparison to
643 // determine whether it succeeded. We can exploit existing control-flow in
644 // ldrex/strex loops to simplify this, but it needs tidying up.
645 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAtomicTidy)
646 addPass(P: createCFGSimplificationPass(Options: SimplifyCFGOptions()
647 .forwardSwitchCondToPhi(B: true)
648 .convertSwitchRangeToICmp(B: true)
649 .convertSwitchToLookupTable(B: true)
650 .needCanonicalLoops(B: false)
651 .hoistCommonInsts(B: true)
652 .sinkCommonInsts(B: true)));
653
654 // Run LoopDataPrefetch
655 //
656 // Run this before LSR to remove the multiplies involved in computing the
657 // pointer values N iterations ahead.
658 if (TM->getOptLevel() != CodeGenOptLevel::None) {
659 if (EnableLoopDataPrefetch)
660 addPass(P: createLoopDataPrefetchPass());
661 if (EnableFalkorHWPFFix)
662 addPass(P: createFalkorMarkStridedAccessesPass());
663 }
664
665 if (EnableGEPOpt) {
666 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
667 // and lower a GEP with multiple indices to either arithmetic operations or
668 // multiple GEPs with single index.
669 addPass(P: createSeparateConstOffsetFromGEPPass(LowerGEP: true));
670 // Call EarlyCSE pass to find and remove subexpressions in the lowered
671 // result.
672 addPass(P: createEarlyCSEPass());
673 // Do loop invariant code motion in case part of the lowered result is
674 // invariant.
675 addPass(P: createLICMPass());
676 }
677
678 TargetPassConfig::addIRPasses();
679
680 if (getOptLevel() == CodeGenOptLevel::Aggressive && EnableSelectOpt)
681 addPass(P: createSelectOptimizePass());
682
683 addPass(P: createAArch64StackTaggingPass(
684 /*IsOptNone=*/TM->getOptLevel() == CodeGenOptLevel::None));
685
686 // Match complex arithmetic patterns
687 if (TM->getOptLevel() >= CodeGenOptLevel::Default)
688 addPass(P: createComplexDeinterleavingPass(TM));
689
690 // Match interleaved memory accesses to ldN/stN intrinsics.
691 if (TM->getOptLevel() != CodeGenOptLevel::None) {
692 addPass(P: createInterleavedLoadCombinePass());
693 addPass(P: createInterleavedAccessPass());
694 }
695
696 if (!EnableNewSMEABILowering) {
697 // Expand any functions marked with SME attributes which require special
698 // changes for the calling convention or that require the lazy-saving
699 // mechanism specified in the SME ABI.
700 addPass(P: createSMEABIPass());
701 }
702
703 // Add Control Flow Guard checks.
704 if (TM->getTargetTriple().isOSWindows()) {
705 if (TM->getTargetTriple().isWindowsArm64EC())
706 addPass(P: createAArch64Arm64ECCallLoweringPass());
707 else
708 addPass(P: createCFGuardCheckPass());
709 }
710
711 if (TM->Options.JMCInstrument)
712 addPass(P: createJMCInstrumenterPass());
713}
714
715// Pass Pipeline Configuration
716bool AArch64PassConfig::addPreISel() {
717 // Run promote constant before global merge, so that the promoted constants
718 // get a chance to be merged
719 if (TM->getOptLevel() != CodeGenOptLevel::None && EnablePromoteConstant)
720 addPass(P: createAArch64PromoteConstantPass());
721 // FIXME: On AArch64, this depends on the type.
722 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
723 // and the offset has to be a multiple of the related size in bytes.
724 if ((TM->getOptLevel() != CodeGenOptLevel::None &&
725 EnableGlobalMerge == cl::BOU_UNSET) ||
726 EnableGlobalMerge == cl::BOU_TRUE) {
727 bool OnlyOptimizeForSize =
728 (TM->getOptLevel() < CodeGenOptLevel::Aggressive) &&
729 (EnableGlobalMerge == cl::BOU_UNSET);
730
731 // Merging of extern globals is enabled by default on non-Mach-O as we
732 // expect it to be generally either beneficial or harmless. On Mach-O it
733 // is disabled as we emit the .subsections_via_symbols directive which
734 // means that merging extern globals is not safe.
735 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
736 addPass(P: createGlobalMergePass(TM, MaximalOffset: 4095, OnlyOptimizeForSize,
737 MergeExternalByDefault));
738 }
739
740 return false;
741}
742
743void AArch64PassConfig::addCodeGenPrepare() {
744 if (getOptLevel() != CodeGenOptLevel::None)
745 addPass(P: createTypePromotionLegacyPass());
746 TargetPassConfig::addCodeGenPrepare();
747}
748
749bool AArch64PassConfig::addInstSelector() {
750 addPass(P: createAArch64ISelDag(TM&: getAArch64TargetMachine(), OptLevel: getOptLevel()));
751
752 // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
753 // references to _TLS_MODULE_BASE_ as possible.
754 if (TM->getTargetTriple().isOSBinFormatELF() &&
755 getOptLevel() != CodeGenOptLevel::None)
756 addPass(P: createAArch64CleanupLocalDynamicTLSPass());
757
758 return false;
759}
760
761bool AArch64PassConfig::addIRTranslator() {
762 addPass(P: new IRTranslator(getOptLevel()));
763 return false;
764}
765
766void AArch64PassConfig::addPreLegalizeMachineIR() {
767 if (isGlobalISelOptNone()) {
768 addPass(P: createAArch64O0PreLegalizerCombiner());
769 addPass(P: new Localizer());
770 } else {
771 addPass(P: createAArch64PreLegalizerCombiner());
772 addPass(P: new Localizer());
773 if (EnableGISelLoadStoreOptPreLegal)
774 addPass(P: new LoadStoreOpt());
775 }
776}
777
778bool AArch64PassConfig::addLegalizeMachineIR() {
779 addPass(P: new Legalizer());
780 return false;
781}
782
783void AArch64PassConfig::addPreRegBankSelect() {
784 if (!isGlobalISelOptNone()) {
785 addPass(P: createAArch64PostLegalizerCombiner(IsOptNone: isGlobalISelOptNone()));
786 if (EnableGISelLoadStoreOptPostLegal)
787 addPass(P: new LoadStoreOpt());
788 }
789 addPass(P: createAArch64PostLegalizerLowering());
790}
791
792bool AArch64PassConfig::addRegBankSelect() {
793 addPass(P: new RegBankSelect());
794 return false;
795}
796
797bool AArch64PassConfig::addGlobalInstructionSelect() {
798 addPass(P: new InstructionSelect(getOptLevel()));
799 if (!isGlobalISelOptNone())
800 addPass(P: createAArch64PostSelectOptimize());
801 return false;
802}
803
804void AArch64PassConfig::addMachineSSAOptimization() {
805 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableNewSMEABILowering)
806 addPass(P: createMachineSMEABIPass(TM->getOptLevel()));
807
808 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableSMEPeepholeOpt)
809 addPass(P: createSMEPeepholeOptPass());
810
811 // Run default MachineSSAOptimization first.
812 TargetPassConfig::addMachineSSAOptimization();
813
814 if (TM->getOptLevel() != CodeGenOptLevel::None)
815 addPass(P: createAArch64MIPeepholeOptPass());
816}
817
818bool AArch64PassConfig::addILPOpts() {
819 if (EnableCondOpt)
820 addPass(P: createAArch64ConditionOptimizerLegacyPass());
821 if (EnableCCMP)
822 addPass(P: createAArch64ConditionalCompares());
823 if (EnableMCR)
824 addPass(PassID: &MachineCombinerID);
825 if (EnableCondBrTuning)
826 addPass(P: createAArch64CondBrTuning());
827 if (EnableEarlyIfConversion)
828 addPass(PassID: &EarlyIfConverterLegacyID);
829 if (EnableStPairSuppress)
830 addPass(P: createAArch64StorePairSuppressPass());
831 addPass(P: createAArch64SIMDInstrOptPass());
832 if (TM->getOptLevel() != CodeGenOptLevel::None)
833 addPass(P: createAArch64StackTaggingPreRAPass());
834 return true;
835}
836
837void AArch64PassConfig::addPreRegAlloc() {
838 if (TM->getOptLevel() == CodeGenOptLevel::None && EnableNewSMEABILowering)
839 addPass(P: createMachineSMEABIPass(CodeGenOptLevel::None));
840
841 // Change dead register definitions to refer to the zero register.
842 if (TM->getOptLevel() != CodeGenOptLevel::None &&
843 EnableDeadRegisterElimination)
844 addPass(P: createAArch64DeadRegisterDefinitions());
845
846 // Use AdvSIMD scalar instructions whenever profitable.
847 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAdvSIMDScalar) {
848 addPass(P: createAArch64AdvSIMDScalar());
849 // The AdvSIMD pass may produce copies that can be rewritten to
850 // be register coalescer friendly.
851 addPass(PassID: &PeepholeOptimizerLegacyID);
852 }
853 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableMachinePipeliner)
854 addPass(PassID: &MachinePipelinerID);
855}
856
857void AArch64PassConfig::addPostRewrite() {
858 if (EnableSRLTSubregToRegMitigation)
859 addPass(P: createAArch64SRLTDefineSuperRegsPass());
860}
861
862void AArch64PassConfig::addPostRegAlloc() {
863 // Remove redundant copy instructions.
864 if (TM->getOptLevel() != CodeGenOptLevel::None &&
865 EnableRedundantCopyElimination)
866 addPass(P: createAArch64RedundantCopyEliminationPass());
867
868 if (TM->getOptLevel() != CodeGenOptLevel::None && usingDefaultRegAlloc())
869 // Improve performance for some FP/SIMD code for A57.
870 addPass(P: createAArch64A57FPLoadBalancing());
871}
872
873void AArch64PassConfig::addPreSched2() {
874 // Lower homogeneous frame instructions
875 if (EnableHomogeneousPrologEpilog)
876 addPass(P: createAArch64LowerHomogeneousPrologEpilogPass());
877 // Expand some pseudo instructions to allow proper scheduling.
878 addPass(P: createAArch64ExpandPseudoPass());
879 // Use load/store pair instructions when possible.
880 if (TM->getOptLevel() != CodeGenOptLevel::None) {
881 if (EnableLoadStoreOpt)
882 addPass(P: createAArch64LoadStoreOptLegacyPass());
883 }
884 // Emit KCFI checks for indirect calls.
885 addPass(P: createKCFIPass());
886
887 // The AArch64SpeculationHardeningPass destroys dominator tree and natural
888 // loop info, which is needed for the FalkorHWPFFixPass and also later on.
889 // Therefore, run the AArch64SpeculationHardeningPass before the
890 // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
891 // info.
892 addPass(P: createAArch64SpeculationHardeningPass());
893
894 if (TM->getOptLevel() != CodeGenOptLevel::None) {
895 if (EnableFalkorHWPFFix)
896 addPass(P: createFalkorHWPFFixPass());
897 }
898}
899
900void AArch64PassConfig::addPreEmitPass() {
901 // Machine Block Placement might have created new opportunities when run
902 // at O3, where the Tail Duplication Threshold is set to 4 instructions.
903 // Run the load/store optimizer once more.
904 if (TM->getOptLevel() >= CodeGenOptLevel::Aggressive && EnableLoadStoreOpt)
905 addPass(P: createAArch64LoadStoreOptLegacyPass());
906
907 if (TM->getOptLevel() >= CodeGenOptLevel::Aggressive &&
908 EnableAArch64CopyPropagation)
909 addPass(P: createMachineCopyPropagationPass(UseCopyInstr: true));
910 if (TM->getOptLevel() != CodeGenOptLevel::None)
911 addPass(P: createAArch64RedundantCondBranchPass());
912
913 addPass(P: createAArch64A53Fix835769LegacyPass());
914
915 if (TM->getTargetTriple().isOSWindows()) {
916 // Identify valid longjmp targets for Windows Control Flow Guard.
917 addPass(P: createCFGuardLongjmpPass());
918 // Identify valid eh continuation targets for Windows EHCont Guard.
919 addPass(P: createEHContGuardTargetsPass());
920 }
921
922 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableCollectLOH &&
923 TM->getTargetTriple().isOSBinFormatMachO())
924 addPass(P: createAArch64CollectLOHPass());
925}
926
927void AArch64PassConfig::addPostBBSections() {
928 addPass(P: createAArch64SLSHardeningPass());
929 addPass(P: createAArch64PointerAuthPass());
930 if (EnableBranchTargets)
931 addPass(P: createAArch64BranchTargetsPass());
932 // Relax conditional branch instructions if they're otherwise out of
933 // range of their destination.
934 if (BranchRelaxation)
935 addPass(PassID: &BranchRelaxationPassID);
936
937 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableCompressJumpTables)
938 addPass(P: createAArch64CompressJumpTablesPass());
939}
940
941void AArch64PassConfig::addPreEmitPass2() {
942 // SVE bundles move prefixes with destructive operations. BLR_RVMARKER pseudo
943 // instructions are lowered to bundles as well.
944 addPass(P: createUnpackMachineBundlesLegacy(Ftor: nullptr));
945}
946
947bool AArch64PassConfig::addRegAssignAndRewriteOptimized() {
948 addPass(P: createAArch64PostCoalescerPass());
949 return TargetPassConfig::addRegAssignAndRewriteOptimized();
950}
951
952MachineFunctionInfo *AArch64TargetMachine::createMachineFunctionInfo(
953 BumpPtrAllocator &Allocator, const Function &F,
954 const TargetSubtargetInfo *STI) const {
955 return AArch64FunctionInfo::create<AArch64FunctionInfo>(
956 Allocator, F, STI: static_cast<const AArch64Subtarget *>(STI));
957}
958
959yaml::MachineFunctionInfo *
960AArch64TargetMachine::createDefaultFuncInfoYAML() const {
961 return new yaml::AArch64FunctionInfo();
962}
963
964yaml::MachineFunctionInfo *
965AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
966 const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
967 return new yaml::AArch64FunctionInfo(*MFI);
968}
969
970bool AArch64TargetMachine::parseMachineFunctionInfo(
971 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
972 SMDiagnostic &Error, SMRange &SourceRange) const {
973 const auto &YamlMFI = static_cast<const yaml::AArch64FunctionInfo &>(MFI);
974 MachineFunction &MF = PFS.MF;
975 MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
976 return false;
977}
978