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
7 //===----------------------------------------------------------------------===//
9 // This file implements the LLVMTargetMachine class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Analysis/Passes.h"
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/CodeGen/BasicTTIImpl.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/TargetPassConfig.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCCodeEmitter.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
37 static cl::opt
<bool> EnableTrapUnreachable("trap-unreachable",
38 cl::Hidden
, cl::ZeroOrMore
, cl::init(false),
39 cl::desc("Enable generating trap for unreachable"));
41 void LLVMTargetMachine::initAsmInfo() {
42 MRI
.reset(TheTarget
.createMCRegInfo(getTargetTriple().str()));
43 assert(MRI
&& "Unable to create reg info");
44 MII
.reset(TheTarget
.createMCInstrInfo());
45 assert(MII
&& "Unable to create instruction info");
46 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
47 // to some backends having subtarget feature dependent module level
48 // code generation. This is similar to the hack in the AsmPrinter for
49 // module level assembly etc.
50 STI
.reset(TheTarget
.createMCSubtargetInfo(
51 getTargetTriple().str(), getTargetCPU(), getTargetFeatureString()));
52 assert(STI
&& "Unable to create subtarget info");
54 MCAsmInfo
*TmpAsmInfo
= TheTarget
.createMCAsmInfo(
55 *MRI
, getTargetTriple().str(), Options
.MCOptions
);
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
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!");
64 if (Options
.BinutilsVersion
.first
> 0)
65 TmpAsmInfo
->setBinutilsVersion(Options
.BinutilsVersion
);
67 if (Options
.DisableIntegratedAS
) {
68 TmpAsmInfo
->setUseIntegratedAssembler(false);
69 // If there is explict option disable integratedAS, we can't use it for
71 TmpAsmInfo
->setParseInlineAsmUsingAsmParser(false);
74 TmpAsmInfo
->setPreserveAsmComments(Options
.MCOptions
.PreserveAsmComments
);
76 TmpAsmInfo
->setCompressDebugSections(Options
.CompressDebugSections
);
78 TmpAsmInfo
->setRelaxELFRelocations(Options
.RelaxELFRelocations
);
80 if (Options
.ExceptionModel
!= ExceptionHandling::None
)
81 TmpAsmInfo
->setExceptionsType(Options
.ExceptionModel
);
83 AsmInfo
.reset(TmpAsmInfo
);
86 LLVMTargetMachine::LLVMTargetMachine(const Target
&T
,
87 StringRef DataLayoutString
,
88 const Triple
&TT
, StringRef CPU
,
89 StringRef FS
, const TargetOptions
&Options
,
90 Reloc::Model RM
, CodeModel::Model CM
,
92 : TargetMachine(T
, DataLayoutString
, TT
, CPU
, FS
, Options
) {
97 if (EnableTrapUnreachable
)
98 this->Options
.TrapUnreachable
= true;
102 LLVMTargetMachine::getTargetTransformInfo(const Function
&F
) {
103 return TargetTransformInfo(BasicTTIImpl(this, F
));
106 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
107 static TargetPassConfig
*
108 addPassesToGenerateCode(LLVMTargetMachine
&TM
, PassManagerBase
&PM
,
110 MachineModuleInfoWrapperPass
&MMIWP
) {
111 // Targets may override createPassConfig to provide a target-specific
113 TargetPassConfig
*PassConfig
= TM
.createPassConfig(PM
);
114 // Set PassConfig options provided by TargetMachine.
115 PassConfig
->setDisableVerify(DisableVerify
);
119 if (PassConfig
->addISelPasses())
121 PassConfig
->addMachinePasses();
122 PassConfig
->setInitialized();
126 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase
&PM
,
127 raw_pwrite_stream
&Out
,
128 raw_pwrite_stream
*DwoOut
,
129 CodeGenFileType FileType
,
130 MCContext
&Context
) {
131 Expected
<std::unique_ptr
<MCStreamer
>> MCStreamerOrErr
=
132 createMCStreamer(Out
, DwoOut
, FileType
, Context
);
133 if (auto Err
= MCStreamerOrErr
.takeError())
136 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
137 FunctionPass
*Printer
=
138 getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr
));
146 Expected
<std::unique_ptr
<MCStreamer
>> LLVMTargetMachine::createMCStreamer(
147 raw_pwrite_stream
&Out
, raw_pwrite_stream
*DwoOut
, CodeGenFileType FileType
,
148 MCContext
&Context
) {
149 if (Options
.MCOptions
.MCSaveTempLabels
)
150 Context
.setAllowTemporaryLabels(false);
152 const MCSubtargetInfo
&STI
= *getMCSubtargetInfo();
153 const MCAsmInfo
&MAI
= *getMCAsmInfo();
154 const MCRegisterInfo
&MRI
= *getMCRegisterInfo();
155 const MCInstrInfo
&MII
= *getMCInstrInfo();
157 std::unique_ptr
<MCStreamer
> AsmStreamer
;
160 case CGFT_AssemblyFile
: {
161 MCInstPrinter
*InstPrinter
= getTarget().createMCInstPrinter(
162 getTargetTriple(), MAI
.getAssemblerDialect(), MAI
, MII
, MRI
);
164 // Create a code emitter if asked to show the encoding.
165 std::unique_ptr
<MCCodeEmitter
> MCE
;
166 if (Options
.MCOptions
.ShowMCEncoding
)
167 MCE
.reset(getTarget().createMCCodeEmitter(MII
, MRI
, Context
));
169 std::unique_ptr
<MCAsmBackend
> MAB(
170 getTarget().createMCAsmBackend(STI
, MRI
, Options
.MCOptions
));
171 auto FOut
= std::make_unique
<formatted_raw_ostream
>(Out
);
172 MCStreamer
*S
= getTarget().createAsmStreamer(
173 Context
, std::move(FOut
), Options
.MCOptions
.AsmVerbose
,
174 Options
.MCOptions
.MCUseDwarfDirectory
, InstPrinter
, std::move(MCE
),
175 std::move(MAB
), Options
.MCOptions
.ShowMCInst
);
176 AsmStreamer
.reset(S
);
179 case CGFT_ObjectFile
: {
180 // Create the code emitter for the target if it exists. If not, .o file
182 MCCodeEmitter
*MCE
= getTarget().createMCCodeEmitter(MII
, MRI
, Context
);
184 return make_error
<StringError
>("createMCCodeEmitter failed",
185 inconvertibleErrorCode());
187 getTarget().createMCAsmBackend(STI
, MRI
, Options
.MCOptions
);
189 return make_error
<StringError
>("createMCAsmBackend failed",
190 inconvertibleErrorCode());
192 Triple
T(getTargetTriple().str());
193 AsmStreamer
.reset(getTarget().createMCObjectStreamer(
194 T
, Context
, std::unique_ptr
<MCAsmBackend
>(MAB
),
195 DwoOut
? MAB
->createDwoObjectWriter(Out
, *DwoOut
)
196 : MAB
->createObjectWriter(Out
),
197 std::unique_ptr
<MCCodeEmitter
>(MCE
), STI
, Options
.MCOptions
.MCRelaxAll
,
198 Options
.MCOptions
.MCIncrementalLinkerCompatible
,
199 /*DWARFMustBeAtTheEnd*/ true));
203 // The Null output is intended for use for performance analysis and testing,
205 AsmStreamer
.reset(getTarget().createNullStreamer(Context
));
209 return std::move(AsmStreamer
);
212 bool LLVMTargetMachine::addPassesToEmitFile(
213 PassManagerBase
&PM
, raw_pwrite_stream
&Out
, raw_pwrite_stream
*DwoOut
,
214 CodeGenFileType FileType
, bool DisableVerify
,
215 MachineModuleInfoWrapperPass
*MMIWP
) {
216 // Add common CodeGen passes.
218 MMIWP
= new MachineModuleInfoWrapperPass(this);
219 TargetPassConfig
*PassConfig
=
220 addPassesToGenerateCode(*this, PM
, DisableVerify
, *MMIWP
);
224 if (TargetPassConfig::willCompleteCodeGenPipeline()) {
225 if (addAsmPrinter(PM
, Out
, DwoOut
, FileType
, MMIWP
->getMMI().getContext()))
228 // MIR printing is redundant with -filetype=null.
229 if (FileType
!= CGFT_Null
)
230 PM
.add(createPrintMIRPass(Out
));
233 PM
.add(createFreeMachineFunctionPass());
237 /// addPassesToEmitMC - Add passes to the specified pass manager to get
238 /// machine code emitted with the MCJIT. This method returns true if machine
239 /// code is not supported. It fills the MCContext Ctx pointer which can be
240 /// used to build custom MCStreamer.
242 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase
&PM
, MCContext
*&Ctx
,
243 raw_pwrite_stream
&Out
,
244 bool DisableVerify
) {
245 // Add common CodeGen passes.
246 MachineModuleInfoWrapperPass
*MMIWP
= new MachineModuleInfoWrapperPass(this);
247 TargetPassConfig
*PassConfig
=
248 addPassesToGenerateCode(*this, PM
, DisableVerify
, *MMIWP
);
251 assert(TargetPassConfig::willCompleteCodeGenPipeline() &&
252 "Cannot emit MC with limited codegen pipeline");
254 Ctx
= &MMIWP
->getMMI().getContext();
255 if (Options
.MCOptions
.MCSaveTempLabels
)
256 Ctx
->setAllowTemporaryLabels(false);
258 // Create the code emitter for the target if it exists. If not, .o file
260 const MCSubtargetInfo
&STI
= *getMCSubtargetInfo();
261 const MCRegisterInfo
&MRI
= *getMCRegisterInfo();
263 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI
, *Ctx
);
265 getTarget().createMCAsmBackend(STI
, MRI
, Options
.MCOptions
);
269 const Triple
&T
= getTargetTriple();
270 std::unique_ptr
<MCStreamer
> AsmStreamer(getTarget().createMCObjectStreamer(
271 T
, *Ctx
, std::unique_ptr
<MCAsmBackend
>(MAB
), MAB
->createObjectWriter(Out
),
272 std::unique_ptr
<MCCodeEmitter
>(MCE
), STI
, Options
.MCOptions
.MCRelaxAll
,
273 Options
.MCOptions
.MCIncrementalLinkerCompatible
,
274 /*DWARFMustBeAtTheEnd*/ true));
276 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
277 FunctionPass
*Printer
=
278 getTarget().createAsmPrinter(*this, std::move(AsmStreamer
));
283 PM
.add(createFreeMachineFunctionPass());
285 return false; // success!