LLVM  10.0.0
LLVMContext.cpp
Go to the documentation of this file.
1 //===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
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 implements LLVMContext, as a wrapper around the opaque
10 // class LLVMContextImpl.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/LLVMContext.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/IR/Metadata.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/RemarkStreamer.h"
25 #include "llvm/Support/Casting.h"
28 #include <cassert>
29 #include <cstdlib>
30 #include <string>
31 #include <utility>
32 
33 using namespace llvm;
34 
36  // Create the fixed metadata kinds. This is done in the same order as the
37  // MD_* enum values so that they correspond.
38  std::pair<unsigned, StringRef> MDKinds[] = {
39 #define LLVM_FIXED_MD_KIND(EnumID, Name, Value) {EnumID, Name},
40 #include "llvm/IR/FixedMetadataKinds.def"
41 #undef LLVM_FIXED_MD_KIND
42  };
43 
44  for (auto &MDKind : MDKinds) {
45  unsigned ID = getMDKindID(MDKind.second);
46  assert(ID == MDKind.first && "metadata kind id drifted");
47  (void)ID;
48  }
49 
50  auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt");
51  assert(DeoptEntry->second == LLVMContext::OB_deopt &&
52  "deopt operand bundle id drifted!");
53  (void)DeoptEntry;
54 
55  auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet");
56  assert(FuncletEntry->second == LLVMContext::OB_funclet &&
57  "funclet operand bundle id drifted!");
58  (void)FuncletEntry;
59 
60  auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition");
61  assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition &&
62  "gc-transition operand bundle id drifted!");
63  (void)GCTransitionEntry;
64 
65  auto *CFGuardTargetEntry = pImpl->getOrInsertBundleTag("cfguardtarget");
66  assert(CFGuardTargetEntry->second == LLVMContext::OB_cfguardtarget &&
67  "cfguardtarget operand bundle id drifted!");
68  (void)CFGuardTargetEntry;
69 
70  SyncScope::ID SingleThreadSSID =
71  pImpl->getOrInsertSyncScopeID("singlethread");
72  assert(SingleThreadSSID == SyncScope::SingleThread &&
73  "singlethread synchronization scope ID drifted!");
74  (void)SingleThreadSSID;
75 
76  SyncScope::ID SystemSSID =
78  assert(SystemSSID == SyncScope::System &&
79  "system synchronization scope ID drifted!");
80  (void)SystemSSID;
81 }
82 
84 
85 void LLVMContext::addModule(Module *M) {
87 }
88 
89 void LLVMContext::removeModule(Module *M) {
91 }
92 
93 //===----------------------------------------------------------------------===//
94 // Recoverable Backend Errors
95 //===----------------------------------------------------------------------===//
96 
97 void LLVMContext::
99  void *DiagContext) {
101  pImpl->InlineAsmDiagContext = DiagContext;
102 }
103 
104 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
105 /// setInlineAsmDiagnosticHandler.
108  return pImpl->InlineAsmDiagHandler;
109 }
110 
111 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
112 /// setInlineAsmDiagnosticHandler.
114  return pImpl->InlineAsmDiagContext;
115 }
116 
119  void *DiagnosticContext, bool RespectFilters) {
120  pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler;
121  pImpl->DiagHandler->DiagnosticContext = DiagnosticContext;
122  pImpl->RespectDiagnosticFilters = RespectFilters;
123 }
124 
125 void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
126  bool RespectFilters) {
127  pImpl->DiagHandler = std::move(DH);
128  pImpl->RespectDiagnosticFilters = RespectFilters;
129 }
130 
132  pImpl->DiagnosticsHotnessRequested = Requested;
133 }
136 }
137 
140 }
143 }
144 
146  return pImpl->RemarkDiagStreamer.get();
147 }
149  return const_cast<LLVMContext *>(this)->getRemarkStreamer();
150 }
152  std::unique_ptr<RemarkStreamer> RemarkStreamer) {
153  pImpl->RemarkDiagStreamer = std::move(RemarkStreamer);
154 }
155 
158  return pImpl->DiagHandler->DiagHandlerCallback;
159 }
160 
162  return pImpl->DiagHandler->DiagnosticContext;
163 }
164 
165 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
166 {
167  pImpl->YieldCallback = Callback;
168  pImpl->YieldOpaqueHandle = OpaqueHandle;
169 }
170 
172  if (pImpl->YieldCallback)
174 }
175 
176 void LLVMContext::emitError(const Twine &ErrorStr) {
178 }
179 
180 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
181  assert (I && "Invalid instruction");
182  diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
183 }
184 
185 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
186  // Optimization remarks are selective. They need to check whether the regexp
187  // pattern, passed via one of the -pass-remarks* flags, matches the name of
188  // the pass that is emitting the diagnostic. If there is no match, ignore the
189  // diagnostic and return.
190  //
191  // Also noisy remarks are only enabled if we have hotness information to sort
192  // them.
193  if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
194  return Remark->isEnabled() &&
195  (!Remark->isVerbose() || Remark->getHotness());
196 
197  return true;
198 }
199 
200 const char *
202  switch (Severity) {
203  case DS_Error:
204  return "error";
205  case DS_Warning:
206  return "warning";
207  case DS_Remark:
208  return "remark";
209  case DS_Note:
210  return "note";
211  }
212  llvm_unreachable("Unknown DiagnosticSeverity");
213 }
214 
216  if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
217  if (RemarkStreamer *RS = getRemarkStreamer())
218  RS->emit(*OptDiagBase);
219 
220  // If there is a report handler, use it.
221  if (pImpl->DiagHandler &&
223  pImpl->DiagHandler->handleDiagnostics(DI))
224  return;
225 
226  if (!isDiagnosticEnabled(DI))
227  return;
228 
229  // Otherwise, print the message with a prefix based on the severity.
231  errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
232  DI.print(DP);
233  errs() << "\n";
234  if (DI.getSeverity() == DS_Error)
235  exit(1);
236 }
237 
238 void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
239  diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
240 }
241 
242 //===----------------------------------------------------------------------===//
243 // Metadata Kind Uniquing
244 //===----------------------------------------------------------------------===//
245 
246 /// Return a unique non-zero ID for the specified metadata kind.
248  // If this is new, assign it its ID.
250  std::make_pair(
251  Name, pImpl->CustomMDKindNames.size()))
252  .first->second;
253 }
254 
255 /// getHandlerNames - Populate client-supplied smallvector using custom
256 /// metadata name and ID.
260  E = pImpl->CustomMDKindNames.end(); I != E; ++I)
261  Names[I->second] = I->first();
262 }
263 
266 }
267 
269  return pImpl->getOperandBundleTagID(Tag);
270 }
271 
273  return pImpl->getOrInsertSyncScopeID(SSN);
274 }
275 
277  pImpl->getSyncScopeNames(SSNs);
278 }
279 
280 void LLVMContext::setGC(const Function &Fn, std::string GCName) {
281  auto It = pImpl->GCNames.find(&Fn);
282 
283  if (It == pImpl->GCNames.end()) {
284  pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
285  return;
286  }
287  It->second = std::move(GCName);
288 }
289 
290 const std::string &LLVMContext::getGC(const Function &Fn) {
291  return pImpl->GCNames[&Fn];
292 }
293 
295  pImpl->GCNames.erase(&Fn);
296 }
297 
299  return pImpl->DiscardValueNames;
300 }
301 
303 
305  if (pImpl->DITypeMap)
306  return;
307 
308  pImpl->DITypeMap.emplace();
309 }
310 
312 
314  pImpl->DiscardValueNames = Discard;
315 }
316 
318  return pImpl->getOptPassGate();
319 }
320 
322  pImpl->setOptPassGate(OPG);
323 }
324 
326  return pImpl->DiagHandler.get();
327 }
328 
329 std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
330  return std::move(pImpl->DiagHandler);
331 }
void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
This is the base class for diagnostic handling in LLVM.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void setRemarkStreamer(std::unique_ptr< RemarkStreamer > RemarkStreamer)
Set the diagnostics output used for optimization diagnostics.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Tags) const
This class represents lattice values for constants.
Definition: AllocatorList.h:23
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
const std::string & getGC(const Function &Fn)
Return the GC for a function.
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
Definition: OptBisect.h:25
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
RemarkStreamer * getRemarkStreamer()
Return the streamer used by the backend to save remark diagnostics.
std::unique_ptr< DiagnosticHandler > getDiagnosticHandler()
getDiagnosticHandler - transfers owenership of DiagnosticHandler unique_ptr to caller.
void(*)(LLVMContext *Context, void *OpaqueHandle) YieldCallbackTy
Defines the type of a yield callback.
Definition: LLVMContext.h:148
uint32_t getOperandBundleTagID(StringRef Tag) const
void setGC(const Function &Fn, std::string GCName)
Define the GC for a function.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
This file contains the declarations for metadata subclasses.
void enableDebugTypeODRUniquing()
void * getInlineAsmDiagnosticContext() const
getInlineAsmDiagnosticContext - Return the diagnostic context set by setInlineAsmDiagnosticHandler.
void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler, void *DiagContext=nullptr)
setInlineAsmDiagnosticHandler - This method sets a handler that is invoked when problems with inline ...
Definition: LLVMContext.cpp:98
void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
Registers a yield callback with the given context.
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
void yield()
Calls the yield callback (if applicable).
LLVMContext::InlineAsmDiagHandlerTy InlineAsmDiagHandler
Synchronized with respect to signal handlers executing in the same thread.
Definition: LLVMContext.h:50
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void disableDebugTypeODRUniquing()
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
void setDiagnosticsHotnessThreshold(uint64_t Threshold)
Set the minimum hotness value a diagnostic needs in order to be included in optimization diagnostics...
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
unsigned size() const
Definition: StringMap.h:111
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
getMDKindNames - Populate client supplied SmallVector with the name for custom metadata IDs registere...
void deleteGC(const Function &Fn)
Remove the GC for a function.
std::unique_ptr< DiagnosticHandler > DiagHandler
bool DiscardValueNames
Flag to indicate if Value (other than GlobalValue) retains their name or not.
static void DiagHandler(const SMDiagnostic &Diag, void *Context)
Definition: TextStub.cpp:1093
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time...
void setDiagnosticsHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
void setOptPassGate(OptPassGate &)
Set the object which can disable optional passes and individual optimizations at compile time...
void(*)(const DiagnosticInfo &DI, void *Context) DiagnosticHandlerTy
LLVMContext::YieldCallbackTy YieldCallback
void setDiagnosticHandlerCallBack(DiagnosticHandler::DiagnosticHandlerTy DiagHandler, void *DiagContext=nullptr, bool RespectFilters=false)
setDiagnosticHandlerCallBack - This method sets a handler call back that is invoked when the backend ...
StringMap< unsigned > CustomMDKindNames
CustomMDKindNames - Map to hold the metadata string to ID mapping.
void setOptPassGate(OptPassGate &)
Set the object which can disable optional passes and individual optimizations at compile time...
This is the base abstract class for diagnostic reporting in the backend.
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time...
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
StringMapEntry< uint32_t > * getOrInsertBundleTag(StringRef Tag)
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
getOperandBundleTags - Populate client supplied SmallVector with the bundle tags registered in this L...
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
uint64_t getDiagnosticsHotnessThreshold() const
Return the minimum hotness value a diagnostic would need in order to be included in optimization diag...
bool getDiagnosticsHotnessRequested() const
Return if a code hotness metric should be included in optimization diagnostics.
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
uint64_t DiagnosticsHotnessThreshold
Diagnostic information for inline asm reporting.
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:65
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:53
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:377
Module.h This file contains the declarations for the Module class.
static const char * getDiagnosticMessagePrefix(DiagnosticSeverity Severity)
Get the prefix that should be printed in front of a diagnostic of the given Severity.
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:393
SmallPtrSet< Module *, 4 > OwnedModules
OwnedModules - The set of modules instantiated in this context, and which will be automatically delet...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:242
void(*)(const SMDiagnostic &, void *Context, unsigned LocCookie) InlineAsmDiagHandlerTy
Definition: LLVMContext.h:144
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
Streamer for remarks.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID...
Basic diagnostic printer that uses an underlying raw_ostream.
iterator begin()
Definition: StringMap.h:337
#define I(x, y, z)
Definition: MD5.cpp:58
DenseMap< const Function *, std::string > GCNames
Maintain the GC name for each function.
DiagnosticSeverity getSeverity() const
InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const
getInlineAsmDiagnosticHandler - Return the diagnostic handler set by setInlineAsmDiagnosticHandler.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
std::unique_ptr< RemarkStreamer > RemarkDiagStreamer
const DiagnosticHandler * getDiagHandlerPtr() const
getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by setDiagnosticHandler.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
void * getDiagnosticContext() const
getDiagnosticContext - Return the diagnostic context set by setDiagnosticContext. ...
static bool isDiagnosticEnabled(const DiagnosticInfo &DI)
DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const
getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by setDiagnosticHandlerCal...
Optional< DenseMap< const MDString *, DICompositeType * > > DITypeMap
iterator end()
Definition: StringMap.h:340
uint32_t getOperandBundleTagID(StringRef Tag) const
getOperandBundleTagID - Maps a bundle tag to an integer ID.
void resize(size_type N)
Definition: SmallVector.h:344