LLVMContext.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/LLVMContext.h - Class for managing "global" state ---*- 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 declares LLVMContext, a container of "global" state in LLVM, such
  15. // as the global type and constant uniquing tables.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_LLVMCONTEXT_H
  19. #define LLVM_IR_LLVMCONTEXT_H
  20. #include "llvm-c/Types.h"
  21. #include "llvm/IR/DiagnosticHandler.h"
  22. #include "llvm/Support/CBindingWrapping.h"
  23. #include <cstdint>
  24. #include <memory>
  25. #include <optional>
  26. #include <string>
  27. namespace llvm {
  28. class DiagnosticInfo;
  29. enum DiagnosticSeverity : char;
  30. class Function;
  31. class Instruction;
  32. class LLVMContextImpl;
  33. class Module;
  34. class OptPassGate;
  35. template <typename T> class SmallVectorImpl;
  36. template <typename T> class StringMapEntry;
  37. class StringRef;
  38. class Twine;
  39. class LLVMRemarkStreamer;
  40. namespace remarks {
  41. class RemarkStreamer;
  42. }
  43. namespace SyncScope {
  44. typedef uint8_t ID;
  45. /// Known synchronization scope IDs, which always have the same value. All
  46. /// synchronization scope IDs that LLVM has special knowledge of are listed
  47. /// here. Additionally, this scheme allows LLVM to efficiently check for
  48. /// specific synchronization scope ID without comparing strings.
  49. enum {
  50. /// Synchronized with respect to signal handlers executing in the same thread.
  51. SingleThread = 0,
  52. /// Synchronized with respect to all concurrently executing threads.
  53. System = 1
  54. };
  55. } // end namespace SyncScope
  56. /// This is an important class for using LLVM in a threaded context. It
  57. /// (opaquely) owns and manages the core "global" data of LLVM's core
  58. /// infrastructure, including the type and constant uniquing tables.
  59. /// LLVMContext itself provides no locking guarantees, so you should be careful
  60. /// to have one context per thread.
  61. class LLVMContext {
  62. public:
  63. LLVMContextImpl *const pImpl;
  64. LLVMContext();
  65. LLVMContext(LLVMContext &) = delete;
  66. LLVMContext &operator=(const LLVMContext &) = delete;
  67. ~LLVMContext();
  68. // Pinned metadata names, which always have the same value. This is a
  69. // compile-time performance optimization, not a correctness optimization.
  70. enum : unsigned {
  71. #define LLVM_FIXED_MD_KIND(EnumID, Name, Value) EnumID = Value,
  72. #include "llvm/IR/FixedMetadataKinds.def"
  73. #undef LLVM_FIXED_MD_KIND
  74. };
  75. /// Known operand bundle tag IDs, which always have the same value. All
  76. /// operand bundle tags that LLVM has special knowledge of are listed here.
  77. /// Additionally, this scheme allows LLVM to efficiently check for specific
  78. /// operand bundle tags without comparing strings. Keep this in sync with
  79. /// LLVMContext::LLVMContext().
  80. enum : unsigned {
  81. OB_deopt = 0, // "deopt"
  82. OB_funclet = 1, // "funclet"
  83. OB_gc_transition = 2, // "gc-transition"
  84. OB_cfguardtarget = 3, // "cfguardtarget"
  85. OB_preallocated = 4, // "preallocated"
  86. OB_gc_live = 5, // "gc-live"
  87. OB_clang_arc_attachedcall = 6, // "clang.arc.attachedcall"
  88. OB_ptrauth = 7, // "ptrauth"
  89. OB_kcfi = 8, // "kcfi"
  90. };
  91. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  92. /// This ID is uniqued across modules in the current LLVMContext.
  93. unsigned getMDKindID(StringRef Name) const;
  94. /// getMDKindNames - Populate client supplied SmallVector with the name for
  95. /// custom metadata IDs registered in this LLVMContext.
  96. void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
  97. /// getOperandBundleTags - Populate client supplied SmallVector with the
  98. /// bundle tags registered in this LLVMContext. The bundle tags are ordered
  99. /// by increasing bundle IDs.
  100. /// \see LLVMContext::getOperandBundleTagID
  101. void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
  102. /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
  103. /// name TagName.
  104. StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef TagName) const;
  105. /// getOperandBundleTagID - Maps a bundle tag to an integer ID. Every bundle
  106. /// tag registered with an LLVMContext has an unique ID.
  107. uint32_t getOperandBundleTagID(StringRef Tag) const;
  108. /// getOrInsertSyncScopeID - Maps synchronization scope name to
  109. /// synchronization scope ID. Every synchronization scope registered with
  110. /// LLVMContext has unique ID except pre-defined ones.
  111. SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
  112. /// getSyncScopeNames - Populates client supplied SmallVector with
  113. /// synchronization scope names registered with LLVMContext. Synchronization
  114. /// scope names are ordered by increasing synchronization scope IDs.
  115. void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
  116. /// Define the GC for a function
  117. void setGC(const Function &Fn, std::string GCName);
  118. /// Return the GC for a function
  119. const std::string &getGC(const Function &Fn);
  120. /// Remove the GC for a function
  121. void deleteGC(const Function &Fn);
  122. /// Return true if the Context runtime configuration is set to discard all
  123. /// value names. When true, only GlobalValue names will be available in the
  124. /// IR.
  125. bool shouldDiscardValueNames() const;
  126. /// Set the Context runtime configuration to discard all value name (but
  127. /// GlobalValue). Clients can use this flag to save memory and runtime,
  128. /// especially in release mode.
  129. void setDiscardValueNames(bool Discard);
  130. /// Whether there is a string map for uniquing debug info
  131. /// identifiers across the context. Off by default.
  132. bool isODRUniquingDebugTypes() const;
  133. void enableDebugTypeODRUniquing();
  134. void disableDebugTypeODRUniquing();
  135. /// Defines the type of a yield callback.
  136. /// \see LLVMContext::setYieldCallback.
  137. using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
  138. /// setDiagnosticHandlerCallBack - This method sets a handler call back
  139. /// that is invoked when the backend needs to report anything to the user.
  140. /// The first argument is a function pointer and the second is a context pointer
  141. /// that gets passed into the DiagHandler. The third argument should be set to
  142. /// true if the handler only expects enabled diagnostics.
  143. ///
  144. /// LLVMContext doesn't take ownership or interpret either of these
  145. /// pointers.
  146. void setDiagnosticHandlerCallBack(
  147. DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
  148. void *DiagContext = nullptr, bool RespectFilters = false);
  149. /// setDiagnosticHandler - This method sets unique_ptr to object of
  150. /// DiagnosticHandler to provide custom diagnostic handling. The first
  151. /// argument is unique_ptr of object of type DiagnosticHandler or a derived
  152. /// of that. The second argument should be set to true if the handler only
  153. /// expects enabled diagnostics.
  154. ///
  155. /// Ownership of this pointer is moved to LLVMContextImpl.
  156. void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
  157. bool RespectFilters = false);
  158. /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
  159. /// setDiagnosticHandlerCallBack.
  160. DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;
  161. /// getDiagnosticContext - Return the diagnostic context set by
  162. /// setDiagnosticContext.
  163. void *getDiagnosticContext() const;
  164. /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
  165. /// setDiagnosticHandler.
  166. const DiagnosticHandler *getDiagHandlerPtr() const;
  167. /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
  168. /// to caller.
  169. std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
  170. /// Return if a code hotness metric should be included in optimization
  171. /// diagnostics.
  172. bool getDiagnosticsHotnessRequested() const;
  173. /// Set if a code hotness metric should be included in optimization
  174. /// diagnostics.
  175. void setDiagnosticsHotnessRequested(bool Requested);
  176. bool getMisExpectWarningRequested() const;
  177. void setMisExpectWarningRequested(bool Requested);
  178. void setDiagnosticsMisExpectTolerance(std::optional<uint32_t> Tolerance);
  179. uint32_t getDiagnosticsMisExpectTolerance() const;
  180. /// Return the minimum hotness value a diagnostic would need in order
  181. /// to be included in optimization diagnostics.
  182. ///
  183. /// Three possible return values:
  184. /// 0 - threshold is disabled. Everything will be printed out.
  185. /// positive int - threshold is set.
  186. /// UINT64_MAX - threshold is not yet set, and needs to be synced from
  187. /// profile summary. Note that in case of missing profile
  188. /// summary, threshold will be kept at "MAX", effectively
  189. /// suppresses all remarks output.
  190. uint64_t getDiagnosticsHotnessThreshold() const;
  191. /// Set the minimum hotness value a diagnostic needs in order to be
  192. /// included in optimization diagnostics.
  193. void setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold);
  194. /// Return if hotness threshold is requested from PSI.
  195. bool isDiagnosticsHotnessThresholdSetFromPSI() const;
  196. /// The "main remark streamer" used by all the specialized remark streamers.
  197. /// This streamer keeps generic remark metadata in memory throughout the life
  198. /// of the LLVMContext. This metadata may be emitted in a section in object
  199. /// files depending on the format requirements.
  200. ///
  201. /// All specialized remark streamers should convert remarks to
  202. /// llvm::remarks::Remark and emit them through this streamer.
  203. remarks::RemarkStreamer *getMainRemarkStreamer();
  204. const remarks::RemarkStreamer *getMainRemarkStreamer() const;
  205. void setMainRemarkStreamer(
  206. std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
  207. /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
  208. /// comming from IR and MIR passes.
  209. ///
  210. /// If it does not exist, diagnostics are not saved in a file but only emitted
  211. /// via the diagnostic handler.
  212. LLVMRemarkStreamer *getLLVMRemarkStreamer();
  213. const LLVMRemarkStreamer *getLLVMRemarkStreamer() const;
  214. void
  215. setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
  216. /// Get the prefix that should be printed in front of a diagnostic of
  217. /// the given \p Severity
  218. static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
  219. /// Report a message to the currently installed diagnostic handler.
  220. ///
  221. /// This function returns, in particular in the case of error reporting
  222. /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
  223. /// process in a self-consistent state, even though the generated code
  224. /// need not be correct.
  225. ///
  226. /// The diagnostic message will be implicitly prefixed with a severity keyword
  227. /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
  228. /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
  229. void diagnose(const DiagnosticInfo &DI);
  230. /// Registers a yield callback with the given context.
  231. ///
  232. /// The yield callback function may be called by LLVM to transfer control back
  233. /// to the client that invoked the LLVM compilation. This can be used to yield
  234. /// control of the thread, or perform periodic work needed by the client.
  235. /// There is no guaranteed frequency at which callbacks must occur; in fact,
  236. /// the client is not guaranteed to ever receive this callback. It is at the
  237. /// sole discretion of LLVM to do so and only if it can guarantee that
  238. /// suspending the thread won't block any forward progress in other LLVM
  239. /// contexts in the same process.
  240. ///
  241. /// At a suspend point, the state of the current LLVM context is intentionally
  242. /// undefined. No assumptions about it can or should be made. Only LLVM
  243. /// context API calls that explicitly state that they can be used during a
  244. /// yield callback are allowed to be used. Any other API calls into the
  245. /// context are not supported until the yield callback function returns
  246. /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
  247. void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
  248. /// Calls the yield callback (if applicable).
  249. ///
  250. /// This transfers control of the current thread back to the client, which may
  251. /// suspend the current thread. Only call this method when LLVM doesn't hold
  252. /// any global mutex or cannot block the execution in another LLVM context.
  253. void yield();
  254. /// emitError - Emit an error message to the currently installed error handler
  255. /// with optional location information. This function returns, so code should
  256. /// be prepared to drop the erroneous construct on the floor and "not crash".
  257. /// The generated code need not be correct. The error message will be
  258. /// implicitly prefixed with "error: " and should not end with a ".".
  259. void emitError(uint64_t LocCookie, const Twine &ErrorStr);
  260. void emitError(const Instruction *I, const Twine &ErrorStr);
  261. void emitError(const Twine &ErrorStr);
  262. /// Access the object which can disable optional passes and individual
  263. /// optimizations at compile time.
  264. OptPassGate &getOptPassGate() const;
  265. /// Set the object which can disable optional passes and individual
  266. /// optimizations at compile time.
  267. ///
  268. /// The lifetime of the object must be guaranteed to extend as long as the
  269. /// LLVMContext is used by compilation.
  270. void setOptPassGate(OptPassGate&);
  271. /// Set whether opaque pointers are enabled. The method may be called multiple
  272. /// times, but only with the same value. Note that creating a pointer type or
  273. /// otherwise querying the opaque pointer mode performs an implicit set to
  274. /// the default value.
  275. void setOpaquePointers(bool Enable) const;
  276. /// Whether typed pointers are supported. If false, all pointers are opaque.
  277. bool supportsTypedPointers() const;
  278. private:
  279. // Module needs access to the add/removeModule methods.
  280. friend class Module;
  281. /// addModule - Register a module as being instantiated in this context. If
  282. /// the context is deleted, the module will be deleted as well.
  283. void addModule(Module*);
  284. /// removeModule - Unregister a module from this context.
  285. void removeModule(Module*);
  286. };
  287. // Create wrappers for C Binding types (see CBindingWrapping.h).
  288. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
  289. /* Specialized opaque context conversions.
  290. */
  291. inline LLVMContext **unwrap(LLVMContextRef* Tys) {
  292. return reinterpret_cast<LLVMContext**>(Tys);
  293. }
  294. inline LLVMContextRef *wrap(const LLVMContext **Tys) {
  295. return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
  296. }
  297. } // end namespace llvm
  298. #endif // LLVM_IR_LLVMCONTEXT_H
  299. #ifdef __GNUC__
  300. #pragma GCC diagnostic pop
  301. #endif