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