Add TargetPassConfig to the PassManager for use inside passes
[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   PM.add(PassConfig);
120
121   PassConfig->addIRPasses();
122
123   addPassesToHandleExceptions(TM, PM);
124
125   PassConfig->addISelPrepare();
126
127   // Install a MachineModuleInfo class, which is an immutable pass that holds
128   // all the per-module stuff we're generating, including MCContext.
129   MachineModuleInfo *MMI =
130     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
131                           &TM->getTargetLowering()->getObjFileLowering());
132   PM.add(MMI);
133   MCContext *Context = &MMI->getContext(); // Return the MCContext specifically by-ref.
134
135   // Set up a MachineFunction for the rest of CodeGen to work on.
136   PM.add(new MachineFunctionAnalysis(*TM));
137
138   // Enable FastISel with -fast, but allow that to be overridden.
139   if (EnableFastISelOption == cl::BOU_TRUE ||
140       (TM->getOptLevel() == CodeGenOpt::None &&
141        EnableFastISelOption != cl::BOU_FALSE))
142     TM->setFastISel(true);
143
144   // Ask the target for an isel.
145   if (PassConfig->addInstSelector())
146     return NULL;
147
148   PassConfig->addMachinePasses();
149
150   return Context;
151 }
152
153 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
154                                             formatted_raw_ostream &Out,
155                                             CodeGenFileType FileType,
156                                             bool DisableVerify) {
157   // Add common CodeGen passes.
158   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify);
159   if (!Context)
160     return true;
161
162   if (hasMCSaveTempLabels())
163     Context->setAllowTemporaryLabels(false);
164
165   const MCAsmInfo &MAI = *getMCAsmInfo();
166   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
167   OwningPtr<MCStreamer> AsmStreamer;
168
169   switch (FileType) {
170   case CGFT_AssemblyFile: {
171     MCInstPrinter *InstPrinter =
172       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
173
174     // Create a code emitter if asked to show the encoding.
175     MCCodeEmitter *MCE = 0;
176     MCAsmBackend *MAB = 0;
177     if (ShowMCEncoding) {
178       const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
179       MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
180       MAB = getTarget().createMCAsmBackend(getTargetTriple());
181     }
182
183     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
184                                                   getVerboseAsm(),
185                                                   hasMCUseLoc(),
186                                                   hasMCUseCFI(),
187                                                   hasMCUseDwarfDirectory(),
188                                                   InstPrinter,
189                                                   MCE, MAB,
190                                                   ShowMCInst);
191     AsmStreamer.reset(S);
192     break;
193   }
194   case CGFT_ObjectFile: {
195     // Create the code emitter for the target if it exists.  If not, .o file
196     // emission fails.
197     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
198                                                          *Context);
199     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
200     if (MCE == 0 || MAB == 0)
201       return true;
202
203     AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
204                                                          *Context, *MAB, Out,
205                                                          MCE, hasMCRelaxAll(),
206                                                          hasMCNoExecStack()));
207     AsmStreamer.get()->InitSections();
208     break;
209   }
210   case CGFT_Null:
211     // The Null output is intended for use for performance analysis and testing,
212     // not real users.
213     AsmStreamer.reset(createNullStreamer(*Context));
214     break;
215   }
216
217   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
218   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
219   if (Printer == 0)
220     return true;
221
222   // If successful, createAsmPrinter took ownership of AsmStreamer.
223   AsmStreamer.take();
224
225   PM.add(Printer);
226
227   PM.add(createGCInfoDeleter());
228   return false;
229 }
230
231 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
232 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
233 /// actually outputting the machine code and resolving things like the address
234 /// of functions.  This method should returns true if machine code emission is
235 /// not supported.
236 ///
237 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
238                                                    JITCodeEmitter &JCE,
239                                                    bool DisableVerify) {
240   // Add common CodeGen passes.
241   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify);
242   if (!Context)
243     return true;
244
245   addCodeEmitter(PM, JCE);
246   PM.add(createGCInfoDeleter());
247
248   return false; // success!
249 }
250
251 /// addPassesToEmitMC - Add passes to the specified pass manager to get
252 /// machine code emitted with the MCJIT. This method returns true if machine
253 /// code is not supported. It fills the MCContext Ctx pointer which can be
254 /// used to build custom MCStreamer.
255 ///
256 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
257                                           MCContext *&Ctx,
258                                           raw_ostream &Out,
259                                           bool DisableVerify) {
260   // Add common CodeGen passes.
261   Ctx = addPassesToGenerateCode(this, PM, DisableVerify);
262   if (!Ctx)
263     return true;
264
265   if (hasMCSaveTempLabels())
266     Ctx->setAllowTemporaryLabels(false);
267
268   // Create the code emitter for the target if it exists.  If not, .o file
269   // emission fails.
270   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
271   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
272   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
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 }