1 //===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Top-level implementation for the PowerPC target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCTargetMachine.h"
14 #include "MCTargetDesc/PPCMCTargetDesc.h"
15 #include "PPC.h"
16 #include "PPCMachineScheduler.h"
17 #include "PPCSubtarget.h"
18 #include "PPCTargetObjectFile.h"
19 #include "PPCTargetTransformInfo.h"
20 #include "TargetInfo/PowerPCTargetInfo.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/CodeGen/MachineScheduler.h"
29 #include "llvm/IR/Attributes.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CodeGen.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Transforms/Scalar.h"
39 #include <cassert>
40 #include <memory>
41 #include <string>
42 
43 using namespace llvm;
44 
45 
46 static cl::opt<bool>
47     EnableBranchCoalescing("enable-ppc-branch-coalesce", cl::Hidden,
48                            cl::desc("enable coalescing of duplicate branches for PPC"));
49 static cl::
50 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
51                         cl::desc("Disable CTR loops for PPC"));
52 
53 static cl::
54 opt<bool> DisableInstrFormPrep("disable-ppc-instr-form-prep", cl::Hidden,
55                             cl::desc("Disable PPC loop instr form prep"));
56 
57 static cl::opt<bool>
58 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
59   cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
60 
61 static cl::
62 opt<bool> DisableVSXSwapRemoval("disable-ppc-vsx-swap-removal", cl::Hidden,
63                                 cl::desc("Disable VSX Swap Removal for PPC"));
64 
65 static cl::
66 opt<bool> DisableQPXLoadSplat("disable-ppc-qpx-load-splat", cl::Hidden,
67                               cl::desc("Disable QPX load splat simplification"));
68 
69 static cl::
70 opt<bool> DisableMIPeephole("disable-ppc-peephole", cl::Hidden,
71                             cl::desc("Disable machine peepholes for PPC"));
72 
73 static cl::opt<bool>
74 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
75              cl::desc("Enable optimizations on complex GEPs"),
76              cl::init(true));
77 
78 static cl::opt<bool>
79 EnablePrefetch("enable-ppc-prefetching",
80                   cl::desc("enable software prefetching on PPC"),
81                   cl::init(false), cl::Hidden);
82 
83 static cl::opt<bool>
84 EnableExtraTOCRegDeps("enable-ppc-extra-toc-reg-deps",
85                       cl::desc("Add extra TOC register dependencies"),
86                       cl::init(true), cl::Hidden);
87 
88 static cl::opt<bool>
89 EnableMachineCombinerPass("ppc-machine-combiner",
90                           cl::desc("Enable the machine combiner pass"),
91                           cl::init(true), cl::Hidden);
92 
93 static cl::opt<bool>
94   ReduceCRLogical("ppc-reduce-cr-logicals",
95                   cl::desc("Expand eligible cr-logical binary ops to branches"),
96                   cl::init(true), cl::Hidden);
97 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCTarget() {
98   // Register the targets
99   RegisterTargetMachine<PPCTargetMachine> A(getThePPC32Target());
100   RegisterTargetMachine<PPCTargetMachine> B(getThePPC64Target());
101   RegisterTargetMachine<PPCTargetMachine> C(getThePPC64LETarget());
102 
103   PassRegistry &PR = *PassRegistry::getPassRegistry();
104 #ifndef NDEBUG
105   initializePPCCTRLoopsVerifyPass(PR);
106 #endif
107   initializePPCLoopInstrFormPrepPass(PR);
108   initializePPCTOCRegDepsPass(PR);
109   initializePPCEarlyReturnPass(PR);
110   initializePPCVSXCopyPass(PR);
111   initializePPCVSXFMAMutatePass(PR);
112   initializePPCVSXSwapRemovalPass(PR);
113   initializePPCReduceCRLogicalsPass(PR);
114   initializePPCBSelPass(PR);
115   initializePPCBranchCoalescingPass(PR);
116   initializePPCQPXLoadSplatPass(PR);
117   initializePPCBoolRetToIntPass(PR);
118   initializePPCExpandISELPass(PR);
119   initializePPCPreEmitPeepholePass(PR);
120   initializePPCTLSDynamicCallPass(PR);
121   initializePPCMIPeepholePass(PR);
122   initializePPCLowerMASSVEntriesPass(PR);
123 }
124 
125 /// Return the datalayout string of a subtarget.
126 static std::string getDataLayoutString(const Triple &T) {
127   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
128   std::string Ret;
129 
130   // Most PPC* platforms are big endian, PPC64LE is little endian.
131   if (T.getArch() == Triple::ppc64le)
132     Ret = "e";
133   else
134     Ret = "E";
135 
136   Ret += DataLayout::getManglingComponent(T);
137 
138   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
139   // pointers.
140   if (!is64Bit || T.getOS() == Triple::Lv2)
141     Ret += "-p:32:32";
142 
143   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
144   // documentation are wrong; these are correct (i.e. "what gcc does").
145   if (is64Bit || !T.isOSDarwin())
146     Ret += "-i64:64";
147   else
148     Ret += "-f64:32:64";
149 
150   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
151   if (is64Bit)
152     Ret += "-n32:64";
153   else
154     Ret += "-n32";
155 
156   return Ret;
157 }
158 
159 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL,
160                                       const Triple &TT) {
161   std::string FullFS = std::string(FS);
162 
163   // Make sure 64-bit features are available when CPUname is generic
164   if (TT.getArch() == Triple::ppc64 || TT.getArch() == Triple::ppc64le) {
165     if (!FullFS.empty())
166       FullFS = "+64bit," + FullFS;
167     else
168       FullFS = "+64bit";
169   }
170 
171   if (OL >= CodeGenOpt::Default) {
172     if (!FullFS.empty())
173       FullFS = "+crbits," + FullFS;
174     else
175       FullFS = "+crbits";
176   }
177 
178   if (OL != CodeGenOpt::None) {
179     if (!FullFS.empty())
180       FullFS = "+invariant-function-descriptors," + FullFS;
181     else
182       FullFS = "+invariant-function-descriptors";
183   }
184 
185   return FullFS;
186 }
187 
188 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
189   if (TT.isOSDarwin())
190     return std::make_unique<TargetLoweringObjectFileMachO>();
191 
192   if (TT.isOSAIX())
193     return std::make_unique<TargetLoweringObjectFileXCOFF>();
194 
195   return std::make_unique<PPC64LinuxTargetObjectFile>();
196 }
197 
198 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
199                                                  const TargetOptions &Options) {
200   if (TT.isOSDarwin())
201     report_fatal_error("Darwin is no longer supported for PowerPC");
202 
203   if (Options.MCOptions.getABIName().startswith("elfv1"))
204     return PPCTargetMachine::PPC_ABI_ELFv1;
205   else if (Options.MCOptions.getABIName().startswith("elfv2"))
206     return PPCTargetMachine::PPC_ABI_ELFv2;
207 
208   assert(Options.MCOptions.getABIName().empty() &&
209          "Unknown target-abi option!");
210 
211   if (TT.isMacOSX())
212     return PPCTargetMachine::PPC_ABI_UNKNOWN;
213 
214   switch (TT.getArch()) {
215   case Triple::ppc64le:
216     return PPCTargetMachine::PPC_ABI_ELFv2;
217   case Triple::ppc64:
218     return PPCTargetMachine::PPC_ABI_ELFv1;
219   default:
220     return PPCTargetMachine::PPC_ABI_UNKNOWN;
221   }
222 }
223 
224 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
225                                            Optional<Reloc::Model> RM) {
226   assert((!TT.isOSAIX() || !RM.hasValue() || *RM == Reloc::PIC_) &&
227          "Invalid relocation model for AIX.");
228 
229   if (RM.hasValue())
230     return *RM;
231 
232   // Darwin defaults to dynamic-no-pic.
233   if (TT.isOSDarwin())
234     return Reloc::DynamicNoPIC;
235 
236   // Big Endian PPC and AIX default to PIC.
237   if (TT.getArch() == Triple::ppc64 || TT.isOSAIX())
238     return Reloc::PIC_;
239 
240   // Rest are static by default.
241   return Reloc::Static;
242 }
243 
244 static CodeModel::Model getEffectivePPCCodeModel(const Triple &TT,
245                                                  Optional<CodeModel::Model> CM,
246                                                  bool JIT) {
247   if (CM) {
248     if (*CM == CodeModel::Tiny)
249       report_fatal_error("Target does not support the tiny CodeModel", false);
250     if (*CM == CodeModel::Kernel)
251       report_fatal_error("Target does not support the kernel CodeModel", false);
252     return *CM;
253   }
254 
255   if (JIT)
256     return CodeModel::Small;
257   if (TT.isOSAIX())
258     return CodeModel::Small;
259 
260   assert(TT.isOSBinFormatELF() && "All remaining PPC OSes are ELF based.");
261 
262   if (TT.isArch32Bit())
263     return CodeModel::Small;
264 
265   assert(TT.isArch64Bit() && "Unsupported PPC architecture.");
266   return CodeModel::Medium;
267 }
268 
269 
270 static ScheduleDAGInstrs *createPPCMachineScheduler(MachineSchedContext *C) {
271   const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>();
272   ScheduleDAGMILive *DAG =
273     new ScheduleDAGMILive(C, ST.usePPCPreRASchedStrategy() ?
274                           std::make_unique<PPCPreRASchedStrategy>(C) :
275                           std::make_unique<GenericScheduler>(C));
276   // add DAG Mutations here.
277   DAG->addMutation(createCopyConstrainDAGMutation(DAG->TII, DAG->TRI));
278   return DAG;
279 }
280 
281 static ScheduleDAGInstrs *createPPCPostMachineScheduler(
282   MachineSchedContext *C) {
283   const PPCSubtarget &ST = C->MF->getSubtarget<PPCSubtarget>();
284   ScheduleDAGMI *DAG =
285     new ScheduleDAGMI(C, ST.usePPCPostRASchedStrategy() ?
286                       std::make_unique<PPCPostRASchedStrategy>(C) :
287                       std::make_unique<PostGenericScheduler>(C), true);
288   // add DAG Mutations here.
289   return DAG;
290 }
291 
292 // The FeatureString here is a little subtle. We are modifying the feature
293 // string with what are (currently) non-function specific overrides as it goes
294 // into the LLVMTargetMachine constructor and then using the stored value in the
295 // Subtarget constructor below it.
296 PPCTargetMachine::PPCTargetMachine(const Target &T, const Triple &TT,
297                                    StringRef CPU, StringRef FS,
298                                    const TargetOptions &Options,
299                                    Optional<Reloc::Model> RM,
300                                    Optional<CodeModel::Model> CM,
301                                    CodeGenOpt::Level OL, bool JIT)
302     : LLVMTargetMachine(T, getDataLayoutString(TT), TT, CPU,
303                         computeFSAdditions(FS, OL, TT), Options,
304                         getEffectiveRelocModel(TT, RM),
305                         getEffectivePPCCodeModel(TT, CM, JIT), OL),
306       TLOF(createTLOF(getTargetTriple())),
307       TargetABI(computeTargetABI(TT, Options)) {
308   initAsmInfo();
309 }
310 
311 PPCTargetMachine::~PPCTargetMachine() = default;
312 
313 const PPCSubtarget *
314 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
315   Attribute CPUAttr = F.getFnAttribute("target-cpu");
316   Attribute FSAttr = F.getFnAttribute("target-features");
317 
318   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
319                         ? CPUAttr.getValueAsString().str()
320                         : TargetCPU;
321   std::string FS = !FSAttr.hasAttribute(Attribute::None)
322                        ? FSAttr.getValueAsString().str()
323                        : TargetFS;
324 
325   // FIXME: This is related to the code below to reset the target options,
326   // we need to know whether or not the soft float flag is set on the
327   // function before we can generate a subtarget. We also need to use
328   // it as a key for the subtarget since that can be the only difference
329   // between two functions.
330   bool SoftFloat =
331       F.getFnAttribute("use-soft-float").getValueAsString() == "true";
332   // If the soft float attribute is set on the function turn on the soft float
333   // subtarget feature.
334   if (SoftFloat)
335     FS += FS.empty() ? "-hard-float" : ",-hard-float";
336 
337   auto &I = SubtargetMap[CPU + FS];
338   if (!I) {
339     // This needs to be done before we create a new subtarget since any
340     // creation will depend on the TM and the code generation flags on the
341     // function that reside in TargetOptions.
342     resetTargetOptions(F);
343     I = std::make_unique<PPCSubtarget>(
344         TargetTriple, CPU,
345         // FIXME: It would be good to have the subtarget additions here
346         // not necessary. Anything that turns them on/off (overrides) ends
347         // up being put at the end of the feature string, but the defaults
348         // shouldn't require adding them. Fixing this means pulling Feature64Bit
349         // out of most of the target cpus in the .td file and making it set only
350         // as part of initialization via the TargetTriple.
351         computeFSAdditions(FS, getOptLevel(), getTargetTriple()), *this);
352   }
353   return I.get();
354 }
355 
356 //===----------------------------------------------------------------------===//
357 // Pass Pipeline Configuration
358 //===----------------------------------------------------------------------===//
359 
360 namespace {
361 
362 /// PPC Code Generator Pass Configuration Options.
363 class PPCPassConfig : public TargetPassConfig {
364 public:
365   PPCPassConfig(PPCTargetMachine &TM, PassManagerBase &PM)
366     : TargetPassConfig(TM, PM) {
367     // At any optimization level above -O0 we use the Machine Scheduler and not
368     // the default Post RA List Scheduler.
369     if (TM.getOptLevel() != CodeGenOpt::None)
370       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
371   }
372 
373   PPCTargetMachine &getPPCTargetMachine() const {
374     return getTM<PPCTargetMachine>();
375   }
376 
377   void addIRPasses() override;
378   bool addPreISel() override;
379   bool addILPOpts() override;
380   bool addInstSelector() override;
381   void addMachineSSAOptimization() override;
382   void addPreRegAlloc() override;
383   void addPreSched2() override;
384   void addPreEmitPass() override;
385   ScheduleDAGInstrs *
386   createMachineScheduler(MachineSchedContext *C) const override {
387     return createPPCMachineScheduler(C);
388   }
389   ScheduleDAGInstrs *
390   createPostMachineScheduler(MachineSchedContext *C) const override {
391     return createPPCPostMachineScheduler(C);
392   }
393 };
394 
395 } // end anonymous namespace
396 
397 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
398   return new PPCPassConfig(*this, PM);
399 }
400 
401 void PPCPassConfig::addIRPasses() {
402   if (TM->getOptLevel() != CodeGenOpt::None)
403     addPass(createPPCBoolRetToIntPass());
404   addPass(createAtomicExpandPass());
405 
406   // Lower generic MASSV routines to PowerPC subtarget-specific entries.
407   addPass(createPPCLowerMASSVEntriesPass());
408 
409   // For the BG/Q (or if explicitly requested), add explicit data prefetch
410   // intrinsics.
411   bool UsePrefetching = TM->getTargetTriple().getVendor() == Triple::BGQ &&
412                         getOptLevel() != CodeGenOpt::None;
413   if (EnablePrefetch.getNumOccurrences() > 0)
414     UsePrefetching = EnablePrefetch;
415   if (UsePrefetching)
416     addPass(createLoopDataPrefetchPass());
417 
418   if (TM->getOptLevel() >= CodeGenOpt::Default && EnableGEPOpt) {
419     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
420     // and lower a GEP with multiple indices to either arithmetic operations or
421     // multiple GEPs with single index.
422     addPass(createSeparateConstOffsetFromGEPPass(true));
423     // Call EarlyCSE pass to find and remove subexpressions in the lowered
424     // result.
425     addPass(createEarlyCSEPass());
426     // Do loop invariant code motion in case part of the lowered result is
427     // invariant.
428     addPass(createLICMPass());
429   }
430 
431   TargetPassConfig::addIRPasses();
432 }
433 
434 bool PPCPassConfig::addPreISel() {
435   if (!DisableInstrFormPrep && getOptLevel() != CodeGenOpt::None)
436     addPass(createPPCLoopInstrFormPrepPass(getPPCTargetMachine()));
437 
438   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
439     addPass(createHardwareLoopsPass());
440 
441   return false;
442 }
443 
444 bool PPCPassConfig::addILPOpts() {
445   addPass(&EarlyIfConverterID);
446 
447   if (EnableMachineCombinerPass)
448     addPass(&MachineCombinerID);
449 
450   return true;
451 }
452 
453 bool PPCPassConfig::addInstSelector() {
454   // Install an instruction selector.
455   addPass(createPPCISelDag(getPPCTargetMachine(), getOptLevel()));
456 
457 #ifndef NDEBUG
458   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
459     addPass(createPPCCTRLoopsVerify());
460 #endif
461 
462   addPass(createPPCVSXCopyPass());
463   return false;
464 }
465 
466 void PPCPassConfig::addMachineSSAOptimization() {
467   // PPCBranchCoalescingPass need to be done before machine sinking
468   // since it merges empty blocks.
469   if (EnableBranchCoalescing && getOptLevel() != CodeGenOpt::None)
470     addPass(createPPCBranchCoalescingPass());
471   TargetPassConfig::addMachineSSAOptimization();
472   // For little endian, remove where possible the vector swap instructions
473   // introduced at code generation to normalize vector element order.
474   if (TM->getTargetTriple().getArch() == Triple::ppc64le &&
475       !DisableVSXSwapRemoval)
476     addPass(createPPCVSXSwapRemovalPass());
477   // Reduce the number of cr-logical ops.
478   if (ReduceCRLogical && getOptLevel() != CodeGenOpt::None)
479     addPass(createPPCReduceCRLogicalsPass());
480   // Target-specific peephole cleanups performed after instruction
481   // selection.
482   if (!DisableMIPeephole) {
483     addPass(createPPCMIPeepholePass());
484     addPass(&DeadMachineInstructionElimID);
485   }
486 }
487 
488 void PPCPassConfig::addPreRegAlloc() {
489   if (getOptLevel() != CodeGenOpt::None) {
490     initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
491     insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
492                &PPCVSXFMAMutateID);
493   }
494 
495   // FIXME: We probably don't need to run these for -fPIE.
496   if (getPPCTargetMachine().isPositionIndependent()) {
497     // FIXME: LiveVariables should not be necessary here!
498     // PPCTLSDynamicCallPass uses LiveIntervals which previously dependent on
499     // LiveVariables. This (unnecessary) dependency has been removed now,
500     // however a stage-2 clang build fails without LiveVariables computed here.
501     addPass(&LiveVariablesID, false);
502     addPass(createPPCTLSDynamicCallPass());
503   }
504   if (EnableExtraTOCRegDeps)
505     addPass(createPPCTOCRegDepsPass());
506 
507   if (getOptLevel() != CodeGenOpt::None)
508     addPass(&MachinePipelinerID);
509 }
510 
511 void PPCPassConfig::addPreSched2() {
512   if (getOptLevel() != CodeGenOpt::None) {
513     addPass(&IfConverterID);
514 
515     // This optimization must happen after anything that might do store-to-load
516     // forwarding. Here we're after RA (and, thus, when spills are inserted)
517     // but before post-RA scheduling.
518     if (!DisableQPXLoadSplat)
519       addPass(createPPCQPXLoadSplatPass());
520   }
521 }
522 
523 void PPCPassConfig::addPreEmitPass() {
524   addPass(createPPCPreEmitPeepholePass());
525   addPass(createPPCExpandISELPass());
526 
527   if (getOptLevel() != CodeGenOpt::None)
528     addPass(createPPCEarlyReturnPass(), false);
529   // Must run branch selection immediately preceding the asm printer.
530   addPass(createPPCBranchSelectionPass(), false);
531 }
532 
533 TargetTransformInfo
534 PPCTargetMachine::getTargetTransformInfo(const Function &F) {
535   return TargetTransformInfo(PPCTTIImpl(this, F));
536 }
537 
538 static MachineSchedRegistry
539 PPCPreRASchedRegistry("ppc-prera",
540                       "Run PowerPC PreRA specific scheduler",
541                       createPPCMachineScheduler);
542 
543 static MachineSchedRegistry
544 PPCPostRASchedRegistry("ppc-postra",
545                        "Run PowerPC PostRA specific scheduler",
546                        createPPCPostMachineScheduler);
547