• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
LLVMContext()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   auto *GCLiveEntry = pImpl->getOrInsertBundleTag("gc-live");
77   assert(GCLiveEntry->second == LLVMContext::OB_gc_live &&
78          "gc-transition operand bundle id drifted!");
79   (void)GCLiveEntry;
80 
81   SyncScope::ID SingleThreadSSID =
82       pImpl->getOrInsertSyncScopeID("singlethread");
83   assert(SingleThreadSSID == SyncScope::SingleThread &&
84          "singlethread synchronization scope ID drifted!");
85   (void)SingleThreadSSID;
86 
87   SyncScope::ID SystemSSID =
88       pImpl->getOrInsertSyncScopeID("");
89   assert(SystemSSID == SyncScope::System &&
90          "system synchronization scope ID drifted!");
91   (void)SystemSSID;
92 }
93 
~LLVMContext()94 LLVMContext::~LLVMContext() { delete pImpl; }
95 
addModule(Module * M)96 void LLVMContext::addModule(Module *M) {
97   pImpl->OwnedModules.insert(M);
98 }
99 
removeModule(Module * M)100 void LLVMContext::removeModule(Module *M) {
101   pImpl->OwnedModules.erase(M);
102 }
103 
104 //===----------------------------------------------------------------------===//
105 // Recoverable Backend Errors
106 //===----------------------------------------------------------------------===//
107 
108 void LLVMContext::
setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,void * DiagContext)109 setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
110                               void *DiagContext) {
111   pImpl->InlineAsmDiagHandler = DiagHandler;
112   pImpl->InlineAsmDiagContext = DiagContext;
113 }
114 
115 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
116 /// setInlineAsmDiagnosticHandler.
117 LLVMContext::InlineAsmDiagHandlerTy
getInlineAsmDiagnosticHandler() const118 LLVMContext::getInlineAsmDiagnosticHandler() const {
119   return pImpl->InlineAsmDiagHandler;
120 }
121 
122 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
123 /// setInlineAsmDiagnosticHandler.
getInlineAsmDiagnosticContext() const124 void *LLVMContext::getInlineAsmDiagnosticContext() const {
125   return pImpl->InlineAsmDiagContext;
126 }
127 
setDiagnosticHandlerCallBack(DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler,void * DiagnosticContext,bool RespectFilters)128 void LLVMContext::setDiagnosticHandlerCallBack(
129     DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler,
130     void *DiagnosticContext, bool RespectFilters) {
131   pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler;
132   pImpl->DiagHandler->DiagnosticContext = DiagnosticContext;
133   pImpl->RespectDiagnosticFilters = RespectFilters;
134 }
135 
setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> && DH,bool RespectFilters)136 void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
137                                       bool RespectFilters) {
138   pImpl->DiagHandler = std::move(DH);
139   pImpl->RespectDiagnosticFilters = RespectFilters;
140 }
141 
setDiagnosticsHotnessRequested(bool Requested)142 void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) {
143   pImpl->DiagnosticsHotnessRequested = Requested;
144 }
getDiagnosticsHotnessRequested() const145 bool LLVMContext::getDiagnosticsHotnessRequested() const {
146   return pImpl->DiagnosticsHotnessRequested;
147 }
148 
setDiagnosticsHotnessThreshold(Optional<uint64_t> Threshold)149 void LLVMContext::setDiagnosticsHotnessThreshold(Optional<uint64_t> Threshold) {
150   pImpl->DiagnosticsHotnessThreshold = Threshold;
151 }
152 
getDiagnosticsHotnessThreshold() const153 uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const {
154   return pImpl->DiagnosticsHotnessThreshold.getValueOr(UINT64_MAX);
155 }
156 
isDiagnosticsHotnessThresholdSetFromPSI() const157 bool LLVMContext::isDiagnosticsHotnessThresholdSetFromPSI() const {
158   return !pImpl->DiagnosticsHotnessThreshold.hasValue();
159 }
160 
getMainRemarkStreamer()161 remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() {
162   return pImpl->MainRemarkStreamer.get();
163 }
getMainRemarkStreamer() const164 const remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() const {
165   return const_cast<LLVMContext *>(this)->getMainRemarkStreamer();
166 }
setMainRemarkStreamer(std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer)167 void LLVMContext::setMainRemarkStreamer(
168     std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) {
169   pImpl->MainRemarkStreamer = std::move(RemarkStreamer);
170 }
171 
getLLVMRemarkStreamer()172 LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() {
173   return pImpl->LLVMRS.get();
174 }
getLLVMRemarkStreamer() const175 const LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() const {
176   return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer();
177 }
setLLVMRemarkStreamer(std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer)178 void LLVMContext::setLLVMRemarkStreamer(
179     std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) {
180   pImpl->LLVMRS = std::move(RemarkStreamer);
181 }
182 
183 DiagnosticHandler::DiagnosticHandlerTy
getDiagnosticHandlerCallBack() const184 LLVMContext::getDiagnosticHandlerCallBack() const {
185   return pImpl->DiagHandler->DiagHandlerCallback;
186 }
187 
getDiagnosticContext() const188 void *LLVMContext::getDiagnosticContext() const {
189   return pImpl->DiagHandler->DiagnosticContext;
190 }
191 
setYieldCallback(YieldCallbackTy Callback,void * OpaqueHandle)192 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
193 {
194   pImpl->YieldCallback = Callback;
195   pImpl->YieldOpaqueHandle = OpaqueHandle;
196 }
197 
yield()198 void LLVMContext::yield() {
199   if (pImpl->YieldCallback)
200     pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
201 }
202 
emitError(const Twine & ErrorStr)203 void LLVMContext::emitError(const Twine &ErrorStr) {
204   diagnose(DiagnosticInfoInlineAsm(ErrorStr));
205 }
206 
emitError(const Instruction * I,const Twine & ErrorStr)207 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
208   assert (I && "Invalid instruction");
209   diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
210 }
211 
isDiagnosticEnabled(const DiagnosticInfo & DI)212 static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
213   // Optimization remarks are selective. They need to check whether the regexp
214   // pattern, passed via one of the -pass-remarks* flags, matches the name of
215   // the pass that is emitting the diagnostic. If there is no match, ignore the
216   // diagnostic and return.
217   //
218   // Also noisy remarks are only enabled if we have hotness information to sort
219   // them.
220   if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
221     return Remark->isEnabled() &&
222            (!Remark->isVerbose() || Remark->getHotness());
223 
224   return true;
225 }
226 
227 const char *
getDiagnosticMessagePrefix(DiagnosticSeverity Severity)228 LLVMContext::getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
229   switch (Severity) {
230   case DS_Error:
231     return "error";
232   case DS_Warning:
233     return "warning";
234   case DS_Remark:
235     return "remark";
236   case DS_Note:
237     return "note";
238   }
239   llvm_unreachable("Unknown DiagnosticSeverity");
240 }
241 
diagnose(const DiagnosticInfo & DI)242 void LLVMContext::diagnose(const DiagnosticInfo &DI) {
243   if (auto *OptDiagBase = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
244     if (LLVMRemarkStreamer *RS = getLLVMRemarkStreamer())
245       RS->emit(*OptDiagBase);
246 
247   // If there is a report handler, use it.
248   if (pImpl->DiagHandler &&
249       (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI)) &&
250       pImpl->DiagHandler->handleDiagnostics(DI))
251     return;
252 
253   if (!isDiagnosticEnabled(DI))
254     return;
255 
256   // Otherwise, print the message with a prefix based on the severity.
257   DiagnosticPrinterRawOStream DP(errs());
258   errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
259   DI.print(DP);
260   errs() << "\n";
261   if (DI.getSeverity() == DS_Error)
262     exit(1);
263 }
264 
emitError(unsigned LocCookie,const Twine & ErrorStr)265 void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
266   diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
267 }
268 
269 //===----------------------------------------------------------------------===//
270 // Metadata Kind Uniquing
271 //===----------------------------------------------------------------------===//
272 
273 /// Return a unique non-zero ID for the specified metadata kind.
getMDKindID(StringRef Name) const274 unsigned LLVMContext::getMDKindID(StringRef Name) const {
275   // If this is new, assign it its ID.
276   return pImpl->CustomMDKindNames.insert(
277                                      std::make_pair(
278                                          Name, pImpl->CustomMDKindNames.size()))
279       .first->second;
280 }
281 
282 /// getHandlerNames - Populate client-supplied smallvector using custom
283 /// metadata name and ID.
getMDKindNames(SmallVectorImpl<StringRef> & Names) const284 void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
285   Names.resize(pImpl->CustomMDKindNames.size());
286   for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
287        E = pImpl->CustomMDKindNames.end(); I != E; ++I)
288     Names[I->second] = I->first();
289 }
290 
getOperandBundleTags(SmallVectorImpl<StringRef> & Tags) const291 void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
292   pImpl->getOperandBundleTags(Tags);
293 }
294 
295 StringMapEntry<uint32_t> *
getOrInsertBundleTag(StringRef TagName) const296 LLVMContext::getOrInsertBundleTag(StringRef TagName) const {
297   return pImpl->getOrInsertBundleTag(TagName);
298 }
299 
getOperandBundleTagID(StringRef Tag) const300 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const {
301   return pImpl->getOperandBundleTagID(Tag);
302 }
303 
getOrInsertSyncScopeID(StringRef SSN)304 SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) {
305   return pImpl->getOrInsertSyncScopeID(SSN);
306 }
307 
getSyncScopeNames(SmallVectorImpl<StringRef> & SSNs) const308 void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const {
309   pImpl->getSyncScopeNames(SSNs);
310 }
311 
setGC(const Function & Fn,std::string GCName)312 void LLVMContext::setGC(const Function &Fn, std::string GCName) {
313   auto It = pImpl->GCNames.find(&Fn);
314 
315   if (It == pImpl->GCNames.end()) {
316     pImpl->GCNames.insert(std::make_pair(&Fn, std::move(GCName)));
317     return;
318   }
319   It->second = std::move(GCName);
320 }
321 
getGC(const Function & Fn)322 const std::string &LLVMContext::getGC(const Function &Fn) {
323   return pImpl->GCNames[&Fn];
324 }
325 
deleteGC(const Function & Fn)326 void LLVMContext::deleteGC(const Function &Fn) {
327   pImpl->GCNames.erase(&Fn);
328 }
329 
shouldDiscardValueNames() const330 bool LLVMContext::shouldDiscardValueNames() const {
331   return pImpl->DiscardValueNames;
332 }
333 
isODRUniquingDebugTypes() const334 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; }
335 
enableDebugTypeODRUniquing()336 void LLVMContext::enableDebugTypeODRUniquing() {
337   if (pImpl->DITypeMap)
338     return;
339 
340   pImpl->DITypeMap.emplace();
341 }
342 
disableDebugTypeODRUniquing()343 void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); }
344 
setDiscardValueNames(bool Discard)345 void LLVMContext::setDiscardValueNames(bool Discard) {
346   pImpl->DiscardValueNames = Discard;
347 }
348 
getOptPassGate() const349 OptPassGate &LLVMContext::getOptPassGate() const {
350   return pImpl->getOptPassGate();
351 }
352 
setOptPassGate(OptPassGate & OPG)353 void LLVMContext::setOptPassGate(OptPassGate& OPG) {
354   pImpl->setOptPassGate(OPG);
355 }
356 
getDiagHandlerPtr() const357 const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const {
358   return pImpl->DiagHandler.get();
359 }
360 
getDiagnosticHandler()361 std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() {
362   return std::move(pImpl->DiagHandler);
363 }
364