TargetMachine.h 20 KB

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