1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===// 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 // Top-level implementation for the PowerPC target. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "PPCTargetMachine.h" 15 #include "PPC.h" 16 #include "PPCTargetObjectFile.h" 17 #include "PPCTargetTransformInfo.h" 18 #include "llvm/CodeGen/LiveVariables.h" 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/CodeGen/TargetPassConfig.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/LegacyPassManager.h" 23 #include "llvm/MC/MCStreamer.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/FormattedStream.h" 26 #include "llvm/Support/TargetRegistry.h" 27 #include "llvm/Target/TargetOptions.h" 28 #include "llvm/Transforms/Scalar.h" 29 using namespace llvm; 30 31 static cl:: 32 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden, 33 cl::desc("Disable CTR loops for PPC")); 34 35 static cl:: 36 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden, 37 cl::desc("Disable PPC loop preinc prep")); 38 39 static cl::opt<bool> 40 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early", 41 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early")); 42 43 static cl:: 44 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden, 45 cl::desc("Disable VSX Swap Removal for PPC")); 46 47 static cl:: 48 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden, 49 cl::desc("Disable QPX load splat simplification")); 50 51 static cl:: 52 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden, 53 cl::desc("Disable machine peepholes for PPC")); 54 55 static cl::opt<bool> 56 EnableGEPOpt("ppc-gep-opt", cl::Hidden, 57 cl::desc("Enable optimizations on complex GEPs"), 58 cl::init(true)); 59 60 static cl::opt<bool> 61 EnablePrefetch("enable-ppc-prefetching", 62 cl::desc("disable software prefetching on PPC"), 63 cl::init(false), cl::Hidden); 64 65 static cl::opt<bool> 66 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps", 67 cl::desc("Add extra TOC register dependencies"), 68 cl::init(true), cl::Hidden); 69 70 static cl::opt<bool> 71 EnableMachineCombinerPass("ppc-machine-combiner", 72 cl::desc("Enable the machine combiner pass"), 73 cl::init(true), cl::Hidden); 74 75 extern "C" void LLVMInitializePowerPCTarget() { 76 // Register the targets 77 RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target); 78 RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target); 79 RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget); 80 81 PassRegistry &PR = *PassRegistry::getPassRegistry(); 82 initializePPCBoolRetToIntPass(PR); 83 } 84 85 /// Return the datalayout string of a subtarget. 86 static std::string getDataLayoutString(const Triple &T) { 87 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le; 88 std::string Ret; 89 90 // Most PPC* platforms are big endian, PPC64LE is little endian. 91 if (T.getArch() == Triple::ppc64le) 92 Ret = "e"; 93 else 94 Ret = "E"; 95 96 Ret += DataLayout::getManglingComponent(T); 97 98 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit 99 // pointers. 100 if (!is64Bit || T.getOS() == Triple::Lv2) 101 Ret += "-p:32:32"; 102 103 // Note, the alignment values for f64 and i64 on ppc64 in Darwin 104 // documentation are wrong; these are correct (i.e. "what gcc does"). 105 if (is64Bit || !T.isOSDarwin()) 106 Ret += "-i64:64"; 107 else 108 Ret += "-f64:32:64"; 109 110 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones. 111 if (is64Bit) 112 Ret += "-n32:64"; 113 else 114 Ret += "-n32"; 115 116 return Ret; 117 } 118 119 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL, 120 const Triple &TT) { 121 std::string FullFS = FS; 122 123 // Make sure 64-bit features are available when CPUname is generic 124 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) { 125 if (!FullFS.empty()) 126 FullFS = "+64bit," + FullFS; 127 else 128 FullFS = "+64bit"; 129 } 130 131 if (OL >= CodeGenOpt::Default) { 132 if (!FullFS.empty()) 133 FullFS = "+crbits," + FullFS; 134 else 135 FullFS = "+crbits"; 136 } 137 138 if (OL != CodeGenOpt::None) { 139 if (!FullFS.empty()) 140 FullFS = "+invariant-function-descriptors," + FullFS; 141 else 142 FullFS = "+invariant-function-descriptors"; 143 } 144 145 return FullFS; 146 } 147 148 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 149 // If it isn't a Mach-O file then it's going to be a linux ELF 150 // object file. 151 if (TT.isOSDarwin()) 152 return make_unique<TargetLoweringObjectFileMachO>(); 153 154 return make_unique<PPC64LinuxTargetObjectFile>(); 155 } 156 157 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT, 158 const TargetOptions &Options) { 159 if (Options.MCOptions.getABIName().startswith("elfv1")) 160 return PPCTargetMachine::PPC_ABI_ELFv1; 161 else if (Options.MCOptions.getABIName().startswith("elfv2")) 162 return PPCTargetMachine::PPC_ABI_ELFv2; 163 164 assert(Options.MCOptions.getABIName().empty() && 165 "Unknown target-abi option!"); 166 167 if (!TT.isMacOSX()) { 168 switch (TT.getArch()) { 169 case Triple::ppc64le: 170 return PPCTargetMachine::PPC_ABI_ELFv2; 171 case Triple::ppc64: 172 return PPCTargetMachine::PPC_ABI_ELFv1; 173 default: 174 // Fallthrough. 175 ; 176 } 177 } 178 return PPCTargetMachine::PPC_ABI_UNKNOWN; 179 } 180 181 // The FeatureString here is a little subtle. We are modifying the feature 182 // string with what are (currently) non-function specific overrides as it goes 183 // into the LLVMTargetMachine constructor and then using the stored value in the 184 // Subtarget constructor below it. 185 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT, 186 StringRef CPU, StringRef FS, 187 const TargetOptions &Options, 188 Reloc::Model RM, CodeModel::Model CM, 189 CodeGenOpt::Level OL) 190 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU, 191 computeFSAdditions(FS, OL, TT), Options, RM, CM, OL), 192 TLOF(createTLOF(getTargetTriple())), 193 TargetABI(computeTargetABI(TT, Options)), 194 Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) { 195 196 // For the estimates, convergence is quadratic, so we essentially double the 197 // number of digits correct after every iteration. For both FRE and FRSQRTE, 198 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(), 199 // this is 2^-14. IEEE float has 23 digits and double has 52 digits. 200 unsigned RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3, 201 RefinementSteps64 = RefinementSteps + 1; 202 203 this->Options.Reciprocals.setDefaults("sqrtf", true, RefinementSteps); 204 this->Options.Reciprocals.setDefaults("vec-sqrtf", true, RefinementSteps); 205 this->Options.Reciprocals.setDefaults("divf", true, RefinementSteps); 206 this->Options.Reciprocals.setDefaults("vec-divf", true, RefinementSteps); 207 208 this->Options.Reciprocals.setDefaults("sqrtd", true, RefinementSteps64); 209 this->Options.Reciprocals.setDefaults("vec-sqrtd", true, RefinementSteps64); 210 this->Options.Reciprocals.setDefaults("divd", true, RefinementSteps64); 211 this->Options.Reciprocals.setDefaults("vec-divd", true, RefinementSteps64); 212 213 initAsmInfo(); 214 } 215 216 PPCTargetMachine::~PPCTargetMachine() {} 217 218 void PPC32TargetMachine::anchor() { } 219 220 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT, 221 StringRef CPU, StringRef FS, 222 const TargetOptions &Options, 223 Reloc::Model RM, CodeModel::Model CM, 224 CodeGenOpt::Level OL) 225 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {} 226 227 void PPC64TargetMachine::anchor() { } 228 229 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT, 230 StringRef CPU, StringRef FS, 231 const TargetOptions &Options, 232 Reloc::Model RM, CodeModel::Model CM, 233 CodeGenOpt::Level OL) 234 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {} 235 236 const PPCSubtarget * 237 PPCTargetMachine::getSubtargetImpl(const Function &F) const { 238 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 239 Attribute FSAttr = F.getFnAttribute("target-features"); 240 241 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 242 ? CPUAttr.getValueAsString().str() 243 : TargetCPU; 244 std::string FS = !FSAttr.hasAttribute(Attribute::None) 245 ? FSAttr.getValueAsString().str() 246 : TargetFS; 247 248 // FIXME: This is related to the code below to reset the target options, 249 // we need to know whether or not the soft float flag is set on the 250 // function before we can generate a subtarget. We also need to use 251 // it as a key for the subtarget since that can be the only difference 252 // between two functions. 253 bool SoftFloat = 254 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 255 // If the soft float attribute is set on the function turn on the soft float 256 // subtarget feature. 257 if (SoftFloat) 258 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 259 260 auto &I = SubtargetMap[CPU + FS]; 261 if (!I) { 262 // This needs to be done before we create a new subtarget since any 263 // creation will depend on the TM and the code generation flags on the 264 // function that reside in TargetOptions. 265 resetTargetOptions(F); 266 I = llvm::make_unique<PPCSubtarget>( 267 TargetTriple, CPU, 268 // FIXME: It would be good to have the subtarget additions here 269 // not necessary. Anything that turns them on/off (overrides) ends 270 // up being put at the end of the feature string, but the defaults 271 // shouldn't require adding them. Fixing this means pulling Feature64Bit 272 // out of most of the target cpus in the .td file and making it set only 273 // as part of initialization via the TargetTriple. 274 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this); 275 } 276 return I.get(); 277 } 278 279 //===----------------------------------------------------------------------===// 280 // Pass Pipeline Configuration 281 //===----------------------------------------------------------------------===// 282 283 namespace { 284 /// PPC Code Generator Pass Configuration Options. 285 class PPCPassConfig : public TargetPassConfig { 286 public: 287 PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM) 288 : TargetPassConfig(TM, PM) {} 289 290 PPCTargetMachine &getPPCTargetMachine() const { 291 return getTM<PPCTargetMachine>(); 292 } 293 294 void addIRPasses() override; 295 bool addPreISel() override; 296 bool addILPOpts() override; 297 bool addInstSelector() override; 298 void addMachineSSAOptimization() override; 299 void addPreRegAlloc() override; 300 void addPreSched2() override; 301 void addPreEmitPass() override; 302 }; 303 } // namespace 304 305 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) { 306 return new PPCPassConfig(this, PM); 307 } 308 309 void PPCPassConfig::addIRPasses() { 310 if (TM->getOptLevel() != CodeGenOpt::None) 311 addPass(createPPCBoolRetToIntPass()); 312 addPass(createAtomicExpandPass(&getPPCTargetMachine())); 313 314 // For the BG/Q (or if explicitly requested), add explicit data prefetch 315 // intrinsics. 316 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ && 317 getOptLevel() != CodeGenOpt::None; 318 if (EnablePrefetch.getNumOccurrences() > 0) 319 UsePrefetching = EnablePrefetch; 320 if (UsePrefetching) 321 addPass(createLoopDataPrefetchPass()); 322 323 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) { 324 // Call SeparateConstOffsetFromGEP pass to extract constants within indices 325 // and lower a GEP with multiple indices to either arithmetic operations or 326 // multiple GEPs with single index. 327 addPass(createSeparateConstOffsetFromGEPPass(TM, true)); 328 // Call EarlyCSE pass to find and remove subexpressions in the lowered 329 // result. 330 addPass(createEarlyCSEPass()); 331 // Do loop invariant code motion in case part of the lowered result is 332 // invariant. 333 addPass(createLICMPass()); 334 } 335 336 TargetPassConfig::addIRPasses(); 337 } 338 339 bool PPCPassConfig::addPreISel() { 340 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None) 341 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine())); 342 343 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) 344 addPass(createPPCCTRLoops(getPPCTargetMachine())); 345 346 return false; 347 } 348 349 bool PPCPassConfig::addILPOpts() { 350 addPass(&EarlyIfConverterID); 351 352 if (EnableMachineCombinerPass) 353 addPass(&MachineCombinerID); 354 355 return true; 356 } 357 358 bool PPCPassConfig::addInstSelector() { 359 // Install an instruction selector. 360 addPass(createPPCISelDag(getPPCTargetMachine())); 361 362 #ifndef NDEBUG 363 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) 364 addPass(createPPCCTRLoopsVerify()); 365 #endif 366 367 addPass(createPPCVSXCopyPass()); 368 return false; 369 } 370 371 void PPCPassConfig::addMachineSSAOptimization() { 372 TargetPassConfig::addMachineSSAOptimization(); 373 // For little endian, remove where possible the vector swap instructions 374 // introduced at code generation to normalize vector element order. 375 if (TM->getTargetTriple().getArch() == Triple::ppc64le && 376 !DisableVSXSwapRemoval) 377 addPass(createPPCVSXSwapRemovalPass()); 378 // Target-specific peephole cleanups performed after instruction 379 // selection. 380 if (!DisableMIPeephole) { 381 addPass(createPPCMIPeepholePass()); 382 addPass(&DeadMachineInstructionElimID); 383 } 384 } 385 386 void PPCPassConfig::addPreRegAlloc() { 387 if (getOptLevel() != CodeGenOpt::None) { 388 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry()); 389 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID, 390 &PPCVSXFMAMutateID); 391 } 392 if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_) { 393 // FIXME: LiveVariables should not be necessary here! 394 // PPCTLSDYnamicCallPass uses LiveIntervals which previously dependet on 395 // LiveVariables. This (unnecessary) dependency has been removed now, 396 // however a stage-2 clang build fails without LiveVariables computed here. 397 addPass(&LiveVariablesID, false); 398 addPass(createPPCTLSDynamicCallPass()); 399 } 400 if (EnableExtraTOCRegDeps) 401 addPass(createPPCTOCRegDepsPass()); 402 } 403 404 void PPCPassConfig::addPreSched2() { 405 if (getOptLevel() != CodeGenOpt::None) { 406 addPass(&IfConverterID); 407 408 // This optimization must happen after anything that might do store-to-load 409 // forwarding. Here we're after RA (and, thus, when spills are inserted) 410 // but before post-RA scheduling. 411 if (!DisableQPXLoadSplat) 412 addPass(createPPCQPXLoadSplatPass()); 413 } 414 } 415 416 void PPCPassConfig::addPreEmitPass() { 417 if (getOptLevel() != CodeGenOpt::None) 418 addPass(createPPCEarlyReturnPass(), false); 419 // Must run branch selection immediately preceding the asm printer. 420 addPass(createPPCBranchSelectionPass(), false); 421 } 422 423 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() { 424 return TargetIRAnalysis([this](const Function &F) { 425 return TargetTransformInfo(PPCTTIImpl(this, F)); 426 }); 427 } 428