1 //===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements LLVMContext, as a wrapper around the opaque
10 // class LLVMContextImpl.
12 //===----------------------------------------------------------------------===//
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"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LLVMRemarkStreamer.h"
23 #include "llvm/Remarks/RemarkStreamer.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
34 static StringRef
knownBundleName(unsigned BundleTagID
) {
35 switch (BundleTagID
) {
36 case LLVMContext::OB_deopt
:
38 case LLVMContext::OB_funclet
:
40 case LLVMContext::OB_gc_transition
:
41 return "gc-transition";
42 case LLVMContext::OB_cfguardtarget
:
43 return "cfguardtarget";
44 case LLVMContext::OB_preallocated
:
45 return "preallocated";
46 case LLVMContext::OB_gc_live
:
48 case LLVMContext::OB_clang_arc_attachedcall
:
49 return "clang.arc.attachedcall";
50 case LLVMContext::OB_ptrauth
:
52 case LLVMContext::OB_kcfi
:
54 case LLVMContext::OB_convergencectrl
:
55 return "convergencectrl";
57 llvm_unreachable("unknown bundle id");
60 llvm_unreachable("covered switch");
63 LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
64 // Create the fixed metadata kinds. This is done in the same order as the
65 // MD_* enum values so that they correspond.
66 std::pair
<unsigned, StringRef
> MDKinds
[] = {
67 #define LLVM_FIXED_MD_KIND(EnumID, Name, Value) {EnumID, Name},
68 #include "llvm/IR/FixedMetadataKinds.def"
69 #undef LLVM_FIXED_MD_KIND
72 for (auto &MDKind
: MDKinds
) {
73 unsigned ID
= getMDKindID(MDKind
.second
);
74 assert(ID
== MDKind
.first
&& "metadata kind id drifted");
78 for (unsigned BundleTagID
= LLVMContext::OB_deopt
;
79 BundleTagID
<= LLVMContext::OB_convergencectrl
; ++BundleTagID
) {
80 [[maybe_unused
]] const auto *Entry
=
81 pImpl
->getOrInsertBundleTag(knownBundleName(BundleTagID
));
82 assert(Entry
->second
== BundleTagID
&& "operand bundle id drifted!");
85 SyncScope::ID SingleThreadSSID
=
86 pImpl
->getOrInsertSyncScopeID("singlethread");
87 assert(SingleThreadSSID
== SyncScope::SingleThread
&&
88 "singlethread synchronization scope ID drifted!");
89 (void)SingleThreadSSID
;
91 SyncScope::ID SystemSSID
=
92 pImpl
->getOrInsertSyncScopeID("");
93 assert(SystemSSID
== SyncScope::System
&&
94 "system synchronization scope ID drifted!");
98 LLVMContext::~LLVMContext() { delete pImpl
; }
100 void LLVMContext::addModule(Module
*M
) {
101 pImpl
->OwnedModules
.insert(M
);
104 void LLVMContext::removeModule(Module
*M
) {
105 pImpl
->OwnedModules
.erase(M
);
106 pImpl
->MachineFunctionNums
.erase(M
);
109 unsigned LLVMContext::generateMachineFunctionNum(Function
&F
) {
110 Module
*M
= F
.getParent();
111 assert(pImpl
->OwnedModules
.contains(M
) && "Unexpected module!");
112 return pImpl
->MachineFunctionNums
[M
]++;
115 //===----------------------------------------------------------------------===//
116 // Recoverable Backend Errors
117 //===----------------------------------------------------------------------===//
119 void LLVMContext::setDiagnosticHandlerCallBack(
120 DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler
,
121 void *DiagnosticContext
, bool RespectFilters
) {
122 pImpl
->DiagHandler
->DiagHandlerCallback
= DiagnosticHandler
;
123 pImpl
->DiagHandler
->DiagnosticContext
= DiagnosticContext
;
124 pImpl
->RespectDiagnosticFilters
= RespectFilters
;
127 void LLVMContext::setDiagnosticHandler(std::unique_ptr
<DiagnosticHandler
> &&DH
,
128 bool RespectFilters
) {
129 pImpl
->DiagHandler
= std::move(DH
);
130 pImpl
->RespectDiagnosticFilters
= RespectFilters
;
133 void LLVMContext::setDiagnosticsHotnessRequested(bool Requested
) {
134 pImpl
->DiagnosticsHotnessRequested
= Requested
;
136 bool LLVMContext::getDiagnosticsHotnessRequested() const {
137 return pImpl
->DiagnosticsHotnessRequested
;
140 void LLVMContext::setDiagnosticsHotnessThreshold(std::optional
<uint64_t> Threshold
) {
141 pImpl
->DiagnosticsHotnessThreshold
= Threshold
;
143 void LLVMContext::setMisExpectWarningRequested(bool Requested
) {
144 pImpl
->MisExpectWarningRequested
= Requested
;
146 bool LLVMContext::getMisExpectWarningRequested() const {
147 return pImpl
->MisExpectWarningRequested
;
149 uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const {
150 return pImpl
->DiagnosticsHotnessThreshold
.value_or(UINT64_MAX
);
152 void LLVMContext::setDiagnosticsMisExpectTolerance(
153 std::optional
<uint32_t> Tolerance
) {
154 pImpl
->DiagnosticsMisExpectTolerance
= Tolerance
;
156 uint32_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
157 return pImpl
->DiagnosticsMisExpectTolerance
.value_or(0);
160 bool LLVMContext::isDiagnosticsHotnessThresholdSetFromPSI() const {
161 return !pImpl
->DiagnosticsHotnessThreshold
.has_value();
164 remarks::RemarkStreamer
*LLVMContext::getMainRemarkStreamer() {
165 return pImpl
->MainRemarkStreamer
.get();
167 const remarks::RemarkStreamer
*LLVMContext::getMainRemarkStreamer() const {
168 return const_cast<LLVMContext
*>(this)->getMainRemarkStreamer();
170 void LLVMContext::setMainRemarkStreamer(
171 std::unique_ptr
<remarks::RemarkStreamer
> RemarkStreamer
) {
172 pImpl
->MainRemarkStreamer
= std::move(RemarkStreamer
);
175 LLVMRemarkStreamer
*LLVMContext::getLLVMRemarkStreamer() {
176 return pImpl
->LLVMRS
.get();
178 const LLVMRemarkStreamer
*LLVMContext::getLLVMRemarkStreamer() const {
179 return const_cast<LLVMContext
*>(this)->getLLVMRemarkStreamer();
181 void LLVMContext::setLLVMRemarkStreamer(
182 std::unique_ptr
<LLVMRemarkStreamer
> RemarkStreamer
) {
183 pImpl
->LLVMRS
= std::move(RemarkStreamer
);
186 DiagnosticHandler::DiagnosticHandlerTy
187 LLVMContext::getDiagnosticHandlerCallBack() const {
188 return pImpl
->DiagHandler
->DiagHandlerCallback
;
191 void *LLVMContext::getDiagnosticContext() const {
192 return pImpl
->DiagHandler
->DiagnosticContext
;
195 void LLVMContext::setYieldCallback(YieldCallbackTy Callback
, void *OpaqueHandle
)
197 pImpl
->YieldCallback
= Callback
;
198 pImpl
->YieldOpaqueHandle
= OpaqueHandle
;
201 void LLVMContext::yield() {
202 if (pImpl
->YieldCallback
)
203 pImpl
->YieldCallback(this, pImpl
->YieldOpaqueHandle
);
206 void LLVMContext::emitError(const Twine
&ErrorStr
) {
207 diagnose(DiagnosticInfoGeneric(ErrorStr
));
210 void LLVMContext::emitError(const Instruction
*I
, const Twine
&ErrorStr
) {
211 assert(I
&& "Invalid instruction");
212 diagnose(DiagnosticInfoGeneric(I
, ErrorStr
));
215 static bool isDiagnosticEnabled(const DiagnosticInfo
&DI
) {
216 // Optimization remarks are selective. They need to check whether the regexp
217 // pattern, passed via one of the -pass-remarks* flags, matches the name of
218 // the pass that is emitting the diagnostic. If there is no match, ignore the
219 // diagnostic and return.
221 // Also noisy remarks are only enabled if we have hotness information to sort
223 if (auto *Remark
= dyn_cast
<DiagnosticInfoOptimizationBase
>(&DI
))
224 return Remark
->isEnabled() &&
225 (!Remark
->isVerbose() || Remark
->getHotness());
231 LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity
) {
242 llvm_unreachable("Unknown DiagnosticSeverity");
245 void LLVMContext::diagnose(const DiagnosticInfo
&DI
) {
246 if (auto *OptDiagBase
= dyn_cast
<DiagnosticInfoOptimizationBase
>(&DI
))
247 if (LLVMRemarkStreamer
*RS
= getLLVMRemarkStreamer())
248 RS
->emit(*OptDiagBase
);
250 // If there is a report handler, use it.
251 if (pImpl
->DiagHandler
) {
252 if (DI
.getSeverity() == DS_Error
)
253 pImpl
->DiagHandler
->HasErrors
= true;
254 if ((!pImpl
->RespectDiagnosticFilters
|| isDiagnosticEnabled(DI
)) &&
255 pImpl
->DiagHandler
->handleDiagnostics(DI
))
259 if (!isDiagnosticEnabled(DI
))
262 // Otherwise, print the message with a prefix based on the severity.
263 DiagnosticPrinterRawOStream
DP(errs());
264 errs() << getDiagnosticMessagePrefix(DI
.getSeverity()) << ": ";
267 if (DI
.getSeverity() == DS_Error
)
271 //===----------------------------------------------------------------------===//
272 // Metadata Kind Uniquing
273 //===----------------------------------------------------------------------===//
275 /// Return a unique non-zero ID for the specified metadata kind.
276 unsigned LLVMContext::getMDKindID(StringRef Name
) const {
277 // If this is new, assign it its ID.
278 return pImpl
->CustomMDKindNames
.insert(
280 Name
, pImpl
->CustomMDKindNames
.size()))
284 /// getHandlerNames - Populate client-supplied smallvector using custom
285 /// metadata name and ID.
286 void LLVMContext::getMDKindNames(SmallVectorImpl
<StringRef
> &Names
) const {
287 Names
.resize(pImpl
->CustomMDKindNames
.size());
288 for (StringMap
<unsigned>::const_iterator I
= pImpl
->CustomMDKindNames
.begin(),
289 E
= pImpl
->CustomMDKindNames
.end(); I
!= E
; ++I
)
290 Names
[I
->second
] = I
->first();
293 void LLVMContext::getOperandBundleTags(SmallVectorImpl
<StringRef
> &Tags
) const {
294 pImpl
->getOperandBundleTags(Tags
);
297 StringMapEntry
<uint32_t> *
298 LLVMContext::getOrInsertBundleTag(StringRef TagName
) const {
299 return pImpl
->getOrInsertBundleTag(TagName
);
302 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag
) const {
303 return pImpl
->getOperandBundleTagID(Tag
);
306 SyncScope::ID
LLVMContext::getOrInsertSyncScopeID(StringRef SSN
) {
307 return pImpl
->getOrInsertSyncScopeID(SSN
);
310 void LLVMContext::getSyncScopeNames(SmallVectorImpl
<StringRef
> &SSNs
) const {
311 pImpl
->getSyncScopeNames(SSNs
);
314 std::optional
<StringRef
> LLVMContext::getSyncScopeName(SyncScope::ID Id
) const {
315 return pImpl
->getSyncScopeName(Id
);
318 void LLVMContext::setGC(const Function
&Fn
, std::string GCName
) {
319 pImpl
->GCNames
[&Fn
] = std::move(GCName
);
322 const std::string
&LLVMContext::getGC(const Function
&Fn
) {
323 return pImpl
->GCNames
[&Fn
];
326 void LLVMContext::deleteGC(const Function
&Fn
) {
327 pImpl
->GCNames
.erase(&Fn
);
330 bool LLVMContext::shouldDiscardValueNames() const {
331 return pImpl
->DiscardValueNames
;
334 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl
->DITypeMap
; }
336 void LLVMContext::enableDebugTypeODRUniquing() {
337 if (pImpl
->DITypeMap
)
340 pImpl
->DITypeMap
.emplace();
343 void LLVMContext::disableDebugTypeODRUniquing() { pImpl
->DITypeMap
.reset(); }
345 void LLVMContext::setDiscardValueNames(bool Discard
) {
346 pImpl
->DiscardValueNames
= Discard
;
349 OptPassGate
&LLVMContext::getOptPassGate() const {
350 return pImpl
->getOptPassGate();
353 void LLVMContext::setOptPassGate(OptPassGate
& OPG
) {
354 pImpl
->setOptPassGate(OPG
);
357 const DiagnosticHandler
*LLVMContext::getDiagHandlerPtr() const {
358 return pImpl
->DiagHandler
.get();
361 std::unique_ptr
<DiagnosticHandler
> LLVMContext::getDiagnosticHandler() {
362 return std::move(pImpl
->DiagHandler
);
365 StringRef
LLVMContext::getDefaultTargetCPU() {
366 return pImpl
->DefaultTargetCPU
;
369 void LLVMContext::setDefaultTargetCPU(StringRef CPU
) {
370 pImpl
->DefaultTargetCPU
= CPU
;
373 StringRef
LLVMContext::getDefaultTargetFeatures() {
374 return pImpl
->DefaultTargetFeatures
;
377 void LLVMContext::setDefaultTargetFeatures(StringRef Features
) {
378 pImpl
->DefaultTargetFeatures
= Features
;