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/LiveVariables.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/TargetPassConfig.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/FormattedStream.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Target/TargetOptions.h"
28 #include "llvm/Transforms/Scalar.h"
32 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
33 cl::desc("Disable CTR loops for PPC"));
36 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
37 cl::desc("Disable PPC loop preinc prep"));
40 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
41 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
44 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
45 cl::desc("Disable VSX Swap Removal for PPC"));
48 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden,
49 cl::desc("Disable QPX load splat simplification"));
52 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
53 cl::desc("Disable machine peepholes for PPC"));
56 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
57 cl::desc("Enable optimizations on complex GEPs"),
61 EnablePrefetch("enable-ppc-prefetching",
62 cl::desc("disable software prefetching on PPC"),
63 cl::init(false), cl::Hidden);
66 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
67 cl::desc("Add extra TOC register dependencies"),
68 cl::init(true), cl::Hidden);
71 EnableMachineCombinerPass("ppc-machine-combiner",
72 cl::desc("Enable the machine combiner pass"),
73 cl::init(true), cl::Hidden);
75 extern "C" void LLVMInitializePowerPCTarget() {
76 // Register the targets
77 RegisterTargetMachine<PPC32TargetMachine> A(getThePPC32Target());
78 RegisterTargetMachine<PPC64TargetMachine> B(getThePPC64Target());
79 RegisterTargetMachine<PPC64TargetMachine> C(getThePPC64LETarget());
81 PassRegistry &PR = *PassRegistry::getPassRegistry();
82 initializePPCBoolRetToIntPass(PR);
85 /// Return the datalayout string of a subtarget.
86 static std::string getDataLayoutString(const Triple &T) {
87 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
90 // Most PPC* platforms are big endian, PPC64LE is little endian.
91 if (T.getArch() == Triple::ppc64le)
96 Ret += DataLayout::getManglingComponent(T);
98 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
100 if (!is64Bit || T.getOS() == Triple::Lv2)
103 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
104 // documentation are wrong; these are correct (i.e. "what gcc does").
105 if (is64Bit || !T.isOSDarwin())
110 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
119 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
121 std::string FullFS = FS;
123 // Make sure 64-bit features are available when CPUname is generic
124 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
126 FullFS = "+64bit," + FullFS;
131 if (OL >= CodeGenOpt::Default) {
133 FullFS = "+crbits," + FullFS;
138 if (OL != CodeGenOpt::None) {
140 FullFS = "+invariant-function-descriptors," + FullFS;
142 FullFS = "+invariant-function-descriptors";
148 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
149 // If it isn't a Mach-O file then it's going to be a linux ELF
152 return make_unique<TargetLoweringObjectFileMachO>();
154 return make_unique<PPC64LinuxTargetObjectFile>();
157 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
158 const TargetOptions &Options) {
159 if (Options.MCOptions.getABIName().startswith("elfv1"))
160 return PPCTargetMachine::PPC_ABI_ELFv1;
161 else if (Options.MCOptions.getABIName().startswith("elfv2"))
162 return PPCTargetMachine::PPC_ABI_ELFv2;
164 assert(Options.MCOptions.getABIName().empty() &&
165 "Unknown target-abi option!");
167 if (!TT.isMacOSX()) {
168 switch (TT.getArch()) {
169 case Triple::ppc64le:
170 return PPCTargetMachine::PPC_ABI_ELFv2;
172 return PPCTargetMachine::PPC_ABI_ELFv1;
178 return PPCTargetMachine::PPC_ABI_UNKNOWN;
181 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
182 Optional<Reloc::Model> RM) {
183 if (!RM.hasValue()) {
184 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
185 if (!TT.isOSBinFormatMachO() && !TT.isMacOSX())
189 return Reloc::DynamicNoPIC;
190 return Reloc::Static;
195 // The FeatureString here is a little subtle. We are modifying the feature
196 // string with what are (currently) non-function specific overrides as it goes
197 // into the LLVMTargetMachine constructor and then using the stored value in the
198 // Subtarget constructor below it.
199 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
200 StringRef CPU, StringRef FS,
201 const TargetOptions &Options,
202 Optional<Reloc::Model> RM,
203 CodeModel::Model CM, CodeGenOpt::Level OL)
204 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
205 computeFSAdditions(FS, OL, TT), Options,
206 getEffectiveRelocModel(TT, RM), CM, OL),
207 TLOF(createTLOF(getTargetTriple())),
208 TargetABI(computeTargetABI(TT, Options)),
209 Subtarget(TargetTriple, CPU, computeFSAdditions(FS, OL, TT), *this) {
214 PPCTargetMachine::~PPCTargetMachine() {}
216 void PPC32TargetMachine::anchor() { }
218 PPC32TargetMachine::PPC32TargetMachine(const Target &T, const Triple &TT,
219 StringRef CPU, StringRef FS,
220 const TargetOptions &Options,
221 Optional<Reloc::Model> RM,
223 CodeGenOpt::Level OL)
224 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
226 void PPC64TargetMachine::anchor() { }
228 PPC64TargetMachine::PPC64TargetMachine(const Target &T, const Triple &TT,
229 StringRef CPU, StringRef FS,
230 const TargetOptions &Options,
231 Optional<Reloc::Model> RM,
233 CodeGenOpt::Level OL)
234 : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {}
237 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
238 Attribute CPUAttr = F.getFnAttribute("target-cpu");
239 Attribute FSAttr = F.getFnAttribute("target-features");
241 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
242 ? CPUAttr.getValueAsString().str()
244 std::string FS = !FSAttr.hasAttribute(Attribute::None)
245 ? FSAttr.getValueAsString().str()
248 // FIXME: This is related to the code below to reset the target options,
249 // we need to know whether or not the soft float flag is set on the
250 // function before we can generate a subtarget. We also need to use
251 // it as a key for the subtarget since that can be the only difference
252 // between two functions.
254 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
255 // If the soft float attribute is set on the function turn on the soft float
256 // subtarget feature.
258 FS += FS.empty() ? "-hard-float" : ",-hard-float";
260 auto &I = SubtargetMap[CPU + FS];
262 // This needs to be done before we create a new subtarget since any
263 // creation will depend on the TM and the code generation flags on the
264 // function that reside in TargetOptions.
265 resetTargetOptions(F);
266 I = llvm::make_unique<PPCSubtarget>(
268 // FIXME: It would be good to have the subtarget additions here
269 // not necessary. Anything that turns them on/off (overrides) ends
270 // up being put at the end of the feature string, but the defaults
271 // shouldn't require adding them. Fixing this means pulling Feature64Bit
272 // out of most of the target cpus in the .td file and making it set only
273 // as part of initialization via the TargetTriple.
274 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
279 //===----------------------------------------------------------------------===//
280 // Pass Pipeline Configuration
281 //===----------------------------------------------------------------------===//
284 /// PPC Code Generator Pass Configuration Options.
285 class PPCPassConfig : public TargetPassConfig {
287 PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
288 : TargetPassConfig(TM, PM) {}
290 PPCTargetMachine &getPPCTargetMachine() const {
291 return getTM<PPCTargetMachine>();
294 void addIRPasses() override;
295 bool addPreISel() override;
296 bool addILPOpts() override;
297 bool addInstSelector() override;
298 void addMachineSSAOptimization() override;
299 void addPreRegAlloc() override;
300 void addPreSched2() override;
301 void addPreEmitPass() override;
305 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
306 return new PPCPassConfig(this, PM);
309 void PPCPassConfig::addIRPasses() {
310 if (TM->getOptLevel() != CodeGenOpt::None)
311 addPass(createPPCBoolRetToIntPass());
312 addPass(createAtomicExpandPass(&getPPCTargetMachine()));
314 // For the BG/Q (or if explicitly requested), add explicit data prefetch
316 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
317 getOptLevel() != CodeGenOpt::None;
318 if (EnablePrefetch.getNumOccurrences() > 0)
319 UsePrefetching = EnablePrefetch;
321 addPass(createLoopDataPrefetchPass());
323 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
324 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
325 // and lower a GEP with multiple indices to either arithmetic operations or
326 // multiple GEPs with single index.
327 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
328 // Call EarlyCSE pass to find and remove subexpressions in the lowered
330 addPass(createEarlyCSEPass());
331 // Do loop invariant code motion in case part of the lowered result is
333 addPass(createLICMPass());
336 TargetPassConfig::addIRPasses();
339 bool PPCPassConfig::addPreISel() {
340 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
341 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
343 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
344 addPass(createPPCCTRLoops(getPPCTargetMachine()));
349 bool PPCPassConfig::addILPOpts() {
350 addPass(&EarlyIfConverterID);
352 if (EnableMachineCombinerPass)
353 addPass(&MachineCombinerID);
358 bool PPCPassConfig::addInstSelector() {
359 // Install an instruction selector.
360 addPass(createPPCISelDag(getPPCTargetMachine()));
363 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
364 addPass(createPPCCTRLoopsVerify());
367 addPass(createPPCVSXCopyPass());
371 void PPCPassConfig::addMachineSSAOptimization() {
372 TargetPassConfig::addMachineSSAOptimization();
373 // For little endian, remove where possible the vector swap instructions
374 // introduced at code generation to normalize vector element order.
375 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
376 !DisableVSXSwapRemoval)
377 addPass(createPPCVSXSwapRemovalPass());
378 // Target-specific peephole cleanups performed after instruction
380 if (!DisableMIPeephole) {
381 addPass(createPPCMIPeepholePass());
382 addPass(&DeadMachineInstructionElimID);
386 void PPCPassConfig::addPreRegAlloc() {
387 if (getOptLevel() != CodeGenOpt::None) {
388 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
389 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
393 // FIXME: We probably don't need to run these for -fPIE.
394 if (getPPCTargetMachine().isPositionIndependent()) {
395 // FIXME: LiveVariables should not be necessary here!
396 // PPCTLSDYnamicCallPass uses LiveIntervals which previously dependet on
397 // LiveVariables. This (unnecessary) dependency has been removed now,
398 // however a stage-2 clang build fails without LiveVariables computed here.
399 addPass(&LiveVariablesID, false);
400 addPass(createPPCTLSDynamicCallPass());
402 if (EnableExtraTOCRegDeps)
403 addPass(createPPCTOCRegDepsPass());
406 void PPCPassConfig::addPreSched2() {
407 if (getOptLevel() != CodeGenOpt::None) {
408 addPass(&IfConverterID);
410 // This optimization must happen after anything that might do store-to-load
411 // forwarding. Here we're after RA (and, thus, when spills are inserted)
412 // but before post-RA scheduling.
413 if (!DisableQPXLoadSplat)
414 addPass(createPPCQPXLoadSplatPass());
418 void PPCPassConfig::addPreEmitPass() {
419 if (getOptLevel() != CodeGenOpt::None)
420 addPass(createPPCEarlyReturnPass(), false);
421 // Must run branch selection immediately preceding the asm printer.
422 addPass(createPPCBranchSelectionPass(), false);
425 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
426 return TargetIRAnalysis([this](const Function &F) {
427 return TargetTransformInfo(PPCTTIImpl(this, F));