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