Move ABI handling and 64-bitness to the PowerPC target machine.
[oota-llvm.git] / lib / Target / PowerPC / PPCTargetMachine.cpp
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 "PPC.h"
16 #include "PPCTargetObjectFile.h"
17 #include "PPCTargetTransformInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/LegacyPassManager.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/Transforms/Scalar.h"
27 using namespace llvm;
28
29 static cl::
30 opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden,
31                         cl::desc("Disable CTR loops for PPC"));
32
33 static cl::
34 opt<bool> DisablePreIncPrep("disable-ppc-preinc-prep", cl::Hidden,
35                             cl::desc("Disable PPC loop preinc prep"));
36
37 static cl::opt<bool>
38 VSXFMAMutateEarly("schedule-ppc-vsx-fma-mutation-early",
39   cl::Hidden, cl::desc("Schedule VSX FMA instruction mutation early"));
40
41 static cl::opt<bool>
42 EnableGEPOpt("ppc-gep-opt", cl::Hidden,
43              cl::desc("Enable optimizations on complex GEPs"),
44              cl::init(true));
45
46 extern "C" void LLVMInitializePowerPCTarget() {
47   // Register the targets
48   RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target);
49   RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target);
50   RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget);
51 }
52
53 /// Return the datalayout string of a subtarget.
54 static std::string getDataLayoutString(const Triple &T) {
55   bool is64Bit = T.getArch() == Triple::ppc64 || T.getArch() == Triple::ppc64le;
56   std::string Ret;
57
58   // Most PPC* platforms are big endian, PPC64LE is little endian.
59   if (T.getArch() == Triple::ppc64le)
60     Ret = "e";
61   else
62     Ret = "E";
63
64   Ret += DataLayout::getManglingComponent(T);
65
66   // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit
67   // pointers.
68   if (!is64Bit || T.getOS() == Triple::Lv2)
69     Ret += "-p:32:32";
70
71   // Note, the alignment values for f64 and i64 on ppc64 in Darwin
72   // documentation are wrong; these are correct (i.e. "what gcc does").
73   if (is64Bit || !T.isOSDarwin())
74     Ret += "-i64:64";
75   else
76     Ret += "-f64:32:64";
77
78   // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones.
79   if (is64Bit)
80     Ret += "-n32:64";
81   else
82     Ret += "-n32";
83
84   return Ret;
85 }
86
87 static std::string computeFSAdditions(StringRef FS, CodeGenOpt::Level OL, StringRef TT) {
88   std::string FullFS = FS;
89   Triple TargetTriple(TT);
90
91   // Make sure 64-bit features are available when CPUname is generic
92   if (TargetTriple.getArch() == Triple::ppc64 ||
93       TargetTriple.getArch() == Triple::ppc64le) {
94     if (!FullFS.empty())
95       FullFS = "+64bit," + FullFS;
96     else
97       FullFS = "+64bit";
98   }
99
100   if (OL >= CodeGenOpt::Default) {
101     if (!FullFS.empty())
102       FullFS = "+crbits," + FullFS;
103     else
104       FullFS = "+crbits";
105   }
106
107   if (OL != CodeGenOpt::None) {
108      if (!FullFS.empty())
109       FullFS = "+invariant-function-descriptors," + FullFS;
110     else
111       FullFS = "+invariant-function-descriptors";
112   }
113
114   return FullFS;
115 }
116
117 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
118   // If it isn't a Mach-O file then it's going to be a linux ELF
119   // object file.
120   if (TT.isOSDarwin())
121     return make_unique<TargetLoweringObjectFileMachO>();
122
123   return make_unique<PPC64LinuxTargetObjectFile>();
124 }
125
126 static PPCTargetMachine::PPCABI computeTargetABI(const Triple &TT,
127                                                  const TargetOptions &Options) {
128   if (Options.MCOptions.getABIName().startswith("elfv1"))
129     return PPCTargetMachine::PPC_ABI_ELFv1;
130   else if (Options.MCOptions.getABIName().startswith("elfv2"))
131     return PPCTargetMachine::PPC_ABI_ELFv2;
132
133   assert(Options.MCOptions.getABIName().empty() &&
134          "Unknown target-abi option!");
135
136   if (!TT.isMacOSX()) {
137     switch (TT.getArch()) {
138     case Triple::ppc64le:
139       return PPCTargetMachine::PPC_ABI_ELFv2;
140     case Triple::ppc64:
141       return PPCTargetMachine::PPC_ABI_ELFv1;
142     default:
143       // Fallthrough.
144       ;
145     }
146   }
147   return PPCTargetMachine::PPC_ABI_UNKNOWN;
148 }
149
150 // The FeatureString here is a little subtle. We are modifying the feature string
151 // with what are (currently) non-function specific overrides as it goes into the
152 // LLVMTargetMachine constructor and then using the stored value in the
153 // Subtarget constructor below it.
154 PPCTargetMachine::PPCTargetMachine(const Target &T, StringRef TT, StringRef CPU,
155                                    StringRef FS, const TargetOptions &Options,
156                                    Reloc::Model RM, CodeModel::Model CM,
157                                    CodeGenOpt::Level OL)
158     : LLVMTargetMachine(T, TT, CPU, computeFSAdditions(FS, OL, TT), Options, RM,
159                         CM, OL),
160       TLOF(createTLOF(Triple(getTargetTriple()))),
161       TargetABI(computeTargetABI(Triple(TT), Options)),
162       DL(getDataLayoutString(Triple(TT))), Subtarget(TT, CPU, TargetFS, *this) {
163   initAsmInfo();
164 }
165
166 PPCTargetMachine::~PPCTargetMachine() {}
167
168 void PPC32TargetMachine::anchor() { }
169
170 PPC32TargetMachine::PPC32TargetMachine(const Target &T, StringRef TT,
171                                        StringRef CPU, StringRef FS,
172                                        const TargetOptions &Options,
173                                        Reloc::Model RM, CodeModel::Model CM,
174                                        CodeGenOpt::Level OL)
175   : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
176 }
177
178 void PPC64TargetMachine::anchor() { }
179
180 PPC64TargetMachine::PPC64TargetMachine(const Target &T, StringRef TT,
181                                        StringRef CPU,  StringRef FS,
182                                        const TargetOptions &Options,
183                                        Reloc::Model RM, CodeModel::Model CM,
184                                        CodeGenOpt::Level OL)
185   : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL) {
186 }
187
188 const PPCSubtarget *
189 PPCTargetMachine::getSubtargetImpl(const Function &F) const {
190   Attribute CPUAttr = F.getFnAttribute("target-cpu");
191   Attribute FSAttr = F.getFnAttribute("target-features");
192
193   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
194                         ? CPUAttr.getValueAsString().str()
195                         : TargetCPU;
196   std::string FS = !FSAttr.hasAttribute(Attribute::None)
197                        ? FSAttr.getValueAsString().str()
198                        : TargetFS;
199
200   auto &I = SubtargetMap[CPU + FS];
201   if (!I) {
202     // This needs to be done before we create a new subtarget since any
203     // creation will depend on the TM and the code generation flags on the
204     // function that reside in TargetOptions.
205     resetTargetOptions(F);
206     I = llvm::make_unique<PPCSubtarget>(TargetTriple, CPU, FS, *this);
207   }
208   return I.get();
209 }
210
211 //===----------------------------------------------------------------------===//
212 // Pass Pipeline Configuration
213 //===----------------------------------------------------------------------===//
214
215 namespace {
216 /// PPC Code Generator Pass Configuration Options.
217 class PPCPassConfig : public TargetPassConfig {
218 public:
219   PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM)
220     : TargetPassConfig(TM, PM) {}
221
222   PPCTargetMachine &getPPCTargetMachine() const {
223     return getTM<PPCTargetMachine>();
224   }
225
226   void addIRPasses() override;
227   bool addPreISel() override;
228   bool addILPOpts() override;
229   bool addInstSelector() override;
230   void addPreRegAlloc() override;
231   void addPreSched2() override;
232   void addPreEmitPass() override;
233 };
234 } // namespace
235
236 TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) {
237   return new PPCPassConfig(this, PM);
238 }
239
240 void PPCPassConfig::addIRPasses() {
241   addPass(createAtomicExpandPass(&getPPCTargetMachine()));
242
243   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
244     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
245     // and lower a GEP with multiple indices to either arithmetic operations or
246     // multiple GEPs with single index.
247     addPass(createSeparateConstOffsetFromGEPPass(TM, true));
248     // Call EarlyCSE pass to find and remove subexpressions in the lowered
249     // result.
250     addPass(createEarlyCSEPass());
251     // Do loop invariant code motion in case part of the lowered result is
252     // invariant.
253     addPass(createLICMPass());
254   }
255
256   TargetPassConfig::addIRPasses();
257 }
258
259 bool PPCPassConfig::addPreISel() {
260   if (!DisablePreIncPrep && getOptLevel() != CodeGenOpt::None)
261     addPass(createPPCLoopPreIncPrepPass(getPPCTargetMachine()));
262
263   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
264     addPass(createPPCCTRLoops(getPPCTargetMachine()));
265
266   return false;
267 }
268
269 bool PPCPassConfig::addILPOpts() {
270   addPass(&EarlyIfConverterID);
271   return true;
272 }
273
274 bool PPCPassConfig::addInstSelector() {
275   // Install an instruction selector.
276   addPass(createPPCISelDag(getPPCTargetMachine()));
277
278 #ifndef NDEBUG
279   if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None)
280     addPass(createPPCCTRLoopsVerify());
281 #endif
282
283   addPass(createPPCVSXCopyPass());
284   return false;
285 }
286
287 void PPCPassConfig::addPreRegAlloc() {
288   initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
289   insertPass(VSXFMAMutateEarly ? &RegisterCoalescerID : &MachineSchedulerID,
290              &PPCVSXFMAMutateID);
291   if (getPPCTargetMachine().getRelocationModel() == Reloc::PIC_)
292     addPass(createPPCTLSDynamicCallPass());
293 }
294
295 void PPCPassConfig::addPreSched2() {
296   if (getOptLevel() != CodeGenOpt::None)
297     addPass(&IfConverterID);
298 }
299
300 void PPCPassConfig::addPreEmitPass() {
301   if (getOptLevel() != CodeGenOpt::None)
302     addPass(createPPCEarlyReturnPass(), false);
303   // Must run branch selection immediately preceding the asm printer.
304   addPass(createPPCBranchSelectionPass(), false);
305 }
306
307 TargetIRAnalysis PPCTargetMachine::getTargetIRAnalysis() {
308   return TargetIRAnalysis(
309       [this](Function &F) { return TargetTransformInfo(PPCTTIImpl(this, F)); });
310 }