1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVMTargetMachine class.
12 //===----------------------------------------------------------------------===//
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"
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"));
45 static cl::opt<cl::boolOrDefault>
46 EnableGlobalISel("global-isel", cl::Hidden,
47 cl::desc("Enable the \"global\" instruction selector"));
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());
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
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!");
69 if (Options.DisableIntegratedAS)
70 TmpAsmInfo->setUseIntegratedAssembler(false);
72 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
74 if (Options.CompressDebugSections)
75 TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
77 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
79 if (Options.ExceptionModel != ExceptionHandling::None)
80 TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
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,
91 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
92 T.adjustCodeGenOpts(TT, RM, CM);
98 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
99 return TargetIRAnalysis([this](const Function &F) {
100 return TargetTransformInfo(BasicTTIImpl(this, F));
104 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
106 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
107 bool DisableVerify, AnalysisID StartBefore,
108 AnalysisID StartAfter, AnalysisID StopBefore,
109 AnalysisID StopAfter,
110 MachineFunctionInitializer *MFInitializer = nullptr) {
112 // Targets may override createPassConfig to provide a target-specific
114 TargetPassConfig *PassConfig = TM->createPassConfig(PM);
115 PassConfig->setStartStopPasses(StartBefore, StartAfter, StopBefore,
117 // Set PassConfig options provided by TargetMachine.
118 PassConfig->setDisableVerify(DisableVerify);
121 // When in emulated TLS mode, add the LowerEmuTLS pass.
122 if (TM->Options.EmulatedTLS)
123 PM.add(createLowerEmuTLSPass());
125 PM.add(createPreISelIntrinsicLoweringPass());
127 // Add internal analysis passes from the target machine.
128 PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
130 PassConfig->addIRPasses();
132 PassConfig->addCodeGenPrepare();
134 PassConfig->addPassesToHandleExceptions();
136 PassConfig->addISelPrepare();
138 MachineModuleInfo *MMI = new MachineModuleInfo(TM);
139 MMI->setMachineFunctionInitializer(MFInitializer);
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);
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())
156 PassConfig->addPreLegalizeMachineIR();
158 if (PassConfig->addLegalizeMachineIR())
161 // Before running the register bank selector, ask the target if it
162 // wants to run some passes.
163 PassConfig->addPreRegBankSelect();
165 if (PassConfig->addRegBankSelect())
168 PassConfig->addPreGlobalInstructionSelect();
170 if (PassConfig->addGlobalInstructionSelect())
173 // Pass to reset the MachineFunction if the ISel failed.
174 PM.add(createResetMachineFunctionPass(
175 PassConfig->reportDiagnosticWhenGlobalISelFallback(),
176 PassConfig->isGlobalISelAbortEnabled()));
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())
184 } else if (PassConfig->addInstSelector())
187 PassConfig->addMachinePasses();
189 PassConfig->setInitialized();
191 return &MMI->getContext();
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.
201 addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
202 StopBefore, StopAfter, MFInitializer);
206 if (StopBefore || StopAfter) {
207 PM.add(createPrintMIRPass(Out));
211 if (Options.MCOptions.MCSaveTempLabels)
212 Context->setAllowTemporaryLabels(false);
214 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
215 const MCAsmInfo &MAI = *getMCAsmInfo();
216 const MCRegisterInfo &MRI = *getMCRegisterInfo();
217 const MCInstrInfo &MII = *getMCInstrInfo();
219 std::unique_ptr<MCStreamer> AsmStreamer;
222 case CGFT_AssemblyFile: {
223 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
224 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
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);
232 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
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);
242 case CGFT_ObjectFile: {
243 // Create the code emitter for the target if it exists. If not, .o file
245 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
247 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
252 // Don't waste memory on names of temp labels.
253 Context->setUseNamesOnTempLabels(false);
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));
263 // The Null output is intended for use for performance analysis and testing,
265 AsmStreamer.reset(getTarget().createNullStreamer(*Context));
269 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
270 FunctionPass *Printer =
271 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
276 PM.add(createFreeMachineFunctionPass());
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.
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,
295 if (Options.MCOptions.MCSaveTempLabels)
296 Ctx->setAllowTemporaryLabels(false);
298 // Create the code emitter for the target if it exists. If not, .o file
300 const MCRegisterInfo &MRI = *getMCRegisterInfo();
302 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
304 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU,
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));
316 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
317 FunctionPass *Printer =
318 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
323 PM.add(createFreeMachineFunctionPass());
325 return false; // success!