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