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 "AArch64AsmPrinter.h"
15#include "AArch64MachineFunctionInfo.h"
16#include "AArch64MachineScheduler.h"
17#include "AArch64MacroFusion.h"
18#include "AArch64Subtarget.h"
19#include "AArch64TargetObjectFile.h"
20#include "AArch64TargetTransformInfo.h"
21#include "MCTargetDesc/AArch64MCTargetDesc.h"
22#include "TargetInfo/AArch64TargetInfo.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/Analysis/TargetTransformInfo.h"
25#include "llvm/Analysis/ValueTracking.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/Support/Compiler.h"
50#include "llvm/Target/TargetLoweringObjectFile.h"
51#include "llvm/Target/TargetOptions.h"
52#include "llvm/TargetParser/Triple.h"
53#include "llvm/Transforms/CFGuard.h"
54#include "llvm/Transforms/Scalar.h"
55#include "llvm/Transforms/Utils/LowerIFunc.h"
56#include "llvm/Transforms/Vectorize/LoopIdiomVectorize.h"
57#include <memory>
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 " definitions 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 EnableSMEPeepholeOpt("enable-aarch64-sme-peephole-opt", cl::init(Val: true),
167 cl::Hidden,
168 cl::desc("Perform SME peephole optimization"));
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
222static cl::opt<bool> EnableSRLTSubregToRegMitigation(
223 "aarch64-srlt-mitigate-sr2r",
224 cl::desc("Enable SUBREG_TO_REG mitigation by adding 'implicit-def' for "
225 "super-regs when using Subreg Liveness Tracking"),
226 cl::init(Val: true), cl::Hidden);
227
228static cl::opt<bool> EnableSVEShuffleOpt(
229 "aarch64-enable-sve-shuffle-opts",
230 cl::desc("Enable pattern matching of shuffles that could make use of SVE "
231 "instructions like tbl or the bottom/top variants"),
232 cl::init(Val: true), cl::Hidden);
233
234extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
235LLVMInitializeAArch64Target() {
236 // Register the target.
237 RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
238 RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
239 RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
240 RegisterTargetMachine<AArch64leTargetMachine> W(getTheARM64_32Target());
241 RegisterTargetMachine<AArch64leTargetMachine> V(getTheAArch64_32Target());
242 auto &PR = *PassRegistry::getPassRegistry();
243 initializeGlobalISel(PR);
244 initializeAArch64A53Fix835769LegacyPass(PR);
245 initializeAArch64A57FPLoadBalancingLegacyPass(PR);
246 initializeAArch64CodeLayoutOptPass(PR);
247 initializeAArch64AdvSIMDScalarLegacyPass(PR);
248 initializeAArch64AsmPrinterPass(PR);
249 initializeAArch64BranchTargetsLegacyPass(PR);
250 initializeAArch64CollectLOHLegacyPass(PR);
251 initializeAArch64CompressJumpTablesLegacyPass(PR);
252 initializeAArch64ConditionalComparesLegacyPass(PR);
253 initializeAArch64ConditionOptimizerLegacyPass(PR);
254 initializeAArch64DeadRegisterDefinitionsLegacyPass(PR);
255 initializeAArch64ExpandPseudoLegacyPass(PR);
256 initializeAArch64LoadStoreOptLegacyPass(PR);
257 initializeAArch64MIPeepholeOptLegacyPass(PR);
258 initializeAArch64PTrueCoalescingLegacyPass(PR);
259 initializeAArch64SIMDInstrOptLegacyPass(PR);
260 initializeAArch64O0PreLegalizerCombinerLegacyPass(PR);
261 initializeAArch64PreLegalizerCombinerLegacyPass(PR);
262 initializeAArch64PointerAuthLegacyPass(PR);
263 initializeAArch64PostCoalescerLegacyPass(PR);
264 initializeAArch64PostLegalizerCombinerLegacyPass(PR);
265 initializeAArch64PostSelectOptimizeLegacyPass(PR);
266 initializeAArch64PostLegalizerLoweringLegacyPass(PR);
267 initializeAArch64PromoteConstantPass(PR);
268 initializeAArch64RedundantCopyEliminationLegacyPass(PR);
269 initializeAArch64RedundantCondBranchLegacyPass(PR);
270 initializeAArch64StorePairSuppressPass(PR);
271 initializeFalkorHWPFFixPass(PR);
272 initializeFalkorMarkStridedAccessesLegacyPass(PR);
273 initializeLDTLSCleanupPass(PR);
274 initializeMachineKCFILegacyPass(PR);
275 initializeMachineSMEABIPass(PR);
276 initializeAArch64SRLTDefineSuperRegsLegacyPass(PR);
277 initializeSMEPeepholeOptPass(PR);
278 initializeAArch64SpeculationHardeningPass(PR);
279 initializeAArch64SLSHardeningLegacyPass(PR);
280 initializeAArch64StackTaggingPass(PR);
281 initializeAArch64StackTaggingPreRALegacyPass(PR);
282 initializeAArch64LowerHomogeneousPrologEpilogLegacyPass(PR);
283 initializeAArch64DAGToDAGISelLegacyPass(PR);
284 initializeAArch64CondBrTuningPass(PR);
285 initializeAArch64Arm64ECCallLoweringPass(PR);
286 initializeSVEShuffleOptsPass(PR);
287}
288
289bool AArch64TargetMachine::isGlobalISelOptNone() const {
290 const bool GlobalISelFlag = getCGPassBuilderOption().EnableGlobalISelOption ==
291 cl::boolOrDefault::BOU_TRUE;
292
293 return getOptLevel() == CodeGenOptLevel::None ||
294 (static_cast<unsigned>(getOptLevel()) >
295 static_cast<unsigned>(EnableGlobalISelAtO) &&
296 !GlobalISelFlag);
297}
298
299void AArch64TargetMachine::reset() {
300 SubtargetMap.clear();
301 LastSubtarget = nullptr;
302}
303
304//===----------------------------------------------------------------------===//
305// AArch64 Lowering public interface.
306//===----------------------------------------------------------------------===//
307static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
308 if (TT.isOSBinFormatMachO())
309 return std::make_unique<AArch64_MachoTargetObjectFile>();
310 if (TT.isOSBinFormatCOFF())
311 return std::make_unique<AArch64_COFFTargetObjectFile>();
312
313 return std::make_unique<AArch64_ELFTargetObjectFile>();
314}
315
316static StringRef computeDefaultCPU(const Triple &TT, StringRef CPU) {
317 if (CPU.empty() && TT.isArm64e())
318 return "apple-a12";
319 return CPU;
320}
321
322static Reloc::Model getEffectiveRelocModel(const Triple &TT,
323 std::optional<Reloc::Model> RM) {
324 // AArch64 Darwin and Windows are always PIC.
325 if (TT.isOSDarwin() || TT.isOSWindows())
326 return Reloc::PIC_;
327 // On ELF platforms the default static relocation model has a smart enough
328 // linker to cope with referencing external symbols defined in a shared
329 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
330 if (!RM || *RM == Reloc::DynamicNoPIC)
331 return Reloc::Static;
332 return *RM;
333}
334
335static CodeModel::Model
336getEffectiveAArch64CodeModel(const Triple &TT,
337 std::optional<CodeModel::Model> CM, bool JIT) {
338 if (CM) {
339 if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
340 *CM != CodeModel::Large) {
341 report_fatal_error(
342 reason: "Only small, tiny and large code models are allowed on AArch64");
343 } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF()) {
344 report_fatal_error(reason: "tiny code model is only supported on ELF");
345 }
346 return *CM;
347 }
348 // The default MCJIT memory managers make no guarantees about where they can
349 // find an executable page; JITed code needs to be able to refer to globals
350 // no matter how far away they are.
351 // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
352 // since with large code model LLVM generating 4 MOV instructions, and
353 // Windows doesn't support relocating these long branch (4 MOVs).
354 if (JIT && !TT.isOSWindows())
355 return CodeModel::Large;
356 return CodeModel::Small;
357}
358
359/// Create an AArch64 architecture model.
360///
361AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
362 StringRef CPU, StringRef FS,
363 const TargetOptions &Options,
364 std::optional<Reloc::Model> RM,
365 std::optional<CodeModel::Model> CM,
366 CodeGenOptLevel OL, bool JIT,
367 bool LittleEndian)
368 : CodeGenTargetMachineImpl(T, TT.computeDataLayout(), TT,
369 computeDefaultCPU(TT, CPU), FS, Options,
370 getEffectiveRelocModel(TT, RM),
371 getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
372 TLOF(createTLOF(TT: getTargetTriple())), isLittle(LittleEndian) {
373 initAsmInfo();
374
375 if (TT.isOSBinFormatMachO()) {
376 this->Options.TrapUnreachable = true;
377 this->Options.NoTrapAfterNoreturn = true;
378 }
379
380 if (getMCAsmInfo().usesWindowsCFI()) {
381 // Unwinding can get confused if the last instruction in an
382 // exception-handling region (function, funclet, try block, etc.)
383 // is a call.
384 //
385 // FIXME: We could elide the trap if the next instruction would be in
386 // the same region anyway.
387 this->Options.TrapUnreachable = true;
388 }
389
390 if (this->Options.TLSSize == 0) // default
391 this->Options.TLSSize = 24;
392 if ((getCodeModel() == CodeModel::Small ||
393 getCodeModel() == CodeModel::Kernel) &&
394 this->Options.TLSSize > 32)
395 // for the small (and kernel) code model, the maximum TLS size is 4GiB
396 this->Options.TLSSize = 32;
397 else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
398 // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
399 this->Options.TLSSize = 24;
400
401 const bool TargetSupportsGISel =
402 TT.getArch() != Triple::aarch64_32 &&
403 TT.getEnvironment() != Triple::GNUILP32 &&
404 !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO());
405
406 const bool GlobalISelFlag = getCGPassBuilderOption().EnableGlobalISelOption ==
407 cl::boolOrDefault::BOU_TRUE;
408
409 // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
410 // MachO/CodeModel::Large, which GlobalISel does not support.
411 if (TargetSupportsGISel && EnableGlobalISelAtO != -1 &&
412 (static_cast<int>(getOptLevel()) <= EnableGlobalISelAtO ||
413 (!GlobalISelFlag && !Options.EnableGlobalISel))) {
414 setGlobalISel(true);
415 setGlobalISelAbort(GlobalISelAbortMode::Disable);
416 }
417
418 LLT::setUseExtended(true);
419
420 // AArch64 supports the MachineOutliner.
421 setMachineOutliner(true);
422
423 // AArch64 supports default outlining behaviour.
424 setSupportsDefaultOutlining(true);
425
426 // AArch64 supports the debug entry values.
427 setSupportsDebugEntryValues(true);
428
429 // AArch64 supports fixing up the DWARF unwind information.
430 if (!getMCAsmInfo().usesWindowsCFI())
431 setCFIFixup(true);
432}
433
434unsigned AArch64TargetMachine::getEnableGlobalISelAtO() const {
435 return EnableGlobalISelAtO;
436}
437
438AArch64TargetMachine::~AArch64TargetMachine() = default;
439
440const AArch64Subtarget *
441AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
442 // Constructing the subtarget key is not cheap, avoid rebuilding it for
443 // repeated queries with the same function attributes.
444 AttributeSet FnAttrs = F.getAttributes().getFnAttrs();
445 if (LastSubtarget && LastSubtargetAttrs == FnAttrs)
446 return LastSubtarget;
447
448 Attribute CPUAttr = F.getFnAttribute(Kind: "target-cpu");
449 Attribute TuneAttr = F.getFnAttribute(Kind: "tune-cpu");
450 Attribute FSAttr = F.getFnAttribute(Kind: "target-features");
451
452 StringRef CPU = CPUAttr.isValid() ? CPUAttr.getValueAsString() : TargetCPU;
453 StringRef TuneCPU = TuneAttr.isValid() ? TuneAttr.getValueAsString() : CPU;
454 StringRef FS = FSAttr.isValid() ? FSAttr.getValueAsString() : TargetFS;
455 bool HasMinSize = F.hasMinSize();
456
457 bool IsStreaming = ForceStreaming ||
458 F.hasFnAttribute(Kind: "aarch64_pstate_sm_enabled") ||
459 F.hasFnAttribute(Kind: "aarch64_pstate_sm_body");
460 bool IsStreamingCompatible = ForceStreamingCompatible ||
461 F.hasFnAttribute(Kind: "aarch64_pstate_sm_compatible");
462
463 unsigned MinSVEVectorSize = 0;
464 unsigned MaxSVEVectorSize = 0;
465 if (F.hasFnAttribute(Kind: Attribute::VScaleRange)) {
466 ConstantRange CR = getVScaleRange(F: &F, BitWidth: 64);
467 MinSVEVectorSize = CR.getUnsignedMin().getZExtValue() * 128;
468 MaxSVEVectorSize = CR.getUnsignedMax().getZExtValue() * 128;
469 } else {
470 MinSVEVectorSize = SVEVectorBitsMinOpt;
471 MaxSVEVectorSize = SVEVectorBitsMaxOpt;
472 }
473
474 assert(MinSVEVectorSize % 128 == 0 &&
475 "SVE requires vector length in multiples of 128!");
476 assert(MaxSVEVectorSize % 128 == 0 &&
477 "SVE requires vector length in multiples of 128!");
478 assert((MaxSVEVectorSize >= MinSVEVectorSize || MaxSVEVectorSize == 0) &&
479 "Minimum SVE vector size should not be larger than its maximum!");
480
481 // Sanitize user input in case of no asserts
482 if (MaxSVEVectorSize != 0) {
483 MinSVEVectorSize = std::min(a: MinSVEVectorSize, b: MaxSVEVectorSize);
484 MaxSVEVectorSize = std::max(a: MinSVEVectorSize, b: MaxSVEVectorSize);
485 }
486
487 SmallString<512> Key;
488 // This lookup is hot during repeated TTI queries, so build the key directly
489 // instead of formatting through raw_svector_ostream.
490 Key += "SVEMin";
491 Key += utostr(X: MinSVEVectorSize);
492 Key += "SVEMax";
493 Key += utostr(X: MaxSVEVectorSize);
494 Key += "IsStreaming=";
495 Key += utostr(X: IsStreaming);
496 Key += "IsStreamingCompatible=";
497 Key += utostr(X: IsStreamingCompatible);
498 Key += CPU;
499 Key += TuneCPU;
500 Key += FS;
501 Key += "HasMinSize=";
502 Key += utostr(X: HasMinSize);
503
504 auto &I = SubtargetMap[Key];
505 if (!I) {
506 I = std::make_unique<AArch64Subtarget>(
507 args: TargetTriple, args&: CPU, args&: TuneCPU, args&: FS, args: *this, args: isLittle, args&: MinSVEVectorSize,
508 args&: MaxSVEVectorSize, args&: IsStreaming, args&: IsStreamingCompatible, args&: HasMinSize,
509 args&: EnableSRLTSubregToRegMitigation);
510 }
511
512 if (IsStreaming && !I->hasSME())
513 reportFatalUsageError(reason: "streaming SVE functions require SME");
514
515 LastSubtargetAttrs = FnAttrs;
516 LastSubtarget = I.get();
517 return LastSubtarget;
518}
519
520// Encourage placing FORM_TRANSPOSED_REG immediately before the instruction that
521// uses/consumes it. This ensures its def has a short live range, which means
522// we're more likely to allocate registers its operands first (which works best
523// for the hints in AArch64RegisterInfo::getRegAllocationHints).
524static bool scheduleFormTransposedTupleAdjacentToUsers(
525 const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI,
526 const MachineInstr *FirstMI, const MachineInstr &SecondMI,
527 const SDep *Dep) {
528 if (isNonDataDep(Dep))
529 return false;
530 return !FirstMI ||
531 FirstMI->getOpcode() == AArch64::FORM_TRANSPOSED_REG_TUPLE_X2_PSEUDO ||
532 FirstMI->getOpcode() == AArch64::FORM_TRANSPOSED_REG_TUPLE_X4_PSEUDO;
533}
534
535ScheduleDAGInstrs *
536AArch64TargetMachine::createMachineScheduler(MachineSchedContext *C) const {
537 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
538 ScheduleDAGMILive *DAG = createSchedLive(C);
539 DAG->addMutation(Mutation: createLoadClusterDAGMutation(TII: DAG->TII, TRI: DAG->TRI));
540 DAG->addMutation(Mutation: createStoreClusterDAGMutation(TII: DAG->TII, TRI: DAG->TRI));
541 if (ST.hasFusion())
542 DAG->addMutation(Mutation: createAArch64MacroFusionDAGMutation());
543 if (ST.hasSME() && ST.isStreaming())
544 DAG->addMutation(Mutation: createMacroFusionDAGMutation(
545 Predicates: scheduleFormTransposedTupleAdjacentToUsers));
546 return DAG;
547}
548
549ScheduleDAGInstrs *
550AArch64TargetMachine::createPostMachineScheduler(MachineSchedContext *C) const {
551 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
552 ScheduleDAGMI *DAG = createSchedPostRA<AArch64PostRASchedStrategy>(C);
553 if (ST.hasFusion()) {
554 // Run the Macro Fusion after RA again since literals are expanded from
555 // pseudos then (v. addPreSched2()).
556 DAG->addMutation(Mutation: createAArch64MacroFusionDAGMutation());
557 return DAG;
558 }
559
560 return DAG;
561}
562
563size_t AArch64TargetMachine::clearLinkerOptimizationHints(
564 const SmallPtrSetImpl<MachineInstr *> &MIs) const {
565 if (MIs.empty())
566 return 0;
567 auto *MI = *MIs.begin();
568 auto *FuncInfo = MI->getMF()->getInfo<AArch64FunctionInfo>();
569 return FuncInfo->clearLinkerOptimizationHints(MIs);
570}
571
572void AArch64leTargetMachine::anchor() { }
573
574AArch64leTargetMachine::AArch64leTargetMachine(
575 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
576 const TargetOptions &Options, std::optional<Reloc::Model> RM,
577 std::optional<CodeModel::Model> CM, CodeGenOptLevel OL, bool JIT)
578 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
579
580void AArch64beTargetMachine::anchor() { }
581
582AArch64beTargetMachine::AArch64beTargetMachine(
583 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
584 const TargetOptions &Options, std::optional<Reloc::Model> RM,
585 std::optional<CodeModel::Model> CM, CodeGenOptLevel OL, bool JIT)
586 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
587
588namespace {
589
590/// AArch64 Code Generator Pass Configuration Options.
591class AArch64PassConfig : public TargetPassConfig {
592public:
593 AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
594 : TargetPassConfig(TM, PM) {
595 if (TM.getOptLevel() != CodeGenOptLevel::None)
596 substitutePass(StandardID: &PostRASchedulerID, TargetID: &PostMachineSchedulerID);
597 setEnableSinkAndFold(EnableSinkFold);
598 }
599
600 AArch64TargetMachine &getAArch64TargetMachine() const {
601 return getTM<AArch64TargetMachine>();
602 }
603
604 void addIRPasses() override;
605 bool addPreISel() override;
606 void addCodeGenPrepare() override;
607 bool addInstSelector() override;
608 bool addIRTranslator() override;
609 void addPreLegalizeMachineIR() override;
610 bool addLegalizeMachineIR() override;
611 void addPreRegBankSelect() override;
612 bool addRegBankSelect() override;
613 bool addGlobalInstructionSelect() override;
614 void addMachineSSAOptimization() override;
615 bool addILPOpts() override;
616 void addPreRegAlloc() override;
617 void addPostRewrite() override;
618 void addPostRegAlloc() override;
619 void addPreSched2() override;
620 void addPreEmitPass() override;
621 void addPostBBSections() override;
622 void addPreEmitPass2() override;
623 bool addRegAssignAndRewriteOptimized() override;
624
625 std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
626};
627
628} // end anonymous namespace
629
630void AArch64TargetMachine::registerPassBuilderCallbacks(PassBuilder &PB) {
631#define GET_PASS_REGISTRY "AArch64PassRegistry.def"
632#include "llvm/Passes/TargetPassRegistry.inc"
633
634 PB.registerLateLoopOptimizationsEPCallback(
635 C: [=](LoopPassManager &LPM, OptimizationLevel Level) {
636 if (Level != OptimizationLevel::O0)
637 LPM.addPass(Pass: LoopIdiomVectorizePass());
638 });
639 if (getTargetTriple().isOSWindows())
640 PB.registerPipelineEarlySimplificationEPCallback(
641 C: [](ModulePassManager &PM, OptimizationLevel, ThinOrFullLTOPhase) {
642 PM.addPass(Pass: LowerIFuncPass());
643 });
644}
645
646TargetTransformInfo
647AArch64TargetMachine::getTargetTransformInfo(const Function &F) const {
648 return TargetTransformInfo(std::make_unique<AArch64TTIImpl>(args: this, args: F));
649}
650
651TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
652 return new AArch64PassConfig(*this, PM);
653}
654
655std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
656 return getStandardCSEConfigForOpt(Level: TM->getOptLevel());
657}
658
659void AArch64PassConfig::addIRPasses() {
660 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
661 // ourselves.
662 addPass(P: createAtomicExpandLegacyPass());
663
664 // Cmpxchg instructions are often used with a subsequent comparison to
665 // determine whether it succeeded. We can exploit existing control-flow in
666 // ldrex/strex loops to simplify this, but it needs tidying up.
667 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAtomicTidy)
668 addPass(P: createCFGSimplificationPass(Options: SimplifyCFGOptions()
669 .forwardSwitchCondToPhi(B: true)
670 .convertSwitchRangeToICmp(B: true)
671 .convertSwitchToLookupTable(B: true)
672 .needCanonicalLoops(B: false)
673 .hoistCommonInsts(B: true)
674 .sinkCommonInsts(B: true)));
675
676 // Run LoopDataPrefetch
677 //
678 // Run this before LSR to remove the multiplies involved in computing the
679 // pointer values N iterations ahead.
680 if (TM->getOptLevel() != CodeGenOptLevel::None) {
681 if (EnableLoopDataPrefetch)
682 addPass(P: createLoopDataPrefetchPass());
683 if (EnableFalkorHWPFFix)
684 addPass(P: createFalkorMarkStridedAccessesPass());
685 }
686
687 if (EnableGEPOpt) {
688 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
689 // and lower a GEP with multiple indices to either arithmetic operations or
690 // multiple GEPs with single index.
691 addPass(P: createSeparateConstOffsetFromGEPPass(LowerGEP: true));
692 // Call EarlyCSE pass to find and remove subexpressions in the lowered
693 // result.
694 addPass(P: createEarlyCSEPass());
695 // Do loop invariant code motion in case part of the lowered result is
696 // invariant.
697 addPass(P: createLICMPass());
698 }
699
700 TargetPassConfig::addIRPasses();
701
702 if (getOptLevel() == CodeGenOptLevel::Aggressive && EnableSelectOpt)
703 addPass(P: createSelectOptimizePass());
704
705 addPass(P: createAArch64StackTaggingPass(
706 /*IsOptNone=*/TM->getOptLevel() == CodeGenOptLevel::None));
707
708 // Try to use tbl in place of other shuffling operations if doing so would
709 // reduce the total number of instructions. Shuffle masks for big endian may
710 // be different, so require a little endian target.
711 if (getOptLevel() >= CodeGenOptLevel::Default && EnableSVEShuffleOpt &&
712 TM->getTargetTriple().isLittleEndian())
713 addPass(P: createSVEShuffleOptsPass());
714
715 // Match complex arithmetic patterns
716 if (TM->getOptLevel() >= CodeGenOptLevel::Default)
717 addPass(P: createComplexDeinterleavingPass(TM));
718
719 // Match interleaved memory accesses to ldN/stN intrinsics.
720 if (TM->getOptLevel() != CodeGenOptLevel::None) {
721 addPass(P: createInterleavedLoadCombinePass());
722 addPass(P: createInterleavedAccessPass());
723 }
724
725 // Add Control Flow Guard checks.
726 if (TM->getTargetTriple().isOSWindows()) {
727 if (TM->getTargetTriple().isWindowsArm64EC())
728 addPass(P: createAArch64Arm64ECCallLoweringPass());
729 else
730 addPass(P: createCFGuardPass());
731 }
732
733 if (TM->Options.JMCInstrument)
734 addPass(P: createJMCInstrumenterPass());
735}
736
737// Pass Pipeline Configuration
738bool AArch64PassConfig::addPreISel() {
739 // Run promote constant before global merge, so that the promoted constants
740 // get a chance to be merged
741 if (TM->getOptLevel() != CodeGenOptLevel::None && EnablePromoteConstant)
742 addPass(P: createAArch64PromoteConstantPass());
743 // FIXME: On AArch64, this depends on the type.
744 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
745 // and the offset has to be a multiple of the related size in bytes.
746 if ((TM->getOptLevel() != CodeGenOptLevel::None &&
747 EnableGlobalMerge == cl::boolOrDefault::BOU_UNSET) ||
748 EnableGlobalMerge == cl::boolOrDefault::BOU_TRUE) {
749 bool OnlyOptimizeForSize =
750 (TM->getOptLevel() < CodeGenOptLevel::Aggressive) &&
751 (EnableGlobalMerge == cl::boolOrDefault::BOU_UNSET);
752
753 // Merging of extern globals is enabled by default on non-Mach-O as we
754 // expect it to be generally either beneficial or harmless. On Mach-O it
755 // is disabled as we emit the .subsections_via_symbols directive which
756 // means that merging extern globals is not safe.
757 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
758 addPass(P: createGlobalMergePass(TM, MaximalOffset: 4095, OnlyOptimizeForSize,
759 MergeExternalByDefault));
760 }
761
762 return false;
763}
764
765void AArch64PassConfig::addCodeGenPrepare() {
766 if (getOptLevel() != CodeGenOptLevel::None)
767 addPass(P: createTypePromotionLegacyPass());
768 TargetPassConfig::addCodeGenPrepare();
769}
770
771bool AArch64PassConfig::addInstSelector() {
772 addPass(P: createAArch64ISelDag(TM&: getAArch64TargetMachine(), OptLevel: getOptLevel()));
773 return false;
774}
775
776bool AArch64PassConfig::addIRTranslator() {
777 addPass(P: new IRTranslatorLegacy(getOptLevel()));
778 return false;
779}
780
781void AArch64PassConfig::addPreLegalizeMachineIR() {
782 if (getAArch64TargetMachine().isGlobalISelOptNone()) {
783 addPass(P: createAArch64O0PreLegalizerCombiner());
784 addPass(P: new LocalizerLegacy());
785 } else {
786 addPass(P: createAArch64PreLegalizerCombiner());
787 addPass(P: new LocalizerLegacy());
788 if (EnableGISelLoadStoreOptPreLegal)
789 addPass(P: new LoadStoreOptLegacy());
790 }
791}
792
793bool AArch64PassConfig::addLegalizeMachineIR() {
794 addPass(P: new LegalizerLegacy());
795 return false;
796}
797
798void AArch64PassConfig::addPreRegBankSelect() {
799 const bool IsGlobalISelOptNone =
800 getAArch64TargetMachine().isGlobalISelOptNone();
801 if (!IsGlobalISelOptNone) {
802 addPass(P: createAArch64PostLegalizerCombinerLegacy(IsOptNone: IsGlobalISelOptNone));
803 if (EnableGISelLoadStoreOptPostLegal)
804 addPass(P: new LoadStoreOptLegacy());
805 }
806 addPass(P: createAArch64PostLegalizerLowering());
807}
808
809bool AArch64PassConfig::addRegBankSelect() {
810 addPass(P: new RegBankSelectLegacy());
811 return false;
812}
813
814bool AArch64PassConfig::addGlobalInstructionSelect() {
815 addPass(P: new InstructionSelectLegacy(getOptLevel()));
816 if (!getAArch64TargetMachine().isGlobalISelOptNone())
817 addPass(P: createAArch64PostSelectOptimize());
818
819 return false;
820}
821
822void AArch64PassConfig::addMachineSSAOptimization() {
823 // For ELF, cleanup any local-dynamic TLS accesses
824 // (i.e. combine as many references to _TLS_MODULE_BASE_ as possible.
825 if (TM->getTargetTriple().isOSBinFormatELF() &&
826 getOptLevel() != CodeGenOptLevel::None)
827 addPass(P: createAArch64CleanupLocalDynamicTLSPass());
828
829 if (TM->getOptLevel() != CodeGenOptLevel::None)
830 addPass(P: createMachineSMEABIPass(TM->getOptLevel()));
831
832 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableSMEPeepholeOpt)
833 addPass(P: createSMEPeepholeOptPass());
834
835 // Run default MachineSSAOptimization first.
836 TargetPassConfig::addMachineSSAOptimization();
837
838 if (TM->getOptLevel() != CodeGenOptLevel::None) {
839 addPass(P: createAArch64MIPeepholeOptLegacyPass());
840 addPass(P: createAArch64PTrueCoalescingLegacyPass());
841 }
842}
843
844bool AArch64PassConfig::addILPOpts() {
845 if (EnableCondOpt)
846 addPass(P: createAArch64ConditionOptimizerLegacyPass());
847 if (EnableCCMP)
848 addPass(P: createAArch64ConditionalCompares());
849 if (EnableMCR)
850 addPass(PassID: &MachineCombinerID);
851 if (EnableCondBrTuning)
852 addPass(P: createAArch64CondBrTuning());
853 if (EnableEarlyIfConversion)
854 addPass(PassID: &EarlyIfConverterLegacyID);
855 if (EnableStPairSuppress)
856 addPass(P: createAArch64StorePairSuppressPass());
857 addPass(P: createAArch64SIMDInstrOptPass());
858 if (TM->getOptLevel() != CodeGenOptLevel::None)
859 addPass(P: createAArch64StackTaggingPreRALegacyPass());
860 return true;
861}
862
863void AArch64PassConfig::addPreRegAlloc() {
864 if (TM->getOptLevel() == CodeGenOptLevel::None)
865 addPass(P: createMachineSMEABIPass(CodeGenOptLevel::None));
866
867 // Change dead register definitions to refer to the zero register.
868 if (TM->getOptLevel() != CodeGenOptLevel::None &&
869 EnableDeadRegisterElimination)
870 addPass(P: createAArch64DeadRegisterDefinitions());
871
872 // Use AdvSIMD scalar instructions whenever profitable.
873 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableAdvSIMDScalar) {
874 addPass(P: createAArch64AdvSIMDScalar());
875 // The AdvSIMD pass may produce copies that can be rewritten to
876 // be register coalescer friendly.
877 addPass(PassID: &PeepholeOptimizerLegacyID);
878 }
879 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableMachinePipeliner)
880 addPass(PassID: &MachinePipelinerID);
881}
882
883void AArch64PassConfig::addPostRewrite() {
884 if (EnableSRLTSubregToRegMitigation)
885 addPass(P: createAArch64SRLTDefineSuperRegsLegacyPass());
886}
887
888void AArch64PassConfig::addPostRegAlloc() {
889 // Remove redundant copy instructions.
890 if (TM->getOptLevel() != CodeGenOptLevel::None &&
891 EnableRedundantCopyElimination)
892 addPass(P: createAArch64RedundantCopyEliminationPass());
893
894 if (TM->getOptLevel() != CodeGenOptLevel::None && usingDefaultRegAlloc())
895 // Improve performance for some FP/SIMD code for A57.
896 addPass(P: createAArch64A57FPLoadBalancingLegacyPass());
897}
898
899void AArch64PassConfig::addPreSched2() {
900 // Lower homogeneous frame instructions
901 if (EnableHomogeneousPrologEpilog)
902 addPass(P: createAArch64LowerHomogeneousPrologEpilogPass());
903 // Expand some pseudo instructions to allow proper scheduling.
904 addPass(P: createAArch64ExpandPseudoLegacyPass());
905 // Use load/store pair instructions when possible.
906 if (TM->getOptLevel() != CodeGenOptLevel::None) {
907 if (EnableLoadStoreOpt)
908 addPass(P: createAArch64LoadStoreOptLegacyPass());
909 }
910 // Emit KCFI checks for indirect calls.
911 addPass(P: createKCFIPass());
912
913 // The AArch64SpeculationHardeningPass destroys dominator tree and natural
914 // loop info, which is needed for the FalkorHWPFFixPass and also later on.
915 // Therefore, run the AArch64SpeculationHardeningPass before the
916 // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
917 // info.
918 addPass(P: createAArch64SpeculationHardeningPass());
919
920 if (TM->getOptLevel() != CodeGenOptLevel::None) {
921 if (EnableFalkorHWPFFix)
922 addPass(P: createFalkorHWPFFixPass());
923 }
924}
925
926void AArch64PassConfig::addPreEmitPass() {
927 // Machine Block Placement might have created new opportunities when run
928 // at O3, where the Tail Duplication Threshold is set to 4 instructions.
929 // Run the load/store optimizer once more.
930 if (TM->getOptLevel() >= CodeGenOptLevel::Aggressive && EnableLoadStoreOpt)
931 addPass(P: createAArch64LoadStoreOptLegacyPass());
932
933 if (TM->getOptLevel() >= CodeGenOptLevel::Aggressive &&
934 EnableAArch64CopyPropagation)
935 addPass(P: createMachineCopyPropagationPass(UseCopyInstr: true));
936 if (TM->getOptLevel() != CodeGenOptLevel::None)
937 addPass(P: createAArch64RedundantCondBranchPass());
938
939 addPass(P: createAArch64A53Fix835769LegacyPass());
940
941 if (TM->getTargetTriple().isOSWindows()) {
942 // Identify valid longjmp targets for Windows Control Flow Guard.
943 addPass(P: createCFGuardLongjmpPass());
944 // Identify valid eh continuation targets for Windows EHCont Guard.
945 addPass(P: createEHContGuardTargetsLegacy());
946 }
947
948 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableCollectLOH &&
949 TM->getTargetTriple().isOSBinFormatMachO())
950 addPass(P: createAArch64CollectLOHPass());
951
952 // Apply code layout optimizations. Run late so detection reflects the
953 // final MI stream.
954 if (getOptLevel() != CodeGenOptLevel::None)
955 addPass(P: createAArch64CodeLayoutOptPass());
956}
957
958void AArch64PassConfig::addPostBBSections() {
959 addPass(P: createAArch64SLSHardeningLegacyPass());
960 addPass(P: createAArch64PointerAuthPass());
961 if (EnableBranchTargets)
962 addPass(P: createAArch64BranchTargetsPass());
963 // Relax conditional branch instructions if they're otherwise out of
964 // range of their destination.
965 if (BranchRelaxation)
966 addPass(PassID: &BranchRelaxationPassID);
967
968 if (TM->getOptLevel() != CodeGenOptLevel::None && EnableCompressJumpTables)
969 addPass(P: createAArch64CompressJumpTablesPass());
970}
971
972void AArch64PassConfig::addPreEmitPass2() {
973 // Insert pseudo probe annotation for callsite profiling
974 addPass(P: createPseudoProbeInserter());
975
976 // SVE bundles move prefixes with destructive operations. BLR_RVMARKER pseudo
977 // instructions are lowered to bundles as well.
978 addPass(P: createUnpackMachineBundlesLegacy(Ftor: nullptr));
979}
980
981bool AArch64PassConfig::addRegAssignAndRewriteOptimized() {
982 addPass(P: createAArch64PostCoalescerPass());
983 return TargetPassConfig::addRegAssignAndRewriteOptimized();
984}
985
986MachineFunctionInfo *AArch64TargetMachine::createMachineFunctionInfo(
987 BumpPtrAllocator &Allocator, const Function &F,
988 const TargetSubtargetInfo *STI) const {
989 return AArch64FunctionInfo::create<AArch64FunctionInfo>(
990 Allocator, F, STI: static_cast<const AArch64Subtarget *>(STI));
991}
992
993yaml::MachineFunctionInfo *
994AArch64TargetMachine::createDefaultFuncInfoYAML() const {
995 return new yaml::AArch64FunctionInfo();
996}
997
998yaml::MachineFunctionInfo *
999AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
1000 const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
1001 return new yaml::AArch64FunctionInfo(*MFI);
1002}
1003
1004bool AArch64TargetMachine::parseMachineFunctionInfo(
1005 const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
1006 SMDiagnostic &Error, SMRange &SourceRange) const {
1007 const auto &YamlMFI = static_cast<const yaml::AArch64FunctionInfo &>(MFI);
1008 MachineFunction &MF = PFS.MF;
1009 MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
1010 return false;
1011}
1012