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