Use the new script to sort the includes of every file under lib.
[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 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
66                                      StringRef CPU, StringRef FS,
67                                      TargetOptions Options,
68                                      Reloc::Model RM, CodeModel::Model CM,
69                                      CodeGenOpt::Level OL)
70   : TargetMachine(T, Triple, CPU, FS, Options) {
71   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
72   AsmInfo = T.createMCAsmInfo(Triple);
73   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
74   // and if the old one gets included then MCAsmInfo will be NULL and
75   // we'll crash later.
76   // Provide the user with a useful error message about what's wrong.
77   assert(AsmInfo && "MCAsmInfo not initialized."
78          "Make sure you include the correct TargetSelect.h"
79          "and that InitializeAllTargetMCs() is being invoked!");
80 }
81
82 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
83 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
84                                           PassManagerBase &PM,
85                                           bool DisableVerify,
86                                           AnalysisID StartAfter,
87                                           AnalysisID StopAfter) {
88   // Targets may override createPassConfig to provide a target-specific sublass.
89   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
90   PassConfig->setStartStopPasses(StartAfter, StopAfter);
91
92   // Set PassConfig options provided by TargetMachine.
93   PassConfig->setDisableVerify(DisableVerify);
94
95   PM.add(PassConfig);
96
97   PassConfig->addIRPasses();
98
99   PassConfig->addCodeGenPrepare();
100
101   PassConfig->addPassesToHandleExceptions();
102
103   PassConfig->addISelPrepare();
104
105   // Install a MachineModuleInfo class, which is an immutable pass that holds
106   // all the per-module stuff we're generating, including MCContext.
107   MachineModuleInfo *MMI =
108     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
109                           &TM->getTargetLowering()->getObjFileLowering());
110   PM.add(MMI);
111   MCContext *Context = &MMI->getContext(); // Return the MCContext by-ref.
112
113   // Set up a MachineFunction for the rest of CodeGen to work on.
114   PM.add(new MachineFunctionAnalysis(*TM));
115
116   // Enable FastISel with -fast, but allow that to be overridden.
117   if (EnableFastISelOption == cl::BOU_TRUE ||
118       (TM->getOptLevel() == CodeGenOpt::None &&
119        EnableFastISelOption != cl::BOU_FALSE))
120     TM->setFastISel(true);
121
122   // Ask the target for an isel.
123   if (PassConfig->addInstSelector())
124     return NULL;
125
126   PassConfig->addMachinePasses();
127
128   PassConfig->setInitialized();
129
130   return Context;
131 }
132
133 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
134                                             formatted_raw_ostream &Out,
135                                             CodeGenFileType FileType,
136                                             bool DisableVerify,
137                                             AnalysisID StartAfter,
138                                             AnalysisID StopAfter) {
139   // Add common CodeGen passes.
140   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
141                                                StartAfter, StopAfter);
142   if (!Context)
143     return true;
144
145   if (StopAfter) {
146     // FIXME: The intent is that this should eventually write out a YAML file,
147     // containing the LLVM IR, the machine-level IR (when stopping after a
148     // machine-level pass), and whatever other information is needed to
149     // deserialize the code and resume compilation.  For now, just write the
150     // LLVM IR.
151     PM.add(createPrintModulePass(&Out));
152     return false;
153   }
154
155   if (hasMCSaveTempLabels())
156     Context->setAllowTemporaryLabels(false);
157
158   const MCAsmInfo &MAI = *getMCAsmInfo();
159   const MCRegisterInfo &MRI = *getRegisterInfo();
160   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
161   OwningPtr<MCStreamer> AsmStreamer;
162
163   switch (FileType) {
164   case CGFT_AssemblyFile: {
165     MCInstPrinter *InstPrinter =
166       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
167                                       *getInstrInfo(),
168                                       Context->getRegisterInfo(), STI);
169
170     // Create a code emitter if asked to show the encoding.
171     MCCodeEmitter *MCE = 0;
172     MCAsmBackend *MAB = 0;
173     if (ShowMCEncoding) {
174       const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
175       MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI, STI,
176                                             *Context);
177       MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
178     }
179
180     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
181                                                   getVerboseAsm(),
182                                                   hasMCUseLoc(),
183                                                   hasMCUseCFI(),
184                                                   hasMCUseDwarfDirectory(),
185                                                   InstPrinter,
186                                                   MCE, MAB,
187                                                   ShowMCInst);
188     AsmStreamer.reset(S);
189     break;
190   }
191   case CGFT_ObjectFile: {
192     // Create the code emitter for the target if it exists.  If not, .o file
193     // emission fails.
194     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
195                                                          STI, *Context);
196     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(),
197                                                        TargetCPU);
198     if (MCE == 0 || MAB == 0)
199       return true;
200
201     AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
202                                                          *Context, *MAB, Out,
203                                                          MCE, hasMCRelaxAll(),
204                                                          hasMCNoExecStack()));
205     AsmStreamer.get()->InitSections();
206     break;
207   }
208   case CGFT_Null:
209     // The Null output is intended for use for performance analysis and testing,
210     // not real users.
211     AsmStreamer.reset(createNullStreamer(*Context));
212     break;
213   }
214
215   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
216   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
217   if (Printer == 0)
218     return true;
219
220   // If successful, createAsmPrinter took ownership of AsmStreamer.
221   AsmStreamer.take();
222
223   PM.add(Printer);
224
225   PM.add(createGCInfoDeleter());
226   return false;
227 }
228
229 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
230 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
231 /// actually outputting the machine code and resolving things like the address
232 /// of functions.  This method should returns true if machine code emission is
233 /// not supported.
234 ///
235 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
236                                                    JITCodeEmitter &JCE,
237                                                    bool DisableVerify) {
238   // Add common CodeGen passes.
239   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
240   if (!Context)
241     return true;
242
243   addCodeEmitter(PM, JCE);
244   PM.add(createGCInfoDeleter());
245
246   return false; // success!
247 }
248
249 /// addPassesToEmitMC - Add passes to the specified pass manager to get
250 /// machine code emitted with the MCJIT. This method returns true if machine
251 /// code is not supported. It fills the MCContext Ctx pointer which can be
252 /// used to build custom MCStreamer.
253 ///
254 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
255                                           MCContext *&Ctx,
256                                           raw_ostream &Out,
257                                           bool DisableVerify) {
258   // Add common CodeGen passes.
259   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
260   if (!Ctx)
261     return true;
262
263   if (hasMCSaveTempLabels())
264     Ctx->setAllowTemporaryLabels(false);
265
266   // Create the code emitter for the target if it exists.  If not, .o file
267   // emission fails.
268   const MCRegisterInfo &MRI = *getRegisterInfo();
269   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
270   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
271                                                        STI, *Ctx);
272   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
273   if (MCE == 0 || MAB == 0)
274     return true;
275
276   OwningPtr<MCStreamer> AsmStreamer;
277   AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
278                                                        *MAB, Out, MCE,
279                                                        hasMCRelaxAll(),
280                                                        hasMCNoExecStack()));
281   AsmStreamer.get()->InitSections();
282
283   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
284   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
285   if (Printer == 0)
286     return true;
287
288   // If successful, createAsmPrinter took ownership of AsmStreamer.
289   AsmStreamer.take();
290
291   PM.add(Printer);
292
293   return false; // success!
294 }