LLVM  mainline
PPCTargetMachine.cpp
Go to the documentation of this file.
00001 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Top-level implementation for the PowerPC target.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "PPCTargetMachine.h"
00015 #include "PPC.h"
00016 #include "PPCTargetObjectFile.h"
00017 #include "PPCTargetTransformInfo.h"
00018 #include "llvm/CodeGen/Passes.h"
00019 #include "llvm/IR/Function.h"
00020 #include "llvm/IR/LegacyPassManager.h"
00021 #include "llvm/MC/MCStreamer.h"
00022 #include "llvm/Support/CommandLine.h"
00023 #include "llvm/Support/FormattedStream.h"
00024 #include "llvm/Support/TargetRegistry.h"
00025 #include "llvm/Target/TargetOptions.h"
00026 #include "llvm/Transforms/Scalar.h"
00027 using namespace llvm;
00028 
00029 static cl::
00030 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
00031                         cl::desc("Disable CTR loops for PPC"));
00032 
00033 static cl::
00034 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
00035                             cl::desc("Disable PPC loop preinc prep"));
00036 
00037 static cl::opt<bool>
00038 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
00039   cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
00040 
00041 static cl::
00042 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
00043                                 cl::desc("Disable VSX Swap Removal for PPC"));
00044 
00045 static cl::
00046 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
00047                             cl::desc("Disable machine peepholes for PPC"));
00048 
00049 static cl::opt<bool>
00050 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
00051              cl::desc("Enable optimizations on complex GEPs"),
00052              cl::init(true));
00053 
00054 static cl::opt<bool>
00055 EnablePrefetch("enable-ppc-prefetching",
00056                   cl::desc("disable software prefetching on PPC"),
00057                   cl::init(false), cl::Hidden);
00058 
00059 static cl::opt<bool>
00060 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
00061                       cl::desc("Add extra TOC register dependencies"),
00062                       cl::init(true), cl::Hidden);
00063 
00064 static cl::opt<bool>
00065 EnableMachineCombinerPass("ppc-machine-combiner",
00066                           cl::desc("Enable the machine combiner pass"),
00067                           cl::init(true), cl::Hidden);
00068 
00069 extern "C" void LLVMInitializePowerPCTarget() {
00070   // Register the targets
00071   RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
00072   RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
00073   RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
00074 
00075   PassRegistry &PR = *PassRegistry::getPassRegistry();
00076   initializePPCBoolRetToIntPass(PR);
00077 }
00078 
00079 /// Return the datalayout string of a subtarget.
00080 static std::string getDataLayoutString(const Triple &T) {
00081   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
00082   std::string Ret;
00083 
00084   // Most PPC* platforms are big endian, PPC64LE is little endian.
00085   if (T.getArch() == Triple::ppc64le)
00086     Ret = "e";
00087   else
00088     Ret = "E";
00089 
00090   Ret += DataLayout::getManglingComponent(T);
00091 
00092   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
00093   // pointers.
00094   if (!is64Bit || T.getOS() == Triple::Lv2)
00095     Ret += "-p:32:32";
00096 
00097   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
00098   // documentation are wrong; these are correct (i.e. "what gcc does").
00099   if (is64Bit || !T.isOSDarwin())
00100     Ret += "-i64:64";
00101   else
00102     Ret += "-f64:32:64";
00103 
00104   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
00105   if (is64Bit)
00106     Ret += "-n32:64";
00107   else
00108     Ret += "-n32";
00109 
00110   return Ret;
00111 }
00112 
00113 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
00114                                       const Triple &TT) {
00115   std::string FullFS = FS;
00116 
00117   // Make sure 64-bit features are available when CPUname is generic
00118   if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
00119     if (!FullFS.empty())
00120       FullFS = "+64bit," + FullFS;
00121     else
00122       FullFS = "+64bit";
00123   }
00124 
00125   if (OL >= CodeGenOpt::Default) {
00126     if (!FullFS.empty())
00127       FullFS = "+crbits," + FullFS;
00128     else
00129       FullFS = "+crbits";
00130   }
00131 
00132   if (OL != CodeGenOpt::None) {
00133     if (!FullFS.empty())
00134       FullFS = "+invariant-function-descriptors," + FullFS;
00135     else
00136       FullFS = "+invariant-function-descriptors";
00137   }
00138 
00139   return FullFS;
00140 }
00141 
00142 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
00143   // If it isn't a Mach-O file then it's going to be a linux ELF
00144   // object file.
00145   if (TT.isOSDarwin())
00146     return make_unique<TargetLoweringObjectFileMachO>();
00147 
00148   return make_unique<PPC64LinuxTargetObjectFile>();
00149 }
00150 
00151 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
00152                                                  const TargetOptions &Options) {
00153   if (Options.MCOptions.getABIName().startswith("elfv1"))
00154     return PPCTargetMachine::PPC_ABI_ELFv1;
00155   else if (Options.MCOptions.getABIName().startswith("elfv2"))
00156     return PPCTargetMachine::PPC_ABI_ELFv2;
00157 
00158   assert(Options.MCOptions.getABIName().empty() &&
00159          "Unknown target-abi option!");
00160 
00161   if (!TT.isMacOSX()) {
00162     switch (TT.getArch()) {
00163     case Triple::ppc64le:
00164       return PPCTargetMachine::PPC_ABI_ELFv2;
00165     case Triple::ppc64:
00166       return PPCTargetMachine::PPC_ABI_ELFv1;
00167     default:
00168       // Fallthrough.
00169       ;
00170     }
00171   }
00172   return PPCTargetMachine::PPC_ABI_UNKNOWN;
00173 }
00174 
00175 // The FeatureString here is a little subtle. We are modifying the feature
00176 // string with what are (currently) non-function specific overrides as it goes
00177 // into the LLVMTargetMachine constructor and then using the stored value in the
00178 // Subtarget constructor below it.
00179 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
00180                                    StringRef CPU, StringRef FS,
00181                                    const TargetOptions &Options,
00182                                    Reloc::Model RM, CodeModel::Model CM,
00183                                    CodeGenOpt::Level OL)
00184     : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
00185                         computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
00186       TLOF(createTLOF(getTargetTriple())),
00187       TargetABI(computeTargetABI(TT, Options)),
00188       Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
00189 
00190   // For the estimates, convergence is quadratic, so we essentially double the
00191   // number of digits correct after every iteration. For both FRE and FRSQRTE,
00192   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
00193   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
00194   unsigned RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3,
00195            RefinementSteps64 = RefinementSteps + 1;
00196 
00197   this->Options.Reciprocals.setDefaults("sqrtf", true, RefinementSteps);
00198   this->Options.Reciprocals.setDefaults("vec-sqrtf", true, RefinementSteps);
00199   this->Options.Reciprocals.setDefaults("divf", true, RefinementSteps);
00200   this->Options.Reciprocals.setDefaults("vec-divf", true, RefinementSteps);
00201 
00202   this->Options.Reciprocals.setDefaults("sqrtd", true, RefinementSteps64);
00203   this->Options.Reciprocals.setDefaults("vec-sqrtd", true, RefinementSteps64);
00204   this->Options.Reciprocals.setDefaults("divd", true, RefinementSteps64);
00205   this->Options.Reciprocals.setDefaults("vec-divd", true, RefinementSteps64);
00206 
00207   initAsmInfo();
00208 }
00209 
00210 PPCTargetMachine::~PPCTargetMachine() {}
00211 
00212 void PPC32TargetMachine::anchor() { }
00213 
00214 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
00215                                        StringRef CPU, StringRef FS,
00216                                        const TargetOptions &Options,
00217                                        Reloc::Model RM, CodeModel::Model CM,
00218                                        CodeGenOpt::Level OL)
00219     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
00220 
00221 void PPC64TargetMachine::anchor() { }
00222 
00223 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
00224                                        StringRef CPU, StringRef FS,
00225                                        const TargetOptions &Options,
00226                                        Reloc::Model RM, CodeModel::Model CM,
00227                                        CodeGenOpt::Level OL)
00228     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
00229 
00230 const PPCSubtarget *
00231 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
00232   Attribute CPUAttr = F.getFnAttribute("target-cpu");
00233   Attribute FSAttr = F.getFnAttribute("target-features");
00234 
00235   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
00236                         ? CPUAttr.getValueAsString().str()
00237                         : TargetCPU;
00238   std::string FS = !FSAttr.hasAttribute(Attribute::None)
00239                        ? FSAttr.getValueAsString().str()
00240                        : TargetFS;
00241 
00242   // FIXME: This is related to the code below to reset the target options,
00243   // we need to know whether or not the soft float flag is set on the
00244   // function before we can generate a subtarget. We also need to use
00245   // it as a key for the subtarget since that can be the only difference
00246   // between two functions.
00247   bool SoftFloat =
00248     F.hasFnAttribute("use-soft-float") &&
00249     F.getFnAttribute("use-soft-float").getValueAsString() == "true";
00250   // If the soft float attribute is set on the function turn on the soft float
00251   // subtarget feature.
00252   if (SoftFloat)
00253     FS += FS.empty() ? "+soft-float" : ",+soft-float";
00254 
00255   auto &I = SubtargetMap[CPU + FS];
00256   if (!I) {
00257     // This needs to be done before we create a new subtarget since any
00258     // creation will depend on the TM and the code generation flags on the
00259     // function that reside in TargetOptions.
00260     resetTargetOptions(F);
00261     I = llvm::make_unique<PPCSubtarget>(
00262         TargetTriple, CPU,
00263         // FIXME: It would be good to have the subtarget additions here
00264         // not necessary. Anything that turns them on/off (overrides) ends
00265         // up being put at the end of the feature string, but the defaults
00266         // shouldn't require adding them. Fixing this means pulling Feature64Bit
00267         // out of most of the target cpus in the .td file and making it set only
00268         // as part of initialization via the TargetTriple.
00269         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
00270   }
00271   return I.get();
00272 }
00273 
00274 //===----------------------------------------------------------------------===//
00275 // Pass Pipeline Configuration
00276 //===----------------------------------------------------------------------===//
00277 
00278 namespace {
00279 /// PPC Code Generator Pass Configuration Options.
00280 class PPCPassConfig : public TargetPassConfig {
00281 public:
00282   PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
00283     : TargetPassConfig(TM, PM) {}
00284 
00285   PPCTargetMachine &getPPCTargetMachine() const {
00286     return getTM<PPCTargetMachine>();
00287   }
00288 
00289   void addIRPasses() override;
00290   bool addPreISel() override;
00291   bool addILPOpts() override;
00292   bool addInstSelector() override;
00293   void addMachineSSAOptimization() override;
00294   void addPreRegAlloc() override;
00295   void addPreSched2() override;
00296   void addPreEmitPass() override;
00297 };
00298 } // namespace
00299 
00300 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
00301   return new PPCPassConfig(this, PM);
00302 }
00303 
00304 void PPCPassConfig::addIRPasses() {
00305   if (TM->getOptLevel() != CodeGenOpt::None)
00306     addPass(createPPCBoolRetToIntPass());
00307   addPass(createAtomicExpandPass(&getPPCTargetMachine()));
00308 
00309   // For the BG/Q (or if explicitly requested), add explicit data prefetch
00310   // intrinsics.
00311   bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
00312                         getOptLevel() != CodeGenOpt::None;
00313   if (EnablePrefetch.getNumOccurrences() > 0)
00314     UsePrefetching = EnablePrefetch;
00315   if (UsePrefetching)
00316     addPass(createPPCLoopDataPrefetchPass());
00317 
00318   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
00319     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
00320     // and lower a GEP with multiple indices to either arithmetic operations or
00321     // multiple GEPs with single index.
00322     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
00323     // Call EarlyCSE pass to find and remove subexpressions in the lowered
00324     // result.
00325     addPass(createEarlyCSEPass());
00326     // Do loop invariant code motion in case part of the lowered result is
00327     // invariant.
00328     addPass(createLICMPass());
00329   }
00330 
00331   TargetPassConfig::addIRPasses();
00332 }
00333 
00334 bool PPCPassConfig::addPreISel() {
00335   if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
00336     addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
00337 
00338   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
00339     addPass(createPPCCTRLoops(getPPCTargetMachine()));
00340 
00341   return false;
00342 }
00343 
00344 bool PPCPassConfig::addILPOpts() {
00345   addPass(&EarlyIfConverterID);
00346 
00347   if (EnableMachineCombinerPass)
00348     addPass(&MachineCombinerID);
00349 
00350   return true;
00351 }
00352 
00353 bool PPCPassConfig::addInstSelector() {
00354   // Install an instruction selector.
00355   addPass(createPPCISelDag(getPPCTargetMachine()));
00356 
00357 #ifndef NDEBUG
00358   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
00359     addPass(createPPCCTRLoopsVerify());
00360 #endif
00361 
00362   addPass(createPPCVSXCopyPass());
00363   return false;
00364 }
00365 
00366 void PPCPassConfig::addMachineSSAOptimization() {
00367   TargetPassConfig::addMachineSSAOptimization();
00368   // For little endian, remove where possible the vector swap instructions
00369   // introduced at code generation to normalize vector element order.
00370   if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
00371       !DisableVSXSwapRemoval)
00372     addPass(createPPCVSXSwapRemovalPass());
00373   // Target-specific peephole cleanups performed after instruction
00374   // selection.
00375   if (!DisableMIPeephole) {
00376     addPass(createPPCMIPeepholePass());
00377     addPass(&DeadMachineInstructionElimID);
00378   }
00379 }
00380 
00381 void PPCPassConfig::addPreRegAlloc() {
00382   initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
00383   insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
00384              &PPCVSXFMAMutateID);
00385   if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
00386     addPass(createPPCTLSDynamicCallPass());
00387   if (EnableExtraTOCRegDeps)
00388     addPass(createPPCTOCRegDepsPass());
00389 }
00390 
00391 void PPCPassConfig::addPreSched2() {
00392   if (getOptLevel() != CodeGenOpt::None)
00393     addPass(&IfConverterID);
00394 }
00395 
00396 void PPCPassConfig::addPreEmitPass() {
00397   if (getOptLevel() != CodeGenOpt::None)
00398     addPass(createPPCEarlyReturnPass(), false);
00399   // Must run branch selection immediately preceding the asm printer.
00400   addPass(createPPCBranchSelectionPass(), false);
00401 }
00402 
00403 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
00404   return TargetIRAnalysis([this](const Function &F) {
00405     return TargetTransformInfo(PPCTTIImpl(this, F));
00406   });
00407 }