TargetMachine.h 19 KB

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