[mips] The naming convention for private labels is ABI dependant.
[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/Analysis/Passes.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/BasicTTIImpl.h"
18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/IR/IRPrintingPasses.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Transforms/Scalar.h"
36 using namespace llvm;
37
38 // Enable or disable FastISel. Both options are needed, because
39 // FastISel is enabled by default with -fast, and we wish to be
40 // able to enable or disable fast-isel independently from -O0.
41 static cl::opt<cl::boolOrDefault>
42 EnableFastISelOption("fast-isel", cl::Hidden,
43   cl::desc("Enable the \"fast\" instruction selector"));
44
45 void LLVMTargetMachine::initAsmInfo() {
46   MRI = TheTarget.createMCRegInfo(getTargetTriple());
47   MII = TheTarget.createMCInstrInfo();
48   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
49   // to some backends having subtarget feature dependent module level
50   // code generation. This is similar to the hack in the AsmPrinter for
51   // module level assembly etc.
52   STI = TheTarget.createMCSubtargetInfo(getTargetTriple(), getTargetCPU(),
53                                         getTargetFeatureString());
54
55   MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(*MRI, getTargetTriple());
56   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
57   // and if the old one gets included then MCAsmInfo will be NULL and
58   // we'll crash later.
59   // Provide the user with a useful error message about what's wrong.
60   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
61          "Make sure you include the correct TargetSelect.h"
62          "and that InitializeAllTargetMCs() is being invoked!");
63
64   if (Options.DisableIntegratedAS)
65     TmpAsmInfo->setUseIntegratedAssembler(false);
66
67   if (Options.CompressDebugSections)
68     TmpAsmInfo->setCompressDebugSections(true);
69
70   TmpAsmInfo->finishInit(*this);
71   AsmInfo = TmpAsmInfo;
72 }
73
74 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
75                                      StringRef DataLayoutString,
76                                      StringRef Triple, StringRef CPU,
77                                      StringRef FS, TargetOptions Options,
78                                      Reloc::Model RM, CodeModel::Model CM,
79                                      CodeGenOpt::Level OL)
80     : TargetMachine(T, DataLayoutString, Triple, CPU, FS, Options) {
81   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
82 }
83
84 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
85   return TargetIRAnalysis([this](Function &F) {
86     return TargetTransformInfo(BasicTTIImpl(this, F));
87   });
88 }
89
90 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
91 static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
92                                           PassManagerBase &PM,
93                                           bool DisableVerify,
94                                           AnalysisID StartAfter,
95                                           AnalysisID StopAfter) {
96
97   // Add internal analysis passes from the target machine.
98   PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
99
100   // Targets may override createPassConfig to provide a target-specific
101   // subclass.
102   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
103   PassConfig->setStartStopPasses(StartAfter, StopAfter);
104
105   // Set PassConfig options provided by TargetMachine.
106   PassConfig->setDisableVerify(DisableVerify);
107
108   PM.add(PassConfig);
109
110   PassConfig->addIRPasses();
111
112   PassConfig->addCodeGenPrepare();
113
114   PassConfig->addPassesToHandleExceptions();
115
116   PassConfig->addISelPrepare();
117
118   // Install a MachineModuleInfo class, which is an immutable pass that holds
119   // all the per-module stuff we're generating, including MCContext.
120   MachineModuleInfo *MMI = new MachineModuleInfo(
121       *TM->getMCAsmInfo(), *TM->getMCRegisterInfo(), TM->getObjFileLowering());
122   PM.add(MMI);
123
124   // Set up a MachineFunction for the rest of CodeGen to work on.
125   PM.add(new MachineFunctionAnalysis(*TM));
126
127   // Enable FastISel with -fast, but allow that to be overridden.
128   if (EnableFastISelOption == cl::BOU_TRUE ||
129       (TM->getOptLevel() == CodeGenOpt::None &&
130        EnableFastISelOption != cl::BOU_FALSE))
131     TM->setFastISel(true);
132
133   // Ask the target for an isel.
134   if (PassConfig->addInstSelector())
135     return nullptr;
136
137   PassConfig->addMachinePasses();
138
139   PassConfig->setInitialized();
140
141   return &MMI->getContext();
142 }
143
144 bool LLVMTargetMachine::addPassesToEmitFile(
145     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
146     bool DisableVerify, AnalysisID StartAfter, AnalysisID StopAfter) {
147   // Add common CodeGen passes.
148   MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
149                                                StartAfter, StopAfter);
150   if (!Context)
151     return true;
152
153   if (StopAfter) {
154     // FIXME: The intent is that this should eventually write out a YAML file,
155     // containing the LLVM IR, the machine-level IR (when stopping after a
156     // machine-level pass), and whatever other information is needed to
157     // deserialize the code and resume compilation.  For now, just write the
158     // LLVM IR.
159     PM.add(createPrintModulePass(Out));
160     return false;
161   }
162
163   if (Options.MCOptions.MCSaveTempLabels)
164     Context->setAllowTemporaryLabels(false);
165
166   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
167   const MCAsmInfo &MAI = *getMCAsmInfo();
168   const MCRegisterInfo &MRI = *getMCRegisterInfo();
169   const MCInstrInfo &MII = *getMCInstrInfo();
170
171   std::unique_ptr<MCStreamer> AsmStreamer;
172
173   switch (FileType) {
174   case CGFT_AssemblyFile: {
175     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
176         Triple(getTargetTriple()), MAI.getAssemblerDialect(), MAI, MII, MRI);
177
178     // Create a code emitter if asked to show the encoding.
179     MCCodeEmitter *MCE = nullptr;
180     if (Options.MCOptions.ShowMCEncoding)
181       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
182
183     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
184                                                        TargetCPU);
185     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
186     MCStreamer *S = getTarget().createAsmStreamer(
187         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
188         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
189         Options.MCOptions.ShowMCInst);
190     AsmStreamer.reset(S);
191     break;
192   }
193   case CGFT_ObjectFile: {
194     // Create the code emitter for the target if it exists.  If not, .o file
195     // emission fails.
196     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
197     MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
198                                                        TargetCPU);
199     if (!MCE || !MAB)
200       return true;
201
202     // Don't waste memory on names of temp labels.
203     Context->setUseNamesOnTempLabels(false);
204
205     Triple T(getTargetTriple());
206     AsmStreamer.reset(getTarget().createMCObjectStreamer(
207         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
208         /*DWARFMustBeAtTheEnd*/ true));
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(getTarget().createNullStreamer(*Context));
215     break;
216   }
217
218   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
219   FunctionPass *Printer =
220       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
221   if (!Printer)
222     return true;
223
224   PM.add(Printer);
225
226   return false;
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, MCContext *&Ctx,
235                                           raw_pwrite_stream &Out,
236                                           bool DisableVerify) {
237   // Add common CodeGen passes.
238   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr);
239   if (!Ctx)
240     return true;
241
242   if (Options.MCOptions.MCSaveTempLabels)
243     Ctx->setAllowTemporaryLabels(false);
244
245   // Create the code emitter for the target if it exists.  If not, .o file
246   // emission fails.
247   const MCRegisterInfo &MRI = *getMCRegisterInfo();
248   MCCodeEmitter *MCE =
249       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
250   MCAsmBackend *MAB = getTarget().createMCAsmBackend(MRI, getTargetTriple(),
251                                                      TargetCPU);
252   if (!MCE || !MAB)
253     return true;
254
255   Triple T(getTargetTriple());
256   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
257   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
258       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
259       /*DWARFMustBeAtTheEnd*/ true));
260
261   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
262   FunctionPass *Printer =
263       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
264   if (!Printer)
265     return true;
266
267   PM.add(Printer);
268
269   return false; // success!
270 }