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"
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"
27 #include <cassert>
28 #include <cstdlib>
29 #include <string>
30 #include <utility>
31
32 using namespace llvm;
33
LLVMContext()34 LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
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 SyncScope::ID SingleThreadSSID =
96 pImpl->getOrInsertSyncScopeID("singlethread");
97 assert(SingleThreadSSID == SyncScope::SingleThread &&
98 "singlethread synchronization scope ID drifted!");
99 (void)SingleThreadSSID;
100
101 SyncScope::ID SystemSSID =
102 pImpl->getOrInsertSyncScopeID("");
103 assert(SystemSSID == SyncScope::System &&
104 "system synchronization scope ID drifted!");
105 (void)SystemSSID;
106 }
107
~LLVMContext()108 LLVMContext::~LLVMContext() { delete pImpl; }
109
addModule(Module * M)110 void LLVMContext::addModule(Module *M) {
111 pImpl->OwnedModules.insert(M);
112 }
113
removeModule(Module * M)114 void LLVMContext::removeModule(Module *M) {
115 pImpl->OwnedModules.erase(M);
116 }
117
118 //===----------------------------------------------------------------------===//
119 // Recoverable Backend Errors
120 //===----------------------------------------------------------------------===//
121
setDiagnosticHandlerCallBack(DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler,void * DiagnosticContext,bool RespectFilters)122 void LLVMContext::setDiagnosticHandlerCallBack(
123 DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler,
124 void *DiagnosticContext, bool RespectFilters) {
125 pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler;
126 pImpl->DiagHandler->DiagnosticContext = DiagnosticContext;
127 pImpl->RespectDiagnosticFilters = RespectFilters;
128 }
129
setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> && DH,bool RespectFilters)130 void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
131 bool RespectFilters) {
132 pImpl->DiagHandler = std::move(DH);
133 pImpl->RespectDiagnosticFilters = RespectFilters;
134 }
135
setDiagnosticsHotnessRequested(bool Requested)136 void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) {
137 pImpl->DiagnosticsHotnessRequested = Requested;
138 }
getDiagnosticsHotnessRequested() const139 bool LLVMContext::getDiagnosticsHotnessRequested() const {
140 return pImpl->DiagnosticsHotnessRequested;
141 }
142
setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold)143 void LLVMContext::setDiagnosticsHotnessThreshold(std::optional<uint64_t> Threshold) {
144 pImpl->DiagnosticsHotnessThreshold = Threshold;
145 }
setMisExpectWarningRequested(bool Requested)146 void LLVMContext::setMisExpectWarningRequested(bool Requested) {
147 pImpl->MisExpectWarningRequested = Requested;
148 }
getMisExpectWarningRequested() const149 bool LLVMContext::getMisExpectWarningRequested() const {
150 return pImpl->MisExpectWarningRequested;
151 }
getDiagnosticsHotnessThreshold() const152 uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const {
153 return pImpl->DiagnosticsHotnessThreshold.value_or(UINT64_MAX);
154 }
setDiagnosticsMisExpectTolerance(std::optional<uint32_t> Tolerance)155 void LLVMContext::setDiagnosticsMisExpectTolerance(
156 std::optional<uint32_t> Tolerance) {
157 pImpl->DiagnosticsMisExpectTolerance = Tolerance;
158 }
getDiagnosticsMisExpectTolerance() const159 uint32_t LLVMContext::getDiagnosticsMisExpectTolerance() const {
160 return pImpl->DiagnosticsMisExpectTolerance.value_or(0);
161 }
162
isDiagnosticsHotnessThresholdSetFromPSI() const163 bool LLVMContext::isDiagnosticsHotnessThresholdSetFromPSI() const {
164 return !pImpl->DiagnosticsHotnessThreshold.has_value();
165 }
166
getMainRemarkStreamer()167 remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() {
168 return pImpl->MainRemarkStreamer.get();
169 }
getMainRemarkStreamer() const170 const remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() const {
171 return const_cast<LLVMContext *>(this)->getMainRemarkStreamer();
172 }
setMainRemarkStreamer(std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer)173 void LLVMContext::setMainRemarkStreamer(
174 std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) {
175 pImpl->MainRemarkStreamer = std::move(RemarkStreamer);
176 }
177
getLLVMRemarkStreamer()178 LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() {
179 return pImpl->LLVMRS.get();
180 }
getLLVMRemarkStreamer() const181 const LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() const {
182 return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer();
183 }
setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer)184 void LLVMContext::setLLVMRemarkStreamer(
185 std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) {
186 pImpl->LLVMRS = std::move(RemarkStreamer);
187 }
188
189 DiagnosticHandler::DiagnosticHandlerTy
getDiagnosticHandlerCallBack() const190 LLVMContext::getDiagnosticHandlerCallBack() const {
191 return pImpl->DiagHandler->DiagHandlerCallback;
192 }
193
getDiagnosticContext() const194 void *LLVMContext::getDiagnosticContext() const {
195 return pImpl->DiagHandler->DiagnosticContext;
196 }
197
setYieldCallback(YieldCallbackTy Callback,void * OpaqueHandle)198 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
199 {
200 pImpl->YieldCallback = Callback;
201 pImpl->YieldOpaqueHandle = OpaqueHandle;
202 }
203
yield()204 void LLVMContext::yield() {
205 if (pImpl->YieldCallback)
206 pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
207 }
208
emitError(const Twine & ErrorStr)209 void LLVMContext::emitError(const Twine &ErrorStr) {
210 diagnose(DiagnosticInfoInlineAsm(ErrorStr));
211 }
212
emitError(const Instruction * I,const Twine & ErrorStr)213 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
214 assert (I && "Invalid instruction");
215 diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
216 }
217
isDiagnosticEnabled(const DiagnosticInfo & DI)218 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
219 // Optimization remarks are selective. They need to check whether the regexp
220 // pattern, passed via one of the -pass-remarks* flags, matches the name of
221 // the pass that is emitting the diagnostic. If there is no match, ignore the
222 // diagnostic and return.
223 //
224 // Also noisy remarks are only enabled if we have hotness information to sort
225 // them.
226 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
227 return Remark->isEnabled() &&
228 (!Remark->isVerbose() || Remark->getHotness());
229
230 return true;
231 }
232
233 const char *
getDiagnosticMessagePrefix(DiagnosticSeverity Severity)234 LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
235 switch (Severity) {
236 case DS_Error:
237 return "error";
238 case DS_Warning:
239 return "warning";
240 case DS_Remark:
241 return "remark";
242 case DS_Note:
243 return "note";
244 }
245 llvm_unreachable("Unknown DiagnosticSeverity");
246 }
247
diagnose(const DiagnosticInfo & DI)248 void LLVMContext::diagnose(const DiagnosticInfo &DI) {
249 if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
250 if (LLVMRemarkStreamer *RS = getLLVMRemarkStreamer())
251 RS->emit(*OptDiagBase);
252
253 // If there is a report handler, use it.
254 if (pImpl->DiagHandler &&
255 (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) &&
256 pImpl->DiagHandler->handleDiagnostics(DI))
257 return;
258
259 if (!isDiagnosticEnabled(DI))
260 return;
261
262 // Otherwise, print the message with a prefix based on the severity.
263 DiagnosticPrinterRawOStream DP(errs());
264 errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
265 DI.print(DP);
266 errs() << "\n";
267 if (DI.getSeverity() == DS_Error)
268 exit(1);
269 }
270
emitError(uint64_t LocCookie,const Twine & ErrorStr)271 void LLVMContext::emitError(uint64_t LocCookie, const Twine &ErrorStr) {
272 diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
273 }
274
275 //===----------------------------------------------------------------------===//
276 // Metadata Kind Uniquing
277 //===----------------------------------------------------------------------===//
278
279 /// Return a unique non-zero ID for the specified metadata kind.
getMDKindID(StringRef Name) const280 unsigned LLVMContext::getMDKindID(StringRef Name) const {
281 // If this is new, assign it its ID.
282 return pImpl->CustomMDKindNames.insert(
283 std::make_pair(
284 Name, pImpl->CustomMDKindNames.size()))
285 .first->second;
286 }
287
288 /// getHandlerNames - Populate client-supplied smallvector using custom
289 /// metadata name and ID.
getMDKindNames(SmallVectorImpl<StringRef> & Names) const290 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
291 Names.resize(pImpl->CustomMDKindNames.size());
292 for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
293 E = pImpl->CustomMDKindNames.end(); I != E; ++I)
294 Names[I->second] = I->first();
295 }
296
getOperandBundleTags(SmallVectorImpl<StringRef> & Tags) const297 void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
298 pImpl->getOperandBundleTags(Tags);
299 }
300
301 StringMapEntry<uint32_t> *
getOrInsertBundleTag(StringRef TagName) const302 LLVMContext::getOrInsertBundleTag(StringRef TagName) const {
303 return pImpl->getOrInsertBundleTag(TagName);
304 }
305
getOperandBundleTagID(StringRef Tag) const306 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
307 return pImpl->getOperandBundleTagID(Tag);
308 }
309
getOrInsertSyncScopeID(StringRef SSN)310 SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) {
311 return pImpl->getOrInsertSyncScopeID(SSN);
312 }
313
getSyncScopeNames(SmallVectorImpl<StringRef> & SSNs) const314 void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const {
315 pImpl->getSyncScopeNames(SSNs);
316 }
317
setGC(const Function & Fn,std::string GCName)318 void LLVMContext::setGC(const Function &Fn, std::string GCName) {
319 auto It = pImpl->GCNames.find(&Fn);
320
321 if (It == pImpl->GCNames.end()) {
322 pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
323 return;
324 }
325 It->second = std::move(GCName);
326 }
327
getGC(const Function & Fn)328 const std::string &LLVMContext::getGC(const Function &Fn) {
329 return pImpl->GCNames[&Fn];
330 }
331
deleteGC(const Function & Fn)332 void LLVMContext::deleteGC(const Function &Fn) {
333 pImpl->GCNames.erase(&Fn);
334 }
335
shouldDiscardValueNames() const336 bool LLVMContext::shouldDiscardValueNames() const {
337 return pImpl->DiscardValueNames;
338 }
339
isODRUniquingDebugTypes() const340 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; }
341
enableDebugTypeODRUniquing()342 void LLVMContext::enableDebugTypeODRUniquing() {
343 if (pImpl->DITypeMap)
344 return;
345
346 pImpl->DITypeMap.emplace();
347 }
348
disableDebugTypeODRUniquing()349 void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); }
350
setDiscardValueNames(bool Discard)351 void LLVMContext::setDiscardValueNames(bool Discard) {
352 pImpl->DiscardValueNames = Discard;
353 }
354
getOptPassGate() const355 OptPassGate &LLVMContext::getOptPassGate() const {
356 return pImpl->getOptPassGate();
357 }
358
setOptPassGate(OptPassGate & OPG)359 void LLVMContext::setOptPassGate(OptPassGate& OPG) {
360 pImpl->setOptPassGate(OPG);
361 }
362
getDiagHandlerPtr() const363 const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const {
364 return pImpl->DiagHandler.get();
365 }
366
getDiagnosticHandler()367 std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
368 return std::move(pImpl->DiagHandler);
369 }
370
setOpaquePointers(bool Enable) const371 void LLVMContext::setOpaquePointers(bool Enable) const {
372 pImpl->setOpaquePointers(Enable);
373 }
374
supportsTypedPointers() const375 bool LLVMContext::supportsTypedPointers() const {
376 return !pImpl->getOpaquePointers();
377 }
378