LLVMContext.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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/ADT/Optional.h"
  22. #include "llvm/IR/DiagnosticHandler.h"
  23. #include "llvm/Support/CBindingWrapping.h"
  24. #include <cstdint>
  25. #include <memory>
  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. };
  89. /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  90. /// This ID is uniqued across modules in the current LLVMContext.
  91. unsigned getMDKindID(StringRef Name) const;
  92. /// getMDKindNames - Populate client supplied SmallVector with the name for
  93. /// custom metadata IDs registered in this LLVMContext.
  94. void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;
  95. /// getOperandBundleTags - Populate client supplied SmallVector with the
  96. /// bundle tags registered in this LLVMContext. The bundle tags are ordered
  97. /// by increasing bundle IDs.
  98. /// \see LLVMContext::getOperandBundleTagID
  99. void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;
  100. /// getOrInsertBundleTag - Returns the Tag to use for an operand bundle of
  101. /// name TagName.
  102. StringMapEntry<uint32_t> *getOrInsertBundleTag(StringRef TagName) const;
  103. /// getOperandBundleTagID - Maps a bundle tag to an integer ID. Every bundle
  104. /// tag registered with an LLVMContext has an unique ID.
  105. uint32_t getOperandBundleTagID(StringRef Tag) const;
  106. /// getOrInsertSyncScopeID - Maps synchronization scope name to
  107. /// synchronization scope ID. Every synchronization scope registered with
  108. /// LLVMContext has unique ID except pre-defined ones.
  109. SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);
  110. /// getSyncScopeNames - Populates client supplied SmallVector with
  111. /// synchronization scope names registered with LLVMContext. Synchronization
  112. /// scope names are ordered by increasing synchronization scope IDs.
  113. void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;
  114. /// Define the GC for a function
  115. void setGC(const Function &Fn, std::string GCName);
  116. /// Return the GC for a function
  117. const std::string &getGC(const Function &Fn);
  118. /// Remove the GC for a function
  119. void deleteGC(const Function &Fn);
  120. /// Return true if the Context runtime configuration is set to discard all
  121. /// value names. When true, only GlobalValue names will be available in the
  122. /// IR.
  123. bool shouldDiscardValueNames() const;
  124. /// Set the Context runtime configuration to discard all value name (but
  125. /// GlobalValue). Clients can use this flag to save memory and runtime,
  126. /// especially in release mode.
  127. void setDiscardValueNames(bool Discard);
  128. /// Whether there is a string map for uniquing debug info
  129. /// identifiers across the context. Off by default.
  130. bool isODRUniquingDebugTypes() const;
  131. void enableDebugTypeODRUniquing();
  132. void disableDebugTypeODRUniquing();
  133. /// Defines the type of a yield callback.
  134. /// \see LLVMContext::setYieldCallback.
  135. using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);
  136. /// setDiagnosticHandlerCallBack - This method sets a handler call back
  137. /// that is invoked when the backend needs to report anything to the user.
  138. /// The first argument is a function pointer and the second is a context pointer
  139. /// that gets passed into the DiagHandler. The third argument should be set to
  140. /// true if the handler only expects enabled diagnostics.
  141. ///
  142. /// LLVMContext doesn't take ownership or interpret either of these
  143. /// pointers.
  144. void setDiagnosticHandlerCallBack(
  145. DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
  146. void *DiagContext = nullptr, bool RespectFilters = false);
  147. /// setDiagnosticHandler - This method sets unique_ptr to object of
  148. /// DiagnosticHandler to provide custom diagnostic handling. The first
  149. /// argument is unique_ptr of object of type DiagnosticHandler or a derived
  150. /// of that. The second argument should be set to true if the handler only
  151. /// expects enabled diagnostics.
  152. ///
  153. /// Ownership of this pointer is moved to LLVMContextImpl.
  154. void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
  155. bool RespectFilters = false);
  156. /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
  157. /// setDiagnosticHandlerCallBack.
  158. DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;
  159. /// getDiagnosticContext - Return the diagnostic context set by
  160. /// setDiagnosticContext.
  161. void *getDiagnosticContext() const;
  162. /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
  163. /// setDiagnosticHandler.
  164. const DiagnosticHandler *getDiagHandlerPtr() const;
  165. /// getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr
  166. /// to caller.
  167. std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();
  168. /// Return if a code hotness metric should be included in optimization
  169. /// diagnostics.
  170. bool getDiagnosticsHotnessRequested() const;
  171. /// Set if a code hotness metric should be included in optimization
  172. /// diagnostics.
  173. void setDiagnosticsHotnessRequested(bool Requested);
  174. /// Return the minimum hotness value a diagnostic would need in order
  175. /// to be included in optimization diagnostics.
  176. ///
  177. /// Three possible return values:
  178. /// 0 - threshold is disabled. Everything will be printed out.
  179. /// positive int - threshold is set.
  180. /// UINT64_MAX - threshold is not yet set, and needs to be synced from
  181. /// profile summary. Note that in case of missing profile
  182. /// summary, threshold will be kept at "MAX", effectively
  183. /// suppresses all remarks output.
  184. uint64_t getDiagnosticsHotnessThreshold() const;
  185. /// Set the minimum hotness value a diagnostic needs in order to be
  186. /// included in optimization diagnostics.
  187. void setDiagnosticsHotnessThreshold(Optional<uint64_t> Threshold);
  188. /// Return if hotness threshold is requested from PSI.
  189. bool isDiagnosticsHotnessThresholdSetFromPSI() const;
  190. /// The "main remark streamer" used by all the specialized remark streamers.
  191. /// This streamer keeps generic remark metadata in memory throughout the life
  192. /// of the LLVMContext. This metadata may be emitted in a section in object
  193. /// files depending on the format requirements.
  194. ///
  195. /// All specialized remark streamers should convert remarks to
  196. /// llvm::remarks::Remark and emit them through this streamer.
  197. remarks::RemarkStreamer *getMainRemarkStreamer();
  198. const remarks::RemarkStreamer *getMainRemarkStreamer() const;
  199. void setMainRemarkStreamer(
  200. std::unique_ptr<remarks::RemarkStreamer> MainRemarkStreamer);
  201. /// The "LLVM remark streamer" used by LLVM to serialize remark diagnostics
  202. /// comming from IR and MIR passes.
  203. ///
  204. /// If it does not exist, diagnostics are not saved in a file but only emitted
  205. /// via the diagnostic handler.
  206. LLVMRemarkStreamer *getLLVMRemarkStreamer();
  207. const LLVMRemarkStreamer *getLLVMRemarkStreamer() const;
  208. void
  209. setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer);
  210. /// Get the prefix that should be printed in front of a diagnostic of
  211. /// the given \p Severity
  212. static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);
  213. /// Report a message to the currently installed diagnostic handler.
  214. ///
  215. /// This function returns, in particular in the case of error reporting
  216. /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
  217. /// process in a self-consistent state, even though the generated code
  218. /// need not be correct.
  219. ///
  220. /// The diagnostic message will be implicitly prefixed with a severity keyword
  221. /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
  222. /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
  223. void diagnose(const DiagnosticInfo &DI);
  224. /// Registers a yield callback with the given context.
  225. ///
  226. /// The yield callback function may be called by LLVM to transfer control back
  227. /// to the client that invoked the LLVM compilation. This can be used to yield
  228. /// control of the thread, or perform periodic work needed by the client.
  229. /// There is no guaranteed frequency at which callbacks must occur; in fact,
  230. /// the client is not guaranteed to ever receive this callback. It is at the
  231. /// sole discretion of LLVM to do so and only if it can guarantee that
  232. /// suspending the thread won't block any forward progress in other LLVM
  233. /// contexts in the same process.
  234. ///
  235. /// At a suspend point, the state of the current LLVM context is intentionally
  236. /// undefined. No assumptions about it can or should be made. Only LLVM
  237. /// context API calls that explicitly state that they can be used during a
  238. /// yield callback are allowed to be used. Any other API calls into the
  239. /// context are not supported until the yield callback function returns
  240. /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
  241. void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);
  242. /// Calls the yield callback (if applicable).
  243. ///
  244. /// This transfers control of the current thread back to the client, which may
  245. /// suspend the current thread. Only call this method when LLVM doesn't hold
  246. /// any global mutex or cannot block the execution in another LLVM context.
  247. void yield();
  248. /// emitError - Emit an error message to the currently installed error handler
  249. /// with optional location information. This function returns, so code should
  250. /// be prepared to drop the erroneous construct on the floor and "not crash".
  251. /// The generated code need not be correct. The error message will be
  252. /// implicitly prefixed with "error: " and should not end with a ".".
  253. void emitError(uint64_t LocCookie, const Twine &ErrorStr);
  254. void emitError(const Instruction *I, const Twine &ErrorStr);
  255. void emitError(const Twine &ErrorStr);
  256. /// Access the object which can disable optional passes and individual
  257. /// optimizations at compile time.
  258. OptPassGate &getOptPassGate() const;
  259. /// Set the object which can disable optional passes and individual
  260. /// optimizations at compile time.
  261. ///
  262. /// The lifetime of the object must be guaranteed to extend as long as the
  263. /// LLVMContext is used by compilation.
  264. void setOptPassGate(OptPassGate&);
  265. /// Enable opaque pointers. Can only be called before creating the first
  266. /// pointer type.
  267. void enableOpaquePointers() const;
  268. /// Whether typed pointers are supported. If false, all pointers are opaque.
  269. bool supportsTypedPointers() const;
  270. private:
  271. // Module needs access to the add/removeModule methods.
  272. friend class Module;
  273. /// addModule - Register a module as being instantiated in this context. If
  274. /// the context is deleted, the module will be deleted as well.
  275. void addModule(Module*);
  276. /// removeModule - Unregister a module from this context.
  277. void removeModule(Module*);
  278. };
  279. // Create wrappers for C Binding types (see CBindingWrapping.h).
  280. DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)
  281. /* Specialized opaque context conversions.
  282. */
  283. inline LLVMContext **unwrap(LLVMContextRef* Tys) {
  284. return reinterpret_cast<LLVMContext**>(Tys);
  285. }
  286. inline LLVMContextRef *wrap(const LLVMContext **Tys) {
  287. return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
  288. }
  289. } // end namespace llvm
  290. #endif // LLVM_IR_LLVMCONTEXT_H
  291. #ifdef __GNUC__
  292. #pragma GCC diagnostic pop
  293. #endif