1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===// 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 #include "clang/CodeGen/CodeGenAction.h" 10 #include "CodeGenModule.h" 11 #include "CoverageMappingGen.h" 12 #include "MacroPPCallbacks.h" 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/DeclCXX.h" 16 #include "clang/AST/DeclGroup.h" 17 #include "clang/Basic/DiagnosticFrontend.h" 18 #include "clang/Basic/FileManager.h" 19 #include "clang/Basic/LangStandard.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Basic/TargetInfo.h" 22 #include "clang/CodeGen/BackendUtil.h" 23 #include "clang/CodeGen/ModuleBuilder.h" 24 #include "clang/Driver/DriverDiagnostic.h" 25 #include "clang/Frontend/CompilerInstance.h" 26 #include "clang/Frontend/FrontendDiagnostic.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "llvm/ADT/Hashing.h" 29 #include "llvm/Bitcode/BitcodeReader.h" 30 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 31 #include "llvm/Demangle/Demangle.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DiagnosticInfo.h" 34 #include "llvm/IR/DiagnosticPrinter.h" 35 #include "llvm/IR/GlobalValue.h" 36 #include "llvm/IR/LLVMContext.h" 37 #include "llvm/IR/LLVMRemarkStreamer.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IRReader/IRReader.h" 40 #include "llvm/LTO/LTOBackend.h" 41 #include "llvm/Linker/Linker.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/SourceMgr.h" 45 #include "llvm/Support/TimeProfiler.h" 46 #include "llvm/Support/Timer.h" 47 #include "llvm/Support/ToolOutputFile.h" 48 #include "llvm/Support/YAMLTraits.h" 49 #include "llvm/Transforms/IPO/Internalize.h" 50 51 #include <memory> 52 #include <optional> 53 using namespace clang; 54 using namespace llvm; 55 56 #define DEBUG_TYPE "codegenaction" 57 58 namespace clang { 59 class BackendConsumer; 60 class ClangDiagnosticHandler final : public DiagnosticHandler { 61 public: 62 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon) 63 : CodeGenOpts(CGOpts), BackendCon(BCon) {} 64 65 bool handleDiagnostics(const DiagnosticInfo &DI) override; 66 67 bool isAnalysisRemarkEnabled(StringRef PassName) const override { 68 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName); 69 } 70 bool isMissedOptRemarkEnabled(StringRef PassName) const override { 71 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName); 72 } 73 bool isPassedOptRemarkEnabled(StringRef PassName) const override { 74 return CodeGenOpts.OptimizationRemark.patternMatches(PassName); 75 } 76 77 bool isAnyRemarkEnabled() const override { 78 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() || 79 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() || 80 CodeGenOpts.OptimizationRemark.hasValidPattern(); 81 } 82 83 private: 84 const CodeGenOptions &CodeGenOpts; 85 BackendConsumer *BackendCon; 86 }; 87 88 static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, 89 const CodeGenOptions CodeGenOpts) { 90 handleAllErrors( 91 std::move(E), 92 [&](const LLVMRemarkSetupFileError &E) { 93 Diags.Report(diag::err_cannot_open_file) 94 << CodeGenOpts.OptRecordFile << E.message(); 95 }, 96 [&](const LLVMRemarkSetupPatternError &E) { 97 Diags.Report(diag::err_drv_optimization_remark_pattern) 98 << E.message() << CodeGenOpts.OptRecordPasses; 99 }, 100 [&](const LLVMRemarkSetupFormatError &E) { 101 Diags.Report(diag::err_drv_optimization_remark_format) 102 << CodeGenOpts.OptRecordFormat; 103 }); 104 } 105 106 class BackendConsumer : public ASTConsumer { 107 using LinkModule = CodeGenAction::LinkModule; 108 109 virtual void anchor(); 110 DiagnosticsEngine &Diags; 111 BackendAction Action; 112 const HeaderSearchOptions &HeaderSearchOpts; 113 const CodeGenOptions &CodeGenOpts; 114 const TargetOptions &TargetOpts; 115 const LangOptions &LangOpts; 116 std::unique_ptr<raw_pwrite_stream> AsmOutStream; 117 ASTContext *Context; 118 119 Timer LLVMIRGeneration; 120 unsigned LLVMIRGenerationRefCount; 121 122 /// True if we've finished generating IR. This prevents us from generating 123 /// additional LLVM IR after emitting output in HandleTranslationUnit. This 124 /// can happen when Clang plugins trigger additional AST deserialization. 125 bool IRGenFinished = false; 126 127 bool TimerIsEnabled = false; 128 129 std::unique_ptr<CodeGenerator> Gen; 130 131 SmallVector<LinkModule, 4> LinkModules; 132 133 // A map from mangled names to their function's source location, used for 134 // backend diagnostics as the Clang AST may be unavailable. We actually use 135 // the mangled name's hash as the key because mangled names can be very 136 // long and take up lots of space. Using a hash can cause name collision, 137 // but that is rare and the consequences are pointing to a wrong source 138 // location which is not severe. This is a vector instead of an actual map 139 // because we optimize for time building this map rather than time 140 // retrieving an entry, as backend diagnostics are uncommon. 141 std::vector<std::pair<llvm::hash_code, FullSourceLoc>> 142 ManglingFullSourceLocs; 143 144 // This is here so that the diagnostic printer knows the module a diagnostic 145 // refers to. 146 llvm::Module *CurLinkModule = nullptr; 147 148 public: 149 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 150 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 151 const HeaderSearchOptions &HeaderSearchOpts, 152 const PreprocessorOptions &PPOpts, 153 const CodeGenOptions &CodeGenOpts, 154 const TargetOptions &TargetOpts, 155 const LangOptions &LangOpts, const std::string &InFile, 156 SmallVector<LinkModule, 4> LinkModules, 157 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C, 158 CoverageSourceInfo *CoverageInfo = nullptr) 159 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts), 160 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts), 161 AsmOutStream(std::move(OS)), Context(nullptr), 162 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), 163 LLVMIRGenerationRefCount(0), 164 Gen(CreateLLVMCodeGen(Diags, InFile, std::move(FS), HeaderSearchOpts, 165 PPOpts, CodeGenOpts, C, CoverageInfo)), 166 LinkModules(std::move(LinkModules)) { 167 TimerIsEnabled = CodeGenOpts.TimePasses; 168 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses; 169 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun; 170 } 171 172 // This constructor is used in installing an empty BackendConsumer 173 // to use the clang diagnostic handler for IR input files. It avoids 174 // initializing the OS field. 175 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, 176 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 177 const HeaderSearchOptions &HeaderSearchOpts, 178 const PreprocessorOptions &PPOpts, 179 const CodeGenOptions &CodeGenOpts, 180 const TargetOptions &TargetOpts, 181 const LangOptions &LangOpts, llvm::Module *Module, 182 SmallVector<LinkModule, 4> LinkModules, LLVMContext &C, 183 CoverageSourceInfo *CoverageInfo = nullptr) 184 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts), 185 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts), 186 Context(nullptr), 187 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), 188 LLVMIRGenerationRefCount(0), 189 Gen(CreateLLVMCodeGen(Diags, "", std::move(FS), HeaderSearchOpts, 190 PPOpts, CodeGenOpts, C, CoverageInfo)), 191 LinkModules(std::move(LinkModules)), CurLinkModule(Module) { 192 TimerIsEnabled = CodeGenOpts.TimePasses; 193 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses; 194 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun; 195 } 196 llvm::Module *getModule() const { return Gen->GetModule(); } 197 std::unique_ptr<llvm::Module> takeModule() { 198 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule()); 199 } 200 201 CodeGenerator *getCodeGenerator() { return Gen.get(); } 202 203 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 204 Gen->HandleCXXStaticMemberVarInstantiation(VD); 205 } 206 207 void Initialize(ASTContext &Ctx) override { 208 assert(!Context && "initialized multiple times"); 209 210 Context = &Ctx; 211 212 if (TimerIsEnabled) 213 LLVMIRGeneration.startTimer(); 214 215 Gen->Initialize(Ctx); 216 217 if (TimerIsEnabled) 218 LLVMIRGeneration.stopTimer(); 219 } 220 221 bool HandleTopLevelDecl(DeclGroupRef D) override { 222 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), 223 Context->getSourceManager(), 224 "LLVM IR generation of declaration"); 225 226 // Recurse. 227 if (TimerIsEnabled) { 228 LLVMIRGenerationRefCount += 1; 229 if (LLVMIRGenerationRefCount == 1) 230 LLVMIRGeneration.startTimer(); 231 } 232 233 Gen->HandleTopLevelDecl(D); 234 235 if (TimerIsEnabled) { 236 LLVMIRGenerationRefCount -= 1; 237 if (LLVMIRGenerationRefCount == 0) 238 LLVMIRGeneration.stopTimer(); 239 } 240 241 return true; 242 } 243 244 void HandleInlineFunctionDefinition(FunctionDecl *D) override { 245 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 246 Context->getSourceManager(), 247 "LLVM IR generation of inline function"); 248 if (TimerIsEnabled) 249 LLVMIRGeneration.startTimer(); 250 251 Gen->HandleInlineFunctionDefinition(D); 252 253 if (TimerIsEnabled) 254 LLVMIRGeneration.stopTimer(); 255 } 256 257 void HandleInterestingDecl(DeclGroupRef D) override { 258 // Ignore interesting decls from the AST reader after IRGen is finished. 259 if (!IRGenFinished) 260 HandleTopLevelDecl(D); 261 } 262 263 // Links each entry in LinkModules into our module. Returns true on error. 264 bool LinkInModules() { 265 for (auto &LM : LinkModules) { 266 if (LM.PropagateAttrs) 267 for (Function &F : *LM.Module) { 268 // Skip intrinsics. Keep consistent with how intrinsics are created 269 // in LLVM IR. 270 if (F.isIntrinsic()) 271 continue; 272 Gen->CGM().addDefaultFunctionDefinitionAttributes(F); 273 } 274 275 CurLinkModule = LM.Module.get(); 276 277 bool Err; 278 if (LM.Internalize) { 279 Err = Linker::linkModules( 280 *getModule(), std::move(LM.Module), LM.LinkFlags, 281 [](llvm::Module &M, const llvm::StringSet<> &GVS) { 282 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) { 283 return !GV.hasName() || (GVS.count(GV.getName()) == 0); 284 }); 285 }); 286 } else { 287 Err = Linker::linkModules(*getModule(), std::move(LM.Module), 288 LM.LinkFlags); 289 } 290 291 if (Err) 292 return true; 293 } 294 return false; // success 295 } 296 297 void HandleTranslationUnit(ASTContext &C) override { 298 { 299 llvm::TimeTraceScope TimeScope("Frontend"); 300 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); 301 if (TimerIsEnabled) { 302 LLVMIRGenerationRefCount += 1; 303 if (LLVMIRGenerationRefCount == 1) 304 LLVMIRGeneration.startTimer(); 305 } 306 307 Gen->HandleTranslationUnit(C); 308 309 if (TimerIsEnabled) { 310 LLVMIRGenerationRefCount -= 1; 311 if (LLVMIRGenerationRefCount == 0) 312 LLVMIRGeneration.stopTimer(); 313 } 314 315 IRGenFinished = true; 316 } 317 318 // Silently ignore if we weren't initialized for some reason. 319 if (!getModule()) 320 return; 321 322 LLVMContext &Ctx = getModule()->getContext(); 323 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler = 324 Ctx.getDiagnosticHandler(); 325 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>( 326 CodeGenOpts, this)); 327 328 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr = 329 setupLLVMOptimizationRemarks( 330 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses, 331 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness, 332 CodeGenOpts.DiagnosticsHotnessThreshold); 333 334 if (Error E = OptRecordFileOrErr.takeError()) { 335 reportOptRecordError(std::move(E), Diags, CodeGenOpts); 336 return; 337 } 338 339 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile = 340 std::move(*OptRecordFileOrErr); 341 342 if (OptRecordFile && 343 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone) 344 Ctx.setDiagnosticsHotnessRequested(true); 345 346 if (CodeGenOpts.MisExpect) { 347 Ctx.setMisExpectWarningRequested(true); 348 } 349 350 if (CodeGenOpts.DiagnosticsMisExpectTolerance) { 351 Ctx.setDiagnosticsMisExpectTolerance( 352 CodeGenOpts.DiagnosticsMisExpectTolerance); 353 } 354 355 // Link each LinkModule into our module. 356 if (LinkInModules()) 357 return; 358 359 for (auto &F : getModule()->functions()) { 360 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) { 361 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation()); 362 // TODO: use a fast content hash when available. 363 auto NameHash = llvm::hash_value(F.getName()); 364 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc)); 365 } 366 } 367 368 if (CodeGenOpts.ClearASTBeforeBackend) { 369 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n"); 370 // Access to the AST is no longer available after this. 371 // Other things that the ASTContext manages are still available, e.g. 372 // the SourceManager. It'd be nice if we could separate out all the 373 // things in ASTContext used after this point and null out the 374 // ASTContext, but too many various parts of the ASTContext are still 375 // used in various parts. 376 C.cleanup(); 377 C.getAllocator().Reset(); 378 } 379 380 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef()); 381 382 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, 383 LangOpts, C.getTargetInfo().getDataLayoutString(), 384 getModule(), Action, std::move(AsmOutStream)); 385 386 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); 387 388 if (OptRecordFile) 389 OptRecordFile->keep(); 390 } 391 392 void HandleTagDeclDefinition(TagDecl *D) override { 393 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 394 Context->getSourceManager(), 395 "LLVM IR generation of declaration"); 396 Gen->HandleTagDeclDefinition(D); 397 } 398 399 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 400 Gen->HandleTagDeclRequiredDefinition(D); 401 } 402 403 void CompleteTentativeDefinition(VarDecl *D) override { 404 Gen->CompleteTentativeDefinition(D); 405 } 406 407 void CompleteExternalDeclaration(VarDecl *D) override { 408 Gen->CompleteExternalDeclaration(D); 409 } 410 411 void AssignInheritanceModel(CXXRecordDecl *RD) override { 412 Gen->AssignInheritanceModel(RD); 413 } 414 415 void HandleVTable(CXXRecordDecl *RD) override { 416 Gen->HandleVTable(RD); 417 } 418 419 /// Get the best possible source location to represent a diagnostic that 420 /// may have associated debug info. 421 const FullSourceLoc 422 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, 423 bool &BadDebugInfo, StringRef &Filename, 424 unsigned &Line, unsigned &Column) const; 425 426 std::optional<FullSourceLoc> 427 getFunctionSourceLocation(const Function &F) const; 428 429 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI); 430 /// Specialized handler for InlineAsm diagnostic. 431 /// \return True if the diagnostic has been successfully reported, false 432 /// otherwise. 433 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D); 434 /// Specialized handler for diagnostics reported using SMDiagnostic. 435 void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D); 436 /// Specialized handler for StackSize diagnostic. 437 /// \return True if the diagnostic has been successfully reported, false 438 /// otherwise. 439 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D); 440 /// Specialized handler for ResourceLimit diagnostic. 441 /// \return True if the diagnostic has been successfully reported, false 442 /// otherwise. 443 bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D); 444 445 /// Specialized handler for unsupported backend feature diagnostic. 446 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D); 447 /// Specialized handlers for optimization remarks. 448 /// Note that these handlers only accept remarks and they always handle 449 /// them. 450 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, 451 unsigned DiagID); 452 void 453 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D); 454 void OptimizationRemarkHandler( 455 const llvm::OptimizationRemarkAnalysisFPCommute &D); 456 void OptimizationRemarkHandler( 457 const llvm::OptimizationRemarkAnalysisAliasing &D); 458 void OptimizationFailureHandler( 459 const llvm::DiagnosticInfoOptimizationFailure &D); 460 void DontCallDiagHandler(const DiagnosticInfoDontCall &D); 461 /// Specialized handler for misexpect warnings. 462 /// Note that misexpect remarks are emitted through ORE 463 void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D); 464 }; 465 466 void BackendConsumer::anchor() {} 467 } 468 469 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) { 470 BackendCon->DiagnosticHandlerImpl(DI); 471 return true; 472 } 473 474 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr 475 /// buffer to be a valid FullSourceLoc. 476 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, 477 SourceManager &CSM) { 478 // Get both the clang and llvm source managers. The location is relative to 479 // a memory buffer that the LLVM Source Manager is handling, we need to add 480 // a copy to the Clang source manager. 481 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 482 483 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr 484 // already owns its one and clang::SourceManager wants to own its one. 485 const MemoryBuffer *LBuf = 486 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 487 488 // Create the copy and transfer ownership to clang::SourceManager. 489 // TODO: Avoid copying files into memory. 490 std::unique_ptr<llvm::MemoryBuffer> CBuf = 491 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), 492 LBuf->getBufferIdentifier()); 493 // FIXME: Keep a file ID map instead of creating new IDs for each location. 494 FileID FID = CSM.createFileID(std::move(CBuf)); 495 496 // Translate the offset into the file. 497 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 498 SourceLocation NewLoc = 499 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); 500 return FullSourceLoc(NewLoc, CSM); 501 } 502 503 #define ComputeDiagID(Severity, GroupName, DiagID) \ 504 do { \ 505 switch (Severity) { \ 506 case llvm::DS_Error: \ 507 DiagID = diag::err_fe_##GroupName; \ 508 break; \ 509 case llvm::DS_Warning: \ 510 DiagID = diag::warn_fe_##GroupName; \ 511 break; \ 512 case llvm::DS_Remark: \ 513 llvm_unreachable("'remark' severity not expected"); \ 514 break; \ 515 case llvm::DS_Note: \ 516 DiagID = diag::note_fe_##GroupName; \ 517 break; \ 518 } \ 519 } while (false) 520 521 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \ 522 do { \ 523 switch (Severity) { \ 524 case llvm::DS_Error: \ 525 DiagID = diag::err_fe_##GroupName; \ 526 break; \ 527 case llvm::DS_Warning: \ 528 DiagID = diag::warn_fe_##GroupName; \ 529 break; \ 530 case llvm::DS_Remark: \ 531 DiagID = diag::remark_fe_##GroupName; \ 532 break; \ 533 case llvm::DS_Note: \ 534 DiagID = diag::note_fe_##GroupName; \ 535 break; \ 536 } \ 537 } while (false) 538 539 void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) { 540 const llvm::SMDiagnostic &D = DI.getSMDiag(); 541 542 unsigned DiagID; 543 if (DI.isInlineAsmDiag()) 544 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID); 545 else 546 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID); 547 548 // This is for the empty BackendConsumer that uses the clang diagnostic 549 // handler for IR input files. 550 if (!Context) { 551 D.print(nullptr, llvm::errs()); 552 Diags.Report(DiagID).AddString("cannot compile inline asm"); 553 return; 554 } 555 556 // There are a couple of different kinds of errors we could get here. 557 // First, we re-format the SMDiagnostic in terms of a clang diagnostic. 558 559 // Strip "error: " off the start of the message string. 560 StringRef Message = D.getMessage(); 561 (void)Message.consume_front("error: "); 562 563 // If the SMDiagnostic has an inline asm source location, translate it. 564 FullSourceLoc Loc; 565 if (D.getLoc() != SMLoc()) 566 Loc = ConvertBackendLocation(D, Context->getSourceManager()); 567 568 // If this problem has clang-level source location information, report the 569 // issue in the source with a note showing the instantiated 570 // code. 571 if (DI.isInlineAsmDiag()) { 572 SourceLocation LocCookie = 573 SourceLocation::getFromRawEncoding(DI.getLocCookie()); 574 if (LocCookie.isValid()) { 575 Diags.Report(LocCookie, DiagID).AddString(Message); 576 577 if (D.getLoc().isValid()) { 578 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here); 579 // Convert the SMDiagnostic ranges into SourceRange and attach them 580 // to the diagnostic. 581 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) { 582 unsigned Column = D.getColumnNo(); 583 B << SourceRange(Loc.getLocWithOffset(Range.first - Column), 584 Loc.getLocWithOffset(Range.second - Column)); 585 } 586 } 587 return; 588 } 589 } 590 591 // Otherwise, report the backend issue as occurring in the generated .s file. 592 // If Loc is invalid, we still need to report the issue, it just gets no 593 // location info. 594 Diags.Report(Loc, DiagID).AddString(Message); 595 } 596 597 bool 598 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) { 599 unsigned DiagID; 600 ComputeDiagID(D.getSeverity(), inline_asm, DiagID); 601 std::string Message = D.getMsgStr().str(); 602 603 // If this problem has clang-level source location information, report the 604 // issue as being a problem in the source with a note showing the instantiated 605 // code. 606 SourceLocation LocCookie = 607 SourceLocation::getFromRawEncoding(D.getLocCookie()); 608 if (LocCookie.isValid()) 609 Diags.Report(LocCookie, DiagID).AddString(Message); 610 else { 611 // Otherwise, report the backend diagnostic as occurring in the generated 612 // .s file. 613 // If Loc is invalid, we still need to report the diagnostic, it just gets 614 // no location info. 615 FullSourceLoc Loc; 616 Diags.Report(Loc, DiagID).AddString(Message); 617 } 618 // We handled all the possible severities. 619 return true; 620 } 621 622 bool 623 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) { 624 if (D.getSeverity() != llvm::DS_Warning) 625 // For now, the only support we have for StackSize diagnostic is warning. 626 // We do not know how to format other severities. 627 return false; 628 629 auto Loc = getFunctionSourceLocation(D.getFunction()); 630 if (!Loc) 631 return false; 632 633 Diags.Report(*Loc, diag::warn_fe_frame_larger_than) 634 << D.getStackSize() 635 << D.getStackLimit() 636 << llvm::demangle(D.getFunction().getName().str()); 637 return true; 638 } 639 640 bool BackendConsumer::ResourceLimitDiagHandler( 641 const llvm::DiagnosticInfoResourceLimit &D) { 642 auto Loc = getFunctionSourceLocation(D.getFunction()); 643 if (!Loc) 644 return false; 645 unsigned DiagID = diag::err_fe_backend_resource_limit; 646 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID); 647 648 Diags.Report(*Loc, DiagID) 649 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit() 650 << llvm::demangle(D.getFunction().getName().str()); 651 return true; 652 } 653 654 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc( 655 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, 656 StringRef &Filename, unsigned &Line, unsigned &Column) const { 657 SourceManager &SourceMgr = Context->getSourceManager(); 658 FileManager &FileMgr = SourceMgr.getFileManager(); 659 SourceLocation DILoc; 660 661 if (D.isLocationAvailable()) { 662 D.getLocation(Filename, Line, Column); 663 if (Line > 0) { 664 auto FE = FileMgr.getFile(Filename); 665 if (!FE) 666 FE = FileMgr.getFile(D.getAbsolutePath()); 667 if (FE) { 668 // If -gcolumn-info was not used, Column will be 0. This upsets the 669 // source manager, so pass 1 if Column is not set. 670 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1); 671 } 672 } 673 BadDebugInfo = DILoc.isInvalid(); 674 } 675 676 // If a location isn't available, try to approximate it using the associated 677 // function definition. We use the definition's right brace to differentiate 678 // from diagnostics that genuinely relate to the function itself. 679 FullSourceLoc Loc(DILoc, SourceMgr); 680 if (Loc.isInvalid()) { 681 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction())) 682 Loc = *MaybeLoc; 683 } 684 685 if (DILoc.isInvalid() && D.isLocationAvailable()) 686 // If we were not able to translate the file:line:col information 687 // back to a SourceLocation, at least emit a note stating that 688 // we could not translate this location. This can happen in the 689 // case of #line directives. 690 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 691 << Filename << Line << Column; 692 693 return Loc; 694 } 695 696 std::optional<FullSourceLoc> 697 BackendConsumer::getFunctionSourceLocation(const Function &F) const { 698 auto Hash = llvm::hash_value(F.getName()); 699 for (const auto &Pair : ManglingFullSourceLocs) { 700 if (Pair.first == Hash) 701 return Pair.second; 702 } 703 return std::nullopt; 704 } 705 706 void BackendConsumer::UnsupportedDiagHandler( 707 const llvm::DiagnosticInfoUnsupported &D) { 708 // We only support warnings or errors. 709 assert(D.getSeverity() == llvm::DS_Error || 710 D.getSeverity() == llvm::DS_Warning); 711 712 StringRef Filename; 713 unsigned Line, Column; 714 bool BadDebugInfo = false; 715 FullSourceLoc Loc; 716 std::string Msg; 717 raw_string_ostream MsgStream(Msg); 718 719 // Context will be nullptr for IR input files, we will construct the diag 720 // message from llvm::DiagnosticInfoUnsupported. 721 if (Context != nullptr) { 722 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 723 MsgStream << D.getMessage(); 724 } else { 725 DiagnosticPrinterRawOStream DP(MsgStream); 726 D.print(DP); 727 } 728 729 auto DiagType = D.getSeverity() == llvm::DS_Error 730 ? diag::err_fe_backend_unsupported 731 : diag::warn_fe_backend_unsupported; 732 Diags.Report(Loc, DiagType) << MsgStream.str(); 733 734 if (BadDebugInfo) 735 // If we were not able to translate the file:line:col information 736 // back to a SourceLocation, at least emit a note stating that 737 // we could not translate this location. This can happen in the 738 // case of #line directives. 739 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 740 << Filename << Line << Column; 741 } 742 743 void BackendConsumer::EmitOptimizationMessage( 744 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) { 745 // We only support warnings and remarks. 746 assert(D.getSeverity() == llvm::DS_Remark || 747 D.getSeverity() == llvm::DS_Warning); 748 749 StringRef Filename; 750 unsigned Line, Column; 751 bool BadDebugInfo = false; 752 FullSourceLoc Loc; 753 std::string Msg; 754 raw_string_ostream MsgStream(Msg); 755 756 // Context will be nullptr for IR input files, we will construct the remark 757 // message from llvm::DiagnosticInfoOptimizationBase. 758 if (Context != nullptr) { 759 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 760 MsgStream << D.getMsg(); 761 } else { 762 DiagnosticPrinterRawOStream DP(MsgStream); 763 D.print(DP); 764 } 765 766 if (D.getHotness()) 767 MsgStream << " (hotness: " << *D.getHotness() << ")"; 768 769 Diags.Report(Loc, DiagID) 770 << AddFlagValue(D.getPassName()) 771 << MsgStream.str(); 772 773 if (BadDebugInfo) 774 // If we were not able to translate the file:line:col information 775 // back to a SourceLocation, at least emit a note stating that 776 // we could not translate this location. This can happen in the 777 // case of #line directives. 778 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 779 << Filename << Line << Column; 780 } 781 782 void BackendConsumer::OptimizationRemarkHandler( 783 const llvm::DiagnosticInfoOptimizationBase &D) { 784 // Without hotness information, don't show noisy remarks. 785 if (D.isVerbose() && !D.getHotness()) 786 return; 787 788 if (D.isPassed()) { 789 // Optimization remarks are active only if the -Rpass flag has a regular 790 // expression that matches the name of the pass name in \p D. 791 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName())) 792 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 793 } else if (D.isMissed()) { 794 // Missed optimization remarks are active only if the -Rpass-missed 795 // flag has a regular expression that matches the name of the pass 796 // name in \p D. 797 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName())) 798 EmitOptimizationMessage( 799 D, diag::remark_fe_backend_optimization_remark_missed); 800 } else { 801 assert(D.isAnalysis() && "Unknown remark type"); 802 803 bool ShouldAlwaysPrint = false; 804 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D)) 805 ShouldAlwaysPrint = ORA->shouldAlwaysPrint(); 806 807 if (ShouldAlwaysPrint || 808 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 809 EmitOptimizationMessage( 810 D, diag::remark_fe_backend_optimization_remark_analysis); 811 } 812 } 813 814 void BackendConsumer::OptimizationRemarkHandler( 815 const llvm::OptimizationRemarkAnalysisFPCommute &D) { 816 // Optimization analysis remarks are active if the pass name is set to 817 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 818 // regular expression that matches the name of the pass name in \p D. 819 820 if (D.shouldAlwaysPrint() || 821 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 822 EmitOptimizationMessage( 823 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute); 824 } 825 826 void BackendConsumer::OptimizationRemarkHandler( 827 const llvm::OptimizationRemarkAnalysisAliasing &D) { 828 // Optimization analysis remarks are active if the pass name is set to 829 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 830 // regular expression that matches the name of the pass name in \p D. 831 832 if (D.shouldAlwaysPrint() || 833 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())) 834 EmitOptimizationMessage( 835 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing); 836 } 837 838 void BackendConsumer::OptimizationFailureHandler( 839 const llvm::DiagnosticInfoOptimizationFailure &D) { 840 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 841 } 842 843 void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) { 844 SourceLocation LocCookie = 845 SourceLocation::getFromRawEncoding(D.getLocCookie()); 846 847 // FIXME: we can't yet diagnose indirect calls. When/if we can, we 848 // should instead assert that LocCookie.isValid(). 849 if (!LocCookie.isValid()) 850 return; 851 852 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error 853 ? diag::err_fe_backend_error_attr 854 : diag::warn_fe_backend_warning_attr) 855 << llvm::demangle(D.getFunctionName().str()) << D.getNote(); 856 } 857 858 void BackendConsumer::MisExpectDiagHandler( 859 const llvm::DiagnosticInfoMisExpect &D) { 860 StringRef Filename; 861 unsigned Line, Column; 862 bool BadDebugInfo = false; 863 FullSourceLoc Loc = 864 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column); 865 866 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str(); 867 868 if (BadDebugInfo) 869 // If we were not able to translate the file:line:col information 870 // back to a SourceLocation, at least emit a note stating that 871 // we could not translate this location. This can happen in the 872 // case of #line directives. 873 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 874 << Filename << Line << Column; 875 } 876 877 /// This function is invoked when the backend needs 878 /// to report something to the user. 879 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 880 unsigned DiagID = diag::err_fe_inline_asm; 881 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 882 // Get the diagnostic ID based. 883 switch (DI.getKind()) { 884 case llvm::DK_InlineAsm: 885 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 886 return; 887 ComputeDiagID(Severity, inline_asm, DiagID); 888 break; 889 case llvm::DK_SrcMgr: 890 SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI)); 891 return; 892 case llvm::DK_StackSize: 893 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 894 return; 895 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 896 break; 897 case llvm::DK_ResourceLimit: 898 if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI))) 899 return; 900 ComputeDiagID(Severity, backend_resource_limit, DiagID); 901 break; 902 case DK_Linker: 903 ComputeDiagID(Severity, linking_module, DiagID); 904 break; 905 case llvm::DK_OptimizationRemark: 906 // Optimization remarks are always handled completely by this 907 // handler. There is no generic way of emitting them. 908 OptimizationRemarkHandler(cast<OptimizationRemark>(DI)); 909 return; 910 case llvm::DK_OptimizationRemarkMissed: 911 // Optimization remarks are always handled completely by this 912 // handler. There is no generic way of emitting them. 913 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI)); 914 return; 915 case llvm::DK_OptimizationRemarkAnalysis: 916 // Optimization remarks are always handled completely by this 917 // handler. There is no generic way of emitting them. 918 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI)); 919 return; 920 case llvm::DK_OptimizationRemarkAnalysisFPCommute: 921 // Optimization remarks are always handled completely by this 922 // handler. There is no generic way of emitting them. 923 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI)); 924 return; 925 case llvm::DK_OptimizationRemarkAnalysisAliasing: 926 // Optimization remarks are always handled completely by this 927 // handler. There is no generic way of emitting them. 928 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI)); 929 return; 930 case llvm::DK_MachineOptimizationRemark: 931 // Optimization remarks are always handled completely by this 932 // handler. There is no generic way of emitting them. 933 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI)); 934 return; 935 case llvm::DK_MachineOptimizationRemarkMissed: 936 // Optimization remarks are always handled completely by this 937 // handler. There is no generic way of emitting them. 938 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI)); 939 return; 940 case llvm::DK_MachineOptimizationRemarkAnalysis: 941 // Optimization remarks are always handled completely by this 942 // handler. There is no generic way of emitting them. 943 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI)); 944 return; 945 case llvm::DK_OptimizationFailure: 946 // Optimization failures are always handled completely by this 947 // handler. 948 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 949 return; 950 case llvm::DK_Unsupported: 951 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI)); 952 return; 953 case llvm::DK_DontCall: 954 DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI)); 955 return; 956 case llvm::DK_MisExpect: 957 MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI)); 958 return; 959 default: 960 // Plugin IDs are not bound to any value as they are set dynamically. 961 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 962 break; 963 } 964 std::string MsgStorage; 965 { 966 raw_string_ostream Stream(MsgStorage); 967 DiagnosticPrinterRawOStream DP(Stream); 968 DI.print(DP); 969 } 970 971 if (DI.getKind() == DK_Linker) { 972 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics"); 973 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage; 974 return; 975 } 976 977 // Report the backend message using the usual diagnostic mechanism. 978 FullSourceLoc Loc; 979 Diags.Report(Loc, DiagID).AddString(MsgStorage); 980 } 981 #undef ComputeDiagID 982 983 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 984 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), 985 OwnsVMContext(!_VMContext) {} 986 987 CodeGenAction::~CodeGenAction() { 988 TheModule.reset(); 989 if (OwnsVMContext) 990 delete VMContext; 991 } 992 993 bool CodeGenAction::hasIRSupport() const { return true; } 994 995 void CodeGenAction::EndSourceFileAction() { 996 // If the consumer creation failed, do nothing. 997 if (!getCompilerInstance().hasASTConsumer()) 998 return; 999 1000 // Steal the module from the consumer. 1001 TheModule = BEConsumer->takeModule(); 1002 } 1003 1004 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { 1005 return std::move(TheModule); 1006 } 1007 1008 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 1009 OwnsVMContext = false; 1010 return VMContext; 1011 } 1012 1013 CodeGenerator *CodeGenAction::getCodeGenerator() const { 1014 return BEConsumer->getCodeGenerator(); 1015 } 1016 1017 static std::unique_ptr<raw_pwrite_stream> 1018 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { 1019 switch (Action) { 1020 case Backend_EmitAssembly: 1021 return CI.createDefaultOutputFile(false, InFile, "s"); 1022 case Backend_EmitLL: 1023 return CI.createDefaultOutputFile(false, InFile, "ll"); 1024 case Backend_EmitBC: 1025 return CI.createDefaultOutputFile(true, InFile, "bc"); 1026 case Backend_EmitNothing: 1027 return nullptr; 1028 case Backend_EmitMCNull: 1029 return CI.createNullOutputFile(); 1030 case Backend_EmitObj: 1031 return CI.createDefaultOutputFile(true, InFile, "o"); 1032 } 1033 1034 llvm_unreachable("Invalid action!"); 1035 } 1036 1037 std::unique_ptr<ASTConsumer> 1038 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 1039 BackendAction BA = static_cast<BackendAction>(Act); 1040 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream(); 1041 if (!OS) 1042 OS = GetOutputStream(CI, InFile, BA); 1043 1044 if (BA != Backend_EmitNothing && !OS) 1045 return nullptr; 1046 1047 VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers); 1048 1049 // Load bitcode modules to link with, if we need to. 1050 if (LinkModules.empty()) 1051 for (const CodeGenOptions::BitcodeFileToLink &F : 1052 CI.getCodeGenOpts().LinkBitcodeFiles) { 1053 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename); 1054 if (!BCBuf) { 1055 CI.getDiagnostics().Report(diag::err_cannot_open_file) 1056 << F.Filename << BCBuf.getError().message(); 1057 LinkModules.clear(); 1058 return nullptr; 1059 } 1060 1061 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr = 1062 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext); 1063 if (!ModuleOrErr) { 1064 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 1065 CI.getDiagnostics().Report(diag::err_cannot_open_file) 1066 << F.Filename << EIB.message(); 1067 }); 1068 LinkModules.clear(); 1069 return nullptr; 1070 } 1071 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs, 1072 F.Internalize, F.LinkFlags}); 1073 } 1074 1075 CoverageSourceInfo *CoverageInfo = nullptr; 1076 // Add the preprocessor callback only when the coverage mapping is generated. 1077 if (CI.getCodeGenOpts().CoverageMapping) 1078 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks( 1079 CI.getPreprocessor()); 1080 1081 std::unique_ptr<BackendConsumer> Result(new BackendConsumer( 1082 BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(), 1083 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), CI.getCodeGenOpts(), 1084 CI.getTargetOpts(), CI.getLangOpts(), std::string(InFile), 1085 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo)); 1086 BEConsumer = Result.get(); 1087 1088 // Enable generating macro debug info only when debug info is not disabled and 1089 // also macro debug info is enabled. 1090 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo && 1091 CI.getCodeGenOpts().MacroDebugInfo) { 1092 std::unique_ptr<PPCallbacks> Callbacks = 1093 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(), 1094 CI.getPreprocessor()); 1095 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks)); 1096 } 1097 1098 return std::move(Result); 1099 } 1100 1101 std::unique_ptr<llvm::Module> 1102 CodeGenAction::loadModule(MemoryBufferRef MBRef) { 1103 CompilerInstance &CI = getCompilerInstance(); 1104 SourceManager &SM = CI.getSourceManager(); 1105 1106 VMContext->setOpaquePointers(CI.getCodeGenOpts().OpaquePointers); 1107 1108 // For ThinLTO backend invocations, ensure that the context 1109 // merges types based on ODR identifiers. We also need to read 1110 // the correct module out of a multi-module bitcode file. 1111 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) { 1112 VMContext->enableDebugTypeODRUniquing(); 1113 1114 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> { 1115 unsigned DiagID = 1116 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1117 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { 1118 CI.getDiagnostics().Report(DiagID) << EIB.message(); 1119 }); 1120 return {}; 1121 }; 1122 1123 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef); 1124 if (!BMsOrErr) 1125 return DiagErrors(BMsOrErr.takeError()); 1126 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr); 1127 // We have nothing to do if the file contains no ThinLTO module. This is 1128 // possible if ThinLTO compilation was not able to split module. Content of 1129 // the file was already processed by indexing and will be passed to the 1130 // linker using merged object file. 1131 if (!Bm) { 1132 auto M = std::make_unique<llvm::Module>("empty", *VMContext); 1133 M->setTargetTriple(CI.getTargetOpts().Triple); 1134 return M; 1135 } 1136 Expected<std::unique_ptr<llvm::Module>> MOrErr = 1137 Bm->parseModule(*VMContext); 1138 if (!MOrErr) 1139 return DiagErrors(MOrErr.takeError()); 1140 return std::move(*MOrErr); 1141 } 1142 1143 llvm::SMDiagnostic Err; 1144 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) 1145 return M; 1146 1147 // Translate from the diagnostic info to the SourceManager location if 1148 // available. 1149 // TODO: Unify this with ConvertBackendLocation() 1150 SourceLocation Loc; 1151 if (Err.getLineNo() > 0) { 1152 assert(Err.getColumnNo() >= 0); 1153 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()), 1154 Err.getLineNo(), Err.getColumnNo() + 1); 1155 } 1156 1157 // Strip off a leading diagnostic code if there is one. 1158 StringRef Msg = Err.getMessage(); 1159 if (Msg.startswith("error: ")) 1160 Msg = Msg.substr(7); 1161 1162 unsigned DiagID = 1163 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1164 1165 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 1166 return {}; 1167 } 1168 1169 void CodeGenAction::ExecuteAction() { 1170 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) { 1171 this->ASTFrontendAction::ExecuteAction(); 1172 return; 1173 } 1174 1175 // If this is an IR file, we have to treat it specially. 1176 BackendAction BA = static_cast<BackendAction>(Act); 1177 CompilerInstance &CI = getCompilerInstance(); 1178 auto &CodeGenOpts = CI.getCodeGenOpts(); 1179 auto &Diagnostics = CI.getDiagnostics(); 1180 std::unique_ptr<raw_pwrite_stream> OS = 1181 GetOutputStream(CI, getCurrentFileOrBufferName(), BA); 1182 if (BA != Backend_EmitNothing && !OS) 1183 return; 1184 1185 SourceManager &SM = CI.getSourceManager(); 1186 FileID FID = SM.getMainFileID(); 1187 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID); 1188 if (!MainFile) 1189 return; 1190 1191 TheModule = loadModule(*MainFile); 1192 if (!TheModule) 1193 return; 1194 1195 const TargetOptions &TargetOpts = CI.getTargetOpts(); 1196 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 1197 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module) 1198 << TargetOpts.Triple; 1199 TheModule->setTargetTriple(TargetOpts.Triple); 1200 } 1201 1202 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics); 1203 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile); 1204 1205 LLVMContext &Ctx = TheModule->getContext(); 1206 1207 // Restore any diagnostic handler previously set before returning from this 1208 // function. 1209 struct RAII { 1210 LLVMContext &Ctx; 1211 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler(); 1212 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); } 1213 } _{Ctx}; 1214 1215 // Set clang diagnostic handler. To do this we need to create a fake 1216 // BackendConsumer. 1217 BackendConsumer Result(BA, CI.getDiagnostics(), &CI.getVirtualFileSystem(), 1218 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), 1219 CI.getCodeGenOpts(), CI.getTargetOpts(), 1220 CI.getLangOpts(), TheModule.get(), 1221 std::move(LinkModules), *VMContext, nullptr); 1222 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be 1223 // true here because the valued names are needed for reading textual IR. 1224 Ctx.setDiscardValueNames(false); 1225 Ctx.setDiagnosticHandler( 1226 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result)); 1227 1228 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr = 1229 setupLLVMOptimizationRemarks( 1230 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses, 1231 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness, 1232 CodeGenOpts.DiagnosticsHotnessThreshold); 1233 1234 if (Error E = OptRecordFileOrErr.takeError()) { 1235 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts); 1236 return; 1237 } 1238 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile = 1239 std::move(*OptRecordFileOrErr); 1240 1241 EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, 1242 TargetOpts, CI.getLangOpts(), 1243 CI.getTarget().getDataLayoutString(), TheModule.get(), BA, 1244 std::move(OS)); 1245 if (OptRecordFile) 1246 OptRecordFile->keep(); 1247 } 1248 1249 // 1250 1251 void EmitAssemblyAction::anchor() { } 1252 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 1253 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 1254 1255 void EmitBCAction::anchor() { } 1256 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 1257 : CodeGenAction(Backend_EmitBC, _VMContext) {} 1258 1259 void EmitLLVMAction::anchor() { } 1260 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 1261 : CodeGenAction(Backend_EmitLL, _VMContext) {} 1262 1263 void EmitLLVMOnlyAction::anchor() { } 1264 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 1265 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 1266 1267 void EmitCodeGenOnlyAction::anchor() { } 1268 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 1269 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 1270 1271 void EmitObjAction::anchor() { } 1272 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 1273 : CodeGenAction(Backend_EmitObj, _VMContext) {} 1274