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