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