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