1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ARM.h" 14 #include "ARMSubtarget.h" 15 #include "ARMMacroFusion.h" 16 #include "ARMTargetMachine.h" 17 #include "ARMTargetObjectFile.h" 18 #include "ARMTargetTransformInfo.h" 19 #include "MCTargetDesc/ARMMCTargetDesc.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/ExecutionDepsFix.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/Scalar.h" 50 #include <cassert> 51 #include <memory> 52 #include <string> 53 54 using namespace llvm; 55 56 static cl::opt<bool> 57 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden, 58 cl::desc("Inhibit optimization of S->D register accesses on A15"), 59 cl::init(false)); 60 61 static cl::opt<bool> 62 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden, 63 cl::desc("Run SimplifyCFG after expanding atomic operations" 64 " to make use of cmpxchg flow-based information"), 65 cl::init(true)); 66 67 static cl::opt<bool> 68 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden, 69 cl::desc("Enable ARM load/store optimization pass"), 70 cl::init(true)); 71 72 // FIXME: Unify control over GlobalMerge. 73 static cl::opt<cl::boolOrDefault> 74 EnableGlobalMerge("arm-global-merge", cl::Hidden, 75 cl::desc("Enable the global merge pass")); 76 77 namespace llvm { 78 void initializeARMExecutionDepsFixPass(PassRegistry&); 79 } 80 81 extern "C" void LLVMInitializeARMTarget() { 82 // Register the target. 83 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget()); 84 RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget()); 85 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget()); 86 RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget()); 87 88 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 89 initializeGlobalISel(Registry); 90 initializeARMLoadStoreOptPass(Registry); 91 initializeARMPreAllocLoadStoreOptPass(Registry); 92 initializeARMConstantIslandsPass(Registry); 93 initializeARMExecutionDepsFixPass(Registry); 94 } 95 96 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 97 if (TT.isOSBinFormatMachO()) 98 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 99 if (TT.isOSWindows()) 100 return llvm::make_unique<TargetLoweringObjectFileCOFF>(); 101 return llvm::make_unique<ARMElfTargetObjectFile>(); 102 } 103 104 static ARMBaseTargetMachine::ARMABI 105 computeTargetABI(const Triple &TT, StringRef CPU, 106 const TargetOptions &Options) { 107 StringRef ABIName = Options.MCOptions.getABIName(); 108 109 if (ABIName.empty()) 110 ABIName = ARM::computeDefaultTargetABI(TT, CPU); 111 112 if (ABIName == "aapcs16") 113 return ARMBaseTargetMachine::ARM_ABI_AAPCS16; 114 else if (ABIName.startswith("aapcs")) 115 return ARMBaseTargetMachine::ARM_ABI_AAPCS; 116 else if (ABIName.startswith("apcs")) 117 return ARMBaseTargetMachine::ARM_ABI_APCS; 118 119 llvm_unreachable("Unhandled/unknown ABI Name!"); 120 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN; 121 } 122 123 static std::string computeDataLayout(const Triple &TT, StringRef CPU, 124 const TargetOptions &Options, 125 bool isLittle) { 126 auto ABI = computeTargetABI(TT, CPU, Options); 127 std::string Ret; 128 129 if (isLittle) 130 // Little endian. 131 Ret += "e"; 132 else 133 // Big endian. 134 Ret += "E"; 135 136 Ret += DataLayout::getManglingComponent(TT); 137 138 // Pointers are 32 bits and aligned to 32 bits. 139 Ret += "-p:32:32"; 140 141 // ABIs other than APCS have 64 bit integers with natural alignment. 142 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS) 143 Ret += "-i64:64"; 144 145 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32 146 // bits, others to 64 bits. We always try to align to 64 bits. 147 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 148 Ret += "-f64:32:64"; 149 150 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others 151 // to 64. We always ty to give them natural alignment. 152 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 153 Ret += "-v64:32:64-v128:32:128"; 154 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16) 155 Ret += "-v128:64:128"; 156 157 // Try to align aggregates to 32 bits (the default is 64 bits, which has no 158 // particular hardware support on 32-bit ARM). 159 Ret += "-a:0:32"; 160 161 // Integer registers are 32 bits. 162 Ret += "-n32"; 163 164 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit 165 // aligned everywhere else. 166 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16) 167 Ret += "-S128"; 168 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS) 169 Ret += "-S64"; 170 else 171 Ret += "-S32"; 172 173 return Ret; 174 } 175 176 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 177 Optional<Reloc::Model> RM) { 178 if (!RM.hasValue()) 179 // Default relocation model on Darwin is PIC. 180 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static; 181 182 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI) 183 assert(TT.isOSBinFormatELF() && 184 "ROPI/RWPI currently only supported for ELF"); 185 186 // DynamicNoPIC is only used on darwin. 187 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin()) 188 return Reloc::Static; 189 190 return *RM; 191 } 192 193 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) { 194 if (CM) 195 return *CM; 196 return CodeModel::Small; 197 } 198 199 /// Create an ARM architecture model. 200 /// 201 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT, 202 StringRef CPU, StringRef FS, 203 const TargetOptions &Options, 204 Optional<Reloc::Model> RM, 205 Optional<CodeModel::Model> CM, 206 CodeGenOpt::Level OL, bool isLittle) 207 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT, 208 CPU, FS, Options, getEffectiveRelocModel(TT, RM), 209 getEffectiveCodeModel(CM), OL), 210 TargetABI(computeTargetABI(TT, CPU, Options)), 211 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) { 212 213 // Default to triple-appropriate float ABI 214 if (Options.FloatABIType == FloatABI::Default) { 215 if (TargetTriple.getEnvironment() == Triple::GNUEABIHF || 216 TargetTriple.getEnvironment() == Triple::MuslEABIHF || 217 TargetTriple.getEnvironment() == Triple::EABIHF || 218 TargetTriple.isOSWindows() || 219 TargetABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16) 220 this->Options.FloatABIType = FloatABI::Hard; 221 else 222 this->Options.FloatABIType = FloatABI::Soft; 223 } 224 225 // Default to triple-appropriate EABI 226 if (Options.EABIVersion == EABI::Default || 227 Options.EABIVersion == EABI::Unknown) { 228 // musl is compatible with glibc with regard to EABI version 229 if ((TargetTriple.getEnvironment() == Triple::GNUEABI || 230 TargetTriple.getEnvironment() == Triple::GNUEABIHF || 231 TargetTriple.getEnvironment() == Triple::MuslEABI || 232 TargetTriple.getEnvironment() == Triple::MuslEABIHF) && 233 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin())) 234 this->Options.EABIVersion = EABI::GNU; 235 else 236 this->Options.EABIVersion = EABI::EABI5; 237 } 238 239 initAsmInfo(); 240 } 241 242 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default; 243 244 const ARMSubtarget * 245 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const { 246 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 247 Attribute FSAttr = F.getFnAttribute("target-features"); 248 249 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 250 ? CPUAttr.getValueAsString().str() 251 : TargetCPU; 252 std::string FS = !FSAttr.hasAttribute(Attribute::None) 253 ? FSAttr.getValueAsString().str() 254 : TargetFS; 255 256 // FIXME: This is related to the code below to reset the target options, 257 // we need to know whether or not the soft float flag is set on the 258 // function before we can generate a subtarget. We also need to use 259 // it as a key for the subtarget since that can be the only difference 260 // between two functions. 261 bool SoftFloat = 262 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 263 // If the soft float attribute is set on the function turn on the soft float 264 // subtarget feature. 265 if (SoftFloat) 266 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 267 268 auto &I = SubtargetMap[CPU + FS]; 269 if (!I) { 270 // This needs to be done before we create a new subtarget since any 271 // creation will depend on the TM and the code generation flags on the 272 // function that reside in TargetOptions. 273 resetTargetOptions(F); 274 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle); 275 276 if (!I->isThumb() && !I->hasARMOps()) 277 F.getContext().emitError("Function '" + F.getName() + "' uses ARM " 278 "instructions, but the target does not support ARM mode execution."); 279 } 280 281 return I.get(); 282 } 283 284 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() { 285 return TargetIRAnalysis([this](const Function &F) { 286 return TargetTransformInfo(ARMTTIImpl(this, F)); 287 }); 288 } 289 290 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT, 291 StringRef CPU, StringRef FS, 292 const TargetOptions &Options, 293 Optional<Reloc::Model> RM, 294 Optional<CodeModel::Model> CM, 295 CodeGenOpt::Level OL, bool JIT) 296 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 297 298 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT, 299 StringRef CPU, StringRef FS, 300 const TargetOptions &Options, 301 Optional<Reloc::Model> RM, 302 Optional<CodeModel::Model> CM, 303 CodeGenOpt::Level OL, bool JIT) 304 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 305 306 namespace { 307 308 /// ARM Code Generator Pass Configuration Options. 309 class ARMPassConfig : public TargetPassConfig { 310 public: 311 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM) 312 : TargetPassConfig(TM, PM) {} 313 314 ARMBaseTargetMachine &getARMTargetMachine() const { 315 return getTM<ARMBaseTargetMachine>(); 316 } 317 318 ScheduleDAGInstrs * 319 createMachineScheduler(MachineSchedContext *C) const override { 320 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 321 // add DAG Mutations here. 322 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 323 if (ST.hasFusion()) 324 DAG->addMutation(createARMMacroFusionDAGMutation()); 325 return DAG; 326 } 327 328 ScheduleDAGInstrs * 329 createPostMachineScheduler(MachineSchedContext *C) const override { 330 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 331 // add DAG Mutations here. 332 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 333 if (ST.hasFusion()) 334 DAG->addMutation(createARMMacroFusionDAGMutation()); 335 return DAG; 336 } 337 338 void addIRPasses() override; 339 bool addPreISel() override; 340 bool addInstSelector() override; 341 bool addIRTranslator() override; 342 bool addLegalizeMachineIR() override; 343 bool addRegBankSelect() override; 344 bool addGlobalInstructionSelect() override; 345 void addPreRegAlloc() override; 346 void addPreSched2() override; 347 void addPreEmitPass() override; 348 }; 349 350 class ARMExecutionDepsFix : public ExecutionDepsFix { 351 public: 352 static char ID; 353 ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {} 354 StringRef getPassName() const override { 355 return "ARM Execution Dependency Fix"; 356 } 357 }; 358 char ARMExecutionDepsFix::ID; 359 360 } // end anonymous namespace 361 362 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix", 363 "ARM Execution Dependency Fix", false, false) 364 365 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) { 366 return new ARMPassConfig(*this, PM); 367 } 368 369 void ARMPassConfig::addIRPasses() { 370 if (TM->Options.ThreadModel == ThreadModel::Single) 371 addPass(createLowerAtomicPass()); 372 else 373 addPass(createAtomicExpandPass()); 374 375 // Cmpxchg instructions are often used with a subsequent comparison to 376 // determine whether it succeeded. We can exploit existing control-flow in 377 // ldrex/strex loops to simplify this, but it needs tidying up. 378 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) 379 addPass(createCFGSimplificationPass(-1, [this](const Function &F) { 380 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F); 381 return ST.hasAnyDataBarrier() && !ST.isThumb1Only(); 382 })); 383 384 TargetPassConfig::addIRPasses(); 385 386 // Match interleaved memory accesses to ldN/stN intrinsics. 387 if (TM->getOptLevel() != CodeGenOpt::None) 388 addPass(createInterleavedAccessPass()); 389 } 390 391 bool ARMPassConfig::addPreISel() { 392 if ((TM->getOptLevel() != CodeGenOpt::None && 393 EnableGlobalMerge == cl::BOU_UNSET) || 394 EnableGlobalMerge == cl::BOU_TRUE) { 395 // FIXME: This is using the thumb1 only constant value for 396 // maximal global offset for merging globals. We may want 397 // to look into using the old value for non-thumb1 code of 398 // 4095 based on the TargetMachine, but this starts to become 399 // tricky when doing code gen per function. 400 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 401 (EnableGlobalMerge == cl::BOU_UNSET); 402 // Merging of extern globals is enabled by default on non-Mach-O as we 403 // expect it to be generally either beneficial or harmless. On Mach-O it 404 // is disabled as we emit the .subsections_via_symbols directive which 405 // means that merging extern globals is not safe. 406 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO(); 407 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize, 408 MergeExternalByDefault)); 409 } 410 411 return false; 412 } 413 414 bool ARMPassConfig::addInstSelector() { 415 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel())); 416 return false; 417 } 418 419 bool ARMPassConfig::addIRTranslator() { 420 addPass(new IRTranslator()); 421 return false; 422 } 423 424 bool ARMPassConfig::addLegalizeMachineIR() { 425 addPass(new Legalizer()); 426 return false; 427 } 428 429 bool ARMPassConfig::addRegBankSelect() { 430 addPass(new RegBankSelect()); 431 return false; 432 } 433 434 bool ARMPassConfig::addGlobalInstructionSelect() { 435 addPass(new InstructionSelect()); 436 return false; 437 } 438 439 void ARMPassConfig::addPreRegAlloc() { 440 if (getOptLevel() != CodeGenOpt::None) { 441 addPass(createMLxExpansionPass()); 442 443 if (EnableARMLoadStoreOpt) 444 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true)); 445 446 if (!DisableA15SDOptimization) 447 addPass(createA15SDOptimizerPass()); 448 } 449 } 450 451 void ARMPassConfig::addPreSched2() { 452 if (getOptLevel() != CodeGenOpt::None) { 453 if (EnableARMLoadStoreOpt) 454 addPass(createARMLoadStoreOptimizationPass()); 455 456 addPass(new ARMExecutionDepsFix()); 457 } 458 459 // Expand some pseudo instructions into multiple instructions to allow 460 // proper scheduling. 461 addPass(createARMExpandPseudoPass()); 462 463 if (getOptLevel() != CodeGenOpt::None) { 464 // in v8, IfConversion depends on Thumb instruction widths 465 addPass(createThumb2SizeReductionPass([this](const Function &F) { 466 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT(); 467 })); 468 469 addPass(createIfConverter([](const MachineFunction &MF) { 470 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only(); 471 })); 472 } 473 addPass(createThumb2ITBlockPass()); 474 } 475 476 void ARMPassConfig::addPreEmitPass() { 477 addPass(createThumb2SizeReductionPass()); 478 479 // Constant island pass work on unbundled instructions. 480 addPass(createUnpackMachineBundles([](const MachineFunction &MF) { 481 return MF.getSubtarget<ARMSubtarget>().isThumb2(); 482 })); 483 484 // Don't optimize barriers at -O0. 485 if (getOptLevel() != CodeGenOpt::None) 486 addPass(createARMOptimizeBarriersPass()); 487 488 addPass(createARMConstantIslandPass()); 489 } 490