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 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 auto *ClangAttachedCall = 82 pImpl->getOrInsertBundleTag("clang.arc.attachedcall"); 83 assert(ClangAttachedCall->second == LLVMContext::OB_clang_arc_attachedcall && 84 "clang.arc.attachedcall operand bundle id drifted!"); 85 (void)ClangAttachedCall; 86 87 SyncScope::ID SingleThreadSSID = 88 pImpl->getOrInsertSyncScopeID("singlethread"); 89 assert(SingleThreadSSID == SyncScope::SingleThread && 90 "singlethread synchronization scope ID drifted!"); 91 (void)SingleThreadSSID; 92 93 SyncScope::ID SystemSSID = 94 pImpl->getOrInsertSyncScopeID(""); 95 assert(SystemSSID == SyncScope::System && 96 "system synchronization scope ID drifted!"); 97 (void)SystemSSID; 98 } 99 100 LLVMContext::~LLVMContext() { delete pImpl; } 101 102 void LLVMContext::addModule(Module *M) { 103 pImpl->OwnedModules.insert(M); 104 } 105 106 void LLVMContext::removeModule(Module *M) { 107 pImpl->OwnedModules.erase(M); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // Recoverable Backend Errors 112 //===----------------------------------------------------------------------===// 113 114 void LLVMContext:: 115 setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler, 116 void *DiagContext) { 117 pImpl->InlineAsmDiagHandler = DiagHandler; 118 pImpl->InlineAsmDiagContext = DiagContext; 119 } 120 121 /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by 122 /// setInlineAsmDiagnosticHandler. 123 LLVMContext::InlineAsmDiagHandlerTy 124 LLVMContext::getInlineAsmDiagnosticHandler() const { 125 return pImpl->InlineAsmDiagHandler; 126 } 127 128 /// getInlineAsmDiagnosticContext - Return the diagnostic context set by 129 /// setInlineAsmDiagnosticHandler. 130 void *LLVMContext::getInlineAsmDiagnosticContext() const { 131 return pImpl->InlineAsmDiagContext; 132 } 133 134 void LLVMContext::setDiagnosticHandlerCallBack( 135 DiagnosticHandler::DiagnosticHandlerTy DiagnosticHandler, 136 void *DiagnosticContext, bool RespectFilters) { 137 pImpl->DiagHandler->DiagHandlerCallback = DiagnosticHandler; 138 pImpl->DiagHandler->DiagnosticContext = DiagnosticContext; 139 pImpl->RespectDiagnosticFilters = RespectFilters; 140 } 141 142 void LLVMContext::setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH, 143 bool RespectFilters) { 144 pImpl->DiagHandler = std::move(DH); 145 pImpl->RespectDiagnosticFilters = RespectFilters; 146 } 147 148 void LLVMContext::setDiagnosticsHotnessRequested(bool Requested) { 149 pImpl->DiagnosticsHotnessRequested = Requested; 150 } 151 bool LLVMContext::getDiagnosticsHotnessRequested() const { 152 return pImpl->DiagnosticsHotnessRequested; 153 } 154 155 void LLVMContext::setDiagnosticsHotnessThreshold(Optional<uint64_t> Threshold) { 156 pImpl->DiagnosticsHotnessThreshold = Threshold; 157 } 158 159 uint64_t LLVMContext::getDiagnosticsHotnessThreshold() const { 160 return pImpl->DiagnosticsHotnessThreshold.getValueOr(UINT64_MAX); 161 } 162 163 bool LLVMContext::isDiagnosticsHotnessThresholdSetFromPSI() const { 164 return !pImpl->DiagnosticsHotnessThreshold.hasValue(); 165 } 166 167 remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() { 168 return pImpl->MainRemarkStreamer.get(); 169 } 170 const remarks::RemarkStreamer *LLVMContext::getMainRemarkStreamer() const { 171 return const_cast<LLVMContext *>(this)->getMainRemarkStreamer(); 172 } 173 void LLVMContext::setMainRemarkStreamer( 174 std::unique_ptr<remarks::RemarkStreamer> RemarkStreamer) { 175 pImpl->MainRemarkStreamer = std::move(RemarkStreamer); 176 } 177 178 LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() { 179 return pImpl->LLVMRS.get(); 180 } 181 const LLVMRemarkStreamer *LLVMContext::getLLVMRemarkStreamer() const { 182 return const_cast<LLVMContext *>(this)->getLLVMRemarkStreamer(); 183 } 184 void LLVMContext::setLLVMRemarkStreamer( 185 std::unique_ptr<LLVMRemarkStreamer> RemarkStreamer) { 186 pImpl->LLVMRS = std::move(RemarkStreamer); 187 } 188 189 DiagnosticHandler::DiagnosticHandlerTy 190 LLVMContext::getDiagnosticHandlerCallBack() const { 191 return pImpl->DiagHandler->DiagHandlerCallback; 192 } 193 194 void *LLVMContext::getDiagnosticContext() const { 195 return pImpl->DiagHandler->DiagnosticContext; 196 } 197 198 void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle) 199 { 200 pImpl->YieldCallback = Callback; 201 pImpl->YieldOpaqueHandle = OpaqueHandle; 202 } 203 204 void LLVMContext::yield() { 205 if (pImpl->YieldCallback) 206 pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle); 207 } 208 209 void LLVMContext::emitError(const Twine &ErrorStr) { 210 diagnose(DiagnosticInfoInlineAsm(ErrorStr)); 211 } 212 213 void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) { 214 assert (I && "Invalid instruction"); 215 diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr)); 216 } 217 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 * 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 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 271 void LLVMContext::emitError(unsigned 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. 280 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. 290 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 297 void LLVMContext::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const { 298 pImpl->getOperandBundleTags(Tags); 299 } 300 301 StringMapEntry<uint32_t> * 302 LLVMContext::getOrInsertBundleTag(StringRef TagName) const { 303 return pImpl->getOrInsertBundleTag(TagName); 304 } 305 306 uint32_t LLVMContext::getOperandBundleTagID(StringRef Tag) const { 307 return pImpl->getOperandBundleTagID(Tag); 308 } 309 310 SyncScope::ID LLVMContext::getOrInsertSyncScopeID(StringRef SSN) { 311 return pImpl->getOrInsertSyncScopeID(SSN); 312 } 313 314 void LLVMContext::getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const { 315 pImpl->getSyncScopeNames(SSNs); 316 } 317 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 328 const std::string &LLVMContext::getGC(const Function &Fn) { 329 return pImpl->GCNames[&Fn]; 330 } 331 332 void LLVMContext::deleteGC(const Function &Fn) { 333 pImpl->GCNames.erase(&Fn); 334 } 335 336 bool LLVMContext::shouldDiscardValueNames() const { 337 return pImpl->DiscardValueNames; 338 } 339 340 bool LLVMContext::isODRUniquingDebugTypes() const { return !!pImpl->DITypeMap; } 341 342 void LLVMContext::enableDebugTypeODRUniquing() { 343 if (pImpl->DITypeMap) 344 return; 345 346 pImpl->DITypeMap.emplace(); 347 } 348 349 void LLVMContext::disableDebugTypeODRUniquing() { pImpl->DITypeMap.reset(); } 350 351 void LLVMContext::setDiscardValueNames(bool Discard) { 352 pImpl->DiscardValueNames = Discard; 353 } 354 355 OptPassGate &LLVMContext::getOptPassGate() const { 356 return pImpl->getOptPassGate(); 357 } 358 359 void LLVMContext::setOptPassGate(OptPassGate& OPG) { 360 pImpl->setOptPassGate(OPG); 361 } 362 363 const DiagnosticHandler *LLVMContext::getDiagHandlerPtr() const { 364 return pImpl->DiagHandler.get(); 365 } 366 367 std::unique_ptr<DiagnosticHandler> LLVMContext::getDiagnosticHandler() { 368 return std::move(pImpl->DiagHandler); 369 } 370