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::opt<bool>
00046 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
00047              cl::desc("Enable optimizations on complex GEPs"),
00048              cl::init(true));
00049 
00050 static cl::opt<bool>
00051 EnablePrefetch("enable-ppc-prefetching",
00052                   cl::desc("disable software prefetching on PPC"),
00053                   cl::init(false), cl::Hidden);
00054 
00055 static cl::opt<bool>
00056 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
00057                       cl::desc("Add extra TOC register dependencies"),
00058                       cl::init(true), cl::Hidden);
00059 
00060 extern "C" void LLVMInitializePowerPCTarget() {
00061   // Register the targets
00062   RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
00063   RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
00064   RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
00065 }
00066 
00067 /// Return the datalayout string of a subtarget.
00068 static std::string getDataLayoutString(const Triple &T) {
00069   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
00070   std::string Ret;
00071 
00072   // Most PPC* platforms are big endian, PPC64LE is little endian.
00073   if (T.getArch() == Triple::ppc64le)
00074     Ret = "e";
00075   else
00076     Ret = "E";
00077 
00078   Ret += DataLayout::getManglingComponent(T);
00079 
00080   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
00081   // pointers.
00082   if (!is64Bit || T.getOS() == Triple::Lv2)
00083     Ret += "-p:32:32";
00084 
00085   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
00086   // documentation are wrong; these are correct (i.e. "what gcc does").
00087   if (is64Bit || !T.isOSDarwin())
00088     Ret += "-i64:64";
00089   else
00090     Ret += "-f64:32:64";
00091 
00092   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
00093   if (is64Bit)
00094     Ret += "-n32:64";
00095   else
00096     Ret += "-n32";
00097 
00098   return Ret;
00099 }
00100 
00101 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
00102                                       const Triple &TT) {
00103   std::string FullFS = FS;
00104 
00105   // Make sure 64-bit features are available when CPUname is generic
00106   if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
00107     if (!FullFS.empty())
00108       FullFS = "+64bit," + FullFS;
00109     else
00110       FullFS = "+64bit";
00111   }
00112 
00113   if (OL >= CodeGenOpt::Default) {
00114     if (!FullFS.empty())
00115       FullFS = "+crbits," + FullFS;
00116     else
00117       FullFS = "+crbits";
00118   }
00119 
00120   if (OL != CodeGenOpt::None) {
00121      if (!FullFS.empty())
00122       FullFS = "+invariant-function-descriptors," + FullFS;
00123     else
00124       FullFS = "+invariant-function-descriptors";
00125   }
00126 
00127   return FullFS;
00128 }
00129 
00130 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
00131   // If it isn't a Mach-O file then it's going to be a linux ELF
00132   // object file.
00133   if (TT.isOSDarwin())
00134     return make_unique<TargetLoweringObjectFileMachO>();
00135 
00136   return make_unique<PPC64LinuxTargetObjectFile>();
00137 }
00138 
00139 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
00140                                                  const TargetOptions &Options) {
00141   if (Options.MCOptions.getABIName().startswith("elfv1"))
00142     return PPCTargetMachine::PPC_ABI_ELFv1;
00143   else if (Options.MCOptions.getABIName().startswith("elfv2"))
00144     return PPCTargetMachine::PPC_ABI_ELFv2;
00145 
00146   assert(Options.MCOptions.getABIName().empty() &&
00147    "Unknown target-abi option!");
00148 
00149   if (!TT.isMacOSX()) {
00150     switch (TT.getArch()) {
00151     case Triple::ppc64le:
00152       return PPCTargetMachine::PPC_ABI_ELFv2;
00153     case Triple::ppc64:
00154       return PPCTargetMachine::PPC_ABI_ELFv1;
00155     default:
00156       // Fallthrough.
00157       ;
00158     }
00159   }
00160   return PPCTargetMachine::PPC_ABI_UNKNOWN;
00161 }
00162 
00163 // The FeatureString here is a little subtle. We are modifying the feature string
00164 // with what are (currently) non-function specific overrides as it goes into the
00165 // LLVMTargetMachine constructor and then using the stored value in the
00166 // Subtarget constructor below it.
00167 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
00168                                    StringRef CPU, StringRef FS,
00169                                    const TargetOptions &Options,
00170                                    Reloc::Model RM, CodeModel::Model CM,
00171                                    CodeGenOpt::Level OL)
00172     : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
00173                         computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
00174       TLOF(createTLOF(getTargetTriple())),
00175       TargetABI(computeTargetABI(TT, Options)) {
00176   initAsmInfo();
00177 }
00178 
00179 PPCTargetMachine::~PPCTargetMachine() {}
00180 
00181 void PPC32TargetMachine::anchor() { }
00182 
00183 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
00184                                        StringRef CPU, StringRef FS,
00185                                        const TargetOptions &Options,
00186                                        Reloc::Model RM, CodeModel::Model CM,
00187                                        CodeGenOpt::Level OL)
00188     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
00189 
00190 void PPC64TargetMachine::anchor() { }
00191 
00192 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
00193                                        StringRef CPU, StringRef FS,
00194                                        const TargetOptions &Options,
00195                                        Reloc::Model RM, CodeModel::Model CM,
00196                                        CodeGenOpt::Level OL)
00197     : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
00198 
00199 const PPCSubtarget *
00200 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
00201   Attribute CPUAttr = F.getFnAttribute("target-cpu");
00202   Attribute FSAttr = F.getFnAttribute("target-features");
00203 
00204   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
00205                         ? CPUAttr.getValueAsString().str()
00206                         : TargetCPU;
00207   std::string FS = !FSAttr.hasAttribute(Attribute::None)
00208                        ? FSAttr.getValueAsString().str()
00209                        : TargetFS;
00210 
00211   auto &I = SubtargetMap[CPU + FS];
00212   if (!I) {
00213     // This needs to be done before we create a new subtarget since any
00214     // creation will depend on the TM and the code generation flags on the
00215     // function that reside in TargetOptions.
00216     resetTargetOptions(F);
00217     I = llvm::make_unique<PPCSubtarget>(
00218         TargetTriple, CPU,
00219         // FIXME: It would be good to have the subtarget additions here
00220         // not necessary. Anything that turns them on/off (overrides) ends
00221         // up being put at the end of the feature string, but the defaults
00222         // shouldn't require adding them. Fixing this means pulling Feature64Bit
00223         // out of most of the target cpus in the .td file and making it set only
00224         // as part of initialization via the TargetTriple.
00225         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
00226   }
00227   return I.get();
00228 }
00229 
00230 //===----------------------------------------------------------------------===//
00231 // Pass Pipeline Configuration
00232 //===----------------------------------------------------------------------===//
00233 
00234 namespace {
00235 /// PPC Code Generator Pass Configuration Options.
00236 class PPCPassConfig : public TargetPassConfig {
00237 public:
00238   PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
00239     : TargetPassConfig(TM, PM) {}
00240 
00241   PPCTargetMachine &getPPCTargetMachine() const {
00242     return getTM<PPCTargetMachine>();
00243   }
00244 
00245   void addIRPasses() override;
00246   bool addPreISel() override;
00247   bool addILPOpts() override;
00248   bool addInstSelector() override;
00249   void addMachineSSAOptimization() override;
00250   void addPreRegAlloc() override;
00251   void addPreSched2() override;
00252   void addPreEmitPass() override;
00253 };
00254 } // namespace
00255 
00256 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
00257   return new PPCPassConfig(this, PM);
00258 }
00259 
00260 void PPCPassConfig::addIRPasses() {
00261   addPass(createAtomicExpandPass(&getPPCTargetMachine()));
00262 
00263   // For the BG/Q (or if explicitly requested), add explicit data prefetch
00264   // intrinsics.
00265   bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
00266                         getOptLevel() != CodeGenOpt::None;
00267   if (EnablePrefetch.getNumOccurrences() > 0)
00268     UsePrefetching = EnablePrefetch;
00269   if (UsePrefetching)
00270     addPass(createPPCLoopDataPrefetchPass());
00271 
00272   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
00273     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
00274     // and lower a GEP with multiple indices to either arithmetic operations or
00275     // multiple GEPs with single index.
00276     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
00277     // Call EarlyCSE pass to find and remove subexpressions in the lowered
00278     // result.
00279     addPass(createEarlyCSEPass());
00280     // Do loop invariant code motion in case part of the lowered result is
00281     // invariant.
00282     addPass(createLICMPass());
00283   }
00284 
00285   TargetPassConfig::addIRPasses();
00286 }
00287 
00288 bool PPCPassConfig::addPreISel() {
00289   if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
00290     addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
00291 
00292   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
00293     addPass(createPPCCTRLoops(getPPCTargetMachine()));
00294 
00295   return false;
00296 }
00297 
00298 bool PPCPassConfig::addILPOpts() {
00299   addPass(&EarlyIfConverterID);
00300   return true;
00301 }
00302 
00303 bool PPCPassConfig::addInstSelector() {
00304   // Install an instruction selector.
00305   addPass(createPPCISelDag(getPPCTargetMachine()));
00306 
00307 #ifndef NDEBUG
00308   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
00309     addPass(createPPCCTRLoopsVerify());
00310 #endif
00311 
00312   addPass(createPPCVSXCopyPass());
00313   return false;
00314 }
00315 
00316 void PPCPassConfig::addMachineSSAOptimization() {
00317   TargetPassConfig::addMachineSSAOptimization();
00318   // For little endian, remove where possible the vector swap instructions
00319   // introduced at code generation to normalize vector element order.
00320   if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
00321       !DisableVSXSwapRemoval)
00322     addPass(createPPCVSXSwapRemovalPass());
00323 }
00324 
00325 void PPCPassConfig::addPreRegAlloc() {
00326   initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
00327   insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
00328              &PPCVSXFMAMutateID);
00329   if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
00330     addPass(createPPCTLSDynamicCallPass());
00331   if (EnableExtraTOCRegDeps)
00332     addPass(createPPCTOCRegDepsPass());
00333 }
00334 
00335 void PPCPassConfig::addPreSched2() {
00336   if (getOptLevel() != CodeGenOpt::None)
00337     addPass(&IfConverterID);
00338 }
00339 
00340 void PPCPassConfig::addPreEmitPass() {
00341   if (getOptLevel() != CodeGenOpt::None)
00342     addPass(createPPCEarlyReturnPass(), false);
00343   // Must run branch selection immediately preceding the asm printer.
00344   addPass(createPPCBranchSelectionPass(), false);
00345 }
00346 
00347 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
00348   return TargetIRAnalysis(
00349       [this](Function &F) { return TargetTransformInfo(PPCTTIImpl(this, F)); });
00350 }