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