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/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/TargetPassConfig.h"
22 #include "llvm/IR/IRPrintingPasses.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Transforms/Scalar.h"
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"));
47 EnableGlobalISel("global-isel", cl::Hidden, cl::init(false),
48 cl::desc("Enable the \"global\" instruction selector"));
50 void LLVMTargetMachine::initAsmInfo() {
51 MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
52 MII = TheTarget.createMCInstrInfo();
53 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
54 // to some backends having subtarget feature dependent module level
55 // code generation. This is similar to the hack in the AsmPrinter for
56 // module level assembly etc.
57 STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
58 getTargetFeatureString());
60 MCAsmInfo *TmpAsmInfo =
61 TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
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
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!");
70 if (Options.DisableIntegratedAS)
71 TmpAsmInfo->setUseIntegratedAssembler(false);
73 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
75 if (Options.CompressDebugSections)
76 TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu);
78 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
80 if (Options.ExceptionModel != ExceptionHandling::None)
81 TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
86 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
87 StringRef DataLayoutString,
88 const Triple &TT, StringRef CPU,
89 StringRef FS, TargetOptions Options,
90 Reloc::Model RM, CodeModel::Model CM,
92 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
93 T.adjustCodeGenOpts(TT, RM, CM);
99 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
100 return TargetIRAnalysis([this](const Function &F) {
101 return TargetTransformInfo(BasicTTIImpl(this, F));
106 LLVMTargetMachine::addMachineModuleInfo(PassManagerBase &PM) const {
107 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
108 *getMCRegisterInfo(),
109 getObjFileLowering());
114 void LLVMTargetMachine::addMachineFunctionAnalysis(PassManagerBase &PM,
115 MachineFunctionInitializer *MFInitializer) const {
116 PM.add(new MachineFunctionAnalysis(*this, MFInitializer));
119 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
121 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
122 bool DisableVerify, AnalysisID StartBefore,
123 AnalysisID StartAfter, AnalysisID StopAfter,
124 MachineFunctionInitializer *MFInitializer = nullptr) {
126 // When in emulated TLS mode, add the LowerEmuTLS pass.
127 if (TM->Options.EmulatedTLS)
128 PM.add(createLowerEmuTLSPass(TM));
130 PM.add(createPreISelIntrinsicLoweringPass());
132 // Add internal analysis passes from the target machine.
133 PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
135 // Targets may override createPassConfig to provide a target-specific
137 TargetPassConfig *PassConfig = TM->createPassConfig(PM);
138 PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
140 // Set PassConfig options provided by TargetMachine.
141 PassConfig->setDisableVerify(DisableVerify);
145 PassConfig->addIRPasses();
147 PassConfig->addCodeGenPrepare();
149 PassConfig->addPassesToHandleExceptions();
151 PassConfig->addISelPrepare();
153 MachineModuleInfo &MMI = TM->addMachineModuleInfo(PM);
154 TM->addMachineFunctionAnalysis(PM, MFInitializer);
156 // Enable FastISel with -fast, but allow that to be overridden.
157 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
158 if (EnableFastISelOption == cl::BOU_TRUE ||
159 (TM->getOptLevel() == CodeGenOpt::None &&
160 TM->getO0WantsFastISel()))
161 TM->setFastISel(true);
163 // Ask the target for an isel.
164 if (LLVM_UNLIKELY(EnableGlobalISel)) {
165 if (PassConfig->addIRTranslator())
168 // Before running the register bank selector, ask the target if it
169 // wants to run some passes.
170 PassConfig->addPreRegBankSelect();
172 if (PassConfig->addRegBankSelect())
175 } else if (PassConfig->addInstSelector())
178 PassConfig->addMachinePasses();
180 PassConfig->setInitialized();
182 return &MMI.getContext();
185 bool LLVMTargetMachine::addPassesToEmitFile(
186 PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
187 bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
188 AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
189 // Add common CodeGen passes.
191 addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
192 StopAfter, MFInitializer);
197 PM.add(createPrintMIRPass(Out));
201 if (Options.MCOptions.MCSaveTempLabels)
202 Context->setAllowTemporaryLabels(false);
204 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
205 const MCAsmInfo &MAI = *getMCAsmInfo();
206 const MCRegisterInfo &MRI = *getMCRegisterInfo();
207 const MCInstrInfo &MII = *getMCInstrInfo();
209 std::unique_ptr<MCStreamer> AsmStreamer;
212 case CGFT_AssemblyFile: {
213 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
214 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
216 // Create a code emitter if asked to show the encoding.
217 MCCodeEmitter *MCE = nullptr;
218 if (Options.MCOptions.ShowMCEncoding)
219 MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
222 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
223 auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
224 MCStreamer *S = getTarget().createAsmStreamer(
225 *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
226 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
227 Options.MCOptions.ShowMCInst);
228 AsmStreamer.reset(S);
231 case CGFT_ObjectFile: {
232 // Create the code emitter for the target if it exists. If not, .o file
234 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
236 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
240 // Don't waste memory on names of temp labels.
241 Context->setUseNamesOnTempLabels(false);
243 Triple T(getTargetTriple().str());
244 AsmStreamer.reset(getTarget().createMCObjectStreamer(
245 T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
246 Options.MCOptions.MCIncrementalLinkerCompatible,
247 /*DWARFMustBeAtTheEnd*/ true));
251 // The Null output is intended for use for performance analysis and testing,
253 AsmStreamer.reset(getTarget().createNullStreamer(*Context));
257 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
258 FunctionPass *Printer =
259 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
268 /// addPassesToEmitMC - Add passes to the specified pass manager to get
269 /// machine code emitted with the MCJIT. This method returns true if machine
270 /// code is not supported. It fills the MCContext Ctx pointer which can be
271 /// used to build custom MCStreamer.
273 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
274 raw_pwrite_stream &Out,
275 bool DisableVerify) {
276 // Add common CodeGen passes.
277 Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
282 if (Options.MCOptions.MCSaveTempLabels)
283 Ctx->setAllowTemporaryLabels(false);
285 // Create the code emitter for the target if it exists. If not, .o file
287 const MCRegisterInfo &MRI = *getMCRegisterInfo();
289 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
291 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
295 const Triple &T = getTargetTriple();
296 const MCSubtargetInfo &STI = *getMCSubtargetInfo();
297 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
298 T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
299 Options.MCOptions.MCIncrementalLinkerCompatible,
300 /*DWARFMustBeAtTheEnd*/ true));
302 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
303 FunctionPass *Printer =
304 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
310 return false; // success!