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