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