LLVM 20.0.0git
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"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
19#include "llvm/ADT/Twine.h"
27#include <cassert>
28#include <cstdlib>
29#include <string>
30#include <utility>
31
32using namespace llvm;
33
35 // Create the fixed metadata kinds. This is done in the same order as the
36 // MD_* enum values so that they correspond.
37 std::pair<unsigned, StringRef> MDKinds[] = {
38#define LLVM_FIXED_MD_KIND(EnumID, Name, Value) {EnumID, Name},
39#include "llvm/IR/FixedMetadataKinds.def"
40#undef LLVM_FIXED_MD_KIND
41 };
42
43 for (auto &MDKind : MDKinds) {
44 unsigned ID = getMDKindID(MDKind.second);
45 assert(ID == MDKind.first && "metadata kind id drifted");
46 (void)ID;
47 }
48
49 auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt");
50 assert(DeoptEntry->second == LLVMContext::OB_deopt &&
51 "deopt operand bundle id drifted!");
52 (void)DeoptEntry;
53
54 auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet");
55 assert(FuncletEntry->second == LLVMContext::OB_funclet &&
56 "funclet operand bundle id drifted!");
57 (void)FuncletEntry;
58
59 auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition");
60 assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition &&
61 "gc-transition operand bundle id drifted!");
62 (void)GCTransitionEntry;
63
64 auto *CFGuardTargetEntry = pImpl->getOrInsertBundleTag("cfguardtarget");
65 assert(CFGuardTargetEntry->second == LLVMContext::OB_cfguardtarget &&
66 "cfguardtarget operand bundle id drifted!");
67 (void)CFGuardTargetEntry;
68
69 auto *PreallocatedEntry = pImpl->getOrInsertBundleTag("preallocated");
70 assert(PreallocatedEntry->second == LLVMContext::OB_preallocated &&
71 "preallocated operand bundle id drifted!");
72 (void)PreallocatedEntry;
73
74 auto *GCLiveEntry = pImpl->getOrInsertBundleTag("gc-live");
75 assert(GCLiveEntry->second == LLVMContext::OB_gc_live &&
76 "gc-transition operand bundle id drifted!");
77 (void)GCLiveEntry;
78
79 auto *ClangAttachedCall =
80 pImpl->getOrInsertBundleTag("clang.arc.attachedcall");
81 assert(ClangAttachedCall->second == LLVMContext::OB_clang_arc_attachedcall &&
82 "clang.arc.attachedcall operand bundle id drifted!");
83 (void)ClangAttachedCall;
84
85 auto *PtrauthEntry = pImpl->getOrInsertBundleTag("ptrauth");
86 assert(PtrauthEntry->second == LLVMContext::OB_ptrauth &&
87 "ptrauth operand bundle id drifted!");
88 (void)PtrauthEntry;
89
90 auto *KCFIEntry = pImpl->getOrInsertBundleTag("kcfi");
91 assert(KCFIEntry->second == LLVMContext::OB_kcfi &&
92 "kcfi operand bundle id drifted!");
93 (void)KCFIEntry;
94
95 auto *ConvergenceCtrlEntry = pImpl->getOrInsertBundleTag("convergencectrl");
96 assert(ConvergenceCtrlEntry->second == LLVMContext::OB_convergencectrl &&
97 "convergencectrl operand bundle id drifted!");
98 (void)ConvergenceCtrlEntry;
99
100 SyncScope::ID SingleThreadSSID =
101 pImpl->getOrInsertSyncScopeID("singlethread");
102 assert(SingleThreadSSID == SyncScope::SingleThread &&
103 "singlethread synchronization scope ID drifted!");
104 (void)SingleThreadSSID;
105
106 SyncScope::ID SystemSSID =
108 assert(SystemSSID == SyncScope::System &&
109 "system synchronization scope ID drifted!");
110 (void)SystemSSID;
111}
112
114
115void LLVMContext::addModule(Module *M) {
117}
118
119void LLVMContext::removeModule(Module *M) {
121 pImpl->MachineFunctionNums.erase(M);
122}
123
125 Module *M = F.getParent();
126 assert(pImpl->OwnedModules.contains(M) && "Unexpected module!");
127 return pImpl->MachineFunctionNums[M]++;
128}
129
130//===----------------------------------------------------------------------===//
131// Recoverable Backend Errors
132//===----------------------------------------------------------------------===//
133
136 void *DiagnosticContext, bool RespectFilters) {
137 pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler;
138 pImpl->DiagHandler->DiagnosticContext = DiagnosticContext;
139 pImpl->RespectDiagnosticFilters = RespectFilters;
140}
141
142void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
143 bool RespectFilters) {
144 pImpl->DiagHandler = std::move(DH);
145 pImpl->RespectDiagnosticFilters = RespectFilters;
146}
147
150}
153}
154
155void LLVMContext::setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold) {
157}
159 pImpl->MisExpectWarningRequested = Requested;
160}
163}
166}
168 std::optional<uint32_t> Tolerance) {
170}
172 return pImpl->DiagnosticsMisExpectTolerance.value_or(0);
173}
174
176 return !pImpl->DiagnosticsHotnessThreshold.has_value();
177}
178
180 return pImpl->MainRemarkStreamer.get();
181}
183 return const_cast<LLVMContext *>(this)->getMainRemarkStreamer();
184}
186 std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) {
187 pImpl->MainRemarkStreamer = std::move(RemarkStreamer);
188}
189
191 return pImpl->LLVMRS.get();
192}
194 return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer();
195}
197 std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) {
198 pImpl->LLVMRS = std::move(RemarkStreamer);
199}
200
203 return pImpl->DiagHandler->DiagHandlerCallback;
204}
205
207 return pImpl->DiagHandler->DiagnosticContext;
208}
209
210void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
211{
212 pImpl->YieldCallback = Callback;
213 pImpl->YieldOpaqueHandle = OpaqueHandle;
214}
215
217 if (pImpl->YieldCallback)
219}
220
221void LLVMContext::emitError(const Twine &ErrorStr) {
223}
224
225void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
226 assert (I && "Invalid instruction");
228}
229
230static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
231 // Optimization remarks are selective. They need to check whether the regexp
232 // pattern, passed via one of the -pass-remarks* flags, matches the name of
233 // the pass that is emitting the diagnostic. If there is no match, ignore the
234 // diagnostic and return.
235 //
236 // Also noisy remarks are only enabled if we have hotness information to sort
237 // them.
238 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
239 return Remark->isEnabled() &&
240 (!Remark->isVerbose() || Remark->getHotness());
241
242 return true;
243}
244
245const char *
247 switch (Severity) {
248 case DS_Error:
249 return "error";
250 case DS_Warning:
251 return "warning";
252 case DS_Remark:
253 return "remark";
254 case DS_Note:
255 return "note";
256 }
257 llvm_unreachable("Unknown DiagnosticSeverity");
258}
259
261 if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
263 RS->emit(*OptDiagBase);
264
265 // If there is a report handler, use it.
266 if (pImpl->DiagHandler) {
267 if (DI.getSeverity() == DS_Error)
268 pImpl->DiagHandler->HasErrors = true;
270 pImpl->DiagHandler->handleDiagnostics(DI))
271 return;
272 }
273
274 if (!isDiagnosticEnabled(DI))
275 return;
276
277 // Otherwise, print the message with a prefix based on the severity.
280 DI.print(DP);
281 errs() << "\n";
282 if (DI.getSeverity() == DS_Error)
283 exit(1);
284}
285
286void LLVMContext::emitError(uint64_t LocCookie, const Twine &ErrorStr) {
287 diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
288}
289
290//===----------------------------------------------------------------------===//
291// Metadata Kind Uniquing
292//===----------------------------------------------------------------------===//
293
294/// Return a unique non-zero ID for the specified metadata kind.
296 // If this is new, assign it its ID.
298 std::make_pair(
300 .first->second;
301}
302
303/// getHandlerNames - Populate client-supplied smallvector using custom
304/// metadata name and ID.
308 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
309 Names[I->second] = I->first();
310}
311
314}
315
318 return pImpl->getOrInsertBundleTag(TagName);
319}
320
323}
324
326 return pImpl->getOrInsertSyncScopeID(SSN);
327}
328
331}
332
333void LLVMContext::setGC(const Function &Fn, std::string GCName) {
334 auto It = pImpl->GCNames.find(&Fn);
335
336 if (It == pImpl->GCNames.end()) {
337 pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
338 return;
339 }
340 It->second = std::move(GCName);
341}
342
343const std::string &LLVMContext::getGC(const Function &Fn) {
344 return pImpl->GCNames[&Fn];
345}
346
348 pImpl->GCNames.erase(&Fn);
349}
350
352 return pImpl->DiscardValueNames;
353}
354
356
358 if (pImpl->DITypeMap)
359 return;
360
361 pImpl->DITypeMap.emplace();
362}
363
365
367 pImpl->DiscardValueNames = Discard;
368}
369
371 return pImpl->getOptPassGate();
372}
373
375 pImpl->setOptPassGate(OPG);
376}
377
379 return pImpl->DiagHandler.get();
380}
381
382std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
383 return std::move(pImpl->DiagHandler);
384}
385
387 assert(Enable && "Cannot disable opaque pointers");
388}
389
391 return false;
392}
393
395 return pImpl->DefaultTargetCPU;
396}
397
399 pImpl->DefaultTargetCPU = CPU;
400}
401
404}
405
407 pImpl->DefaultTargetFeatures = Features;
408}
This file defines the StringMap class.
std::string Name
static bool isDiagnosticEnabled(const DiagnosticInfo &DI)
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallVector class.
Diagnostic information for inline asm reporting.
This is the base abstract class for diagnostic reporting in the backend.
DiagnosticSeverity getSeverity() const
virtual void print(DiagnosticPrinter &DP) const =0
Print using the given DP a user-friendly message.
Basic diagnostic printer that uses an underlying raw_ostream.
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
SmallPtrSet< Module *, 4 > OwnedModules
OwnedModules - The set of modules instantiated in this context, and which will be automatically delet...
std::optional< uint32_t > DiagnosticsMisExpectTolerance
The percentage of difference between profiling branch weights and llvm.expect branch weights to toler...
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
void setOptPassGate(OptPassGate &)
Set the object which can disable optional passes and individual optimizations at compile time.
std::unique_ptr< LLVMRemarkStreamer > LLVMRS
The specialized remark streamer used by LLVM's OptimizationRemarkEmitter.
bool DiscardValueNames
Flag to indicate if Value (other than GlobalValue) retains their name or not.
DenseMap< const Function *, std::string > GCNames
Maintain the GC name for each function.
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time.
std::string DefaultTargetFeatures
DenseMap< Module *, unsigned > MachineFunctionNums
MachineFunctionNums - Keep the next available unique number available for a MachineFunction in given ...
StringMap< unsigned > CustomMDKindNames
CustomMDKindNames - Map to hold the metadata string to ID mapping.
StringMapEntry< uint32_t > * getOrInsertBundleTag(StringRef Tag)
std::unique_ptr< DiagnosticHandler > DiagHandler
std::unique_ptr< remarks::RemarkStreamer > MainRemarkStreamer
The main remark streamer used by all the other streamers (e.g.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Tags) const
std::optional< uint64_t > DiagnosticsHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
uint32_t getOperandBundleTagID(StringRef Tag) const
LLVMContext::YieldCallbackTy YieldCallback
std::optional< DenseMap< const MDString *, DICompositeType * > > DITypeMap
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
void setMisExpectWarningRequested(bool Requested)
remarks::RemarkStreamer * getMainRemarkStreamer()
The "main remark streamer" used by all the specialized remark streamers.
uint32_t getOperandBundleTagID(StringRef Tag) const
getOperandBundleTagID - Maps a bundle tag to an integer ID.
void disableDebugTypeODRUniquing()
void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
Registers a yield callback with the given context.
void deleteGC(const Function &Fn)
Remove the GC for a function.
const std::string & getGC(const Function &Fn)
Return the GC for a function.
DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const
getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by setDiagnosticHandlerCal...
void setLLVMRemarkStreamer(std::unique_ptr< LLVMRemarkStreamer > RemarkStreamer)
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
static const char * getDiagnosticMessagePrefix(DiagnosticSeverity Severity)
Get the prefix that should be printed in front of a diagnostic of the given Severity.
void enableDebugTypeODRUniquing()
std::unique_ptr< DiagnosticHandler > getDiagnosticHandler()
getDiagnosticHandler - transfers ownership of DiagnosticHandler unique_ptr to caller.
void setDefaultTargetCPU(StringRef CPU)
bool getDiagnosticsHotnessRequested() const
Return if a code hotness metric should be included in optimization diagnostics.
bool getMisExpectWarningRequested() const
void yield()
Calls the yield callback (if applicable).
void setDiagnosticsHotnessThreshold(std::optional< uint64_t > Threshold)
Set the minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
void setMainRemarkStreamer(std::unique_ptr< remarks::RemarkStreamer > MainRemarkStreamer)
bool isDiagnosticsHotnessThresholdSetFromPSI() const
Return if hotness threshold is requested from PSI.
bool supportsTypedPointers() const
Whether typed pointers are supported. If false, all pointers are opaque.
void setOptPassGate(OptPassGate &)
Set the object which can disable optional passes and individual optimizations at compile time.
StringMapEntry< uint32_t > * getOrInsertBundleTag(StringRef TagName) const
getOrInsertBundleTag - Returns the Tag to use for an operand bundle of name TagName.
void setDiagnosticsHotnessRequested(bool Requested)
Set if a code hotness metric should be included in optimization diagnostics.
void setGC(const Function &Fn, std::string GCName)
Define the GC for a function.
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
void(*)(LLVMContext *Context, void *OpaqueHandle) YieldCallbackTy
Defines the type of a yield callback.
Definition: LLVMContext.h:164
bool isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
unsigned generateMachineFunctionNum(Function &)
generateMachineFunctionNum - Get a unique number for MachineFunction that associated with the given F...
StringRef getDefaultTargetFeatures()
Similar to {get,set}DefaultTargetCPU() but for default target-features.
void setDiagnosticsMisExpectTolerance(std::optional< uint32_t > Tolerance)
LLVMContextImpl *const pImpl
Definition: LLVMContext.h:69
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void getOperandBundleTags(SmallVectorImpl< StringRef > &Result) const
getOperandBundleTags - Populate client supplied SmallVector with the bundle tags registered in this L...
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 ...
void setOpaquePointers(bool Enable) const
Set whether opaque pointers are enabled.
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
StringRef getDefaultTargetCPU()
Get or set the current "default" target CPU (target-cpu function attribute).
void getMDKindNames(SmallVectorImpl< StringRef > &Result) const
getMDKindNames - Populate client supplied SmallVector with the name for custom metadata IDs registere...
void * getDiagnosticContext() const
getDiagnosticContext - Return the diagnostic context set by setDiagnosticContext.
SyncScope::ID getOrInsertSyncScopeID(StringRef SSN)
getOrInsertSyncScopeID - Maps synchronization scope name to synchronization scope ID.
uint64_t getDiagnosticsHotnessThreshold() const
Return the minimum hotness value a diagnostic would need in order to be included in optimization diag...
void setDefaultTargetFeatures(StringRef Features)
const DiagnosticHandler * getDiagHandlerPtr() const
getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by setDiagnosticHandler.
void setDiagnosticHandler(std::unique_ptr< DiagnosticHandler > &&DH, bool RespectFilters=false)
setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler to provide custom d...
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time.
LLVMRemarkStreamer * getLLVMRemarkStreamer()
The "LLVM remark streamer" used by LLVM to serialize remark diagnostics comming from IR and MIR passe...
void emitError(uint64_t LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
void getSyncScopeNames(SmallVectorImpl< StringRef > &SSNs) const
getSyncScopeNames - Populates client supplied SmallVector with synchronization scope names registered...
uint32_t getDiagnosticsMisExpectTolerance() const
Streamer for LLVM remarks which has logic for dealing with DiagnosticInfo objects.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
Definition: OptBisect.h:24
bool erase(PtrType Ptr)
Remove pointer from the set.
Definition: SmallPtrSet.h:384
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:367
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:441
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
void resize(size_type N)
Definition: SmallVector.h:651
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
unsigned size() const
Definition: StringMap.h:104
iterator end()
Definition: StringMap.h:220
iterator begin()
Definition: StringMap.h:219
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:308
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
#define UINT64_MAX
Definition: DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
Definition: LLVMContext.h:54
@ System
Synchronized with respect to all concurrently executing threads.
Definition: LLVMContext.h:57
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Remark
@ DS_Warning
@ DS_Error
@ Enable
Enable colors.
This is the base class for diagnostic handling in LLVM.
void(*)(const DiagnosticInfo *DI, void *Context) DiagnosticHandlerTy