LLVM 17.0.0git
Go to the documentation of this file.
1//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
9// This file implements the LLVMTargetMachine class.
17#include "llvm/CodeGen/Passes.h"
21#include "llvm/MC/MCAsmInfo.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCInstrInfo.h"
27#include "llvm/MC/MCStreamer.h"
34using namespace llvm;
36static cl::opt<bool>
37 EnableTrapUnreachable("trap-unreachable", cl::Hidden,
38 cl::desc("Enable generating trap for unreachable"));
42 assert(MRI && "Unable to create reg info");
44 assert(MII && "Unable to create instruction info");
45 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
46 // to some backends having subtarget feature dependent module level
47 // code generation. This is similar to the hack in the AsmPrinter for
48 // module level assembly etc.
51 assert(STI && "Unable to create subtarget info");
55 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
56 // and if the old one gets included then MCAsmInfo will be NULL and
57 // we'll crash later.
58 // Provide the user with a useful error message about what's wrong.
59 assert(TmpAsmInfo && "MCAsmInfo not initialized. "
60 "Make sure you include the correct TargetSelect.h"
61 "and that InitializeAllTargetMCs() is being invoked!");
63 if (Options.BinutilsVersion.first > 0)
67 TmpAsmInfo->setUseIntegratedAssembler(false);
68 // If there is explict option disable integratedAS, we can't use it for
69 // inlineasm either.
70 TmpAsmInfo->setParseInlineAsmUsingAsmParser(false);
71 }
82 AsmInfo.reset(TmpAsmInfo);
86 StringRef DataLayoutString,
87 const Triple &TT, StringRef CPU,
91 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
92 this->RM = RM;
93 this->CMModel = CM;
94 this->OptLevel = OL;
97 this->Options.TrapUnreachable = true;
102 return TargetTransformInfo(BasicTTIImpl(this, F));
105/// addPassesToX helper drives creation and initialization of TargetPassConfig.
106static TargetPassConfig *
108 bool DisableVerify,
110 // Targets may override createPassConfig to provide a target-specific
111 // subclass.
112 TargetPassConfig *PassConfig = TM.createPassConfig(PM);
113 // Set PassConfig options provided by TargetMachine.
114 PassConfig->setDisableVerify(DisableVerify);
115 PM.add(PassConfig);
116 PM.add(&MMIWP);
118 if (PassConfig->addISelPasses())
119 return nullptr;
120 PassConfig->addMachinePasses();
121 PassConfig->setInitialized();
122 return PassConfig;
127 raw_pwrite_stream *DwoOut,
128 CodeGenFileType FileType,
129 MCContext &Context) {
130 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
131 createMCStreamer(Out, DwoOut, FileType, Context);
132 if (auto Err = MCStreamerOrErr.takeError())
133 return true;
135 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
137 getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
138 if (!Printer)
139 return true;
141 PM.add(Printer);
142 return false;
147 MCContext &Context) {
149 Context.setAllowTemporaryLabels(false);
152 const MCAsmInfo &MAI = *getMCAsmInfo();
154 const MCInstrInfo &MII = *getMCInstrInfo();
156 std::unique_ptr<MCStreamer> AsmStreamer;
158 switch (FileType) {
159 case CGFT_AssemblyFile: {
163 // Create a code emitter if asked to show the encoding.
164 std::unique_ptr<MCCodeEmitter> MCE;
166 MCE.reset(getTarget().createMCCodeEmitter(MII, Context));
168 bool UseDwarfDirectory = false;
171 UseDwarfDirectory = false;
172 break;
174 UseDwarfDirectory = true;
175 break;
177 UseDwarfDirectory = MAI.enableDwarfFileDirectoryDefault();
178 break;
179 }
181 std::unique_ptr<MCAsmBackend> MAB(
182 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
183 auto FOut = std::make_unique<formatted_raw_ostream>(Out);
185 Context, std::move(FOut), Options.MCOptions.AsmVerbose,
186 UseDwarfDirectory, InstPrinter, std::move(MCE), std::move(MAB),
188 AsmStreamer.reset(S);
189 break;
190 }
191 case CGFT_ObjectFile: {
192 // Create the code emitter for the target if it exists. If not, .o file
193 // emission fails.
195 if (!MCE)
196 return make_error<StringError>("createMCCodeEmitter failed",
198 MCAsmBackend *MAB =
200 if (!MAB)
201 return make_error<StringError>("createMCAsmBackend failed",
204 Triple T(getTargetTriple().str());
205 AsmStreamer.reset(getTarget().createMCObjectStreamer(
206 T, Context, std::unique_ptr<MCAsmBackend>(MAB),
207 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
208 : MAB->createObjectWriter(Out),
209 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
211 /*DWARFMustBeAtTheEnd*/ true));
212 break;
213 }
214 case CGFT_Null:
215 // The Null output is intended for use for performance analysis and testing,
216 // not real users.
217 AsmStreamer.reset(getTarget().createNullStreamer(Context));
218 break;
219 }
221 return std::move(AsmStreamer);
226 CodeGenFileType FileType, bool DisableVerify,
228 // Add common CodeGen passes.
229 if (!MMIWP)
230 MMIWP = new MachineModuleInfoWrapperPass(this);
231 TargetPassConfig *PassConfig =
232 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
233 if (!PassConfig)
234 return true;
237 if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
238 return true;
239 } else {
240 // MIR printing is redundant with -filetype=null.
241 if (FileType != CGFT_Null)
242 PM.add(createPrintMIRPass(Out));
243 }
246 return false;
249/// addPassesToEmitMC - Add passes to the specified pass manager to get
250/// machine code emitted with the MCJIT. This method returns true if machine
251/// code is not supported. It fills the MCContext Ctx pointer which can be
252/// used to build custom MCStreamer.
256 bool DisableVerify) {
257 // Add common CodeGen passes.
259 TargetPassConfig *PassConfig =
260 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
261 if (!PassConfig)
262 return true;
264 "Cannot emit MC with limited codegen pipeline");
266 Ctx = &MMIWP->getMMI().getContext();
267 // libunwind is unable to load compact unwind dynamically, so we must generate
268 // DWARF unwind info for the JIT.
271 Ctx->setAllowTemporaryLabels(false);
273 // Create the code emitter for the target if it exists. If not, .o file
274 // emission fails.
277 std::unique_ptr<MCCodeEmitter> MCE(
278 getTarget().createMCCodeEmitter(*getMCInstrInfo(), *Ctx));
279 std::unique_ptr<MCAsmBackend> MAB(
280 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
281 if (!MCE || !MAB)
282 return true;
284 const Triple &T = getTargetTriple();
285 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
286 T, *Ctx, std::move(MAB), MAB->createObjectWriter(Out), std::move(MCE),
289 /*DWARFMustBeAtTheEnd*/ true));
291 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
293 getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
294 if (!Printer)
295 return true;
297 PM.add(Printer);
300 return false; // success!
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
static TargetPassConfig * addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM, bool DisableVerify, MachineModuleInfoWrapperPass &MMIWP)
addPassesToX helper drives creation and initialization of TargetPassConfig.
static cl::opt< bool > EnableTrapUnreachable("trap-unreachable", cl::Hidden, cl::desc("Enable generating trap for unreachable"))
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
Memory true print Memory SSA Printer
Definition: MemorySSA.cpp:78
LLVMContext & Context
const char LLVMTargetMachineRef TM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Target-Independent Code Generator Pass Configuration Options pass.
Concrete BasicTTIImpl that can be used if no further customization is needed.
Tagged union holding either a T or a Error.
Definition: Error.h:470
Error takeError()
Take ownership of the stored error.
Definition: Error.h:597
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
This class describes a target machine that is implemented with the LLVM target-independent code gener...
bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Context)
Adds an AsmPrinter pass to the pipeline that prints assembly or machine code from the MI representati...
bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, bool DisableVerify=true, MachineModuleInfoWrapperPass *MMIWP=nullptr) override
Add passes to the specified pass manager to get the specified file emitted.
bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, raw_pwrite_stream &Out, bool DisableVerify=true) override
Add passes to the specified pass manager to get machine code emitted with the MCJIT.
TargetTransformInfo getTargetTransformInfo(const Function &F) const override
Get a TargetTransformInfo implementation for the target.
LLVMTargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL)
Expected< std::unique_ptr< MCStreamer > > createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, MCContext &Ctx)
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:41
std::unique_ptr< MCObjectWriter > createObjectWriter(raw_pwrite_stream &OS) const
Create a new MCObjectWriter instance for use by the assembler backend to emit the final object file.
std::unique_ptr< MCObjectWriter > createDwoObjectWriter(raw_pwrite_stream &OS, raw_pwrite_stream &DwoOS) const
Create an MCObjectWriter that writes two object files: a .o file which is linked into the final progr...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
void setCompressDebugSections(DebugCompressionType CompressDebugSections)
Definition: MCAsmInfo.h:873
void setRelaxELFRelocations(bool V)
Definition: MCAsmInfo.h:880
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:686
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:852
virtual void setPreserveAsmComments(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:865
virtual void setParseInlineAsmUsingAsmParser(bool Value)
Set whether target want to use AsmParser to parse inlineasm.
Definition: MCAsmInfo.h:857
void setBinutilsVersion(std::pair< int, int > Value)
Definition: MCAsmInfo.h:835
void setExceptionsType(ExceptionHandling EH)
Definition: MCAsmInfo.h:784
bool enableDwarfFileDirectoryDefault() const
Definition: MCAsmInfo.h:825
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:21
Context object for machine code objects.
Definition: MCContext.h:76
void setAllowTemporaryLabels(bool Value)
Definition: MCContext.h:456
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:44
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Streaming machine code generation interface.
Definition: MCStreamer.h:212
virtual void reset()
State management.
Definition: MCStreamer.cpp:102
Generic base class for all target subtargets.
bool PreserveAsmComments
Preserve Comments in Assembly.
DwarfDirectory MCUseDwarfDirectory
EmitDwarfUnwindType EmitDwarfUnwind
const MCContext & getContext() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:78
std::unique_ptr< const MCAsmInfo > AsmInfo
Contains target specific asm information.
CodeModel::Model CMModel
const Triple & getTargetTriple() const
const MCSubtargetInfo * getMCSubtargetInfo() const
std::unique_ptr< const MCInstrInfo > MII
StringRef getTargetFeatureString() const
StringRef getTargetCPU() const
const MCInstrInfo * getMCInstrInfo() const
CodeGenOpt::Level OptLevel
std::unique_ptr< const MCSubtargetInfo > STI
TargetOptions Options
const Target & getTarget() const
const Target & TheTarget
The Target that this machine was created for.
Definition: TargetMachine.h:85
const MCRegisterInfo * getMCRegisterInfo() const
std::unique_ptr< const MCRegisterInfo > MRI
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
MCTargetOptions MCOptions
Machine level options.
std::pair< int, int > BinutilsVersion
If greater than 0, override the default value of MCAsmInfo::BinutilsVersion.
DebugCompressionType CompressDebugSections
Compress DWARF debug sections.
unsigned RelaxELFRelocations
unsigned TrapUnreachable
Emit target-specific trap instruction for 'unreachable' IR instructions.
unsigned DisableIntegratedAS
Disable the integrated assembler.
ExceptionHandling ExceptionModel
What exception model to use.
Target-Independent Code Generator Pass Configuration Options.
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
void setDisableVerify(bool Disable)
static bool willCompleteCodeGenPipeline()
Returns true if none of the -stop-before and -stop-after options is set.
bool addISelPasses()
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
MCCodeEmitter * createMCCodeEmitter(const MCInstrInfo &II, MCContext &Ctx) const
createMCCodeEmitter - Create a target specific code emitter.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, bool IsVerboseAsm, bool UseDwarfDirectory, MCInstPrinter *InstPrint, std::unique_ptr< MCCodeEmitter > &&CE, std::unique_ptr< MCAsmBackend > &&TAB, bool ShowInst) const
MCAsmBackend * createMCAsmBackend(const MCSubtargetInfo &STI, const MCRegisterInfo &MRI, const MCTargetOptions &Options) const
createMCAsmBackend - Create a target specific assembly parser.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple, const MCTargetOptions &Options) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
AsmPrinter * createAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer) const
createAsmPrinter - Create a target specific assembly printer pass.
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
virtual void add(Pass *P)=0
Add a pass to the queue of passes to run.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:428
Code generation optimization level.
Definition: CodeGen.h:57
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineFunctionPass * createPrintMIRPass(raw_ostream &OS)
MIRPrinting pass - this pass prints out the LLVM IR into the given stream using the MIR serialization...
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:79
@ None
No exception support.
MCStreamer * createNullStreamer(MCContext &Ctx)
Create a dummy machine code streamer, which does nothing.
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit,...
Definition: CodeGen.h:84
@ CGFT_AssemblyFile
Definition: CodeGen.h:85
@ CGFT_Null
Definition: CodeGen.h:87
@ CGFT_ObjectFile
Definition: CodeGen.h:86
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.