]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/LLVMTargetMachine.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303571, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/MachineModuleInfo.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/TargetPassConfig.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 static cl::opt<cl::boolOrDefault>
46     EnableGlobalISel("global-isel", cl::Hidden,
47                      cl::desc("Enable the \"global\" instruction selector"));
48
49 void LLVMTargetMachine::initAsmInfo() {
50   MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
51   MII = TheTarget.createMCInstrInfo();
52   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
53   // to some backends having subtarget feature dependent module level
54   // code generation. This is similar to the hack in the AsmPrinter for
55   // module level assembly etc.
56   STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
57                                         getTargetFeatureString());
58
59   MCAsmInfo *TmpAsmInfo =
60       TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
61   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
62   // and if the old one gets included then MCAsmInfo will be NULL and
63   // we'll crash later.
64   // Provide the user with a useful error message about what's wrong.
65   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
66          "Make sure you include the correct TargetSelect.h"
67          "and that InitializeAllTargetMCs() is being invoked!");
68
69   if (Options.DisableIntegratedAS)
70     TmpAsmInfo->setUseIntegratedAssembler(false);
71
72   TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
73
74   if (Options.CompressDebugSections)
75     TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
76
77   TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
78
79   if (Options.ExceptionModel != ExceptionHandling::None)
80     TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
81
82   AsmInfo = TmpAsmInfo;
83 }
84
85 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
86                                      StringRef DataLayoutString,
87                                      const Triple &TT, StringRef CPU,
88                                      StringRef FS, const TargetOptions &Options,
89                                      Reloc::Model RM, CodeModel::Model CM,
90                                      CodeGenOpt::Level OL)
91     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
92   T.adjustCodeGenOpts(TT, RM, CM);
93   this->RM = RM;
94   this->CMModel = CM;
95   this->OptLevel = OL;
96 }
97
98 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
99   return TargetIRAnalysis([this](const Function &F) {
100     return TargetTransformInfo(BasicTTIImpl(this, F));
101   });
102 }
103
104 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
105 static MCContext *
106 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
107                         bool DisableVerify, AnalysisID StartBefore,
108                         AnalysisID StartAfter, AnalysisID StopBefore,
109                         AnalysisID StopAfter,
110                         MachineFunctionInitializer *MFInitializer = nullptr) {
111
112   // Targets may override createPassConfig to provide a target-specific
113   // subclass.
114   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
115   PassConfig->setStartStopPasses(StartBefore, StartAfter, StopBefore,
116                                  StopAfter);
117   // Set PassConfig options provided by TargetMachine.
118   PassConfig->setDisableVerify(DisableVerify);
119   PM.add(PassConfig);
120
121   // When in emulated TLS mode, add the LowerEmuTLS pass.
122   if (TM->Options.EmulatedTLS)
123     PM.add(createLowerEmuTLSPass());
124
125   PM.add(createPreISelIntrinsicLoweringPass());
126
127   // Add internal analysis passes from the target machine.
128   PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
129
130   PassConfig->addIRPasses();
131
132   PassConfig->addCodeGenPrepare();
133
134   PassConfig->addPassesToHandleExceptions();
135
136   PassConfig->addISelPrepare();
137
138   MachineModuleInfo *MMI = new MachineModuleInfo(TM);
139   MMI->setMachineFunctionInitializer(MFInitializer);
140   PM.add(MMI);
141
142   // Enable FastISel with -fast, but allow that to be overridden.
143   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
144   if (EnableFastISelOption == cl::BOU_TRUE ||
145       (TM->getOptLevel() == CodeGenOpt::None &&
146        TM->getO0WantsFastISel()))
147     TM->setFastISel(true);
148
149   // Ask the target for an isel.
150   // Enable GlobalISel if the target wants to, but allow that to be overriden.
151   if (EnableGlobalISel == cl::BOU_TRUE || (EnableGlobalISel == cl::BOU_UNSET &&
152                                            PassConfig->isGlobalISelEnabled())) {
153     if (PassConfig->addIRTranslator())
154       return nullptr;
155
156     PassConfig->addPreLegalizeMachineIR();
157
158     if (PassConfig->addLegalizeMachineIR())
159       return nullptr;
160
161     // Before running the register bank selector, ask the target if it
162     // wants to run some passes.
163     PassConfig->addPreRegBankSelect();
164
165     if (PassConfig->addRegBankSelect())
166       return nullptr;
167
168     PassConfig->addPreGlobalInstructionSelect();
169
170     if (PassConfig->addGlobalInstructionSelect())
171       return nullptr;
172
173     // Pass to reset the MachineFunction if the ISel failed.
174     PM.add(createResetMachineFunctionPass(
175         PassConfig->reportDiagnosticWhenGlobalISelFallback(),
176         PassConfig->isGlobalISelAbortEnabled()));
177
178     // Provide a fallback path when we do not want to abort on
179     // not-yet-supported input.
180     if (!PassConfig->isGlobalISelAbortEnabled() &&
181         PassConfig->addInstSelector())
182       return nullptr;
183
184   } else if (PassConfig->addInstSelector())
185     return nullptr;
186
187   PassConfig->addMachinePasses();
188
189   PassConfig->setInitialized();
190
191   return &MMI->getContext();
192 }
193
194 bool LLVMTargetMachine::addPassesToEmitFile(
195     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
196     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
197     AnalysisID StopBefore, AnalysisID StopAfter,
198     MachineFunctionInitializer *MFInitializer) {
199   // Add common CodeGen passes.
200   MCContext *Context =
201       addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
202                               StopBefore, StopAfter, MFInitializer);
203   if (!Context)
204     return true;
205
206   if (StopBefore || StopAfter) {
207     PM.add(createPrintMIRPass(Out));
208     return false;
209   }
210
211   if (Options.MCOptions.MCSaveTempLabels)
212     Context->setAllowTemporaryLabels(false);
213
214   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
215   const MCAsmInfo &MAI = *getMCAsmInfo();
216   const MCRegisterInfo &MRI = *getMCRegisterInfo();
217   const MCInstrInfo &MII = *getMCInstrInfo();
218
219   std::unique_ptr<MCStreamer> AsmStreamer;
220
221   switch (FileType) {
222   case CGFT_AssemblyFile: {
223     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
224         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
225
226     // Create a code emitter if asked to show the encoding.
227     MCCodeEmitter *MCE = nullptr;
228     if (Options.MCOptions.ShowMCEncoding)
229       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
230
231     MCAsmBackend *MAB =
232         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
233                                        Options.MCOptions);
234     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
235     MCStreamer *S = getTarget().createAsmStreamer(
236         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
237         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
238         Options.MCOptions.ShowMCInst);
239     AsmStreamer.reset(S);
240     break;
241   }
242   case CGFT_ObjectFile: {
243     // Create the code emitter for the target if it exists.  If not, .o file
244     // emission fails.
245     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
246     MCAsmBackend *MAB =
247         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
248                                        Options.MCOptions);
249     if (!MCE || !MAB)
250       return true;
251
252     // Don't waste memory on names of temp labels.
253     Context->setUseNamesOnTempLabels(false);
254
255     Triple T(getTargetTriple().str());
256     AsmStreamer.reset(getTarget().createMCObjectStreamer(
257         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
258         Options.MCOptions.MCIncrementalLinkerCompatible,
259         /*DWARFMustBeAtTheEnd*/ true));
260     break;
261   }
262   case CGFT_Null:
263     // The Null output is intended for use for performance analysis and testing,
264     // not real users.
265     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
266     break;
267   }
268
269   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
270   FunctionPass *Printer =
271       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
272   if (!Printer)
273     return true;
274
275   PM.add(Printer);
276   PM.add(createFreeMachineFunctionPass());
277
278   return false;
279 }
280
281 /// addPassesToEmitMC - Add passes to the specified pass manager to get
282 /// machine code emitted with the MCJIT. This method returns true if machine
283 /// code is not supported. It fills the MCContext Ctx pointer which can be
284 /// used to build custom MCStreamer.
285 ///
286 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
287                                           raw_pwrite_stream &Out,
288                                           bool DisableVerify) {
289   // Add common CodeGen passes.
290   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
291                                 nullptr, nullptr);
292   if (!Ctx)
293     return true;
294
295   if (Options.MCOptions.MCSaveTempLabels)
296     Ctx->setAllowTemporaryLabels(false);
297
298   // Create the code emitter for the target if it exists.  If not, .o file
299   // emission fails.
300   const MCRegisterInfo &MRI = *getMCRegisterInfo();
301   MCCodeEmitter *MCE =
302       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
303   MCAsmBackend *MAB =
304       getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
305                                      Options.MCOptions);
306   if (!MCE || !MAB)
307     return true;
308
309   const Triple &T = getTargetTriple();
310   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
311   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
312       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
313       Options.MCOptions.MCIncrementalLinkerCompatible,
314       /*DWARFMustBeAtTheEnd*/ true));
315
316   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
317   FunctionPass *Printer =
318       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
319   if (!Printer)
320     return true;
321
322   PM.add(Printer);
323   PM.add(createFreeMachineFunctionPass());
324
325   return false; // success!
326 }