TargetPassConfig: confine the MC configuration to TargetMachine.
[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 /// Turn exception handling constructs into something the code generators can
82 /// handle.
83 static void addPassesToHandleExceptions(TargetMachine *TM,
84                                         PassManagerBase &PM) {
85   switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
86   case ExceptionHandling::SjLj:
87     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
88     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
89     // catch info can get misplaced when a selector ends up more than one block
90     // removed from the parent invoke(s). This could happen when a landing
91     // pad is shared by multiple invokes and is also a target of a normal
92     // edge from elsewhere.
93     PM.add(createSjLjEHPass(TM->getTargetLowering()));
94     // FALLTHROUGH
95   case ExceptionHandling::DwarfCFI:
96   case ExceptionHandling::ARM:
97   case ExceptionHandling::Win64:
98     PM.add(createDwarfEHPass(TM));
99     break;
100   case ExceptionHandling::None:
101     PM.add(createLowerInvokePass(TM->getTargetLowering()));
102
103     // The lower invoke pass may create unreachable code. Remove it.
104     PM.add(createUnreachableBlockEliminationPass());
105     break;
106   }
107 }
108
109 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
110 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
111                                           PassManagerBase &PM,
112                                           bool DisableVerify) {
113   // Targets may override createPassConfig to provide a target-specific sublass.
114   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
115
116   // Set PassConfig options provided by TargetMachine.
117   PassConfig->setDisableVerify(DisableVerify);
118
119   PassConfig->addIRPasses();
120
121   addPassesToHandleExceptions(TM, PM);
122
123   PassConfig->addISelPrepare();
124
125   // Install a MachineModuleInfo class, which is an immutable pass that holds
126   // all the per-module stuff we're generating, including MCContext.
127   MachineModuleInfo *MMI =
128     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
129                           &TM->getTargetLowering()->getObjFileLowering());
130   PM.add(MMI);
131   MCContext *Context = &MMI->getContext(); // Return the MCContext specifically by-ref.
132
133   // Set up a MachineFunction for the rest of CodeGen to work on.
134   PM.add(new MachineFunctionAnalysis(*TM));
135
136   // Enable FastISel with -fast, but allow that to be overridden.
137   if (EnableFastISelOption == cl::BOU_TRUE ||
138       (TM->getOptLevel() == CodeGenOpt::None &&
139        EnableFastISelOption != cl::BOU_FALSE))
140     TM->setFastISel(true);
141
142   // Ask the target for an isel.
143   if (PassConfig->addInstSelector())
144     return NULL;
145
146   PassConfig->addMachinePasses();
147
148   return Context;
149 }
150
151 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
152                                             formatted_raw_ostream &Out,
153                                             CodeGenFileType FileType,
154                                             bool DisableVerify) {
155   // Add common CodeGen passes.
156   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify);
157   if (!Context)
158     return true;
159
160   if (hasMCSaveTempLabels())
161     Context->setAllowTemporaryLabels(false);
162
163   const MCAsmInfo &MAI = *getMCAsmInfo();
164   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
165   OwningPtr<MCStreamer> AsmStreamer;
166
167   switch (FileType) {
168   case CGFT_AssemblyFile: {
169     MCInstPrinter *InstPrinter =
170       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
171
172     // Create a code emitter if asked to show the encoding.
173     MCCodeEmitter *MCE = 0;
174     MCAsmBackend *MAB = 0;
175     if (ShowMCEncoding) {
176       const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
177       MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
178       MAB = getTarget().createMCAsmBackend(getTargetTriple());
179     }
180
181     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
182                                                   getVerboseAsm(),
183                                                   hasMCUseLoc(),
184                                                   hasMCUseCFI(),
185                                                   hasMCUseDwarfDirectory(),
186                                                   InstPrinter,
187                                                   MCE, MAB,
188                                                   ShowMCInst);
189     AsmStreamer.reset(S);
190     break;
191   }
192   case CGFT_ObjectFile: {
193     // Create the code emitter for the target if it exists.  If not, .o file
194     // emission fails.
195     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
196                                                          *Context);
197     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
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);
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);
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 MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
269   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
270   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
271   if (MCE == 0 || MAB == 0)
272     return true;
273
274   OwningPtr<MCStreamer> AsmStreamer;
275   AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
276                                                        *MAB, Out, MCE,
277                                                        hasMCRelaxAll(),
278                                                        hasMCNoExecStack()));
279   AsmStreamer.get()->InitSections();
280
281   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
282   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
283   if (Printer == 0)
284     return true;
285
286   // If successful, createAsmPrinter took ownership of AsmStreamer.
287   AsmStreamer.take();
288
289   PM.add(Printer);
290
291   return false; // success!
292 }