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/TargetLoweringObjectFile.h"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CodeGen.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Scalar.h"
45 EnableBranchCoalescing("enable-ppc-branch-coalesce", cl::Hidden,
46 cl::desc("enable coalescing of duplicate branches for PPC"));
48 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
49 cl::desc("Disable CTR loops for PPC"));
52 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
53 cl::desc("Disable PPC loop preinc prep"));
56 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
57 cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
60 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
61 cl::desc("Disable VSX Swap Removal for PPC"));
64 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden,
65 cl::desc("Disable QPX load splat simplification"));
68 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
69 cl::desc("Disable machine peepholes for PPC"));
72 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
73 cl::desc("Enable optimizations on complex GEPs"),
77 EnablePrefetch("enable-ppc-prefetching",
78 cl::desc("disable software prefetching on PPC"),
79 cl::init(false), cl::Hidden);
82 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
83 cl::desc("Add extra TOC register dependencies"),
84 cl::init(true), cl::Hidden);
87 EnableMachineCombinerPass("ppc-machine-combiner",
88 cl::desc("Enable the machine combiner pass"),
89 cl::init(true), cl::Hidden);
92 ReduceCRLogical("ppc-reduce-cr-logicals",
93 cl::desc("Expand eligible cr-logical binary ops to branches"),
94 cl::init(false), cl::Hidden);
95 extern "C" void LLVMInitializePowerPCTarget() {
96 // Register the targets
97 RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target());
98 RegisterTargetMachine<PPCTargetMachine> B(getThePPC64Target());
99 RegisterTargetMachine<PPCTargetMachine> C(getThePPC64LETarget());
101 PassRegistry &PR = *PassRegistry::getPassRegistry();
102 initializePPCBoolRetToIntPass(PR);
103 initializePPCExpandISELPass(PR);
104 initializePPCPreEmitPeepholePass(PR);
105 initializePPCTLSDynamicCallPass(PR);
106 initializePPCMIPeepholePass(PR);
109 /// Return the datalayout string of a subtarget.
110 static std::string getDataLayoutString(const Triple &T) {
111 bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
114 // Most PPC* platforms are big endian, PPC64LE is little endian.
115 if (T.getArch() == Triple::ppc64le)
120 Ret += DataLayout::getManglingComponent(T);
122 // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
124 if (!is64Bit || T.getOS() == Triple::Lv2)
127 // Note, the alignment values for f64 and i64 on ppc64 in Darwin
128 // documentation are wrong; these are correct (i.e. "what gcc does").
129 if (is64Bit || !T.isOSDarwin())
134 // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
143 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
145 std::string FullFS = FS;
147 // Make sure 64-bit features are available when CPUname is generic
148 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
150 FullFS = "+64bit," + FullFS;
155 if (OL >= CodeGenOpt::Default) {
157 FullFS = "+crbits," + FullFS;
162 if (OL != CodeGenOpt::None) {
164 FullFS = "+invariant-function-descriptors," + FullFS;
166 FullFS = "+invariant-function-descriptors";
172 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
173 // If it isn't a Mach-O file then it's going to be a linux ELF
176 return llvm::make_unique<TargetLoweringObjectFileMachO>();
178 return llvm::make_unique<PPC64LinuxTargetObjectFile>();
181 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
182 const TargetOptions &Options) {
183 if (Options.MCOptions.getABIName().startswith("elfv1"))
184 return PPCTargetMachine::PPC_ABI_ELFv1;
185 else if (Options.MCOptions.getABIName().startswith("elfv2"))
186 return PPCTargetMachine::PPC_ABI_ELFv2;
188 assert(Options.MCOptions.getABIName().empty() &&
189 "Unknown target-abi option!");
192 return PPCTargetMachine::PPC_ABI_UNKNOWN;
194 switch (TT.getArch()) {
195 case Triple::ppc64le:
196 return PPCTargetMachine::PPC_ABI_ELFv2;
198 return PPCTargetMachine::PPC_ABI_ELFv1;
200 return PPCTargetMachine::PPC_ABI_UNKNOWN;
204 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
205 Optional<Reloc::Model> RM) {
209 // Darwin defaults to dynamic-no-pic.
211 return Reloc::DynamicNoPIC;
213 // Non-darwin 64-bit platforms are PIC by default.
214 if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le)
217 // 32-bit is static by default.
218 return Reloc::Static;
221 static CodeModel::Model getEffectiveCodeModel(const Triple &TT,
222 Optional<CodeModel::Model> CM,
226 if (!TT.isOSDarwin() && !JIT &&
227 (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le))
228 return CodeModel::Medium;
229 return CodeModel::Small;
232 // The FeatureString here is a little subtle. We are modifying the feature
233 // string with what are (currently) non-function specific overrides as it goes
234 // into the LLVMTargetMachine constructor and then using the stored value in the
235 // Subtarget constructor below it.
236 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
237 StringRef CPU, StringRef FS,
238 const TargetOptions &Options,
239 Optional<Reloc::Model> RM,
240 Optional<CodeModel::Model> CM,
241 CodeGenOpt::Level OL, bool JIT)
242 : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
243 computeFSAdditions(FS, OL, TT), Options,
244 getEffectiveRelocModel(TT, RM),
245 getEffectiveCodeModel(TT, CM, JIT), OL),
246 TLOF(createTLOF(getTargetTriple())),
247 TargetABI(computeTargetABI(TT, Options)) {
251 PPCTargetMachine::~PPCTargetMachine() = default;
254 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
255 Attribute CPUAttr = F.getFnAttribute("target-cpu");
256 Attribute FSAttr = F.getFnAttribute("target-features");
258 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
259 ? CPUAttr.getValueAsString().str()
261 std::string FS = !FSAttr.hasAttribute(Attribute::None)
262 ? FSAttr.getValueAsString().str()
265 // FIXME: This is related to the code below to reset the target options,
266 // we need to know whether or not the soft float flag is set on the
267 // function before we can generate a subtarget. We also need to use
268 // it as a key for the subtarget since that can be the only difference
269 // between two functions.
271 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
272 // If the soft float attribute is set on the function turn on the soft float
273 // subtarget feature.
275 FS += FS.empty() ? "-hard-float" : ",-hard-float";
277 auto &I = SubtargetMap[CPU + FS];
279 // This needs to be done before we create a new subtarget since any
280 // creation will depend on the TM and the code generation flags on the
281 // function that reside in TargetOptions.
282 resetTargetOptions(F);
283 I = llvm::make_unique<PPCSubtarget>(
285 // FIXME: It would be good to have the subtarget additions here
286 // not necessary. Anything that turns them on/off (overrides) ends
287 // up being put at the end of the feature string, but the defaults
288 // shouldn't require adding them. Fixing this means pulling Feature64Bit
289 // out of most of the target cpus in the .td file and making it set only
290 // as part of initialization via the TargetTriple.
291 computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
296 //===----------------------------------------------------------------------===//
297 // Pass Pipeline Configuration
298 //===----------------------------------------------------------------------===//
302 /// PPC Code Generator Pass Configuration Options.
303 class PPCPassConfig : public TargetPassConfig {
305 PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM)
306 : TargetPassConfig(TM, PM) {}
308 PPCTargetMachine &getPPCTargetMachine() const {
309 return getTM<PPCTargetMachine>();
312 void addIRPasses() override;
313 bool addPreISel() override;
314 bool addILPOpts() override;
315 bool addInstSelector() override;
316 void addMachineSSAOptimization() override;
317 void addPreRegAlloc() override;
318 void addPreSched2() override;
319 void addPreEmitPass() override;
322 } // end anonymous namespace
324 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
325 return new PPCPassConfig(*this, PM);
328 void PPCPassConfig::addIRPasses() {
329 if (TM->getOptLevel() != CodeGenOpt::None)
330 addPass(createPPCBoolRetToIntPass());
331 addPass(createAtomicExpandPass());
333 // For the BG/Q (or if explicitly requested), add explicit data prefetch
335 bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
336 getOptLevel() != CodeGenOpt::None;
337 if (EnablePrefetch.getNumOccurrences() > 0)
338 UsePrefetching = EnablePrefetch;
340 addPass(createLoopDataPrefetchPass());
342 if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
343 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
344 // and lower a GEP with multiple indices to either arithmetic operations or
345 // multiple GEPs with single index.
346 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
347 // Call EarlyCSE pass to find and remove subexpressions in the lowered
349 addPass(createEarlyCSEPass());
350 // Do loop invariant code motion in case part of the lowered result is
352 addPass(createLICMPass());
355 TargetPassConfig::addIRPasses();
358 bool PPCPassConfig::addPreISel() {
359 if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
360 addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
362 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
363 addPass(createPPCCTRLoops());
368 bool PPCPassConfig::addILPOpts() {
369 addPass(&EarlyIfConverterID);
371 if (EnableMachineCombinerPass)
372 addPass(&MachineCombinerID);
377 bool PPCPassConfig::addInstSelector() {
378 // Install an instruction selector.
379 addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel()));
382 if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
383 addPass(createPPCCTRLoopsVerify());
386 addPass(createPPCVSXCopyPass());
390 void PPCPassConfig::addMachineSSAOptimization() {
391 // PPCBranchCoalescingPass need to be done before machine sinking
392 // since it merges empty blocks.
393 if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None)
394 addPass(createPPCBranchCoalescingPass());
395 TargetPassConfig::addMachineSSAOptimization();
396 // For little endian, remove where possible the vector swap instructions
397 // introduced at code generation to normalize vector element order.
398 if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
399 !DisableVSXSwapRemoval)
400 addPass(createPPCVSXSwapRemovalPass());
401 // Reduce the number of cr-logical ops.
402 if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None)
403 addPass(createPPCReduceCRLogicalsPass());
404 // Target-specific peephole cleanups performed after instruction
406 if (!DisableMIPeephole) {
407 addPass(createPPCMIPeepholePass());
408 addPass(&DeadMachineInstructionElimID);
412 void PPCPassConfig::addPreRegAlloc() {
413 if (getOptLevel() != CodeGenOpt::None) {
414 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
415 insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
419 // FIXME: We probably don't need to run these for -fPIE.
420 if (getPPCTargetMachine().isPositionIndependent()) {
421 // FIXME: LiveVariables should not be necessary here!
422 // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on
423 // LiveVariables. This (unnecessary) dependency has been removed now,
424 // however a stage-2 clang build fails without LiveVariables computed here.
425 addPass(&LiveVariablesID, false);
426 addPass(createPPCTLSDynamicCallPass());
428 if (EnableExtraTOCRegDeps)
429 addPass(createPPCTOCRegDepsPass());
432 void PPCPassConfig::addPreSched2() {
433 if (getOptLevel() != CodeGenOpt::None) {
434 addPass(&IfConverterID);
436 // This optimization must happen after anything that might do store-to-load
437 // forwarding. Here we're after RA (and, thus, when spills are inserted)
438 // but before post-RA scheduling.
439 if (!DisableQPXLoadSplat)
440 addPass(createPPCQPXLoadSplatPass());
444 void PPCPassConfig::addPreEmitPass() {
445 addPass(createPPCPreEmitPeepholePass());
446 addPass(createPPCExpandISELPass());
448 if (getOptLevel() != CodeGenOpt::None)
449 addPass(createPPCEarlyReturnPass(), false);
450 // Must run branch selection immediately preceding the asm printer.
451 addPass(createPPCBranchSelectionPass(), false);
455 PPCTargetMachine::getTargetTransformInfo(const Function &F) {
456 return TargetTransformInfo(PPCTTIImpl(this, F));