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