LLVM  3.7.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 
15 #include "llvm/Analysis/Passes.h"
20 #include "llvm/CodeGen/Passes.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"
35 #include "llvm/Transforms/Scalar.h"
36 using namespace llvm;
37 
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.
42 EnableFastISelOption("fast-isel", cl::Hidden,
43  cl::desc("Enable the \"fast\" instruction selector"));
44 
48  // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
49  // to some backends having subtarget feature dependent module level
50  // code generation. This is similar to the hack in the AsmPrinter for
51  // module level assembly etc.
54 
55  MCAsmInfo *TmpAsmInfo =
57  // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
58  // and if the old one gets included then MCAsmInfo will be NULL and
59  // we'll crash later.
60  // Provide the user with a useful error message about what's wrong.
61  assert(TmpAsmInfo && "MCAsmInfo not initialized. "
62  "Make sure you include the correct TargetSelect.h"
63  "and that InitializeAllTargetMCs() is being invoked!");
64 
66  TmpAsmInfo->setUseIntegratedAssembler(false);
67 
69  TmpAsmInfo->setCompressDebugSections(true);
70 
71  AsmInfo = TmpAsmInfo;
72 }
73 
75  StringRef DataLayoutString,
76  const Triple &TT, StringRef CPU,
77  StringRef FS, TargetOptions Options,
80  : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
81  CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL);
82 }
83 
85  return TargetIRAnalysis([this](Function &F) {
86  return TargetTransformInfo(BasicTTIImpl(this, F));
87  });
88 }
89 
90 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
91 static MCContext *
93  bool DisableVerify, AnalysisID StartBefore,
95  MachineFunctionInitializer *MFInitializer = nullptr) {
96 
97  // Add internal analysis passes from the target machine.
99 
100  // Targets may override createPassConfig to provide a target-specific
101  // subclass.
102  TargetPassConfig *PassConfig = TM->createPassConfig(PM);
103  PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
104 
105  // Set PassConfig options provided by TargetMachine.
106  PassConfig->setDisableVerify(DisableVerify);
107 
108  PM.add(PassConfig);
109 
110  PassConfig->addIRPasses();
111 
112  PassConfig->addCodeGenPrepare();
113 
114  PassConfig->addPassesToHandleExceptions();
115 
116  PassConfig->addISelPrepare();
117 
118  // Install a MachineModuleInfo class, which is an immutable pass that holds
119  // all the per-module stuff we're generating, including MCContext.
121  *TM->getMCAsmInfo(), *TM->getMCRegisterInfo(), TM->getObjFileLowering());
122  PM.add(MMI);
123 
124  // Set up a MachineFunction for the rest of CodeGen to work on.
125  PM.add(new MachineFunctionAnalysis(*TM, MFInitializer));
126 
127  // Enable FastISel with -fast, but allow that to be overridden.
129  (TM->getOptLevel() == CodeGenOpt::None &&
131  TM->setFastISel(true);
132 
133  // Ask the target for an isel.
134  if (PassConfig->addInstSelector())
135  return nullptr;
136 
137  PassConfig->addMachinePasses();
138 
139  PassConfig->setInitialized();
140 
141  return &MMI->getContext();
142 }
143 
145  PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
146  bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
148  // Add common CodeGen passes.
149  MCContext *Context =
150  addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
151  StopAfter, MFInitializer);
152  if (!Context)
153  return true;
154 
155  if (StopAfter) {
156  PM.add(createPrintMIRPass(outs()));
157  return false;
158  }
159 
161  Context->setAllowTemporaryLabels(false);
162 
164  const MCAsmInfo &MAI = *getMCAsmInfo();
166  const MCInstrInfo &MII = *getMCInstrInfo();
167 
168  std::unique_ptr<MCStreamer> AsmStreamer;
169 
170  switch (FileType) {
171  case CGFT_AssemblyFile: {
173  getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
174 
175  // Create a code emitter if asked to show the encoding.
176  MCCodeEmitter *MCE = nullptr;
178  MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
179 
180  MCAsmBackend *MAB =
182  auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
184  *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
185  Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
187  AsmStreamer.reset(S);
188  break;
189  }
190  case CGFT_ObjectFile: {
191  // Create the code emitter for the target if it exists. If not, .o file
192  // emission fails.
193  MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
194  MCAsmBackend *MAB =
196  if (!MCE || !MAB)
197  return true;
198 
199  // Don't waste memory on names of temp labels.
200  Context->setUseNamesOnTempLabels(false);
201 
202  Triple T(getTargetTriple().str());
203  AsmStreamer.reset(getTarget().createMCObjectStreamer(
204  T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
205  /*DWARFMustBeAtTheEnd*/ true));
206  break;
207  }
208  case CGFT_Null:
209  // The Null output is intended for use for performance analysis and testing,
210  // not real users.
211  AsmStreamer.reset(getTarget().createNullStreamer(*Context));
212  break;
213  }
214 
215  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
217  getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
218  if (!Printer)
219  return true;
220 
221  PM.add(Printer);
222 
223  return false;
224 }
225 
226 /// addPassesToEmitMC - Add passes to the specified pass manager to get
227 /// machine code emitted with the MCJIT. This method returns true if machine
228 /// code is not supported. It fills the MCContext Ctx pointer which can be
229 /// used to build custom MCStreamer.
230 ///
231 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
232  raw_pwrite_stream &Out,
233  bool DisableVerify) {
234  // Add common CodeGen passes.
235  Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
236  nullptr);
237  if (!Ctx)
238  return true;
239 
241  Ctx->setAllowTemporaryLabels(false);
242 
243  // Create the code emitter for the target if it exists. If not, .o file
244  // emission fails.
246  MCCodeEmitter *MCE =
248  MCAsmBackend *MAB =
250  if (!MCE || !MAB)
251  return true;
252 
253  const Triple &T = getTargetTriple();
255  std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
256  T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
257  /*DWARFMustBeAtTheEnd*/ true));
258 
259  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
261  getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
262  if (!Printer)
263  return true;
264 
265  PM.add(Printer);
266 
267  return false; // success!
268 }
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:465
StringRef getTargetCPU() const
MCTargetOptions MCOptions
Machine level options.
void setStartStopPasses(AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopAfter)
Set the StartAfter, StartBefore and StopAfter passes to allow running only a portion of the normal co...
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
Definition: Passes.cpp:377
virtual void setUseIntegratedAssembler(bool Value)
Set whether assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:546
void setDisableVerify(bool Disable)
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
virtual void reset()
State management.
Definition: MCStreamer.cpp:53
MCStreamer * createNullStreamer(MCContext &Ctx)
Create a dummy machine code streamer, which does nothing.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
Analysis pass providing the TargetTransformInfo.
MCAsmBackend * createMCAsmBackend(const MCRegisterInfo &MRI, StringRef TheTriple, StringRef CPU) const
createMCAsmBackend - Create a target specific assembly parser.
const std::string & str() const
Definition: Triple.h:306
F(f)
print alias Alias Set Printer
virtual TargetPassConfig * createPassConfig(PassManagerBase &PM)
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
Definition: Passes.cpp:249
MachineFunctionAnalysis - This class is a Pass that manages a MachineFunction object.
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.
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
virtual TargetLoweringObjectFile * getObjFileLowering() const
void setUseNamesOnTempLabels(bool Value)
Definition: MCContext.h:232
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.
Context object for machine code objects.
Definition: MCContext.h:48
const MCInstrInfo * getMCInstrInfo() const
virtual void addMachinePasses()
Add the complete, standard set of LLVM CodeGen passes.
Definition: Passes.cpp:495
const MCSubtargetInfo * STI
#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.
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
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:58
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
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:157
void setAllowTemporaryLabels(bool Value)
Definition: MCContext.h:231
Concrete BasicTTIImpl that can be used if no further customization is needed.
Definition: BasicTTIImpl.h:792
MCCodeEmitter - Generic instruction encoding interface.
Definition: MCCodeEmitter.h:23
MCCodeGenInfo * createMCCodeGenInfo(StringRef TT, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) const
createMCCodeGenInfo - Create a MCCodeGenInfo implementation.
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:24
static MCContext * addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM, bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer=nullptr)
addPassesToX helper drives creation and initialization of TargetPassConfig.
virtual bool addInstSelector()
addInstSelector - This method should install an instruction selector pass, which converts from LLVM c...
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:294
This file provides a helper that implements much of the TTI interface in terms of the target-independ...
virtual void addISelPrepare()
Add common passes that perform LLVM IR to IR transforms in preparation for instruction selection...
Definition: Passes.cpp:459
virtual void addCodeGenPrepare()
Add pass to prepare the LLVM IR for code generation.
Definition: Passes.cpp:451
const Target & TheTarget
The Target that this machine was created for.
const MCInstrInfo * MII
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
void addPassesToHandleExceptions()
Add passes to lower exception handling for the code generator.
Definition: Passes.cpp:418
unsigned CompressDebugSections
Compress DWARF debug sections.
static cl::opt< cl::boolOrDefault > EnableFastISelOption("fast-isel", cl::Hidden, cl::desc("Enable the \"fast\" instruction selector"))
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
MCCodeGenInfo * CodeGenInfo
Low level target information such as relocation model.
void setFastISel(bool Enable)
LLVMTargetMachine(const Target &T, StringRef DataLayoutString, const Triple &TargetTriple, StringRef CPU, StringRef FS, TargetOptions Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL)
Target - Wrapper for Target specific information.
const MCRegisterInfo * MRI
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:38
MCSubtargetInfo - Generic base class for all target subtargets.
cl::opt< std::string > StopAfter("stop-after", cl::desc("Stop compilation after a specific pass"), cl::value_desc("pass-name"), cl::init(""))
cl::opt< std::string > StartAfter("start-after", cl::desc("Resume compilation after a specific pass"), cl::value_desc("pass-name"), cl::init(""))
const MCSubtargetInfo * getMCSubtargetInfo() const
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"), clEnumValEnd))
void setCompressDebugSections(bool CompressDebugSections)
Definition: MCAsmInfo.h:552
const void * AnalysisID
Definition: Pass.h:47
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:321
Generic interface to target specific assembler backends.
Definition: MCAsmBackend.h:34
const Target & getTarget() const
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
This interface provides a way to initialize machine functions after they are created by the machine f...
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.
bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, bool DisableVerify=true, AnalysisID StartBefore=nullptr, AnalysisID StartAfter=nullptr, AnalysisID StopAfter=nullptr, MachineFunctionInitializer *MFInitializer=nullptr) override
Add passes to the specified pass manager to get the specified file emitted.
MachineFunctionPass * createPrintMIRPass(raw_ostream &OS)
MIRPrinting pass - this pass prints out the LLVM IR into the given stream using the MIR serialization...
MachineModuleInfo - This class contains meta information specific to a module.