1 //===-- llvm/Target/TargetMachine.h - Target Information --------*- C++ -*-===//
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 defines the TargetMachine and LLVMTargetMachine classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_TARGET_TARGETMACHINE_H
15 #define LLVM_TARGET_TARGETMACHINE_H
16 
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Support/CodeGen.h"
22 #include "llvm/Target/TargetOptions.h"
23 #include <string>
24 
25 namespace llvm {
26 
27 class Function;
28 class GlobalValue;
29 class MachineModuleInfo;
30 class Mangler;
31 class MCAsmInfo;
32 class MCContext;
33 class MCInstrInfo;
34 class MCRegisterInfo;
35 class MCSubtargetInfo;
36 class MCSymbol;
37 class raw_pwrite_stream;
38 class PassManagerBuilder;
39 class Target;
40 class TargetIntrinsicInfo;
41 class TargetIRAnalysis;
42 class TargetTransformInfo;
43 class TargetLoweringObjectFile;
44 class TargetPassConfig;
45 class TargetSubtargetInfo;
46 
47 // The old pass manager infrastructure is hidden in a legacy namespace now.
48 namespace legacy {
49 class PassManagerBase;
50 }
51 using legacy::PassManagerBase;
52 
53 //===----------------------------------------------------------------------===//
54 ///
55 /// Primary interface to the complete machine description for the target
56 /// machine.  All target-specific information should be accessible through this
57 /// interface.
58 ///
59 class TargetMachine {
60 protected: // Can only create subclasses.
61   TargetMachine(const Target &T, StringRef DataLayoutString,
62                 const Triple &TargetTriple, StringRef CPU, StringRef FS,
63                 const TargetOptions &Options);
64 
65   /// The Target that this machine was created for.
66   const Target &TheTarget;
67 
68   /// DataLayout for the target: keep ABI type size and alignment.
69   ///
70   /// The DataLayout is created based on the string representation provided
71   /// during construction. It is kept here only to avoid reparsing the string
72   /// but should not really be used during compilation, because it has an
73   /// internal cache that is context specific.
74   const DataLayout DL;
75 
76   /// Triple string, CPU name, and target feature strings the TargetMachine
77   /// instance is created with.
78   Triple TargetTriple;
79   std::string TargetCPU;
80   std::string TargetFS;
81 
82   Reloc::Model RM = Reloc::Static;
83   CodeModel::Model CMModel = CodeModel::Small;
84   CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
85 
86   /// Contains target specific asm information.
87   std::unique_ptr<const MCAsmInfo> AsmInfo;
88   std::unique_ptr<const MCRegisterInfo> MRI;
89   std::unique_ptr<const MCInstrInfo> MII;
90   std::unique_ptr<const MCSubtargetInfo> STI;
91 
92   unsigned RequireStructuredCFG : 1;
93   unsigned O0WantsFastISel : 1;
94 
95 public:
96   const TargetOptions DefaultOptions;
97   mutable TargetOptions Options;
98 
99   TargetMachine(const TargetMachine &) = delete;
100   void operator=(const TargetMachine &) = delete;
101   virtual ~TargetMachine();
102 
getTarget()103   const Target &getTarget() const { return TheTarget; }
104 
getTargetTriple()105   const Triple &getTargetTriple() const { return TargetTriple; }
getTargetCPU()106   StringRef getTargetCPU() const { return TargetCPU; }
getTargetFeatureString()107   StringRef getTargetFeatureString() const { return TargetFS; }
108 
109   /// Virtual method implemented by subclasses that returns a reference to that
110   /// target's TargetSubtargetInfo-derived member variable.
getSubtargetImpl(const Function &)111   virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const {
112     return nullptr;
113   }
getObjFileLowering()114   virtual TargetLoweringObjectFile *getObjFileLowering() const {
115     return nullptr;
116   }
117 
118   /// This method returns a pointer to the specified type of
119   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
120   /// returned is of the correct type.
getSubtarget(const Function & F)121   template <typename STC> const STC &getSubtarget(const Function &F) const {
122     return *static_cast<const STC*>(getSubtargetImpl(F));
123   }
124 
125   /// Create a DataLayout.
createDataLayout()126   const DataLayout createDataLayout() const { return DL; }
127 
128   /// Test if a DataLayout if compatible with the CodeGen for this target.
129   ///
130   /// The LLVM Module owns a DataLayout that is used for the target independent
131   /// optimizations and code generation. This hook provides a target specific
132   /// check on the validity of this DataLayout.
isCompatibleDataLayout(const DataLayout & Candidate)133   bool isCompatibleDataLayout(const DataLayout &Candidate) const {
134     return DL == Candidate;
135   }
136 
137   /// Get the pointer size for this target.
138   ///
139   /// This is the only time the DataLayout in the TargetMachine is used.
getPointerSize(unsigned AS)140   unsigned getPointerSize(unsigned AS) const {
141     return DL.getPointerSize(AS);
142   }
143 
getPointerSizeInBits(unsigned AS)144   unsigned getPointerSizeInBits(unsigned AS) const {
145     return DL.getPointerSizeInBits(AS);
146   }
147 
getProgramPointerSize()148   unsigned getProgramPointerSize() const {
149     return DL.getPointerSize(DL.getProgramAddressSpace());
150   }
151 
getAllocaPointerSize()152   unsigned getAllocaPointerSize() const {
153     return DL.getPointerSize(DL.getAllocaAddrSpace());
154   }
155 
156   /// Reset the target options based on the function's attributes.
157   // FIXME: Remove TargetOptions that affect per-function code generation
158   // from TargetMachine.
159   void resetTargetOptions(const Function &F) const;
160 
161   /// Return target specific asm information.
getMCAsmInfo()162   const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
163 
getMCRegisterInfo()164   const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
getMCInstrInfo()165   const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
getMCSubtargetInfo()166   const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
167 
168   /// If intrinsic information is available, return it.  If not, return null.
getIntrinsicInfo()169   virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
170     return nullptr;
171   }
172 
requiresStructuredCFG()173   bool requiresStructuredCFG() const { return RequireStructuredCFG; }
setRequiresStructuredCFG(bool Value)174   void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
175 
176   /// Returns the code generation relocation model. The choices are static, PIC,
177   /// and dynamic-no-pic, and target default.
178   Reloc::Model getRelocationModel() const;
179 
180   /// Returns the code model. The choices are small, kernel, medium, large, and
181   /// target default.
182   CodeModel::Model getCodeModel() const;
183 
184   bool isPositionIndependent() const;
185 
186   bool shouldAssumeDSOLocal(const Module &M, const GlobalValue *GV) const;
187 
188   /// Returns true if this target uses emulated TLS.
189   bool useEmulatedTLS() const;
190 
191   /// Returns the TLS model which should be used for the given global variable.
192   TLSModel::Model getTLSModel(const GlobalValue *GV) const;
193 
194   /// Returns the optimization level: None, Less, Default, or Aggressive.
195   CodeGenOpt::Level getOptLevel() const;
196 
197   /// Overrides the optimization level.
198   void setOptLevel(CodeGenOpt::Level Level);
199 
setFastISel(bool Enable)200   void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
getO0WantsFastISel()201   bool getO0WantsFastISel() { return O0WantsFastISel; }
setO0WantsFastISel(bool Enable)202   void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
setGlobalISel(bool Enable)203   void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
setGlobalISelAbort(GlobalISelAbortMode Mode)204   void setGlobalISelAbort(GlobalISelAbortMode Mode) {
205     Options.GlobalISelAbort = Mode;
206   }
setMachineOutliner(bool Enable)207   void setMachineOutliner(bool Enable) {
208     Options.EnableMachineOutliner = Enable;
209   }
setSupportsDefaultOutlining(bool Enable)210   void setSupportsDefaultOutlining(bool Enable) {
211     Options.SupportsDefaultOutlining = Enable;
212   }
213 
shouldPrintMachineCode()214   bool shouldPrintMachineCode() const { return Options.PrintMachineCode; }
215 
getUniqueSectionNames()216   bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
217 
218   /// Return true if data objects should be emitted into their own section,
219   /// corresponds to -fdata-sections.
getDataSections()220   bool getDataSections() const {
221     return Options.DataSections;
222   }
223 
224   /// Return true if functions should be emitted into their own section,
225   /// corresponding to -ffunction-sections.
getFunctionSections()226   bool getFunctionSections() const {
227     return Options.FunctionSections;
228   }
229 
230   /// Get a \c TargetIRAnalysis appropriate for the target.
231   ///
232   /// This is used to construct the new pass manager's target IR analysis pass,
233   /// set up appropriately for this target machine. Even the old pass manager
234   /// uses this to answer queries about the IR.
235   TargetIRAnalysis getTargetIRAnalysis();
236 
237   /// Return a TargetTransformInfo for a given function.
238   ///
239   /// The returned TargetTransformInfo is specialized to the subtarget
240   /// corresponding to \p F.
241   virtual TargetTransformInfo getTargetTransformInfo(const Function &F);
242 
243   /// Allow the target to modify the pass manager, e.g. by calling
244   /// PassManagerBuilder::addExtension.
adjustPassManager(PassManagerBuilder &)245   virtual void adjustPassManager(PassManagerBuilder &) {}
246 
247   /// These enums are meant to be passed into addPassesToEmitFile to indicate
248   /// what type of file to emit, and returned by it to indicate what type of
249   /// file could actually be made.
250   enum CodeGenFileType {
251     CGFT_AssemblyFile,
252     CGFT_ObjectFile,
253     CGFT_Null         // Do not emit any output.
254   };
255 
256   /// Add passes to the specified pass manager to get the specified file
257   /// emitted.  Typically this will involve several steps of code generation.
258   /// This method should return true if emission of this file type is not
259   /// supported, or false on success.
260   /// \p MMI is an optional parameter that, if set to non-nullptr,
261   /// will be used to set the MachineModuloInfo for this PM.
262   virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
263                                    raw_pwrite_stream *, CodeGenFileType,
264                                    bool /*DisableVerify*/ = true,
265                                    MachineModuleInfo *MMI = nullptr) {
266     return true;
267   }
268 
269   /// Add passes to the specified pass manager to get machine code emitted with
270   /// the MCJIT. This method returns true if machine code is not supported. It
271   /// fills the MCContext Ctx pointer which can be used to build custom
272   /// MCStreamer.
273   ///
274   virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
275                                  raw_pwrite_stream &,
276                                  bool /*DisableVerify*/ = true) {
277     return true;
278   }
279 
280   /// True if subtarget inserts the final scheduling pass on its own.
281   ///
282   /// Branch relaxation, which must happen after block placement, can
283   /// on some targets (e.g. SystemZ) expose additional post-RA
284   /// scheduling opportunities.
targetSchedulesPostRAScheduling()285   virtual bool targetSchedulesPostRAScheduling() const { return false; };
286 
287   void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
288                          Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
289   MCSymbol *getSymbol(const GlobalValue *GV) const;
290 };
291 
292 /// This class describes a target machine that is implemented with the LLVM
293 /// target-independent code generator.
294 ///
295 class LLVMTargetMachine : public TargetMachine {
296 protected: // Can only create subclasses.
297   LLVMTargetMachine(const Target &T, StringRef DataLayoutString,
298                     const Triple &TT, StringRef CPU, StringRef FS,
299                     const TargetOptions &Options, Reloc::Model RM,
300                     CodeModel::Model CM, CodeGenOpt::Level OL);
301 
302   void initAsmInfo();
303 
304 public:
305   /// Get a TargetTransformInfo implementation for the target.
306   ///
307   /// The TTI returned uses the common code generator to answer queries about
308   /// the IR.
309   TargetTransformInfo getTargetTransformInfo(const Function &F) override;
310 
311   /// Create a pass configuration object to be used by addPassToEmitX methods
312   /// for generating a pipeline of CodeGen passes.
313   virtual TargetPassConfig *createPassConfig(PassManagerBase &PM);
314 
315   /// Add passes to the specified pass manager to get the specified file
316   /// emitted.  Typically this will involve several steps of code generation.
317   /// \p MMI is an optional parameter that, if set to non-nullptr,
318   /// will be used to set the MachineModuloInfofor this PM.
319   bool addPassesToEmitFile(PassManagerBase &PM, raw_pwrite_stream &Out,
320                            raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
321                            bool DisableVerify = true,
322                            MachineModuleInfo *MMI = nullptr) override;
323 
324   /// Add passes to the specified pass manager to get machine code emitted with
325   /// the MCJIT. This method returns true if machine code is not supported. It
326   /// fills the MCContext Ctx pointer which can be used to build custom
327   /// MCStreamer.
328   bool addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
329                          raw_pwrite_stream &Out,
330                          bool DisableVerify = true) override;
331 
332   /// Returns true if the target is expected to pass all machine verifier
333   /// checks. This is a stopgap measure to fix targets one by one. We will
334   /// remove this at some point and always enable the verifier when
335   /// EXPENSIVE_CHECKS is enabled.
isMachineVerifierClean()336   virtual bool isMachineVerifierClean() const { return true; }
337 
338   /// Adds an AsmPrinter pass to the pipeline that prints assembly or
339   /// machine code from the MI representation.
340   bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
341                      raw_pwrite_stream *DwoOut, CodeGenFileType FileTYpe,
342                      MCContext &Context);
343 
344   /// True if the target uses physical regs at Prolog/Epilog insertion
345   /// time. If true (most machines), all vregs must be allocated before
346   /// PEI. If false (virtual-register machines), then callee-save register
347   /// spilling and scavenging are not needed or used.
usesPhysRegsForPEI()348   virtual bool usesPhysRegsForPEI() const { return true; }
349 
350   /// True if the target wants to use interprocedural register allocation by
351   /// default. The -enable-ipra flag can be used to override this.
useIPRA()352   virtual bool useIPRA() const {
353     return false;
354   }
355 };
356 
357 /// Helper method for getting the code model, returning Default if
358 /// CM does not have a value. The tiny and kernel models will produce
359 /// an error, so targets that support them or require more complex codemodel
360 /// selection logic should implement and call their own getEffectiveCodeModel.
getEffectiveCodeModel(Optional<CodeModel::Model> CM,CodeModel::Model Default)361 inline CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM,
362                                               CodeModel::Model Default) {
363   if (CM) {
364     // By default, targets do not support the tiny and kernel models.
365     if (*CM == CodeModel::Tiny)
366       report_fatal_error("Target does not support the tiny CodeModel");
367     if (*CM == CodeModel::Kernel)
368       report_fatal_error("Target does not support the kernel CodeModel");
369     return *CM;
370   }
371   return Default;
372 }
373 
374 } // end namespace llvm
375 
376 #endif // LLVM_TARGET_TARGETMACHINE_H
377