Fix typos.
[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/CodeGen/AsmPrinter.h"
16 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
17 #include "llvm/CodeGen/MachineModuleInfo.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/IRPrintingPasses.h"
20 #include "llvm/MC/MCAsmInfo.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSubtargetInfo.h"
25 #include "llvm/PassManager.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
36 #include "llvm/Transforms/Scalar.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<cl::boolOrDefault>
47 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
48            cl::init(cl::BOU_UNSET));
49
50 static bool getVerboseAsm() {
51   switch (AsmVerbose) {
52   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
53   case cl::BOU_TRUE:  return true;
54   case cl::BOU_FALSE: return false;
55   }
56   llvm_unreachable("Invalid verbose asm state");
57 }
58
59 void LLVMTargetMachine::initAsmInfo() {
60   MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(*getRegisterInfo(),
61                                                     TargetTriple);
62   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
63   // and if the old one gets included then MCAsmInfo will be NULL and
64   // we'll crash later.
65   // Provide the user with a useful error message about what's wrong.
66   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
67          "Make sure you include the correct TargetSelect.h"
68          "and that InitializeAllTargetMCs() is being invoked!");
69
70   if (Options.DisableIntegratedAS)
71     TmpAsmInfo->setUseIntegratedAssembler(false);
72
73   if (Options.CompressDebugSections)
74     TmpAsmInfo->setCompressDebugSections(true);
75
76   AsmInfo = TmpAsmInfo;
77 }
78
79 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
80                                      StringRef CPU, StringRef FS,
81                                      TargetOptions Options,
82                                      Reloc::Model RM, CodeModel::Model CM,
83                                      CodeGenOpt::Level OL)
84   : TargetMachine(T, Triple, CPU, FS, Options) {
85   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
86 }
87
88 void LLVMTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
89   PM.add(createBasicTargetTransformInfoPass(this));
90 }
91
92 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
93 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
94                                           PassManagerBase &PM,
95                                           bool DisableVerify,
96                                           AnalysisID StartAfter,
97                                           AnalysisID StopAfter) {
98   // Add internal analysis passes from the target machine.
99   TM->addAnalysisPasses(PM);
100
101   // Targets may override createPassConfig to provide a target-specific
102   // subclass.
103   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
104   PassConfig->setStartStopPasses(StartAfter, StopAfter);
105
106   // Set PassConfig options provided by TargetMachine.
107   PassConfig->setDisableVerify(DisableVerify);
108
109   PM.add(PassConfig);
110
111   PassConfig->addIRPasses();
112
113   PassConfig->addCodeGenPrepare();
114
115   PassConfig->addPassesToHandleExceptions();
116
117   PassConfig->addISelPrepare();
118
119   // Install a MachineModuleInfo class, which is an immutable pass that holds
120   // all the per-module stuff we're generating, including MCContext.
121   MachineModuleInfo *MMI =
122     new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
123                           &TM->getTargetLowering()->getObjFileLowering());
124   PM.add(MMI);
125
126   // Set up a MachineFunction for the rest of CodeGen to work on.
127   PM.add(new MachineFunctionAnalysis(*TM));
128
129   // Enable FastISel with -fast, but allow that to be overridden.
130   if (EnableFastISelOption == cl::BOU_TRUE ||
131       (TM->getOptLevel() == CodeGenOpt::None &&
132        EnableFastISelOption != cl::BOU_FALSE))
133     TM->setFastISel(true);
134
135   // Ask the target for an isel.
136   if (PassConfig->addInstSelector())
137     return nullptr;
138
139   PassConfig->addMachinePasses();
140
141   PassConfig->setInitialized();
142
143   return &MMI->getContext();
144 }
145
146 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
147                                             formatted_raw_ostream &Out,
148                                             CodeGenFileType FileType,
149                                             bool DisableVerify,
150                                             AnalysisID StartAfter,
151                                             AnalysisID StopAfter) {
152   // Add common CodeGen passes.
153   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
154                                                StartAfter, StopAfter);
155   if (!Context)
156     return true;
157
158   if (StopAfter) {
159     // FIXME: The intent is that this should eventually write out a YAML file,
160     // containing the LLVM IR, the machine-level IR (when stopping after a
161     // machine-level pass), and whatever other information is needed to
162     // deserialize the code and resume compilation.  For now, just write the
163     // LLVM IR.
164     PM.add(createPrintModulePass(Out));
165     return false;
166   }
167
168   if (Options.MCOptions.MCSaveTempLabels)
169     Context->setAllowTemporaryLabels(false);
170
171   const MCAsmInfo &MAI = *getMCAsmInfo();
172   const MCRegisterInfo &MRI = *getRegisterInfo();
173   const MCInstrInfo &MII = *getInstrInfo();
174   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
175   std::unique_ptr<MCStreamer> AsmStreamer;
176
177   switch (FileType) {
178   case CGFT_AssemblyFile: {
179     MCInstPrinter *InstPrinter =
180       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
181                                       MII, MRI, STI);
182
183     // Create a code emitter if asked to show the encoding.
184     MCCodeEmitter *MCE = nullptr;
185     if (Options.MCOptions.ShowMCEncoding)
186       MCE = getTarget().createMCCodeEmitter(MII, MRI, STI, *Context);
187
188     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
189                                                        TargetCPU);
190     MCStreamer *S = getTarget().createAsmStreamer(
191         *Context, Out, getVerboseAsm(), Options.MCOptions.MCUseDwarfDirectory,
192         InstPrinter, MCE, MAB, Options.MCOptions.ShowMCInst);
193     AsmStreamer.reset(S);
194     break;
195   }
196   case CGFT_ObjectFile: {
197     // Create the code emitter for the target if it exists.  If not, .o file
198     // emission fails.
199     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, STI,
200                                                          *Context);
201     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
202                                                        TargetCPU);
203     if (!MCE || !MAB)
204       return true;
205
206     AsmStreamer.reset(getTarget().createMCObjectStreamer(
207         getTargetTriple(), *Context, *MAB, Out, MCE, STI,
208         Options.MCOptions.MCRelaxAll, Options.MCOptions.MCNoExecStack));
209     break;
210   }
211   case CGFT_Null:
212     // The Null output is intended for use for performance analysis and testing,
213     // not real users.
214     AsmStreamer.reset(createNullStreamer(*Context));
215     break;
216   }
217
218   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
219   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
220   if (!Printer)
221     return true;
222
223   // If successful, createAsmPrinter took ownership of AsmStreamer.
224   AsmStreamer.release();
225
226   PM.add(Printer);
227
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 return 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, nullptr,
242                                                nullptr);
243   if (!Context)
244     return true;
245
246   addCodeEmitter(PM, JCE);
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, nullptr, nullptr);
262   if (!Ctx)
263     return true;
264
265   if (Options.MCOptions.MCSaveTempLabels)
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 MCRegisterInfo &MRI = *getRegisterInfo();
271   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
272   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
273                                                        STI, *Ctx);
274   MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
275                                                      TargetCPU);
276   if (!MCE || !MAB)
277     return true;
278
279   std::unique_ptr<MCStreamer> AsmStreamer;
280   AsmStreamer.reset(getTarget().createMCObjectStreamer(
281       getTargetTriple(), *Ctx, *MAB, Out, MCE, STI,
282       Options.MCOptions.MCRelaxAll, Options.MCOptions.MCNoExecStack));
283
284   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
285   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
286   if (!Printer)
287     return true;
288
289   // If successful, createAsmPrinter took ownership of AsmStreamer.
290   AsmStreamer.release();
291
292   PM.add(Printer);
293
294   return false; // success!
295 }