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