1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// 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 "ARMTargetMachine.h" 13 #include "ARM.h" 14 #include "ARMMacroFusion.h" 15 #include "ARMSubtarget.h" 16 #include "ARMTargetObjectFile.h" 17 #include "ARMTargetTransformInfo.h" 18 #include "MCTargetDesc/ARMMCTargetDesc.h" 19 #include "TargetInfo/ARMTargetInfo.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/CodeGen/ExecutionDomainFix.h" 26 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 28 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" 29 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h" 30 #include "llvm/CodeGen/GlobalISel/Legalizer.h" 31 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" 32 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h" 33 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 34 #include "llvm/CodeGen/MachineFunction.h" 35 #include "llvm/CodeGen/MachineScheduler.h" 36 #include "llvm/CodeGen/Passes.h" 37 #include "llvm/CodeGen/TargetPassConfig.h" 38 #include "llvm/IR/Attributes.h" 39 #include "llvm/IR/DataLayout.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/Pass.h" 42 #include "llvm/Support/CodeGen.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/TargetParser.h" 46 #include "llvm/Support/TargetRegistry.h" 47 #include "llvm/Target/TargetLoweringObjectFile.h" 48 #include "llvm/Target/TargetOptions.h" 49 #include "llvm/Transforms/CFGuard.h" 50 #include "llvm/Transforms/Scalar.h" 51 #include <cassert> 52 #include <memory> 53 #include <string> 54 55 using namespace llvm; 56 57 static cl::opt<bool> 58 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden, 59 cl::desc("Inhibit optimization of S->D register accesses on A15"), 60 cl::init(false)); 61 62 static cl::opt<bool> 63 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden, 64 cl::desc("Run SimplifyCFG after expanding atomic operations" 65 " to make use of cmpxchg flow-based information"), 66 cl::init(true)); 67 68 static cl::opt<bool> 69 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden, 70 cl::desc("Enable ARM load/store optimization pass"), 71 cl::init(true)); 72 73 // FIXME: Unify control over GlobalMerge. 74 static cl::opt<cl::boolOrDefault> 75 EnableGlobalMerge("arm-global-merge", cl::Hidden, 76 cl::desc("Enable the global merge pass")); 77 78 namespace llvm { 79 void initializeARMExecutionDomainFixPass(PassRegistry&); 80 } 81 82 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMTarget() { 83 // Register the target. 84 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget()); 85 RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget()); 86 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget()); 87 RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget()); 88 89 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 90 initializeGlobalISel(Registry); 91 initializeARMLoadStoreOptPass(Registry); 92 initializeARMPreAllocLoadStoreOptPass(Registry); 93 initializeARMParallelDSPPass(Registry); 94 initializeARMConstantIslandsPass(Registry); 95 initializeARMExecutionDomainFixPass(Registry); 96 initializeARMExpandPseudoPass(Registry); 97 initializeThumb2SizeReducePass(Registry); 98 initializeMVEVPTBlockPass(Registry); 99 initializeMVEVPTOptimisationsPass(Registry); 100 initializeMVETailPredicationPass(Registry); 101 initializeARMLowOverheadLoopsPass(Registry); 102 initializeMVEGatherScatterLoweringPass(Registry); 103 initializeARMSLSHardeningPass(Registry); 104 } 105 106 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 107 if (TT.isOSBinFormatMachO()) 108 return std::make_unique<TargetLoweringObjectFileMachO>(); 109 if (TT.isOSWindows()) 110 return std::make_unique<TargetLoweringObjectFileCOFF>(); 111 return std::make_unique<ARMElfTargetObjectFile>(); 112 } 113 114 static ARMBaseTargetMachine::ARMABI 115 computeTargetABI(const Triple &TT, StringRef CPU, 116 const TargetOptions &Options) { 117 StringRef ABIName = Options.MCOptions.getABIName(); 118 119 if (ABIName.empty()) 120 ABIName = ARM::computeDefaultTargetABI(TT, CPU); 121 122 if (ABIName == "aapcs16") 123 return ARMBaseTargetMachine::ARM_ABI_AAPCS16; 124 else if (ABIName.startswith("aapcs")) 125 return ARMBaseTargetMachine::ARM_ABI_AAPCS; 126 else if (ABIName.startswith("apcs")) 127 return ARMBaseTargetMachine::ARM_ABI_APCS; 128 129 llvm_unreachable("Unhandled/unknown ABI Name!"); 130 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN; 131 } 132 133 static std::string computeDataLayout(const Triple &TT, StringRef CPU, 134 const TargetOptions &Options, 135 bool isLittle) { 136 auto ABI = computeTargetABI(TT, CPU, Options); 137 std::string Ret; 138 139 if (isLittle) 140 // Little endian. 141 Ret += "e"; 142 else 143 // Big endian. 144 Ret += "E"; 145 146 Ret += DataLayout::getManglingComponent(TT); 147 148 // Pointers are 32 bits and aligned to 32 bits. 149 Ret += "-p:32:32"; 150 151 // Function pointers are aligned to 8 bits (because the LSB stores the 152 // ARM/Thumb state). 153 Ret += "-Fi8"; 154 155 // ABIs other than APCS have 64 bit integers with natural alignment. 156 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS) 157 Ret += "-i64:64"; 158 159 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32 160 // bits, others to 64 bits. We always try to align to 64 bits. 161 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 162 Ret += "-f64:32:64"; 163 164 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others 165 // to 64. We always ty to give them natural alignment. 166 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 167 Ret += "-v64:32:64-v128:32:128"; 168 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16) 169 Ret += "-v128:64:128"; 170 171 // Try to align aggregates to 32 bits (the default is 64 bits, which has no 172 // particular hardware support on 32-bit ARM). 173 Ret += "-a:0:32"; 174 175 // Integer registers are 32 bits. 176 Ret += "-n32"; 177 178 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit 179 // aligned everywhere else. 180 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16) 181 Ret += "-S128"; 182 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS) 183 Ret += "-S64"; 184 else 185 Ret += "-S32"; 186 187 return Ret; 188 } 189 190 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 191 Optional<Reloc::Model> RM) { 192 if (!RM.hasValue()) 193 // Default relocation model on Darwin is PIC. 194 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static; 195 196 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI) 197 assert(TT.isOSBinFormatELF() && 198 "ROPI/RWPI currently only supported for ELF"); 199 200 // DynamicNoPIC is only used on darwin. 201 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin()) 202 return Reloc::Static; 203 204 return *RM; 205 } 206 207 /// Create an ARM architecture model. 208 /// 209 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT, 210 StringRef CPU, StringRef FS, 211 const TargetOptions &Options, 212 Optional<Reloc::Model> RM, 213 Optional<CodeModel::Model> CM, 214 CodeGenOpt::Level OL, bool isLittle) 215 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT, 216 CPU, FS, Options, getEffectiveRelocModel(TT, RM), 217 getEffectiveCodeModel(CM, CodeModel::Small), OL), 218 TargetABI(computeTargetABI(TT, CPU, Options)), 219 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) { 220 221 // Default to triple-appropriate float ABI 222 if (Options.FloatABIType == FloatABI::Default) { 223 if (isTargetHardFloat()) 224 this->Options.FloatABIType = FloatABI::Hard; 225 else 226 this->Options.FloatABIType = FloatABI::Soft; 227 } 228 229 // Default to triple-appropriate EABI 230 if (Options.EABIVersion == EABI::Default || 231 Options.EABIVersion == EABI::Unknown) { 232 // musl is compatible with glibc with regard to EABI version 233 if ((TargetTriple.getEnvironment() == Triple::GNUEABI || 234 TargetTriple.getEnvironment() == Triple::GNUEABIHF || 235 TargetTriple.getEnvironment() == Triple::MuslEABI || 236 TargetTriple.getEnvironment() == Triple::MuslEABIHF) && 237 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin())) 238 this->Options.EABIVersion = EABI::GNU; 239 else 240 this->Options.EABIVersion = EABI::EABI5; 241 } 242 243 if (TT.isOSBinFormatMachO()) { 244 this->Options.TrapUnreachable = true; 245 this->Options.NoTrapAfterNoreturn = true; 246 } 247 248 // ARM supports the debug entry values. 249 setSupportsDebugEntryValues(true); 250 251 initAsmInfo(); 252 253 // ARM supports the MachineOutliner. 254 setMachineOutliner(true); 255 setSupportsDefaultOutlining(true); 256 } 257 258 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default; 259 260 const ARMSubtarget * 261 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const { 262 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 263 Attribute FSAttr = F.getFnAttribute("target-features"); 264 265 std::string CPU = 266 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU; 267 std::string FS = 268 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS; 269 270 // FIXME: This is related to the code below to reset the target options, 271 // we need to know whether or not the soft float flag is set on the 272 // function before we can generate a subtarget. We also need to use 273 // it as a key for the subtarget since that can be the only difference 274 // between two functions. 275 bool SoftFloat = 276 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 277 // If the soft float attribute is set on the function turn on the soft float 278 // subtarget feature. 279 if (SoftFloat) 280 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 281 282 // Use the optminsize to identify the subtarget, but don't use it in the 283 // feature string. 284 std::string Key = CPU + FS; 285 if (F.hasMinSize()) 286 Key += "+minsize"; 287 288 auto &I = SubtargetMap[Key]; 289 if (!I) { 290 // This needs to be done before we create a new subtarget since any 291 // creation will depend on the TM and the code generation flags on the 292 // function that reside in TargetOptions. 293 resetTargetOptions(F); 294 I = std::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle, 295 F.hasMinSize()); 296 297 if (!I->isThumb() && !I->hasARMOps()) 298 F.getContext().emitError("Function '" + F.getName() + "' uses ARM " 299 "instructions, but the target does not support ARM mode execution."); 300 } 301 302 return I.get(); 303 } 304 305 TargetTransformInfo 306 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) { 307 return TargetTransformInfo(ARMTTIImpl(this, F)); 308 } 309 310 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT, 311 StringRef CPU, StringRef FS, 312 const TargetOptions &Options, 313 Optional<Reloc::Model> RM, 314 Optional<CodeModel::Model> CM, 315 CodeGenOpt::Level OL, bool JIT) 316 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 317 318 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT, 319 StringRef CPU, StringRef FS, 320 const TargetOptions &Options, 321 Optional<Reloc::Model> RM, 322 Optional<CodeModel::Model> CM, 323 CodeGenOpt::Level OL, bool JIT) 324 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 325 326 namespace { 327 328 /// ARM Code Generator Pass Configuration Options. 329 class ARMPassConfig : public TargetPassConfig { 330 public: 331 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM) 332 : TargetPassConfig(TM, PM) {} 333 334 ARMBaseTargetMachine &getARMTargetMachine() const { 335 return getTM<ARMBaseTargetMachine>(); 336 } 337 338 ScheduleDAGInstrs * 339 createMachineScheduler(MachineSchedContext *C) const override { 340 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 341 // add DAG Mutations here. 342 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 343 if (ST.hasFusion()) 344 DAG->addMutation(createARMMacroFusionDAGMutation()); 345 return DAG; 346 } 347 348 ScheduleDAGInstrs * 349 createPostMachineScheduler(MachineSchedContext *C) const override { 350 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 351 // add DAG Mutations here. 352 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 353 if (ST.hasFusion()) 354 DAG->addMutation(createARMMacroFusionDAGMutation()); 355 return DAG; 356 } 357 358 void addIRPasses() override; 359 void addCodeGenPrepare() override; 360 bool addPreISel() override; 361 bool addInstSelector() override; 362 bool addIRTranslator() override; 363 bool addLegalizeMachineIR() override; 364 bool addRegBankSelect() override; 365 bool addGlobalInstructionSelect() override; 366 void addPreRegAlloc() override; 367 void addPreSched2() override; 368 void addPreEmitPass() override; 369 void addPreEmitPass2() override; 370 371 std::unique_ptr<CSEConfigBase> getCSEConfig() const override; 372 }; 373 374 class ARMExecutionDomainFix : public ExecutionDomainFix { 375 public: 376 static char ID; 377 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {} 378 StringRef getPassName() const override { 379 return "ARM Execution Domain Fix"; 380 } 381 }; 382 char ARMExecutionDomainFix::ID; 383 384 } // end anonymous namespace 385 386 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix", 387 "ARM Execution Domain Fix", false, false) 388 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 389 INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix", 390 "ARM Execution Domain Fix", false, false) 391 392 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) { 393 return new ARMPassConfig(*this, PM); 394 } 395 396 std::unique_ptr<CSEConfigBase> ARMPassConfig::getCSEConfig() const { 397 return getStandardCSEConfigForOpt(TM->getOptLevel()); 398 } 399 400 void ARMPassConfig::addIRPasses() { 401 if (TM->Options.ThreadModel == ThreadModel::Single) 402 addPass(createLowerAtomicPass()); 403 else 404 addPass(createAtomicExpandPass()); 405 406 // Cmpxchg instructions are often used with a subsequent comparison to 407 // determine whether it succeeded. We can exploit existing control-flow in 408 // ldrex/strex loops to simplify this, but it needs tidying up. 409 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) 410 addPass(createCFGSimplificationPass( 411 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true), 412 [this](const Function &F) { 413 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F); 414 return ST.hasAnyDataBarrier() && !ST.isThumb1Only(); 415 })); 416 417 addPass(createMVEGatherScatterLoweringPass()); 418 419 TargetPassConfig::addIRPasses(); 420 421 // Run the parallel DSP pass. 422 if (getOptLevel() == CodeGenOpt::Aggressive) 423 addPass(createARMParallelDSPPass()); 424 425 // Match interleaved memory accesses to ldN/stN intrinsics. 426 if (TM->getOptLevel() != CodeGenOpt::None) 427 addPass(createInterleavedAccessPass()); 428 429 // Add Control Flow Guard checks. 430 if (TM->getTargetTriple().isOSWindows()) 431 addPass(createCFGuardCheckPass()); 432 } 433 434 void ARMPassConfig::addCodeGenPrepare() { 435 if (getOptLevel() != CodeGenOpt::None) 436 addPass(createTypePromotionPass()); 437 TargetPassConfig::addCodeGenPrepare(); 438 } 439 440 bool ARMPassConfig::addPreISel() { 441 if ((TM->getOptLevel() != CodeGenOpt::None && 442 EnableGlobalMerge == cl::BOU_UNSET) || 443 EnableGlobalMerge == cl::BOU_TRUE) { 444 // FIXME: This is using the thumb1 only constant value for 445 // maximal global offset for merging globals. We may want 446 // to look into using the old value for non-thumb1 code of 447 // 4095 based on the TargetMachine, but this starts to become 448 // tricky when doing code gen per function. 449 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 450 (EnableGlobalMerge == cl::BOU_UNSET); 451 // Merging of extern globals is enabled by default on non-Mach-O as we 452 // expect it to be generally either beneficial or harmless. On Mach-O it 453 // is disabled as we emit the .subsections_via_symbols directive which 454 // means that merging extern globals is not safe. 455 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO(); 456 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize, 457 MergeExternalByDefault)); 458 } 459 460 if (TM->getOptLevel() != CodeGenOpt::None) { 461 addPass(createHardwareLoopsPass()); 462 addPass(createMVETailPredicationPass()); 463 } 464 465 return false; 466 } 467 468 bool ARMPassConfig::addInstSelector() { 469 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel())); 470 return false; 471 } 472 473 bool ARMPassConfig::addIRTranslator() { 474 addPass(new IRTranslator(getOptLevel())); 475 return false; 476 } 477 478 bool ARMPassConfig::addLegalizeMachineIR() { 479 addPass(new Legalizer()); 480 return false; 481 } 482 483 bool ARMPassConfig::addRegBankSelect() { 484 addPass(new RegBankSelect()); 485 return false; 486 } 487 488 bool ARMPassConfig::addGlobalInstructionSelect() { 489 addPass(new InstructionSelect()); 490 return false; 491 } 492 493 void ARMPassConfig::addPreRegAlloc() { 494 if (getOptLevel() != CodeGenOpt::None) { 495 addPass(createMVEVPTOptimisationsPass()); 496 497 addPass(createMLxExpansionPass()); 498 499 if (EnableARMLoadStoreOpt) 500 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true)); 501 502 if (!DisableA15SDOptimization) 503 addPass(createA15SDOptimizerPass()); 504 } 505 } 506 507 void ARMPassConfig::addPreSched2() { 508 if (getOptLevel() != CodeGenOpt::None) { 509 if (EnableARMLoadStoreOpt) 510 addPass(createARMLoadStoreOptimizationPass()); 511 512 addPass(new ARMExecutionDomainFix()); 513 addPass(createBreakFalseDeps()); 514 } 515 516 // Expand some pseudo instructions into multiple instructions to allow 517 // proper scheduling. 518 addPass(createARMExpandPseudoPass()); 519 520 if (getOptLevel() != CodeGenOpt::None) { 521 // When optimising for size, always run the Thumb2SizeReduction pass before 522 // IfConversion. Otherwise, check whether IT blocks are restricted 523 // (e.g. in v8, IfConversion depends on Thumb instruction widths) 524 addPass(createThumb2SizeReductionPass([this](const Function &F) { 525 return this->TM->getSubtarget<ARMSubtarget>(F).hasMinSize() || 526 this->TM->getSubtarget<ARMSubtarget>(F).restrictIT(); 527 })); 528 529 addPass(createIfConverter([](const MachineFunction &MF) { 530 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only(); 531 })); 532 } 533 addPass(createMVEVPTBlockPass()); 534 addPass(createThumb2ITBlockPass()); 535 536 // Add both scheduling passes to give the subtarget an opportunity to pick 537 // between them. 538 if (getOptLevel() != CodeGenOpt::None) { 539 addPass(&PostMachineSchedulerID); 540 addPass(&PostRASchedulerID); 541 } 542 543 addPass(createARMIndirectThunks()); 544 addPass(createARMSLSHardeningPass()); 545 } 546 547 void ARMPassConfig::addPreEmitPass() { 548 addPass(createThumb2SizeReductionPass()); 549 550 // Constant island pass work on unbundled instructions. 551 addPass(createUnpackMachineBundles([](const MachineFunction &MF) { 552 return MF.getSubtarget<ARMSubtarget>().isThumb2(); 553 })); 554 555 // Don't optimize barriers at -O0. 556 if (getOptLevel() != CodeGenOpt::None) 557 addPass(createARMOptimizeBarriersPass()); 558 } 559 560 void ARMPassConfig::addPreEmitPass2() { 561 addPass(createARMConstantIslandPass()); 562 addPass(createARMLowOverheadLoopsPass()); 563 564 // Identify valid longjmp targets for Windows Control Flow Guard. 565 if (TM->getTargetTriple().isOSWindows()) 566 addPass(createCFGuardLongjmpPass()); 567 } 568