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