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