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"
15 #include "MCTargetDesc/PPCMCTargetDesc.h"
17 #include "PPCSubtarget.h"
18 #include "PPCTargetObjectFile.h"
19 #include "PPCTargetTransformInfo.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CodeGen.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Scalar.h"
44 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
45 cl::desc("Disable CTR loops for PPC"));
48 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
49 cl::desc("Disable PPC loop preinc prep"));
52 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
53 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
56 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
57 cl::desc("Disable VSX Swap Removal for PPC"));
60 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden,
61 cl::desc("Disable QPX load splat simplification"));
64 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
65 cl::desc("Disable machine peepholes for PPC"));
68 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
69 cl::desc("Enable optimizations on complex GEPs"),
73 EnablePrefetch("enable-ppc-prefetching",
74 cl::desc("disable software prefetching on PPC"),
75 cl::init(false), cl::Hidden);
78 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
79 cl::desc("Add extra TOC register dependencies"),
80 cl::init(true), cl::Hidden);
83 EnableMachineCombinerPass("ppc-machine-combiner",
84 cl::desc("Enable the machine combiner pass"),
85 cl::init(true), cl::Hidden);
87 extern "C" void LLVMInitializePowerPCTarget() {
88 // Register the targets
89 RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target());
90 RegisterTargetMachine<PPCTargetMachine> B(getThePPC64Target());
91 RegisterTargetMachine<PPCTargetMachine> C(getThePPC64LETarget());
93 PassRegistry &PR = *PassRegistry::getPassRegistry();
94 initializePPCBoolRetToIntPass(PR);
95 initializePPCExpandISELPass(PR);
96 initializePPCTLSDynamicCallPass(PR);
99 /// Return the datalayout string of a subtarget.
100 static std::string getDataLayoutString(const Triple &T) {
101 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
104 // Most PPC* platforms are big endian, PPC64LE is little endian.
105 if (T.getArch() == Triple::ppc64le)
110 Ret += DataLayout::getManglingComponent(T);
112 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
114 if (!is64Bit || T.getOS() == Triple::Lv2)
117 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
118 // documentation are wrong; these are correct (i.e. "what gcc does").
119 if (is64Bit || !T.isOSDarwin())
124 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
133 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
135 std::string FullFS = FS;
137 // Make sure 64-bit features are available when CPUname is generic
138 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
140 FullFS = "+64bit," + FullFS;
145 if (OL >= CodeGenOpt::Default) {
147 FullFS = "+crbits," + FullFS;
152 if (OL != CodeGenOpt::None) {
154 FullFS = "+invariant-function-descriptors," + FullFS;
156 FullFS = "+invariant-function-descriptors";
162 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
163 // If it isn't a Mach-O file then it's going to be a linux ELF
166 return llvm::make_unique<TargetLoweringObjectFileMachO>();
168 return llvm::make_unique<PPC64LinuxTargetObjectFile>();
171 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
172 const TargetOptions &Options) {
173 if (Options.MCOptions.getABIName().startswith("elfv1"))
174 return PPCTargetMachine::PPC_ABI_ELFv1;
175 else if (Options.MCOptions.getABIName().startswith("elfv2"))
176 return PPCTargetMachine::PPC_ABI_ELFv2;
178 assert(Options.MCOptions.getABIName().empty() &&
179 "Unknown target-abi option!");
182 return PPCTargetMachine::PPC_ABI_UNKNOWN;
184 switch (TT.getArch()) {
185 case Triple::ppc64le:
186 return PPCTargetMachine::PPC_ABI_ELFv2;
188 return PPCTargetMachine::PPC_ABI_ELFv1;
190 return PPCTargetMachine::PPC_ABI_UNKNOWN;
194 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
195 Optional<Reloc::Model> RM) {
199 // Darwin defaults to dynamic-no-pic.
201 return Reloc::DynamicNoPIC;
203 // Non-darwin 64-bit platforms are PIC by default.
204 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le)
207 // 32-bit is static by default.
208 return Reloc::Static;
211 // The FeatureString here is a little subtle. We are modifying the feature
212 // string with what are (currently) non-function specific overrides as it goes
213 // into the LLVMTargetMachine constructor and then using the stored value in the
214 // Subtarget constructor below it.
215 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
216 StringRef CPU, StringRef FS,
217 const TargetOptions &Options,
218 Optional<Reloc::Model> RM,
219 CodeModel::Model CM, CodeGenOpt::Level OL)
220 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
221 computeFSAdditions(FS, OL, TT), Options,
222 getEffectiveRelocModel(TT, RM), CM, OL),
223 TLOF(createTLOF(getTargetTriple())),
224 TargetABI(computeTargetABI(TT, Options)) {
228 PPCTargetMachine::~PPCTargetMachine() = default;
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.getFnAttribute("use-soft-float").getValueAsString() == "true";
249 // If the soft float attribute is set on the function turn on the soft float
250 // subtarget feature.
252 FS += FS.empty() ? "-hard-float" : ",-hard-float";
254 auto &I = SubtargetMap[CPU + FS];
256 // This needs to be done before we create a new subtarget since any
257 // creation will depend on the TM and the code generation flags on the
258 // function that reside in TargetOptions.
259 resetTargetOptions(F);
260 I = llvm::make_unique<PPCSubtarget>(
262 // FIXME: It would be good to have the subtarget additions here
263 // not necessary. Anything that turns them on/off (overrides) ends
264 // up being put at the end of the feature string, but the defaults
265 // shouldn't require adding them. Fixing this means pulling Feature64Bit
266 // out of most of the target cpus in the .td file and making it set only
267 // as part of initialization via the TargetTriple.
268 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
273 //===----------------------------------------------------------------------===//
274 // Pass Pipeline Configuration
275 //===----------------------------------------------------------------------===//
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;
299 } // end anonymous namespace
301 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
302 return new PPCPassConfig(*this, PM);
305 void PPCPassConfig::addIRPasses() {
306 if (TM->getOptLevel() != CodeGenOpt::None)
307 addPass(createPPCBoolRetToIntPass());
308 addPass(createAtomicExpandPass());
310 // For the BG/Q (or if explicitly requested), add explicit data prefetch
312 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
313 getOptLevel() != CodeGenOpt::None;
314 if (EnablePrefetch.getNumOccurrences() > 0)
315 UsePrefetching = EnablePrefetch;
317 addPass(createLoopDataPrefetchPass());
319 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
320 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
321 // and lower a GEP with multiple indices to either arithmetic operations or
322 // multiple GEPs with single index.
323 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
324 // Call EarlyCSE pass to find and remove subexpressions in the lowered
326 addPass(createEarlyCSEPass());
327 // Do loop invariant code motion in case part of the lowered result is
329 addPass(createLICMPass());
332 TargetPassConfig::addIRPasses();
335 bool PPCPassConfig::addPreISel() {
336 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
337 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
339 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
340 addPass(createPPCCTRLoops());
345 bool PPCPassConfig::addILPOpts() {
346 addPass(&EarlyIfConverterID);
348 if (EnableMachineCombinerPass)
349 addPass(&MachineCombinerID);
354 bool PPCPassConfig::addInstSelector() {
355 // Install an instruction selector.
356 addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel()));
359 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
360 addPass(createPPCCTRLoopsVerify());
363 addPass(createPPCVSXCopyPass());
367 void PPCPassConfig::addMachineSSAOptimization() {
368 TargetPassConfig::addMachineSSAOptimization();
369 // For little endian, remove where possible the vector swap instructions
370 // introduced at code generation to normalize vector element order.
371 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
372 !DisableVSXSwapRemoval)
373 addPass(createPPCVSXSwapRemovalPass());
374 // Target-specific peephole cleanups performed after instruction
376 if (!DisableMIPeephole) {
377 addPass(createPPCMIPeepholePass());
378 addPass(&DeadMachineInstructionElimID);
382 void PPCPassConfig::addPreRegAlloc() {
383 if (getOptLevel() != CodeGenOpt::None) {
384 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
385 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
389 // FIXME: We probably don't need to run these for -fPIE.
390 if (getPPCTargetMachine().isPositionIndependent()) {
391 // FIXME: LiveVariables should not be necessary here!
392 // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on
393 // LiveVariables. This (unnecessary) dependency has been removed now,
394 // however a stage-2 clang build fails without LiveVariables computed here.
395 addPass(&LiveVariablesID, false);
396 addPass(createPPCTLSDynamicCallPass());
398 if (EnableExtraTOCRegDeps)
399 addPass(createPPCTOCRegDepsPass());
402 void PPCPassConfig::addPreSched2() {
403 if (getOptLevel() != CodeGenOpt::None) {
404 addPass(&IfConverterID);
406 // This optimization must happen after anything that might do store-to-load
407 // forwarding. Here we're after RA (and, thus, when spills are inserted)
408 // but before post-RA scheduling.
409 if (!DisableQPXLoadSplat)
410 addPass(createPPCQPXLoadSplatPass());
414 void PPCPassConfig::addPreEmitPass() {
415 addPass(createPPCExpandISELPass());
417 if (getOptLevel() != CodeGenOpt::None)
418 addPass(createPPCEarlyReturnPass(), false);
419 // Must run branch selection immediately preceding the asm printer.
420 addPass(createPPCBranchSelectionPass(), false);
423 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
424 return TargetIRAnalysis([this](const Function &F) {
425 return TargetTransformInfo(PPCTTIImpl(this, F));