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);
75 PassRegistry &PR = *PassRegistry::getPassRegistry();
76 initializePPCBoolRetToIntPass(PR);
79 /// Return the datalayout string of a subtarget.
80 static std::string getDataLayoutString(const Triple &T) {
81 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
84 // Most PPC* platforms are big endian, PPC64LE is little endian.
85 if (T.getArch() == Triple::ppc64le)
90 Ret += DataLayout::getManglingComponent(T);
92 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
94 if (!is64Bit || T.getOS() == Triple::Lv2)
97 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
98 // documentation are wrong; these are correct (i.e. "what gcc does").
99 if (is64Bit || !T.isOSDarwin())
104 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
113 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
115 std::string FullFS = FS;
117 // Make sure 64-bit features are available when CPUname is generic
118 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
120 FullFS = "+64bit," + FullFS;
125 if (OL >= CodeGenOpt::Default) {
127 FullFS = "+crbits," + FullFS;
132 if (OL != CodeGenOpt::None) {
134 FullFS = "+invariant-function-descriptors," + FullFS;
136 FullFS = "+invariant-function-descriptors";
142 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
143 // If it isn't a Mach-O file then it's going to be a linux ELF
146 return make_unique<TargetLoweringObjectFileMachO>();
148 return make_unique<PPC64LinuxTargetObjectFile>();
151 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
152 const TargetOptions &Options) {
153 if (Options.MCOptions.getABIName().startswith("elfv1"))
154 return PPCTargetMachine::PPC_ABI_ELFv1;
155 else if (Options.MCOptions.getABIName().startswith("elfv2"))
156 return PPCTargetMachine::PPC_ABI_ELFv2;
158 assert(Options.MCOptions.getABIName().empty() &&
159 "Unknown target-abi option!");
161 if (!TT.isMacOSX()) {
162 switch (TT.getArch()) {
163 case Triple::ppc64le:
164 return PPCTargetMachine::PPC_ABI_ELFv2;
166 return PPCTargetMachine::PPC_ABI_ELFv1;
172 return PPCTargetMachine::PPC_ABI_UNKNOWN;
175 // The FeatureString here is a little subtle. We are modifying the feature
176 // string with what are (currently) non-function specific overrides as it goes
177 // into the LLVMTargetMachine constructor and then using the stored value in the
178 // Subtarget constructor below it.
179 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
180 StringRef CPU, StringRef FS,
181 const TargetOptions &Options,
182 Reloc::Model RM, CodeModel::Model CM,
183 CodeGenOpt::Level OL)
184 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
185 computeFSAdditions(FS, OL, TT), Options, RM, CM, OL),
186 TLOF(createTLOF(getTargetTriple())),
187 TargetABI(computeTargetABI(TT, Options)),
188 Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
190 // For the estimates, convergence is quadratic, so we essentially double the
191 // number of digits correct after every iteration. For both FRE and FRSQRTE,
192 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
193 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
194 unsigned RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3,
195 RefinementSteps64 = RefinementSteps + 1;
197 this->Options.Reciprocals.setDefaults("sqrtf", true, RefinementSteps);
198 this->Options.Reciprocals.setDefaults("vec-sqrtf", true, RefinementSteps);
199 this->Options.Reciprocals.setDefaults("divf", true, RefinementSteps);
200 this->Options.Reciprocals.setDefaults("vec-divf", true, RefinementSteps);
202 this->Options.Reciprocals.setDefaults("sqrtd", true, RefinementSteps64);
203 this->Options.Reciprocals.setDefaults("vec-sqrtd", true, RefinementSteps64);
204 this->Options.Reciprocals.setDefaults("divd", true, RefinementSteps64);
205 this->Options.Reciprocals.setDefaults("vec-divd", true, RefinementSteps64);
210 PPCTargetMachine::~PPCTargetMachine() {}
212 void PPC32TargetMachine::anchor() { }
214 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
215 StringRef CPU, StringRef FS,
216 const TargetOptions &Options,
217 Reloc::Model RM, CodeModel::Model CM,
218 CodeGenOpt::Level OL)
219 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
221 void PPC64TargetMachine::anchor() { }
223 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
224 StringRef CPU, StringRef FS,
225 const TargetOptions &Options,
226 Reloc::Model RM, CodeModel::Model CM,
227 CodeGenOpt::Level OL)
228 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
231 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
232 Attribute CPUAttr = F.getFnAttribute("target-cpu");
233 Attribute FSAttr = F.getFnAttribute("target-features");
235 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
236 ? CPUAttr.getValueAsString().str()
238 std::string FS = !FSAttr.hasAttribute(Attribute::None)
239 ? FSAttr.getValueAsString().str()
242 // FIXME: This is related to the code below to reset the target options,
243 // we need to know whether or not the soft float flag is set on the
244 // function before we can generate a subtarget. We also need to use
245 // it as a key for the subtarget since that can be the only difference
246 // between two functions.
248 F.hasFnAttribute("use-soft-float") &&
249 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
250 // If the soft float attribute is set on the function turn on the soft float
251 // subtarget feature.
253 FS += FS.empty() ? "+soft-float" : ",+soft-float";
255 auto &I = SubtargetMap[CPU + FS];
257 // This needs to be done before we create a new subtarget since any
258 // creation will depend on the TM and the code generation flags on the
259 // function that reside in TargetOptions.
260 resetTargetOptions(F);
261 I = llvm::make_unique<PPCSubtarget>(
263 // FIXME: It would be good to have the subtarget additions here
264 // not necessary. Anything that turns them on/off (overrides) ends
265 // up being put at the end of the feature string, but the defaults
266 // shouldn't require adding them. Fixing this means pulling Feature64Bit
267 // out of most of the target cpus in the .td file and making it set only
268 // as part of initialization via the TargetTriple.
269 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
274 //===----------------------------------------------------------------------===//
275 // Pass Pipeline Configuration
276 //===----------------------------------------------------------------------===//
279 /// PPC Code Generator Pass Configuration Options.
280 class PPCPassConfig : public TargetPassConfig {
282 PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
283 : TargetPassConfig(TM, PM) {}
285 PPCTargetMachine &getPPCTargetMachine() const {
286 return getTM<PPCTargetMachine>();
289 void addIRPasses() override;
290 bool addPreISel() override;
291 bool addILPOpts() override;
292 bool addInstSelector() override;
293 void addMachineSSAOptimization() override;
294 void addPreRegAlloc() override;
295 void addPreSched2() override;
296 void addPreEmitPass() override;
300 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
301 return new PPCPassConfig(this, PM);
304 void PPCPassConfig::addIRPasses() {
305 if (TM->getOptLevel() != CodeGenOpt::None)
306 addPass(createPPCBoolRetToIntPass());
307 addPass(createAtomicExpandPass(&getPPCTargetMachine()));
309 // For the BG/Q (or if explicitly requested), add explicit data prefetch
311 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
312 getOptLevel() != CodeGenOpt::None;
313 if (EnablePrefetch.getNumOccurrences() > 0)
314 UsePrefetching = EnablePrefetch;
316 addPass(createPPCLoopDataPrefetchPass());
318 if (TM->getOptLevel() == CodeGenOpt::Aggressive && 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
325 addPass(createEarlyCSEPass());
326 // Do loop invariant code motion in case part of the lowered result is
328 addPass(createLICMPass());
331 TargetPassConfig::addIRPasses();
334 bool PPCPassConfig::addPreISel() {
335 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
336 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
338 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
339 addPass(createPPCCTRLoops(getPPCTargetMachine()));
344 bool PPCPassConfig::addILPOpts() {
345 addPass(&EarlyIfConverterID);
347 if (EnableMachineCombinerPass)
348 addPass(&MachineCombinerID);
353 bool PPCPassConfig::addInstSelector() {
354 // Install an instruction selector.
355 addPass(createPPCISelDag(getPPCTargetMachine()));
358 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
359 addPass(createPPCCTRLoopsVerify());
362 addPass(createPPCVSXCopyPass());
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
375 if (!DisableMIPeephole) {
376 addPass(createPPCMIPeepholePass());
377 addPass(&DeadMachineInstructionElimID);
381 void PPCPassConfig::addPreRegAlloc() {
382 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
383 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
385 if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
386 addPass(createPPCTLSDynamicCallPass());
387 if (EnableExtraTOCRegDeps)
388 addPass(createPPCTOCRegDepsPass());
391 void PPCPassConfig::addPreSched2() {
392 if (getOptLevel() != CodeGenOpt::None)
393 addPass(&IfConverterID);
396 void PPCPassConfig::addPreEmitPass() {
397 if (getOptLevel() != CodeGenOpt::None)
398 addPass(createPPCEarlyReturnPass(), false);
399 // Must run branch selection immediately preceding the asm printer.
400 addPass(createPPCBranchSelectionPass(), false);
403 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
404 return TargetIRAnalysis([this](const Function &F) {
405 return TargetTransformInfo(PPCTTIImpl(this, F));