Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:36

0001 //===-- llvm/Target/TargetMachine.h - Target Information --------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 ///
0009 /// This file defines the TargetMachine class.
0010 ///
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_TARGET_TARGETMACHINE_H
0014 #define LLVM_TARGET_TARGETMACHINE_H
0015 
0016 #include "llvm/ADT/StringRef.h"
0017 #include "llvm/IR/DataLayout.h"
0018 #include "llvm/IR/PassManager.h"
0019 #include "llvm/MC/MCStreamer.h"
0020 #include "llvm/Support/Allocator.h"
0021 #include "llvm/Support/CodeGen.h"
0022 #include "llvm/Support/Error.h"
0023 #include "llvm/Support/PGOOptions.h"
0024 #include "llvm/Target/CGPassBuilderOption.h"
0025 #include "llvm/Target/TargetOptions.h"
0026 #include "llvm/TargetParser/Triple.h"
0027 #include <optional>
0028 #include <string>
0029 #include <utility>
0030 
0031 namespace llvm {
0032 
0033 class AAManager;
0034 using ModulePassManager = PassManager<Module>;
0035 
0036 class Function;
0037 class GlobalValue;
0038 class MachineModuleInfoWrapperPass;
0039 class Mangler;
0040 class MCAsmInfo;
0041 class MCContext;
0042 class MCInstrInfo;
0043 class MCRegisterInfo;
0044 class MCSubtargetInfo;
0045 class MCSymbol;
0046 class raw_pwrite_stream;
0047 class PassBuilder;
0048 class PassInstrumentationCallbacks;
0049 struct PerFunctionMIParsingState;
0050 class SMDiagnostic;
0051 class SMRange;
0052 class Target;
0053 class TargetIntrinsicInfo;
0054 class TargetIRAnalysis;
0055 class TargetTransformInfo;
0056 class TargetLoweringObjectFile;
0057 class TargetPassConfig;
0058 class TargetSubtargetInfo;
0059 
0060 // The old pass manager infrastructure is hidden in a legacy namespace now.
0061 namespace legacy {
0062 class PassManagerBase;
0063 } // namespace legacy
0064 using legacy::PassManagerBase;
0065 
0066 struct MachineFunctionInfo;
0067 namespace yaml {
0068 struct MachineFunctionInfo;
0069 } // namespace yaml
0070 
0071 //===----------------------------------------------------------------------===//
0072 ///
0073 /// Primary interface to the complete machine description for the target
0074 /// machine.  All target-specific information should be accessible through this
0075 /// interface.
0076 ///
0077 class TargetMachine {
0078 protected: // Can only create subclasses.
0079   TargetMachine(const Target &T, StringRef DataLayoutString,
0080                 const Triple &TargetTriple, StringRef CPU, StringRef FS,
0081                 const TargetOptions &Options);
0082 
0083   /// The Target that this machine was created for.
0084   const Target &TheTarget;
0085 
0086   /// DataLayout for the target: keep ABI type size and alignment.
0087   ///
0088   /// The DataLayout is created based on the string representation provided
0089   /// during construction. It is kept here only to avoid reparsing the string
0090   /// but should not really be used during compilation, because it has an
0091   /// internal cache that is context specific.
0092   const DataLayout DL;
0093 
0094   /// Triple string, CPU name, and target feature strings the TargetMachine
0095   /// instance is created with.
0096   Triple TargetTriple;
0097   std::string TargetCPU;
0098   std::string TargetFS;
0099 
0100   Reloc::Model RM = Reloc::Static;
0101   CodeModel::Model CMModel = CodeModel::Small;
0102   uint64_t LargeDataThreshold = 0;
0103   CodeGenOptLevel OptLevel = CodeGenOptLevel::Default;
0104 
0105   /// Contains target specific asm information.
0106   std::unique_ptr<const MCAsmInfo> AsmInfo;
0107   std::unique_ptr<const MCRegisterInfo> MRI;
0108   std::unique_ptr<const MCInstrInfo> MII;
0109   std::unique_ptr<const MCSubtargetInfo> STI;
0110 
0111   unsigned RequireStructuredCFG : 1;
0112   unsigned O0WantsFastISel : 1;
0113 
0114   // PGO related tunables.
0115   std::optional<PGOOptions> PGOOption;
0116 
0117 public:
0118   mutable TargetOptions Options;
0119 
0120   TargetMachine(const TargetMachine &) = delete;
0121   void operator=(const TargetMachine &) = delete;
0122   virtual ~TargetMachine();
0123 
0124   const Target &getTarget() const { return TheTarget; }
0125 
0126   const Triple &getTargetTriple() const { return TargetTriple; }
0127   StringRef getTargetCPU() const { return TargetCPU; }
0128   StringRef getTargetFeatureString() const { return TargetFS; }
0129   void setTargetFeatureString(StringRef FS) { TargetFS = std::string(FS); }
0130 
0131   /// Virtual method implemented by subclasses that returns a reference to that
0132   /// target's TargetSubtargetInfo-derived member variable.
0133   virtual const TargetSubtargetInfo *getSubtargetImpl(const Function &) const {
0134     return nullptr;
0135   }
0136   virtual TargetLoweringObjectFile *getObjFileLowering() const {
0137     return nullptr;
0138   }
0139 
0140   /// Create the target's instance of MachineFunctionInfo
0141   virtual MachineFunctionInfo *
0142   createMachineFunctionInfo(BumpPtrAllocator &Allocator, const Function &F,
0143                             const TargetSubtargetInfo *STI) const {
0144     return nullptr;
0145   }
0146 
0147   /// Allocate and return a default initialized instance of the YAML
0148   /// representation for the MachineFunctionInfo.
0149   virtual yaml::MachineFunctionInfo *createDefaultFuncInfoYAML() const {
0150     return nullptr;
0151   }
0152 
0153   /// Allocate and initialize an instance of the YAML representation of the
0154   /// MachineFunctionInfo.
0155   virtual yaml::MachineFunctionInfo *
0156   convertFuncInfoToYAML(const MachineFunction &MF) const {
0157     return nullptr;
0158   }
0159 
0160   /// Parse out the target's MachineFunctionInfo from the YAML reprsentation.
0161   virtual bool parseMachineFunctionInfo(const yaml::MachineFunctionInfo &,
0162                                         PerFunctionMIParsingState &PFS,
0163                                         SMDiagnostic &Error,
0164                                         SMRange &SourceRange) const {
0165     return false;
0166   }
0167 
0168   /// This method returns a pointer to the specified type of
0169   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
0170   /// returned is of the correct type.
0171   template <typename STC> const STC &getSubtarget(const Function &F) const {
0172     return *static_cast<const STC*>(getSubtargetImpl(F));
0173   }
0174 
0175   /// Create a DataLayout.
0176   const DataLayout createDataLayout() const { return DL; }
0177 
0178   /// Test if a DataLayout if compatible with the CodeGen for this target.
0179   ///
0180   /// The LLVM Module owns a DataLayout that is used for the target independent
0181   /// optimizations and code generation. This hook provides a target specific
0182   /// check on the validity of this DataLayout.
0183   bool isCompatibleDataLayout(const DataLayout &Candidate) const {
0184     return DL == Candidate;
0185   }
0186 
0187   /// Get the pointer size for this target.
0188   ///
0189   /// This is the only time the DataLayout in the TargetMachine is used.
0190   unsigned getPointerSize(unsigned AS) const {
0191     return DL.getPointerSize(AS);
0192   }
0193 
0194   unsigned getPointerSizeInBits(unsigned AS) const {
0195     return DL.getPointerSizeInBits(AS);
0196   }
0197 
0198   unsigned getProgramPointerSize() const {
0199     return DL.getPointerSize(DL.getProgramAddressSpace());
0200   }
0201 
0202   unsigned getAllocaPointerSize() const {
0203     return DL.getPointerSize(DL.getAllocaAddrSpace());
0204   }
0205 
0206   /// Reset the target options based on the function's attributes.
0207   // FIXME: Remove TargetOptions that affect per-function code generation
0208   // from TargetMachine.
0209   void resetTargetOptions(const Function &F) const;
0210 
0211   /// Return target specific asm information.
0212   const MCAsmInfo *getMCAsmInfo() const { return AsmInfo.get(); }
0213 
0214   const MCRegisterInfo *getMCRegisterInfo() const { return MRI.get(); }
0215   const MCInstrInfo *getMCInstrInfo() const { return MII.get(); }
0216   const MCSubtargetInfo *getMCSubtargetInfo() const { return STI.get(); }
0217 
0218   /// If intrinsic information is available, return it.  If not, return null.
0219   virtual const TargetIntrinsicInfo *getIntrinsicInfo() const {
0220     return nullptr;
0221   }
0222 
0223   bool requiresStructuredCFG() const { return RequireStructuredCFG; }
0224   void setRequiresStructuredCFG(bool Value) { RequireStructuredCFG = Value; }
0225 
0226   /// Returns the code generation relocation model. The choices are static, PIC,
0227   /// and dynamic-no-pic, and target default.
0228   Reloc::Model getRelocationModel() const;
0229 
0230   /// Returns the code model. The choices are small, kernel, medium, large, and
0231   /// target default.
0232   CodeModel::Model getCodeModel() const { return CMModel; }
0233 
0234   /// Returns the maximum code size possible under the code model.
0235   uint64_t getMaxCodeSize() const;
0236 
0237   /// Set the code model.
0238   void setCodeModel(CodeModel::Model CM) { CMModel = CM; }
0239 
0240   void setLargeDataThreshold(uint64_t LDT) { LargeDataThreshold = LDT; }
0241   bool isLargeGlobalValue(const GlobalValue *GV) const;
0242 
0243   bool isPositionIndependent() const;
0244 
0245   bool shouldAssumeDSOLocal(const GlobalValue *GV) const;
0246 
0247   /// Returns true if this target uses emulated TLS.
0248   bool useEmulatedTLS() const;
0249 
0250   /// Returns true if this target uses TLS Descriptors.
0251   bool useTLSDESC() const;
0252 
0253   /// Returns the TLS model which should be used for the given global variable.
0254   TLSModel::Model getTLSModel(const GlobalValue *GV) const;
0255 
0256   /// Returns the optimization level: None, Less, Default, or Aggressive.
0257   CodeGenOptLevel getOptLevel() const { return OptLevel; }
0258 
0259   /// Overrides the optimization level.
0260   void setOptLevel(CodeGenOptLevel Level) { OptLevel = Level; }
0261 
0262   void setFastISel(bool Enable) { Options.EnableFastISel = Enable; }
0263   bool getO0WantsFastISel() { return O0WantsFastISel; }
0264   void setO0WantsFastISel(bool Enable) { O0WantsFastISel = Enable; }
0265   void setGlobalISel(bool Enable) { Options.EnableGlobalISel = Enable; }
0266   void setGlobalISelAbort(GlobalISelAbortMode Mode) {
0267     Options.GlobalISelAbort = Mode;
0268   }
0269   void setMachineOutliner(bool Enable) {
0270     Options.EnableMachineOutliner = Enable;
0271   }
0272   void setSupportsDefaultOutlining(bool Enable) {
0273     Options.SupportsDefaultOutlining = Enable;
0274   }
0275   void setSupportsDebugEntryValues(bool Enable) {
0276     Options.SupportsDebugEntryValues = Enable;
0277   }
0278 
0279   void setCFIFixup(bool Enable) { Options.EnableCFIFixup = Enable; }
0280 
0281   bool getAIXExtendedAltivecABI() const {
0282     return Options.EnableAIXExtendedAltivecABI;
0283   }
0284 
0285   bool getUniqueSectionNames() const { return Options.UniqueSectionNames; }
0286 
0287   /// Return true if unique basic block section names must be generated.
0288   bool getUniqueBasicBlockSectionNames() const {
0289     return Options.UniqueBasicBlockSectionNames;
0290   }
0291 
0292   bool getSeparateNamedSections() const {
0293     return Options.SeparateNamedSections;
0294   }
0295 
0296   /// Return true if data objects should be emitted into their own section,
0297   /// corresponds to -fdata-sections.
0298   bool getDataSections() const {
0299     return Options.DataSections;
0300   }
0301 
0302   /// Return true if functions should be emitted into their own section,
0303   /// corresponding to -ffunction-sections.
0304   bool getFunctionSections() const {
0305     return Options.FunctionSections;
0306   }
0307 
0308   /// Return true if visibility attribute should not be emitted in XCOFF,
0309   /// corresponding to -mignore-xcoff-visibility.
0310   bool getIgnoreXCOFFVisibility() const {
0311     return Options.IgnoreXCOFFVisibility;
0312   }
0313 
0314   /// Return true if XCOFF traceback table should be emitted,
0315   /// corresponding to -xcoff-traceback-table.
0316   bool getXCOFFTracebackTable() const { return Options.XCOFFTracebackTable; }
0317 
0318   /// If basic blocks should be emitted into their own section,
0319   /// corresponding to -fbasic-block-sections.
0320   llvm::BasicBlockSection getBBSectionsType() const {
0321     return Options.BBSections;
0322   }
0323 
0324   /// Get the list of functions and basic block ids that need unique sections.
0325   const MemoryBuffer *getBBSectionsFuncListBuf() const {
0326     return Options.BBSectionsFuncListBuf.get();
0327   }
0328 
0329   /// Returns true if a cast between SrcAS and DestAS is a noop.
0330   virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const {
0331     return false;
0332   }
0333 
0334   void setPGOOption(std::optional<PGOOptions> PGOOpt) { PGOOption = PGOOpt; }
0335   const std::optional<PGOOptions> &getPGOOption() const { return PGOOption; }
0336 
0337   /// If the specified generic pointer could be assumed as a pointer to a
0338   /// specific address space, return that address space.
0339   ///
0340   /// Under offloading programming, the offloading target may be passed with
0341   /// values only prepared on the host side and could assume certain
0342   /// properties.
0343   virtual unsigned getAssumedAddrSpace(const Value *V) const { return -1; }
0344 
0345   /// If the specified predicate checks whether a generic pointer falls within
0346   /// a specified address space, return that generic pointer and the address
0347   /// space being queried.
0348   ///
0349   /// Such predicates could be specified in @llvm.assume intrinsics for the
0350   /// optimizer to assume that the given generic pointer always falls within
0351   /// the address space based on that predicate.
0352   virtual std::pair<const Value *, unsigned>
0353   getPredicatedAddrSpace(const Value *V) const {
0354     return std::make_pair(nullptr, -1);
0355   }
0356 
0357   /// Get a \c TargetIRAnalysis appropriate for the target.
0358   ///
0359   /// This is used to construct the new pass manager's target IR analysis pass,
0360   /// set up appropriately for this target machine. Even the old pass manager
0361   /// uses this to answer queries about the IR.
0362   TargetIRAnalysis getTargetIRAnalysis() const;
0363 
0364   /// Return a TargetTransformInfo for a given function.
0365   ///
0366   /// The returned TargetTransformInfo is specialized to the subtarget
0367   /// corresponding to \p F.
0368   virtual TargetTransformInfo getTargetTransformInfo(const Function &F) const;
0369 
0370   /// Allow the target to modify the pass pipeline.
0371   // TODO: Populate all pass names by using <Target>PassRegistry.def.
0372   virtual void registerPassBuilderCallbacks(PassBuilder &) {}
0373 
0374   /// Allow the target to register alias analyses with the AAManager for use
0375   /// with the new pass manager. Only affects the "default" AAManager.
0376   virtual void registerDefaultAliasAnalyses(AAManager &) {}
0377 
0378   /// Add passes to the specified pass manager to get the specified file
0379   /// emitted.  Typically this will involve several steps of code generation.
0380   /// This method should return true if emission of this file type is not
0381   /// supported, or false on success.
0382   /// \p MMIWP is an optional parameter that, if set to non-nullptr,
0383   /// will be used to set the MachineModuloInfo for this PM.
0384   virtual bool
0385   addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &,
0386                       raw_pwrite_stream *, CodeGenFileType,
0387                       bool /*DisableVerify*/ = true,
0388                       MachineModuleInfoWrapperPass *MMIWP = nullptr) {
0389     return true;
0390   }
0391 
0392   /// Add passes to the specified pass manager to get machine code emitted with
0393   /// the MCJIT. This method returns true if machine code is not supported. It
0394   /// fills the MCContext Ctx pointer which can be used to build custom
0395   /// MCStreamer.
0396   ///
0397   virtual bool addPassesToEmitMC(PassManagerBase &, MCContext *&,
0398                                  raw_pwrite_stream &,
0399                                  bool /*DisableVerify*/ = true) {
0400     return true;
0401   }
0402 
0403   /// True if subtarget inserts the final scheduling pass on its own.
0404   ///
0405   /// Branch relaxation, which must happen after block placement, can
0406   /// on some targets (e.g. SystemZ) expose additional post-RA
0407   /// scheduling opportunities.
0408   virtual bool targetSchedulesPostRAScheduling() const { return false; };
0409 
0410   void getNameWithPrefix(SmallVectorImpl<char> &Name, const GlobalValue *GV,
0411                          Mangler &Mang, bool MayAlwaysUsePrivate = false) const;
0412   MCSymbol *getSymbol(const GlobalValue *GV) const;
0413 
0414   /// The integer bit size to use for SjLj based exception handling.
0415   static constexpr unsigned DefaultSjLjDataSize = 32;
0416   virtual unsigned getSjLjDataSize() const { return DefaultSjLjDataSize; }
0417 
0418   static std::pair<int, int> parseBinutilsVersion(StringRef Version);
0419 
0420   /// getAddressSpaceForPseudoSourceKind - Given the kind of memory
0421   /// (e.g. stack) the target returns the corresponding address space.
0422   virtual unsigned getAddressSpaceForPseudoSourceKind(unsigned Kind) const {
0423     return 0;
0424   }
0425 
0426   /// Entry point for module splitting. Targets can implement custom module
0427   /// splitting logic, mainly used by LTO for --lto-partitions.
0428   ///
0429   /// \returns `true` if the module was split, `false` otherwise. When  `false`
0430   /// is returned, it is assumed that \p ModuleCallback has never been called
0431   /// and \p M has not been modified.
0432   virtual bool splitModule(
0433       Module &M, unsigned NumParts,
0434       function_ref<void(std::unique_ptr<Module> MPart)> ModuleCallback) {
0435     return false;
0436   }
0437 
0438   /// Create a pass configuration object to be used by addPassToEmitX methods
0439   /// for generating a pipeline of CodeGen passes.
0440   virtual TargetPassConfig *createPassConfig(PassManagerBase &PM) {
0441     return nullptr;
0442   }
0443 
0444   virtual Error buildCodeGenPipeline(ModulePassManager &, raw_pwrite_stream &,
0445                                      raw_pwrite_stream *, CodeGenFileType,
0446                                      const CGPassBuilderOption &,
0447                                      PassInstrumentationCallbacks *) {
0448     return make_error<StringError>("buildCodeGenPipeline is not overridden",
0449                                    inconvertibleErrorCode());
0450   }
0451 
0452   /// Returns true if the target is expected to pass all machine verifier
0453   /// checks. This is a stopgap measure to fix targets one by one. We will
0454   /// remove this at some point and always enable the verifier when
0455   /// EXPENSIVE_CHECKS is enabled.
0456   virtual bool isMachineVerifierClean() const { return true; }
0457 
0458   /// Adds an AsmPrinter pass to the pipeline that prints assembly or
0459   /// machine code from the MI representation.
0460   virtual bool addAsmPrinter(PassManagerBase &PM, raw_pwrite_stream &Out,
0461                              raw_pwrite_stream *DwoOut,
0462                              CodeGenFileType FileType, MCContext &Context) {
0463     return false;
0464   }
0465 
0466   virtual Expected<std::unique_ptr<MCStreamer>>
0467   createMCStreamer(raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
0468                    CodeGenFileType FileType, MCContext &Ctx) {
0469     return nullptr;
0470   }
0471 
0472   /// True if the target uses physical regs (as nearly all targets do). False
0473   /// for stack machines such as WebAssembly and other virtual-register
0474   /// machines. If true, all vregs must be allocated before PEI. If false, then
0475   /// callee-save register spilling and scavenging are not needed or used. If
0476   /// false, implicitly defined registers will still be assumed to be physical
0477   /// registers, except that variadic defs will be allocated vregs.
0478   virtual bool usesPhysRegsForValues() const { return true; }
0479 
0480   /// True if the target wants to use interprocedural register allocation by
0481   /// default. The -enable-ipra flag can be used to override this.
0482   virtual bool useIPRA() const { return false; }
0483 
0484   /// The default variant to use in unqualified `asm` instructions.
0485   /// If this returns 0, `asm "$(foo$|bar$)"` will evaluate to `asm "foo"`.
0486   virtual int unqualifiedInlineAsmVariant() const { return 0; }
0487 
0488   // MachineRegisterInfo callback function
0489   virtual void registerMachineRegisterInfoCallback(MachineFunction &MF) const {}
0490 };
0491 
0492 } // end namespace llvm
0493 
0494 #endif // LLVM_TARGET_TARGETMACHINE_H