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