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