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/IR/Metadata.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/Remarks/RemarkStreamer.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cassert>
30 #include <cstdlib>
31 #include <string>
32 #include <utility>
33 
34 using namespace llvm;
35 
36 LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
37   // Create the fixed metadata kinds. This is done in the same order as the
38   // MD_* enum values so that they correspond.
39   std::pair<unsigned, StringRef> MDKinds[] = {
40 #define LLVM_FIXED_MD_KIND(EnumID, Name, Value) {EnumID, Name},
41 #include "llvm/IR/FixedMetadataKinds.def"
42 #undef LLVM_FIXED_MD_KIND
43   };
44 
45   for (auto &MDKind : MDKinds) {
46     unsigned ID = getMDKindID(MDKind.second);
47     assert(ID == MDKind.first && "metadata kind id drifted");
48     (void)ID;
49   }
50 
51   auto *DeoptEntry = pImpl->getOrInsertBundleTag("deopt");
52   assert(DeoptEntry->second == LLVMContext::OB_deopt &&
53          "deopt operand bundle id drifted!");
54   (void)DeoptEntry;
55 
56   auto *FuncletEntry = pImpl->getOrInsertBundleTag("funclet");
57   assert(FuncletEntry->second == LLVMContext::OB_funclet &&
58          "funclet operand bundle id drifted!");
59   (void)FuncletEntry;
60 
61   auto *GCTransitionEntry = pImpl->getOrInsertBundleTag("gc-transition");
62   assert(GCTransitionEntry->second == LLVMContext::OB_gc_transition &&
63          "gc-transition operand bundle id drifted!");
64   (void)GCTransitionEntry;
65 
66   auto *CFGuardTargetEntry = pImpl->getOrInsertBundleTag("cfguardtarget");
67   assert(CFGuardTargetEntry->second == LLVMContext::OB_cfguardtarget &&
68          "cfguardtarget operand bundle id drifted!");
69   (void)CFGuardTargetEntry;
70 
71   auto *PreallocatedEntry = pImpl->getOrInsertBundleTag("preallocated");
72   assert(PreallocatedEntry->second == LLVMContext::OB_preallocated &&
73          "preallocated operand bundle id drifted!");
74   (void)PreallocatedEntry;
75 
76   SyncScope::ID SingleThreadSSID =
77       pImpl->getOrInsertSyncScopeID("singlethread");
78   assert(SingleThreadSSID == SyncScope::SingleThread &&
79          "singlethread synchronization scope ID drifted!");
80   (void)SingleThreadSSID;
81 
82   SyncScope::ID SystemSSID =
83       pImpl->getOrInsertSyncScopeID("");
84   assert(SystemSSID == SyncScope::System &&
85          "system synchronization scope ID drifted!");
86   (void)SystemSSID;
87 }
88 
89 LLVMContext::~LLVMContext() { delete pImpl; }
90 
91 void LLVMContext::addModule(Module *M) {
92   pImpl->OwnedModules.insert(M);
93 }
94 
95 void LLVMContext::removeModule(Module *M) {
96   pImpl->OwnedModules.erase(M);
97 }
98 
99 //===----------------------------------------------------------------------===//
100 // Recoverable Backend Errors
101 //===----------------------------------------------------------------------===//
102 
103 void LLVMContext::
104 setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
105                               void *DiagContext) {
106   pImpl->InlineAsmDiagHandler = DiagHandler;
107   pImpl->InlineAsmDiagContext = DiagContext;
108 }
109 
110 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
111 /// setInlineAsmDiagnosticHandler.
112 LLVMContext::InlineAsmDiagHandlerTy
113 LLVMContext::getInlineAsmDiagnosticHandler() const {
114   return pImpl->InlineAsmDiagHandler;
115 }
116 
117 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
118 /// setInlineAsmDiagnosticHandler.
119 void *LLVMContext::getInlineAsmDiagnosticContext() const {
120   return pImpl->InlineAsmDiagContext;
121 }
122 
123 void LLVMContext::setDiagnosticHandlerCallBack(
124     DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler,
125     void *DiagnosticContext, bool RespectFilters) {
126   pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler;
127   pImpl->DiagHandler->DiagnosticContext = DiagnosticContext;
128   pImpl->RespectDiagnosticFilters = RespectFilters;
129 }
130 
131 void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
132                                       bool RespectFilters) {
133   pImpl->DiagHandler = std::move(DH);
134   pImpl->RespectDiagnosticFilters = RespectFilters;
135 }
136 
137 void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) {
138   pImpl->DiagnosticsHotnessRequested = Requested;
139 }
140 bool LLVMContext::getDiagnosticsHotnessRequested() const {
141   return pImpl->DiagnosticsHotnessRequested;
142 }
143 
144 void LLVMContext::setDiagnosticsHotnessThreshold(uint64_t Threshold) {
145   pImpl->DiagnosticsHotnessThreshold = Threshold;
146 }
147 uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const {
148   return pImpl->DiagnosticsHotnessThreshold;
149 }
150 
151 remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() {
152   return pImpl->MainRemarkStreamer.get();
153 }
154 const remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() const {
155   return const_cast<LLVMContext *>(this)->getMainRemarkStreamer();
156 }
157 void LLVMContext::setMainRemarkStreamer(
158     std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) {
159   pImpl->MainRemarkStreamer = std::move(RemarkStreamer);
160 }
161 
162 LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() {
163   return pImpl->LLVMRS.get();
164 }
165 const LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() const {
166   return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer();
167 }
168 void LLVMContext::setLLVMRemarkStreamer(
169     std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) {
170   pImpl->LLVMRS = std::move(RemarkStreamer);
171 }
172 
173 DiagnosticHandler::DiagnosticHandlerTy
174 LLVMContext::getDiagnosticHandlerCallBack() const {
175   return pImpl->DiagHandler->DiagHandlerCallback;
176 }
177 
178 void *LLVMContext::getDiagnosticContext() const {
179   return pImpl->DiagHandler->DiagnosticContext;
180 }
181 
182 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
183 {
184   pImpl->YieldCallback = Callback;
185   pImpl->YieldOpaqueHandle = OpaqueHandle;
186 }
187 
188 void LLVMContext::yield() {
189   if (pImpl->YieldCallback)
190     pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
191 }
192 
193 void LLVMContext::emitError(const Twine &ErrorStr) {
194   diagnose(DiagnosticInfoInlineAsm(ErrorStr));
195 }
196 
197 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
198   assert (I && "Invalid instruction");
199   diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
200 }
201 
202 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
203   // Optimization remarks are selective. They need to check whether the regexp
204   // pattern, passed via one of the -pass-remarks* flags, matches the name of
205   // the pass that is emitting the diagnostic. If there is no match, ignore the
206   // diagnostic and return.
207   //
208   // Also noisy remarks are only enabled if we have hotness information to sort
209   // them.
210   if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
211     return Remark->isEnabled() &&
212            (!Remark->isVerbose() || Remark->getHotness());
213 
214   return true;
215 }
216 
217 const char *
218 LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
219   switch (Severity) {
220   case DS_Error:
221     return "error";
222   case DS_Warning:
223     return "warning";
224   case DS_Remark:
225     return "remark";
226   case DS_Note:
227     return "note";
228   }
229   llvm_unreachable("Unknown DiagnosticSeverity");
230 }
231 
232 void LLVMContext::diagnose(const DiagnosticInfo &DI) {
233   if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
234     if (LLVMRemarkStreamer *RS = getLLVMRemarkStreamer())
235       RS->emit(*OptDiagBase);
236 
237   // If there is a report handler, use it.
238   if (pImpl->DiagHandler &&
239       (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) &&
240       pImpl->DiagHandler->handleDiagnostics(DI))
241     return;
242 
243   if (!isDiagnosticEnabled(DI))
244     return;
245 
246   // Otherwise, print the message with a prefix based on the severity.
247   DiagnosticPrinterRawOStream DP(errs());
248   errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
249   DI.print(DP);
250   errs() << "\n";
251   if (DI.getSeverity() == DS_Error)
252     exit(1);
253 }
254 
255 void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
256   diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
257 }
258 
259 //===----------------------------------------------------------------------===//
260 // Metadata Kind Uniquing
261 //===----------------------------------------------------------------------===//
262 
263 /// Return a unique non-zero ID for the specified metadata kind.
264 unsigned LLVMContext::getMDKindID(StringRef Name) const {
265   // If this is new, assign it its ID.
266   return pImpl->CustomMDKindNames.insert(
267                                      std::make_pair(
268                                          Name, pImpl->CustomMDKindNames.size()))
269       .first->second;
270 }
271 
272 /// getHandlerNames - Populate client-supplied smallvector using custom
273 /// metadata name and ID.
274 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
275   Names.resize(pImpl->CustomMDKindNames.size());
276   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
277        E = pImpl->CustomMDKindNames.end(); I != E; ++I)
278     Names[I->second] = I->first();
279 }
280 
281 void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
282   pImpl->getOperandBundleTags(Tags);
283 }
284 
285 StringMapEntry<uint32_t> *
286 LLVMContext::getOrInsertBundleTag(StringRef TagName) const {
287   return pImpl->getOrInsertBundleTag(TagName);
288 }
289 
290 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
291   return pImpl->getOperandBundleTagID(Tag);
292 }
293 
294 SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) {
295   return pImpl->getOrInsertSyncScopeID(SSN);
296 }
297 
298 void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const {
299   pImpl->getSyncScopeNames(SSNs);
300 }
301 
302 void LLVMContext::setGC(const Function &Fn, std::string GCName) {
303   auto It = pImpl->GCNames.find(&Fn);
304 
305   if (It == pImpl->GCNames.end()) {
306     pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
307     return;
308   }
309   It->second = std::move(GCName);
310 }
311 
312 const std::string &LLVMContext::getGC(const Function &Fn) {
313   return pImpl->GCNames[&Fn];
314 }
315 
316 void LLVMContext::deleteGC(const Function &Fn) {
317   pImpl->GCNames.erase(&Fn);
318 }
319 
320 bool LLVMContext::shouldDiscardValueNames() const {
321   return pImpl->DiscardValueNames;
322 }
323 
324 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; }
325 
326 void LLVMContext::enableDebugTypeODRUniquing() {
327   if (pImpl->DITypeMap)
328     return;
329 
330   pImpl->DITypeMap.emplace();
331 }
332 
333 void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); }
334 
335 void LLVMContext::setDiscardValueNames(bool Discard) {
336   pImpl->DiscardValueNames = Discard;
337 }
338 
339 OptPassGate &LLVMContext::getOptPassGate() const {
340   return pImpl->getOptPassGate();
341 }
342 
343 void LLVMContext::setOptPassGate(OptPassGate& OPG) {
344   pImpl->setOptPassGate(OPG);
345 }
346 
347 const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const {
348   return pImpl->DiagHandler.get();
349 }
350 
351 std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
352   return std::move(pImpl->DiagHandler);
353 }
354