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