1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Top-level implementation for the PowerPC target.
12 //===----------------------------------------------------------------------===//
14 #include "PPCTargetMachine.h"
16 #include "PPCTargetObjectFile.h"
17 #include "PPCTargetTransformInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Transforms/Scalar.h"
30 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
31 cl::desc("Disable CTR loops for PPC"));
34 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
35 cl::desc("Disable PPC loop preinc prep"));
38 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
39 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
42 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
43 cl::desc("Disable VSX Swap Removal for PPC"));
46 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
47 cl::desc("Disable machine peepholes for PPC"));
50 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
51 cl::desc("Enable optimizations on complex GEPs"),
55 EnablePrefetch("enable-ppc-prefetching",
56 cl::desc("disable software prefetching on PPC"),
57 cl::init(false), cl::Hidden);
60 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
61 cl::desc("Add extra TOC register dependencies"),
62 cl::init(true), cl::Hidden);
65 EnableMachineCombinerPass("ppc-machine-combiner",
66 cl::desc("Enable the machine combiner pass"),
67 cl::init(true), cl::Hidden);
69 extern "C" void LLVMInitializePowerPCTarget() {
70 // Register the targets
71 RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
72 RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
73 RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
76 /// Return the datalayout string of a subtarget.
77 static std::string getDataLayoutString(const Triple &T) {
78 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
81 // Most PPC* platforms are big endian, PPC64LE is little endian.
82 if (T.getArch() == Triple::ppc64le)
87 Ret += DataLayout::getManglingComponent(T);
89 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
91 if (!is64Bit || T.getOS() == Triple::Lv2)
94 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
95 // documentation are wrong; these are correct (i.e. "what gcc does").
96 if (is64Bit || !T.isOSDarwin())
101 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
110 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
112 std::string FullFS = FS;
114 // Make sure 64-bit features are available when CPUname is generic
115 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
117 FullFS = "+64bit," + FullFS;
122 if (OL >= CodeGenOpt::Default) {
124 FullFS = "+crbits," + FullFS;
129 if (OL != CodeGenOpt::None) {
131 FullFS = "+invariant-function-descriptors," + FullFS;
133 FullFS = "+invariant-function-descriptors";
139 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
140 // If it isn't a Mach-O file then it's going to be a linux ELF
143 return make_unique<TargetLoweringObjectFileMachO>();
145 return make_unique<PPC64LinuxTargetObjectFile>();
148 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
149 const TargetOptions &Options) {
150 if (Options.MCOptions.getABIName().startswith("elfv1"))
151 return PPCTargetMachine::PPC_ABI_ELFv1;
152 else if (Options.MCOptions.getABIName().startswith("elfv2"))
153 return PPCTargetMachine::PPC_ABI_ELFv2;
155 assert(Options.MCOptions.getABIName().empty() &&
156 "Unknown target-abi option!");
158 if (!TT.isMacOSX()) {
159 switch (TT.getArch()) {
160 case Triple::ppc64le:
161 return PPCTargetMachine::PPC_ABI_ELFv2;
163 return PPCTargetMachine::PPC_ABI_ELFv1;
169 return PPCTargetMachine::PPC_ABI_UNKNOWN;
172 // The FeatureString here is a little subtle. We are modifying the feature
173 // string with what are (currently) non-function specific overrides as it goes
174 // into the LLVMTargetMachine constructor and then using the stored value in the
175 // Subtarget constructor below it.
176 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
177 StringRef CPU, StringRef FS,
178 const TargetOptions &Options,
179 Reloc::Model RM, CodeModel::Model CM,
180 CodeGenOpt::Level OL)
181 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
182 computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
183 TLOF(createTLOF(getTargetTriple())),
184 TargetABI(computeTargetABI(TT, Options)),
185 Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
187 // For the estimates, convergence is quadratic, so we essentially double the
188 // number of digits correct after every iteration. For both FRE and FRSQRTE,
189 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
190 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
191 unsigned RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3,
192 RefinementSteps64 = RefinementSteps + 1;
194 this->Options.Reciprocals.setDefaults("sqrtf", true, RefinementSteps);
195 this->Options.Reciprocals.setDefaults("vec-sqrtf", true, RefinementSteps);
196 this->Options.Reciprocals.setDefaults("divf", true, RefinementSteps);
197 this->Options.Reciprocals.setDefaults("vec-divf", true, RefinementSteps);
199 this->Options.Reciprocals.setDefaults("sqrtd", true, RefinementSteps64);
200 this->Options.Reciprocals.setDefaults("vec-sqrtd", true, RefinementSteps64);
201 this->Options.Reciprocals.setDefaults("divd", true, RefinementSteps64);
202 this->Options.Reciprocals.setDefaults("vec-divd", true, RefinementSteps64);
207 PPCTargetMachine::~PPCTargetMachine() {}
209 void PPC32TargetMachine::anchor() { }
211 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
212 StringRef CPU, StringRef FS,
213 const TargetOptions &Options,
214 Reloc::Model RM, CodeModel::Model CM,
215 CodeGenOpt::Level OL)
216 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
218 void PPC64TargetMachine::anchor() { }
220 PPC64TargetMachine::PPC64TargetMachine(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) {}
228 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
229 Attribute CPUAttr = F.getFnAttribute("target-cpu");
230 Attribute FSAttr = F.getFnAttribute("target-features");
232 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
233 ? CPUAttr.getValueAsString().str()
235 std::string FS = !FSAttr.hasAttribute(Attribute::None)
236 ? FSAttr.getValueAsString().str()
239 auto &I = SubtargetMap[CPU + FS];
241 // This needs to be done before we create a new subtarget since any
242 // creation will depend on the TM and the code generation flags on the
243 // function that reside in TargetOptions.
244 resetTargetOptions(F);
245 I = llvm::make_unique<PPCSubtarget>(
247 // FIXME: It would be good to have the subtarget additions here
248 // not necessary. Anything that turns them on/off (overrides) ends
249 // up being put at the end of the feature string, but the defaults
250 // shouldn't require adding them. Fixing this means pulling Feature64Bit
251 // out of most of the target cpus in the .td file and making it set only
252 // as part of initialization via the TargetTriple.
253 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
258 //===----------------------------------------------------------------------===//
259 // Pass Pipeline Configuration
260 //===----------------------------------------------------------------------===//
263 /// PPC Code Generator Pass Configuration Options.
264 class PPCPassConfig : public TargetPassConfig {
266 PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
267 : TargetPassConfig(TM, PM) {}
269 PPCTargetMachine &getPPCTargetMachine() const {
270 return getTM<PPCTargetMachine>();
273 void addIRPasses() override;
274 bool addPreISel() override;
275 bool addILPOpts() override;
276 bool addInstSelector() override;
277 void addMachineSSAOptimization() override;
278 void addPreRegAlloc() override;
279 void addPreSched2() override;
280 void addPreEmitPass() override;
284 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
285 return new PPCPassConfig(this, PM);
288 void PPCPassConfig::addIRPasses() {
289 addPass(createAtomicExpandPass(&getPPCTargetMachine()));
291 // For the BG/Q (or if explicitly requested), add explicit data prefetch
293 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
294 getOptLevel() != CodeGenOpt::None;
295 if (EnablePrefetch.getNumOccurrences() > 0)
296 UsePrefetching = EnablePrefetch;
298 addPass(createPPCLoopDataPrefetchPass());
300 if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
301 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
302 // and lower a GEP with multiple indices to either arithmetic operations or
303 // multiple GEPs with single index.
304 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
305 // Call EarlyCSE pass to find and remove subexpressions in the lowered
307 addPass(createEarlyCSEPass());
308 // Do loop invariant code motion in case part of the lowered result is
310 addPass(createLICMPass());
313 TargetPassConfig::addIRPasses();
316 bool PPCPassConfig::addPreISel() {
317 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
318 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
320 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
321 addPass(createPPCCTRLoops(getPPCTargetMachine()));
326 bool PPCPassConfig::addILPOpts() {
327 addPass(&EarlyIfConverterID);
329 if (EnableMachineCombinerPass)
330 addPass(&MachineCombinerID);
335 bool PPCPassConfig::addInstSelector() {
336 // Install an instruction selector.
337 addPass(createPPCISelDag(getPPCTargetMachine()));
340 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
341 addPass(createPPCCTRLoopsVerify());
344 addPass(createPPCVSXCopyPass());
348 void PPCPassConfig::addMachineSSAOptimization() {
349 TargetPassConfig::addMachineSSAOptimization();
350 // For little endian, remove where possible the vector swap instructions
351 // introduced at code generation to normalize vector element order.
352 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
353 !DisableVSXSwapRemoval)
354 addPass(createPPCVSXSwapRemovalPass());
355 // Target-specific peephole cleanups performed after instruction
357 if (!DisableMIPeephole) {
358 addPass(createPPCMIPeepholePass());
359 addPass(&DeadMachineInstructionElimID);
363 void PPCPassConfig::addPreRegAlloc() {
364 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
365 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
367 if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
368 addPass(createPPCTLSDynamicCallPass());
369 if (EnableExtraTOCRegDeps)
370 addPass(createPPCTOCRegDepsPass());
373 void PPCPassConfig::addPreSched2() {
374 if (getOptLevel() != CodeGenOpt::None)
375 addPass(&IfConverterID);
378 void PPCPassConfig::addPreEmitPass() {
379 if (getOptLevel() != CodeGenOpt::None)
380 addPass(createPPCEarlyReturnPass(), false);
381 // Must run branch selection immediately preceding the asm printer.
382 addPass(createPPCBranchSelectionPass(), false);
385 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
386 return TargetIRAnalysis([this](const Function &F) {
387 return TargetTransformInfo(PPCTTIImpl(this, F));