Simplify some of the code. No functionality change.
[oota-llvm.git] / lib / CodeGen / LLVMTargetMachine.cpp
1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
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 // This file implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/ADT/OwningPtr.h"
16 #include "llvm/Assembly/PrintModulePass.h"
17 #include "llvm/CodeGen/AsmPrinter.h"
18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCInstrInfo.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include "llvm/Transforms/Scalar.h"
38 using namespace llvm;
39
40 // Enable or disable FastISel. Both options are needed, because
41 // FastISel is enabled by default with -fast, and we wish to be
42 // able to enable or disable fast-isel independently from -O0.
43 static cl::opt<cl::boolOrDefault>
44 EnableFastISelOption("fast-isel", cl::Hidden,
45   cl::desc("Enable the \"fast\" instruction selector"));
46
47 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
48     cl::desc("Show encoding in .s output"));
49 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
50     cl::desc("Show instruction structure in .s output"));
51
52 static cl::opt<cl::boolOrDefault>
53 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
54            cl::init(cl::BOU_UNSET));
55
56 static bool getVerboseAsm() {
57   switch (AsmVerbose) {
58   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
59   case cl::BOU_TRUE:  return true;
60   case cl::BOU_FALSE: return false;
61   }
62   llvm_unreachable("Invalid verbose asm state");
63 }
64
65 void LLVMTargetMachine::initAsmInfo() {
66   AsmInfo = TheTarget.createMCAsmInfo(*getRegisterInfo(), TargetTriple);
67   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
68   // and if the old one gets included then MCAsmInfo will be NULL and
69   // we'll crash later.
70   // Provide the user with a useful error message about what's wrong.
71   assert(AsmInfo && "MCAsmInfo not initialized. "
72          "Make sure you include the correct TargetSelect.h"
73          "and that InitializeAllTargetMCs() is being invoked!");
74 }
75
76 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
77                                      StringRef CPU, StringRef FS,
78                                      TargetOptions Options,
79                                      Reloc::Model RM, CodeModel::Model CM,
80                                      CodeGenOpt::Level OL)
81   : TargetMachine(T, Triple, CPU, FS, Options) {
82   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
83 }
84
85 void LLVMTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
86   PM.add(createBasicTargetTransformInfoPass(getTargetLowering()));
87 }
88
89 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
90 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
91                                           PassManagerBase &PM,
92                                           bool DisableVerify,
93                                           AnalysisID StartAfter,
94                                           AnalysisID StopAfter) {
95   // Targets may override createPassConfig to provide a target-specific sublass.
96   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
97   PassConfig->setStartStopPasses(StartAfter, StopAfter);
98
99   // Set PassConfig options provided by TargetMachine.
100   PassConfig->setDisableVerify(DisableVerify);
101
102   PM.add(PassConfig);
103
104   PassConfig->addIRPasses();
105
106   PassConfig->addCodeGenPrepare();
107
108   PassConfig->addPassesToHandleExceptions();
109
110   PassConfig->addISelPrepare();
111
112   // Install a MachineModuleInfo class, which is an immutable pass that holds
113   // all the per-module stuff we're generating, including MCContext.
114   MachineModuleInfo *MMI =
115     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
116                           &TM->getTargetLowering()->getObjFileLowering());
117   PM.add(MMI);
118   MCContext *Context = &MMI->getContext(); // Return the MCContext by-ref.
119
120   // Set up a MachineFunction for the rest of CodeGen to work on.
121   PM.add(new MachineFunctionAnalysis(*TM));
122
123   // Enable FastISel with -fast, but allow that to be overridden.
124   if (EnableFastISelOption == cl::BOU_TRUE ||
125       (TM->getOptLevel() == CodeGenOpt::None &&
126        EnableFastISelOption != cl::BOU_FALSE))
127     TM->setFastISel(true);
128
129   // Ask the target for an isel.
130   if (PassConfig->addInstSelector())
131     return NULL;
132
133   PassConfig->addMachinePasses();
134
135   PassConfig->setInitialized();
136
137   return Context;
138 }
139
140 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
141                                             formatted_raw_ostream &Out,
142                                             CodeGenFileType FileType,
143                                             bool DisableVerify,
144                                             AnalysisID StartAfter,
145                                             AnalysisID StopAfter) {
146   // Add common CodeGen passes.
147   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
148                                                StartAfter, StopAfter);
149   if (!Context)
150     return true;
151
152   if (StopAfter) {
153     // FIXME: The intent is that this should eventually write out a YAML file,
154     // containing the LLVM IR, the machine-level IR (when stopping after a
155     // machine-level pass), and whatever other information is needed to
156     // deserialize the code and resume compilation.  For now, just write the
157     // LLVM IR.
158     PM.add(createPrintModulePass(&Out));
159     return false;
160   }
161
162   if (hasMCSaveTempLabels())
163     Context->setAllowTemporaryLabels(false);
164
165   const MCAsmInfo &MAI = *getMCAsmInfo();
166   const MCRegisterInfo &MRI = *getRegisterInfo();
167   const MCInstrInfo &MII = *getInstrInfo();
168   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
169   OwningPtr<MCStreamer> AsmStreamer;
170
171   switch (FileType) {
172   case CGFT_AssemblyFile: {
173     MCInstPrinter *InstPrinter =
174       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
175                                       MII, MRI, STI);
176
177     // Create a code emitter if asked to show the encoding.
178     MCCodeEmitter *MCE = 0;
179     MCAsmBackend *MAB = 0;
180     if (ShowMCEncoding) {
181       MCE = getTarget().createMCCodeEmitter(MII, MRI, STI, *Context);
182       MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
183     }
184
185     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
186                                                   getVerboseAsm(),
187                                                   hasMCUseLoc(),
188                                                   hasMCUseCFI(),
189                                                   hasMCUseDwarfDirectory(),
190                                                   InstPrinter,
191                                                   MCE, MAB,
192                                                   ShowMCInst);
193     AsmStreamer.reset(S);
194     break;
195   }
196   case CGFT_ObjectFile: {
197     // Create the code emitter for the target if it exists.  If not, .o file
198     // emission fails.
199     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, STI,
200                                                          *Context);
201     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(),
202                                                        TargetCPU);
203     if (MCE == 0 || MAB == 0)
204       return true;
205
206     AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
207                                                          *Context, *MAB, Out,
208                                                          MCE, hasMCRelaxAll(),
209                                                          hasMCNoExecStack()));
210     AsmStreamer.get()->setAutoInitSections(true);
211     break;
212   }
213   case CGFT_Null:
214     // The Null output is intended for use for performance analysis and testing,
215     // not real users.
216     AsmStreamer.reset(createNullStreamer(*Context));
217     break;
218   }
219
220   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
221   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
222   if (Printer == 0)
223     return true;
224
225   // If successful, createAsmPrinter took ownership of AsmStreamer.
226   AsmStreamer.take();
227
228   PM.add(Printer);
229
230   return false;
231 }
232
233 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
234 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
235 /// actually outputting the machine code and resolving things like the address
236 /// of functions.  This method should returns true if machine code emission is
237 /// not supported.
238 ///
239 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
240                                                    JITCodeEmitter &JCE,
241                                                    bool DisableVerify) {
242   // Add common CodeGen passes.
243   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
244   if (!Context)
245     return true;
246
247   addCodeEmitter(PM, JCE);
248
249   return false; // success!
250 }
251
252 /// addPassesToEmitMC - Add passes to the specified pass manager to get
253 /// machine code emitted with the MCJIT. This method returns true if machine
254 /// code is not supported. It fills the MCContext Ctx pointer which can be
255 /// used to build custom MCStreamer.
256 ///
257 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
258                                           MCContext *&Ctx,
259                                           raw_ostream &Out,
260                                           bool DisableVerify) {
261   // Add common CodeGen passes.
262   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
263   if (!Ctx)
264     return true;
265
266   if (hasMCSaveTempLabels())
267     Ctx->setAllowTemporaryLabels(false);
268
269   // Create the code emitter for the target if it exists.  If not, .o file
270   // emission fails.
271   const MCRegisterInfo &MRI = *getRegisterInfo();
272   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
273   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
274                                                        STI, *Ctx);
275   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
276   if (MCE == 0 || MAB == 0)
277     return true;
278
279   OwningPtr<MCStreamer> AsmStreamer;
280   AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
281                                                        *MAB, Out, MCE,
282                                                        hasMCRelaxAll(),
283                                                        hasMCNoExecStack()));
284   AsmStreamer.get()->InitSections();
285
286   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
287   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
288   if (Printer == 0)
289     return true;
290
291   // If successful, createAsmPrinter took ownership of AsmStreamer.
292   AsmStreamer.take();
293
294   PM.add(Printer);
295
296   return false; // success!
297 }