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