LLVM  5.0.0
LLVMTargetMachine.cpp
Go to the documentation of this file.
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/Analysis/Passes.h"
18 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCInstrInfo.h"
26 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/Transforms/Scalar.h"
36 using namespace llvm;
37 
41  // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
42  // to some backends having subtarget feature dependent module level
43  // code generation. This is similar to the hack in the AsmPrinter for
44  // module level assembly etc.
47 
48  MCAsmInfo *TmpAsmInfo =
50  // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
51  // and if the old one gets included then MCAsmInfo will be NULL and
52  // we'll crash later.
53  // Provide the user with a useful error message about what's wrong.
54  assert(TmpAsmInfo && "MCAsmInfo not initialized. "
55  "Make sure you include the correct TargetSelect.h"
56  "and that InitializeAllTargetMCs() is being invoked!");
57 
59  TmpAsmInfo->setUseIntegratedAssembler(false);
60 
62 
64 
66 
69 
70  AsmInfo = TmpAsmInfo;
71 }
72 
74  StringRef DataLayoutString,
75  const Triple &TT, StringRef CPU,
76  StringRef FS, const TargetOptions &Options,
79  : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
80  T.adjustCodeGenOpts(TT, RM, CM);
81  this->RM = RM;
82  this->CMModel = CM;
83  this->OptLevel = OL;
84 }
85 
87  return TargetIRAnalysis([this](const Function &F) {
88  return TargetTransformInfo(BasicTTIImpl(this, F));
89  });
90 }
91 
92 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
93 static MCContext *
95  bool DisableVerify, AnalysisID StartBefore,
96  AnalysisID StartAfter, AnalysisID StopBefore,
97  AnalysisID StopAfter) {
98  // Targets may override createPassConfig to provide a target-specific
99  // subclass.
100  TargetPassConfig *PassConfig = TM->createPassConfig(PM);
101  PassConfig->setStartStopPasses(StartBefore, StartAfter, StopBefore,
102  StopAfter);
103  // Set PassConfig options provided by TargetMachine.
104  PassConfig->setDisableVerify(DisableVerify);
105  PM.add(PassConfig);
106  MachineModuleInfo *MMI = new MachineModuleInfo(TM);
107  PM.add(MMI);
108 
109  if (PassConfig->addISelPasses())
110  return nullptr;
111  PassConfig->addMachinePasses();
112  PassConfig->setInitialized();
113 
114  return &MMI->getContext();
115 }
116 
117 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
119  MCContext &Context) {
121  Context.setAllowTemporaryLabels(false);
122 
124  const MCAsmInfo &MAI = *getMCAsmInfo();
126  const MCInstrInfo &MII = *getMCInstrInfo();
127 
128  std::unique_ptr<MCStreamer> AsmStreamer;
129 
130  switch (FileType) {
131  case CGFT_AssemblyFile: {
133  getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
134 
135  // Create a code emitter if asked to show the encoding.
136  MCCodeEmitter *MCE = nullptr;
138  MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
139 
140  MCAsmBackend *MAB =
143  auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
145  Context, std::move(FOut), Options.MCOptions.AsmVerbose,
146  Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
148  AsmStreamer.reset(S);
149  break;
150  }
151  case CGFT_ObjectFile: {
152  // Create the code emitter for the target if it exists. If not, .o file
153  // emission fails.
154  MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
155  MCAsmBackend *MAB =
158  if (!MCE || !MAB)
159  return true;
160 
161  // Don't waste memory on names of temp labels.
162  Context.setUseNamesOnTempLabels(false);
163 
164  Triple T(getTargetTriple().str());
165  AsmStreamer.reset(getTarget().createMCObjectStreamer(
166  T, Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
168  /*DWARFMustBeAtTheEnd*/ true));
169  break;
170  }
171  case CGFT_Null:
172  // The Null output is intended for use for performance analysis and testing,
173  // not real users.
174  AsmStreamer.reset(getTarget().createNullStreamer(Context));
175  break;
176  }
177 
178  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
180  getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
181  if (!Printer)
182  return true;
183 
184  PM.add(Printer);
185  return false;
186 }
187 
189  PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
190  bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
191  AnalysisID StopBefore, AnalysisID StopAfter) {
192  // Add common CodeGen passes.
193  MCContext *Context =
194  addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
195  StopBefore, StopAfter);
196  if (!Context)
197  return true;
198 
199  if (StopBefore || StopAfter) {
200  PM.add(createPrintMIRPass(Out));
201  } else {
202  if (addAsmPrinter(PM, Out, FileType, *Context))
203  return true;
204  }
205 
207  return false;
208 }
209 
210 /// addPassesToEmitMC - Add passes to the specified pass manager to get
211 /// machine code emitted with the MCJIT. This method returns true if machine
212 /// code is not supported. It fills the MCContext Ctx pointer which can be
213 /// used to build custom MCStreamer.
214 ///
215 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
216  raw_pwrite_stream &Out,
217  bool DisableVerify) {
218  // Add common CodeGen passes.
219  Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
220  nullptr, nullptr);
221  if (!Ctx)
222  return true;
223 
225  Ctx->setAllowTemporaryLabels(false);
226 
227  // Create the code emitter for the target if it exists. If not, .o file
228  // emission fails.
230  MCCodeEmitter *MCE =
232  MCAsmBackend *MAB =
235  if (!MCE || !MAB)
236  return true;
237 
238  const Triple &T = getTargetTriple();
240  std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
241  T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
243  /*DWARFMustBeAtTheEnd*/ true));
244 
245  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
247  getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
248  if (!Printer)
249  return true;
250 
251  PM.add(Printer);
253 
254  return false; // success!
255 }
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:493
StringRef getTargetCPU() const
LLVMContext & Context
MCTargetOptions MCOptions
Machine level options.
void setCompressDebugSections(DebugCompressionType CompressDebugSections)
Definition: MCAsmInfo.h:610
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:594
void setDisableVerify(bool Disable)
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
virtual void reset()
State management.
Definition: MCStreamer.cpp:64
MCStreamer * createNullStreamer(MCContext &Ctx)
Create a dummy machine code streamer, which does nothing.
bool addISelPasses()
High level function that adds all passes necessary to go from llvm IR representation to the MI repres...
Analysis pass providing the TargetTransformInfo.
print alias Alias Set Printer
CodeGenOpt::Level OptLevel
Definition: TargetMachine.h:81
virtual TargetPassConfig * createPassConfig(PassManagerBase &PM)
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
const MCRegisterInfo * getMCRegisterInfo() const
const Triple & getTargetTriple() const
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
unsigned DisableIntegratedAS
Disable the integrated assembler.
MCAsmBackend * createMCAsmBackend(const MCRegisterInfo &MRI, StringRef TheTriple, StringRef CPU, const MCTargetOptions &Options) const
createMCAsmBackend - Create a target specific assembly parser.
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
void setUseNamesOnTempLabels(bool Value)
Definition: MCContext.h:292
ExceptionHandling ExceptionModel
What exception model to use.
AsmPrinter * createAsmPrinter(TargetMachine &TM, std::unique_ptr< MCStreamer > &&Streamer) const
createAsmPrinter - Create a target specific assembly printer pass.
Target-Independent Code Generator Pass Configuration Options.
const MCAsmInfo * AsmInfo
Contains target specific asm information.
Definition: TargetMachine.h:84
Context object for machine code objects.
Definition: MCContext.h:59
const MCInstrInfo * getMCInstrInfo() const
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
void setStartStopPasses(AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopBefore, AnalysisID StopAfter)
Set the StartAfter, StartBefore and StopAfter passes to allow running only a portion of the normal co...
#define F(x, y, z)
Definition: MD5.cpp:55
const MCSubtargetInfo * STI
Definition: TargetMachine.h:88
#define T
bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, raw_pwrite_stream &OS, bool DisableVerify=true) override
Add passes to the specified pass manager to get machine code emitted with the MCJIT.
bool PreserveAsmComments
Preserve Comments in Assembly.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
Streaming machine code generation interface.
Definition: MCStreamer.h:167
virtual void setPreserveAsmComments(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:602
void setAllowTemporaryLabels(bool Value)
Definition: MCContext.h:291
Concrete BasicTTIImpl that can be used if no further customization is needed.
CodeModel::Model CMModel
Definition: TargetMachine.h:80
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:22
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:24
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.
static MCContext * addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM, bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopBefore, AnalysisID StopAfter)
addPassesToX helper drives creation and initialization of TargetPassConfig.
MCCodeEmitter * createMCCodeEmitter(const MCInstrInfo &II, const MCRegisterInfo &MRI, MCContext &Ctx) const
createMCCodeEmitter - Create a target specific code emitter.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
void setRelaxELFRelocations(bool V)
Definition: MCAsmInfo.h:617
const Target & TheTarget
The Target that this machine was created for.
Definition: TargetMachine.h:63
cl::opt< TargetMachine::CodeGenFileType > FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values(clEnumValN(TargetMachine::CGFT_AssemblyFile,"asm","Emit an assembly ('.s') file"), clEnumValN(TargetMachine::CGFT_ObjectFile,"obj","Emit a native object ('.o') file"), clEnumValN(TargetMachine::CGFT_Null,"null","Emit nothing, for performance testing")))
void adjustCodeGenOpts(const Triple &TT, Reloc::Model RM, CodeModel::Model &CM) const
const MCInstrInfo * MII
Definition: TargetMachine.h:87
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
StringRef getTargetFeatureString() const
const MCContext & getContext() const
DebugCompressionType CompressDebugSections
Compress DWARF debug sections.
bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, bool DisableVerify=true, AnalysisID StartBefore=nullptr, AnalysisID StartAfter=nullptr, AnalysisID StopBefore=nullptr, AnalysisID StopAfter=nullptr) override
Add passes to the specified pass manager to get the specified file emitted.
Target - Wrapper for Target specific information.
unsigned RelaxELFRelocations
std::string TargetCPU
Definition: TargetMachine.h:76
const MCRegisterInfo * MRI
Definition: TargetMachine.h:86
MCStreamer * createAsmStreamer(MCContext &Ctx, std::unique_ptr< formatted_raw_ostream > OS, bool IsVerboseAsm, bool UseDwarfDirectory, MCInstPrinter *InstPrint, MCCodeEmitter *CE, MCAsmBackend *TAB, bool ShowInst) const
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
Definition: MCInstPrinter.h:41
bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileTYpe, MCContext &Context)
Adds an AsmPrinter pass to the pipeline that prints assembly or machine code from the MI representati...
TargetOptions Options
Definition: TargetMachine.h:95
MCSubtargetInfo - Generic base class for all target subtargets.
const MCSubtargetInfo * getMCSubtargetInfo() const
const void * AnalysisID
Definition: Pass.h:46
This file defines passes to print out IR in various granularities.
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:333
LLVMTargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:35
const Target & getTarget() const
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:56
void setExceptionsType(ExceptionHandling EH)
Definition: MCAsmInfo.h:557
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
CodeGenFileType
These enums are meant to be passed into addPassesToEmitFile to indicate what type of file to emit...
TargetIRAnalysis getTargetIRAnalysis() override
Get a TargetIRAnalysis implementation for the target.
MachineFunctionPass * createPrintMIRPass(raw_ostream &OS)
MIRPrinting pass - this pass prints out the LLVM IR into the given stream using the MIR serialization...
This class contains meta information specific to a module.