1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===// 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 // Top-level implementation for the PowerPC target. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCTargetMachine.h" 14 #include "MCTargetDesc/PPCMCTargetDesc.h" 15 #include "PPC.h" 16 #include "PPCMachineScheduler.h" 17 #include "PPCMacroFusion.h" 18 #include "PPCSubtarget.h" 19 #include "PPCTargetObjectFile.h" 20 #include "PPCTargetTransformInfo.h" 21 #include "TargetInfo/PowerPCTargetInfo.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/Analysis/TargetTransformInfo.h" 27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 28 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" 29 #include "llvm/CodeGen/GlobalISel/Legalizer.h" 30 #include "llvm/CodeGen/GlobalISel/Localizer.h" 31 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h" 32 #include "llvm/CodeGen/MachineScheduler.h" 33 #include "llvm/CodeGen/Passes.h" 34 #include "llvm/CodeGen/TargetPassConfig.h" 35 #include "llvm/IR/Attributes.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/InitializePasses.h" 39 #include "llvm/Pass.h" 40 #include "llvm/Support/CodeGen.h" 41 #include "llvm/Support/CommandLine.h" 42 #include "llvm/Support/TargetRegistry.h" 43 #include "llvm/Target/TargetLoweringObjectFile.h" 44 #include "llvm/Target/TargetOptions.h" 45 #include "llvm/Transforms/Scalar.h" 46 #include <cassert> 47 #include <memory> 48 #include <string> 49 50 using namespace llvm; 51 52 53 static cl::opt<bool> 54 EnableBranchCoalescing("enable-ppc-branch-coalesce", cl::Hidden, 55 cl::desc("enable coalescing of duplicate branches for PPC")); 56 static cl:: 57 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden, 58 cl::desc("Disable CTR loops for PPC")); 59 60 static cl:: 61 opt<bool> DisableInstrFormPrep("disable-ppc-instr-form-prep", cl::Hidden, 62 cl::desc("Disable PPC loop instr form prep")); 63 64 static cl::opt<bool> 65 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early", 66 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early")); 67 68 static cl:: 69 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden, 70 cl::desc("Disable VSX Swap Removal for PPC")); 71 72 static cl:: 73 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden, 74 cl::desc("Disable machine peepholes for PPC")); 75 76 static cl::opt<bool> 77 EnableGEPOpt("ppc-gep-opt", cl::Hidden, 78 cl::desc("Enable optimizations on complex GEPs"), 79 cl::init(true)); 80 81 static cl::opt<bool> 82 EnablePrefetch("enable-ppc-prefetching", 83 cl::desc("enable software prefetching on PPC"), 84 cl::init(false), cl::Hidden); 85 86 static cl::opt<bool> 87 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps", 88 cl::desc("Add extra TOC register dependencies"), 89 cl::init(true), cl::Hidden); 90 91 static cl::opt<bool> 92 EnableMachineCombinerPass("ppc-machine-combiner", 93 cl::desc("Enable the machine combiner pass"), 94 cl::init(true), cl::Hidden); 95 96 static cl::opt<bool> 97 ReduceCRLogical("ppc-reduce-cr-logicals", 98 cl::desc("Expand eligible cr-logical binary ops to branches"), 99 cl::init(true), cl::Hidden); 100 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCTarget() { 101 // Register the targets 102 RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target()); 103 RegisterTargetMachine<PPCTargetMachine> B(getThePPC64Target()); 104 RegisterTargetMachine<PPCTargetMachine> C(getThePPC64LETarget()); 105 106 PassRegistry &PR = *PassRegistry::getPassRegistry(); 107 #ifndef NDEBUG 108 initializePPCCTRLoopsVerifyPass(PR); 109 #endif 110 initializePPCLoopInstrFormPrepPass(PR); 111 initializePPCTOCRegDepsPass(PR); 112 initializePPCEarlyReturnPass(PR); 113 initializePPCVSXCopyPass(PR); 114 initializePPCVSXFMAMutatePass(PR); 115 initializePPCVSXSwapRemovalPass(PR); 116 initializePPCReduceCRLogicalsPass(PR); 117 initializePPCBSelPass(PR); 118 initializePPCBranchCoalescingPass(PR); 119 initializePPCBoolRetToIntPass(PR); 120 initializePPCExpandISELPass(PR); 121 initializePPCPreEmitPeepholePass(PR); 122 initializePPCTLSDynamicCallPass(PR); 123 initializePPCMIPeepholePass(PR); 124 initializePPCLowerMASSVEntriesPass(PR); 125 initializeGlobalISel(PR); 126 } 127 128 /// Return the datalayout string of a subtarget. 129 static std::string getDataLayoutString(const Triple &T) { 130 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le; 131 std::string Ret; 132 133 // Most PPC* platforms are big endian, PPC64LE is little endian. 134 if (T.getArch() == Triple::ppc64le) 135 Ret = "e"; 136 else 137 Ret = "E"; 138 139 Ret += DataLayout::getManglingComponent(T); 140 141 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit 142 // pointers. 143 if (!is64Bit || T.getOS() == Triple::Lv2) 144 Ret += "-p:32:32"; 145 146 // Note, the alignment values for f64 and i64 on ppc64 in Darwin 147 // documentation are wrong; these are correct (i.e. "what gcc does"). 148 if (is64Bit || !T.isOSDarwin()) 149 Ret += "-i64:64"; 150 else 151 Ret += "-f64:32:64"; 152 153 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones. 154 if (is64Bit) 155 Ret += "-n32:64"; 156 else 157 Ret += "-n32"; 158 159 return Ret; 160 } 161 162 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL, 163 const Triple &TT) { 164 std::string FullFS = std::string(FS); 165 166 // Make sure 64-bit features are available when CPUname is generic 167 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) { 168 if (!FullFS.empty()) 169 FullFS = "+64bit," + FullFS; 170 else 171 FullFS = "+64bit"; 172 } 173 174 if (OL >= CodeGenOpt::Default) { 175 if (!FullFS.empty()) 176 FullFS = "+crbits," + FullFS; 177 else 178 FullFS = "+crbits"; 179 } 180 181 if (OL != CodeGenOpt::None) { 182 if (!FullFS.empty()) 183 FullFS = "+invariant-function-descriptors," + FullFS; 184 else 185 FullFS = "+invariant-function-descriptors"; 186 } 187 188 return FullFS; 189 } 190 191 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 192 if (TT.isOSDarwin()) 193 return std::make_unique<TargetLoweringObjectFileMachO>(); 194 195 if (TT.isOSAIX()) 196 return std::make_unique<TargetLoweringObjectFileXCOFF>(); 197 198 return std::make_unique<PPC64LinuxTargetObjectFile>(); 199 } 200 201 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT, 202 const TargetOptions &Options) { 203 if (TT.isOSDarwin()) 204 report_fatal_error("Darwin is no longer supported for PowerPC"); 205 206 if (Options.MCOptions.getABIName().startswith("elfv1")) 207 return PPCTargetMachine::PPC_ABI_ELFv1; 208 else if (Options.MCOptions.getABIName().startswith("elfv2")) 209 return PPCTargetMachine::PPC_ABI_ELFv2; 210 211 assert(Options.MCOptions.getABIName().empty() && 212 "Unknown target-abi option!"); 213 214 if (TT.isMacOSX()) 215 return PPCTargetMachine::PPC_ABI_UNKNOWN; 216 217 switch (TT.getArch()) { 218 case Triple::ppc64le: 219 return PPCTargetMachine::PPC_ABI_ELFv2; 220 case Triple::ppc64: 221 return PPCTargetMachine::PPC_ABI_ELFv1; 222 default: 223 return PPCTargetMachine::PPC_ABI_UNKNOWN; 224 } 225 } 226 227 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 228 Optional<Reloc::Model> RM) { 229 assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) && 230 "Invalid relocation model for AIX."); 231 232 if (RM.hasValue()) 233 return *RM; 234 235 // Darwin defaults to dynamic-no-pic. 236 if (TT.isOSDarwin()) 237 return Reloc::DynamicNoPIC; 238 239 // Big Endian PPC and AIX default to PIC. 240 if (TT.getArch() == Triple::ppc64 || TT.isOSAIX()) 241 return Reloc::PIC_; 242 243 // Rest are static by default. 244 return Reloc::Static; 245 } 246 247 static CodeModel::Model getEffectivePPCCodeModel(const Triple &TT, 248 Optional<CodeModel::Model> CM, 249 bool JIT) { 250 if (CM) { 251 if (*CM == CodeModel::Tiny) 252 report_fatal_error("Target does not support the tiny CodeModel", false); 253 if (*CM == CodeModel::Kernel) 254 report_fatal_error("Target does not support the kernel CodeModel", false); 255 return *CM; 256 } 257 258 if (JIT) 259 return CodeModel::Small; 260 if (TT.isOSAIX()) 261 return CodeModel::Small; 262 263 assert(TT.isOSBinFormatELF() && "All remaining PPC OSes are ELF based."); 264 265 if (TT.isArch32Bit()) 266 return CodeModel::Small; 267 268 assert(TT.isArch64Bit() && "Unsupported PPC architecture."); 269 return CodeModel::Medium; 270 } 271 272 273 static ScheduleDAGInstrs *createPPCMachineScheduler(MachineSchedContext *C) { 274 const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>(); 275 ScheduleDAGMILive *DAG = 276 new ScheduleDAGMILive(C, ST.usePPCPreRASchedStrategy() ? 277 std::make_unique<PPCPreRASchedStrategy>(C) : 278 std::make_unique<GenericScheduler>(C)); 279 // add DAG Mutations here. 280 DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI)); 281 if (ST.hasStoreFusion()) 282 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 283 if (ST.hasFusion()) 284 DAG->addMutation(createPowerPCMacroFusionDAGMutation()); 285 286 return DAG; 287 } 288 289 static ScheduleDAGInstrs *createPPCPostMachineScheduler( 290 MachineSchedContext *C) { 291 const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>(); 292 ScheduleDAGMI *DAG = 293 new ScheduleDAGMI(C, ST.usePPCPostRASchedStrategy() ? 294 std::make_unique<PPCPostRASchedStrategy>(C) : 295 std::make_unique<PostGenericScheduler>(C), true); 296 // add DAG Mutations here. 297 if (ST.hasStoreFusion()) 298 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI)); 299 if (ST.hasFusion()) 300 DAG->addMutation(createPowerPCMacroFusionDAGMutation()); 301 return DAG; 302 } 303 304 // The FeatureString here is a little subtle. We are modifying the feature 305 // string with what are (currently) non-function specific overrides as it goes 306 // into the LLVMTargetMachine constructor and then using the stored value in the 307 // Subtarget constructor below it. 308 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT, 309 StringRef CPU, StringRef FS, 310 const TargetOptions &Options, 311 Optional<Reloc::Model> RM, 312 Optional<CodeModel::Model> CM, 313 CodeGenOpt::Level OL, bool JIT) 314 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU, 315 computeFSAdditions(FS, OL, TT), Options, 316 getEffectiveRelocModel(TT, RM), 317 getEffectivePPCCodeModel(TT, CM, JIT), OL), 318 TLOF(createTLOF(getTargetTriple())), 319 TargetABI(computeTargetABI(TT, Options)) { 320 initAsmInfo(); 321 } 322 323 PPCTargetMachine::~PPCTargetMachine() = default; 324 325 const PPCSubtarget * 326 PPCTargetMachine::getSubtargetImpl(const Function &F) const { 327 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 328 Attribute FSAttr = F.getFnAttribute("target-features"); 329 330 std::string CPU = 331 CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU; 332 std::string FS = 333 FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS; 334 335 // FIXME: This is related to the code below to reset the target options, 336 // we need to know whether or not the soft float flag is set on the 337 // function before we can generate a subtarget. We also need to use 338 // it as a key for the subtarget since that can be the only difference 339 // between two functions. 340 bool SoftFloat = 341 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 342 // If the soft float attribute is set on the function turn on the soft float 343 // subtarget feature. 344 if (SoftFloat) 345 FS += FS.empty() ? "-hard-float" : ",-hard-float"; 346 347 auto &I = SubtargetMap[CPU + FS]; 348 if (!I) { 349 // This needs to be done before we create a new subtarget since any 350 // creation will depend on the TM and the code generation flags on the 351 // function that reside in TargetOptions. 352 resetTargetOptions(F); 353 I = std::make_unique<PPCSubtarget>( 354 TargetTriple, CPU, 355 // FIXME: It would be good to have the subtarget additions here 356 // not necessary. Anything that turns them on/off (overrides) ends 357 // up being put at the end of the feature string, but the defaults 358 // shouldn't require adding them. Fixing this means pulling Feature64Bit 359 // out of most of the target cpus in the .td file and making it set only 360 // as part of initialization via the TargetTriple. 361 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this); 362 } 363 return I.get(); 364 } 365 366 //===----------------------------------------------------------------------===// 367 // Pass Pipeline Configuration 368 //===----------------------------------------------------------------------===// 369 370 namespace { 371 372 /// PPC Code Generator Pass Configuration Options. 373 class PPCPassConfig : public TargetPassConfig { 374 public: 375 PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM) 376 : TargetPassConfig(TM, PM) { 377 // At any optimization level above -O0 we use the Machine Scheduler and not 378 // the default Post RA List Scheduler. 379 if (TM.getOptLevel() != CodeGenOpt::None) 380 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 381 } 382 383 PPCTargetMachine &getPPCTargetMachine() const { 384 return getTM<PPCTargetMachine>(); 385 } 386 387 void addIRPasses() override; 388 bool addPreISel() override; 389 bool addILPOpts() override; 390 bool addInstSelector() override; 391 void addMachineSSAOptimization() override; 392 void addPreRegAlloc() override; 393 void addPreSched2() override; 394 void addPreEmitPass() override; 395 // GlobalISEL 396 bool addIRTranslator() override; 397 bool addLegalizeMachineIR() override; 398 bool addRegBankSelect() override; 399 bool addGlobalInstructionSelect() override; 400 401 ScheduleDAGInstrs * 402 createMachineScheduler(MachineSchedContext *C) const override { 403 return createPPCMachineScheduler(C); 404 } 405 ScheduleDAGInstrs * 406 createPostMachineScheduler(MachineSchedContext *C) const override { 407 return createPPCPostMachineScheduler(C); 408 } 409 }; 410 411 } // end anonymous namespace 412 413 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) { 414 return new PPCPassConfig(*this, PM); 415 } 416 417 void PPCPassConfig::addIRPasses() { 418 if (TM->getOptLevel() != CodeGenOpt::None) 419 addPass(createPPCBoolRetToIntPass()); 420 addPass(createAtomicExpandPass()); 421 422 // Lower generic MASSV routines to PowerPC subtarget-specific entries. 423 addPass(createPPCLowerMASSVEntriesPass()); 424 425 // If explicitly requested, add explicit data prefetch intrinsics. 426 if (EnablePrefetch.getNumOccurrences() > 0) 427 addPass(createLoopDataPrefetchPass()); 428 429 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) { 430 // Call SeparateConstOffsetFromGEP pass to extract constants within indices 431 // and lower a GEP with multiple indices to either arithmetic operations or 432 // multiple GEPs with single index. 433 addPass(createSeparateConstOffsetFromGEPPass(true)); 434 // Call EarlyCSE pass to find and remove subexpressions in the lowered 435 // result. 436 addPass(createEarlyCSEPass()); 437 // Do loop invariant code motion in case part of the lowered result is 438 // invariant. 439 addPass(createLICMPass()); 440 } 441 442 TargetPassConfig::addIRPasses(); 443 } 444 445 bool PPCPassConfig::addPreISel() { 446 if (!DisableInstrFormPrep && getOptLevel() != CodeGenOpt::None) 447 addPass(createPPCLoopInstrFormPrepPass(getPPCTargetMachine())); 448 449 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) 450 addPass(createHardwareLoopsPass()); 451 452 return false; 453 } 454 455 bool PPCPassConfig::addILPOpts() { 456 addPass(&EarlyIfConverterID); 457 458 if (EnableMachineCombinerPass) 459 addPass(&MachineCombinerID); 460 461 return true; 462 } 463 464 bool PPCPassConfig::addInstSelector() { 465 // Install an instruction selector. 466 addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel())); 467 468 #ifndef NDEBUG 469 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) 470 addPass(createPPCCTRLoopsVerify()); 471 #endif 472 473 addPass(createPPCVSXCopyPass()); 474 return false; 475 } 476 477 void PPCPassConfig::addMachineSSAOptimization() { 478 // PPCBranchCoalescingPass need to be done before machine sinking 479 // since it merges empty blocks. 480 if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None) 481 addPass(createPPCBranchCoalescingPass()); 482 TargetPassConfig::addMachineSSAOptimization(); 483 // For little endian, remove where possible the vector swap instructions 484 // introduced at code generation to normalize vector element order. 485 if (TM->getTargetTriple().getArch() == Triple::ppc64le && 486 !DisableVSXSwapRemoval) 487 addPass(createPPCVSXSwapRemovalPass()); 488 // Reduce the number of cr-logical ops. 489 if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None) 490 addPass(createPPCReduceCRLogicalsPass()); 491 // Target-specific peephole cleanups performed after instruction 492 // selection. 493 if (!DisableMIPeephole) { 494 addPass(createPPCMIPeepholePass()); 495 addPass(&DeadMachineInstructionElimID); 496 } 497 } 498 499 void PPCPassConfig::addPreRegAlloc() { 500 if (getOptLevel() != CodeGenOpt::None) { 501 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry()); 502 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID, 503 &PPCVSXFMAMutateID); 504 } 505 506 // FIXME: We probably don't need to run these for -fPIE. 507 if (getPPCTargetMachine().isPositionIndependent()) { 508 // FIXME: LiveVariables should not be necessary here! 509 // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on 510 // LiveVariables. This (unnecessary) dependency has been removed now, 511 // however a stage-2 clang build fails without LiveVariables computed here. 512 addPass(&LiveVariablesID); 513 addPass(createPPCTLSDynamicCallPass()); 514 } 515 if (EnableExtraTOCRegDeps) 516 addPass(createPPCTOCRegDepsPass()); 517 518 if (getOptLevel() != CodeGenOpt::None) 519 addPass(&MachinePipelinerID); 520 } 521 522 void PPCPassConfig::addPreSched2() { 523 if (getOptLevel() != CodeGenOpt::None) 524 addPass(&IfConverterID); 525 } 526 527 void PPCPassConfig::addPreEmitPass() { 528 addPass(createPPCPreEmitPeepholePass()); 529 addPass(createPPCExpandISELPass()); 530 531 if (getOptLevel() != CodeGenOpt::None) 532 addPass(createPPCEarlyReturnPass()); 533 // Must run branch selection immediately preceding the asm printer. 534 addPass(createPPCBranchSelectionPass()); 535 } 536 537 TargetTransformInfo 538 PPCTargetMachine::getTargetTransformInfo(const Function &F) { 539 return TargetTransformInfo(PPCTTIImpl(this, F)); 540 } 541 542 static MachineSchedRegistry 543 PPCPreRASchedRegistry("ppc-prera", 544 "Run PowerPC PreRA specific scheduler", 545 createPPCMachineScheduler); 546 547 static MachineSchedRegistry 548 PPCPostRASchedRegistry("ppc-postra", 549 "Run PowerPC PostRA specific scheduler", 550 createPPCPostMachineScheduler); 551 552 // Global ISEL 553 bool PPCPassConfig::addIRTranslator() { 554 addPass(new IRTranslator()); 555 return false; 556 } 557 558 bool PPCPassConfig::addLegalizeMachineIR() { 559 addPass(new Legalizer()); 560 return false; 561 } 562 563 bool PPCPassConfig::addRegBankSelect() { 564 addPass(new RegBankSelect()); 565 return false; 566 } 567 568 bool PPCPassConfig::addGlobalInstructionSelect() { 569 addPass(new InstructionSelect()); 570 return false; 571 } 572