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