1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "CoverageMappingGen.h" 11 #include "clang/AST/ASTConsumer.h" 12 #include "clang/AST/ASTContext.h" 13 #include "clang/AST/DeclCXX.h" 14 #include "clang/AST/DeclGroup.h" 15 #include "clang/Basic/FileManager.h" 16 #include "clang/Basic/SourceManager.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/CodeGen/BackendUtil.h" 19 #include "clang/CodeGen/CodeGenAction.h" 20 #include "clang/CodeGen/ModuleBuilder.h" 21 #include "clang/Frontend/CompilerInstance.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "llvm/ADT/SmallString.h" 25 #include "llvm/Bitcode/ReaderWriter.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DiagnosticInfo.h" 28 #include "llvm/IR/DiagnosticPrinter.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IRReader/IRReader.h" 32 #include "llvm/Linker/Linker.h" 33 #include "llvm/Pass.h" 34 #include "llvm/Support/MemoryBuffer.h" 35 #include "llvm/Support/SourceMgr.h" 36 #include "llvm/Support/Timer.h" 37 #include <memory> 38 using namespace clang; 39 using namespace llvm; 40 41 namespace clang { 42 class BackendConsumer : public ASTConsumer { 43 virtual void anchor(); 44 DiagnosticsEngine &Diags; 45 BackendAction Action; 46 const CodeGenOptions &CodeGenOpts; 47 const TargetOptions &TargetOpts; 48 const LangOptions &LangOpts; 49 raw_pwrite_stream *AsmOutStream; 50 ASTContext *Context; 51 52 Timer LLVMIRGeneration; 53 54 std::unique_ptr<CodeGenerator> Gen; 55 56 std::unique_ptr<llvm::Module> TheModule; 57 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4> 58 LinkModules; 59 60 // This is here so that the diagnostic printer knows the module a diagnostic 61 // refers to. 62 llvm::Module *CurLinkModule = nullptr; 63 64 public: 65 BackendConsumer( 66 BackendAction Action, DiagnosticsEngine &Diags, 67 const HeaderSearchOptions &HeaderSearchOpts, 68 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, 69 const TargetOptions &TargetOpts, const LangOptions &LangOpts, 70 bool TimePasses, const std::string &InFile, 71 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules, 72 raw_pwrite_stream *OS, LLVMContext &C, 73 CoverageSourceInfo *CoverageInfo = nullptr) 74 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts), 75 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS), 76 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"), 77 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts, 78 CodeGenOpts, C, CoverageInfo)) { 79 llvm::TimePassesIsEnabled = TimePasses; 80 for (auto &I : LinkModules) 81 this->LinkModules.push_back( 82 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second))); 83 } 84 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); } 85 void releaseLinkModules() { 86 for (auto &I : LinkModules) 87 I.second.release(); 88 } 89 90 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override { 91 Gen->HandleCXXStaticMemberVarInstantiation(VD); 92 } 93 94 void Initialize(ASTContext &Ctx) override { 95 assert(!Context && "initialized multiple times"); 96 97 Context = &Ctx; 98 99 if (llvm::TimePassesIsEnabled) 100 LLVMIRGeneration.startTimer(); 101 102 Gen->Initialize(Ctx); 103 104 TheModule.reset(Gen->GetModule()); 105 106 if (llvm::TimePassesIsEnabled) 107 LLVMIRGeneration.stopTimer(); 108 } 109 110 bool HandleTopLevelDecl(DeclGroupRef D) override { 111 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(), 112 Context->getSourceManager(), 113 "LLVM IR generation of declaration"); 114 115 if (llvm::TimePassesIsEnabled) 116 LLVMIRGeneration.startTimer(); 117 118 Gen->HandleTopLevelDecl(D); 119 120 if (llvm::TimePassesIsEnabled) 121 LLVMIRGeneration.stopTimer(); 122 123 return true; 124 } 125 126 void HandleInlineMethodDefinition(CXXMethodDecl *D) override { 127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 128 Context->getSourceManager(), 129 "LLVM IR generation of inline method"); 130 if (llvm::TimePassesIsEnabled) 131 LLVMIRGeneration.startTimer(); 132 133 Gen->HandleInlineMethodDefinition(D); 134 135 if (llvm::TimePassesIsEnabled) 136 LLVMIRGeneration.stopTimer(); 137 } 138 139 void HandleTranslationUnit(ASTContext &C) override { 140 { 141 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation"); 142 if (llvm::TimePassesIsEnabled) 143 LLVMIRGeneration.startTimer(); 144 145 Gen->HandleTranslationUnit(C); 146 147 if (llvm::TimePassesIsEnabled) 148 LLVMIRGeneration.stopTimer(); 149 } 150 151 // Silently ignore if we weren't initialized for some reason. 152 if (!TheModule) 153 return; 154 155 // Make sure IR generation is happy with the module. This is released by 156 // the module provider. 157 llvm::Module *M = Gen->ReleaseModule(); 158 if (!M) { 159 // The module has been released by IR gen on failures, do not double 160 // free. 161 TheModule.release(); 162 return; 163 } 164 165 assert(TheModule.get() == M && 166 "Unexpected module change during IR generation"); 167 168 // Install an inline asm handler so that diagnostics get printed through 169 // our diagnostics hooks. 170 LLVMContext &Ctx = TheModule->getContext(); 171 LLVMContext::InlineAsmDiagHandlerTy OldHandler = 172 Ctx.getInlineAsmDiagnosticHandler(); 173 void *OldContext = Ctx.getInlineAsmDiagnosticContext(); 174 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this); 175 176 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler = 177 Ctx.getDiagnosticHandler(); 178 void *OldDiagnosticContext = Ctx.getDiagnosticContext(); 179 Ctx.setDiagnosticHandler(DiagnosticHandler, this); 180 181 // Link LinkModule into this module if present, preserving its validity. 182 for (auto &I : LinkModules) { 183 unsigned LinkFlags = I.first; 184 CurLinkModule = I.second.get(); 185 if (Linker::linkModules(*M, std::move(I.second), LinkFlags)) 186 return; 187 } 188 189 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, 190 C.getTargetInfo().getDataLayoutString(), 191 TheModule.get(), Action, AsmOutStream); 192 193 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext); 194 195 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext); 196 } 197 198 void HandleTagDeclDefinition(TagDecl *D) override { 199 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 200 Context->getSourceManager(), 201 "LLVM IR generation of declaration"); 202 Gen->HandleTagDeclDefinition(D); 203 } 204 205 void HandleTagDeclRequiredDefinition(const TagDecl *D) override { 206 Gen->HandleTagDeclRequiredDefinition(D); 207 } 208 209 void CompleteTentativeDefinition(VarDecl *D) override { 210 Gen->CompleteTentativeDefinition(D); 211 } 212 213 void AssignInheritanceModel(CXXRecordDecl *RD) override { 214 Gen->AssignInheritanceModel(RD); 215 } 216 217 void HandleVTable(CXXRecordDecl *RD) override { 218 Gen->HandleVTable(RD); 219 } 220 221 void HandleLinkerOption(llvm::StringRef Opts) override { 222 Gen->HandleLinkerOption(Opts); 223 } 224 225 void HandleDetectMismatch(llvm::StringRef Name, 226 llvm::StringRef Value) override { 227 Gen->HandleDetectMismatch(Name, Value); 228 } 229 230 void HandleDependentLibrary(llvm::StringRef Opts) override { 231 Gen->HandleDependentLibrary(Opts); 232 } 233 234 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context, 235 unsigned LocCookie) { 236 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie); 237 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc); 238 } 239 240 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI, 241 void *Context) { 242 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI); 243 } 244 245 /// Get the best possible source location to represent a diagnostic that 246 /// may have associated debug info. 247 const FullSourceLoc 248 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D, 249 bool &BadDebugInfo, StringRef &Filename, 250 unsigned &Line, unsigned &Column) const; 251 252 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &, 253 SourceLocation LocCookie); 254 255 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI); 256 /// \brief Specialized handler for InlineAsm diagnostic. 257 /// \return True if the diagnostic has been successfully reported, false 258 /// otherwise. 259 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D); 260 /// \brief Specialized handler for StackSize diagnostic. 261 /// \return True if the diagnostic has been successfully reported, false 262 /// otherwise. 263 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D); 264 /// \brief Specialized handler for unsupported backend feature diagnostic. 265 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D); 266 /// \brief Specialized handlers for optimization remarks. 267 /// Note that these handlers only accept remarks and they always handle 268 /// them. 269 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, 270 unsigned DiagID); 271 void 272 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D); 273 void OptimizationRemarkHandler( 274 const llvm::DiagnosticInfoOptimizationRemarkMissed &D); 275 void OptimizationRemarkHandler( 276 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D); 277 void OptimizationRemarkHandler( 278 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D); 279 void OptimizationRemarkHandler( 280 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D); 281 void OptimizationFailureHandler( 282 const llvm::DiagnosticInfoOptimizationFailure &D); 283 }; 284 285 void BackendConsumer::anchor() {} 286 } 287 288 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr 289 /// buffer to be a valid FullSourceLoc. 290 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, 291 SourceManager &CSM) { 292 // Get both the clang and llvm source managers. The location is relative to 293 // a memory buffer that the LLVM Source Manager is handling, we need to add 294 // a copy to the Clang source manager. 295 const llvm::SourceMgr &LSM = *D.getSourceMgr(); 296 297 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr 298 // already owns its one and clang::SourceManager wants to own its one. 299 const MemoryBuffer *LBuf = 300 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc())); 301 302 // Create the copy and transfer ownership to clang::SourceManager. 303 // TODO: Avoid copying files into memory. 304 std::unique_ptr<llvm::MemoryBuffer> CBuf = 305 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(), 306 LBuf->getBufferIdentifier()); 307 // FIXME: Keep a file ID map instead of creating new IDs for each location. 308 FileID FID = CSM.createFileID(std::move(CBuf)); 309 310 // Translate the offset into the file. 311 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart(); 312 SourceLocation NewLoc = 313 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset); 314 return FullSourceLoc(NewLoc, CSM); 315 } 316 317 318 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an 319 /// error parsing inline asm. The SMDiagnostic indicates the error relative to 320 /// the temporary memory buffer that the inline asm parser has set up. 321 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D, 322 SourceLocation LocCookie) { 323 // There are a couple of different kinds of errors we could get here. First, 324 // we re-format the SMDiagnostic in terms of a clang diagnostic. 325 326 // Strip "error: " off the start of the message string. 327 StringRef Message = D.getMessage(); 328 if (Message.startswith("error: ")) 329 Message = Message.substr(7); 330 331 // If the SMDiagnostic has an inline asm source location, translate it. 332 FullSourceLoc Loc; 333 if (D.getLoc() != SMLoc()) 334 Loc = ConvertBackendLocation(D, Context->getSourceManager()); 335 336 unsigned DiagID; 337 switch (D.getKind()) { 338 case llvm::SourceMgr::DK_Error: 339 DiagID = diag::err_fe_inline_asm; 340 break; 341 case llvm::SourceMgr::DK_Warning: 342 DiagID = diag::warn_fe_inline_asm; 343 break; 344 case llvm::SourceMgr::DK_Note: 345 DiagID = diag::note_fe_inline_asm; 346 break; 347 } 348 // If this problem has clang-level source location information, report the 349 // issue in the source with a note showing the instantiated 350 // code. 351 if (LocCookie.isValid()) { 352 Diags.Report(LocCookie, DiagID).AddString(Message); 353 354 if (D.getLoc().isValid()) { 355 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here); 356 // Convert the SMDiagnostic ranges into SourceRange and attach them 357 // to the diagnostic. 358 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) { 359 unsigned Column = D.getColumnNo(); 360 B << SourceRange(Loc.getLocWithOffset(Range.first - Column), 361 Loc.getLocWithOffset(Range.second - Column)); 362 } 363 } 364 return; 365 } 366 367 // Otherwise, report the backend issue as occurring in the generated .s file. 368 // If Loc is invalid, we still need to report the issue, it just gets no 369 // location info. 370 Diags.Report(Loc, DiagID).AddString(Message); 371 } 372 373 #define ComputeDiagID(Severity, GroupName, DiagID) \ 374 do { \ 375 switch (Severity) { \ 376 case llvm::DS_Error: \ 377 DiagID = diag::err_fe_##GroupName; \ 378 break; \ 379 case llvm::DS_Warning: \ 380 DiagID = diag::warn_fe_##GroupName; \ 381 break; \ 382 case llvm::DS_Remark: \ 383 llvm_unreachable("'remark' severity not expected"); \ 384 break; \ 385 case llvm::DS_Note: \ 386 DiagID = diag::note_fe_##GroupName; \ 387 break; \ 388 } \ 389 } while (false) 390 391 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \ 392 do { \ 393 switch (Severity) { \ 394 case llvm::DS_Error: \ 395 DiagID = diag::err_fe_##GroupName; \ 396 break; \ 397 case llvm::DS_Warning: \ 398 DiagID = diag::warn_fe_##GroupName; \ 399 break; \ 400 case llvm::DS_Remark: \ 401 DiagID = diag::remark_fe_##GroupName; \ 402 break; \ 403 case llvm::DS_Note: \ 404 DiagID = diag::note_fe_##GroupName; \ 405 break; \ 406 } \ 407 } while (false) 408 409 bool 410 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) { 411 unsigned DiagID; 412 ComputeDiagID(D.getSeverity(), inline_asm, DiagID); 413 std::string Message = D.getMsgStr().str(); 414 415 // If this problem has clang-level source location information, report the 416 // issue as being a problem in the source with a note showing the instantiated 417 // code. 418 SourceLocation LocCookie = 419 SourceLocation::getFromRawEncoding(D.getLocCookie()); 420 if (LocCookie.isValid()) 421 Diags.Report(LocCookie, DiagID).AddString(Message); 422 else { 423 // Otherwise, report the backend diagnostic as occurring in the generated 424 // .s file. 425 // If Loc is invalid, we still need to report the diagnostic, it just gets 426 // no location info. 427 FullSourceLoc Loc; 428 Diags.Report(Loc, DiagID).AddString(Message); 429 } 430 // We handled all the possible severities. 431 return true; 432 } 433 434 bool 435 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) { 436 if (D.getSeverity() != llvm::DS_Warning) 437 // For now, the only support we have for StackSize diagnostic is warning. 438 // We do not know how to format other severities. 439 return false; 440 441 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) { 442 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()), 443 diag::warn_fe_frame_larger_than) 444 << D.getStackSize() << Decl::castToDeclContext(ND); 445 return true; 446 } 447 448 return false; 449 } 450 451 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc( 452 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename, 453 unsigned &Line, unsigned &Column) const { 454 SourceManager &SourceMgr = Context->getSourceManager(); 455 FileManager &FileMgr = SourceMgr.getFileManager(); 456 SourceLocation DILoc; 457 458 if (D.isLocationAvailable()) { 459 D.getLocation(&Filename, &Line, &Column); 460 const FileEntry *FE = FileMgr.getFile(Filename); 461 if (FE && Line > 0) { 462 // If -gcolumn-info was not used, Column will be 0. This upsets the 463 // source manager, so pass 1 if Column is not set. 464 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1); 465 } 466 BadDebugInfo = DILoc.isInvalid(); 467 } 468 469 // If a location isn't available, try to approximate it using the associated 470 // function definition. We use the definition's right brace to differentiate 471 // from diagnostics that genuinely relate to the function itself. 472 FullSourceLoc Loc(DILoc, SourceMgr); 473 if (Loc.isInvalid()) 474 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName())) 475 Loc = FD->getASTContext().getFullLoc(FD->getLocation()); 476 477 if (DILoc.isInvalid() && D.isLocationAvailable()) 478 // If we were not able to translate the file:line:col information 479 // back to a SourceLocation, at least emit a note stating that 480 // we could not translate this location. This can happen in the 481 // case of #line directives. 482 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 483 << Filename << Line; 484 485 return Loc; 486 } 487 488 void BackendConsumer::UnsupportedDiagHandler( 489 const llvm::DiagnosticInfoUnsupported &D) { 490 // We only support errors. 491 assert(D.getSeverity() == llvm::DS_Error); 492 493 StringRef Filename; 494 unsigned Line, Column; 495 bool BadDebugInfo; 496 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, 497 Line, Column); 498 499 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str(); 500 501 if (BadDebugInfo) 502 // If we were not able to translate the file:line:col information 503 // back to a SourceLocation, at least emit a note stating that 504 // we could not translate this location. This can happen in the 505 // case of #line directives. 506 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 507 << Filename << Line << Column; 508 } 509 510 void BackendConsumer::EmitOptimizationMessage( 511 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) { 512 // We only support warnings and remarks. 513 assert(D.getSeverity() == llvm::DS_Remark || 514 D.getSeverity() == llvm::DS_Warning); 515 516 StringRef Filename; 517 unsigned Line, Column; 518 bool BadDebugInfo = false; 519 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, 520 Line, Column); 521 522 Diags.Report(Loc, DiagID) 523 << AddFlagValue(D.getPassName() ? D.getPassName() : "") 524 << D.getMsg().str(); 525 526 if (BadDebugInfo) 527 // If we were not able to translate the file:line:col information 528 // back to a SourceLocation, at least emit a note stating that 529 // we could not translate this location. This can happen in the 530 // case of #line directives. 531 Diags.Report(Loc, diag::note_fe_backend_invalid_loc) 532 << Filename << Line << Column; 533 } 534 535 void BackendConsumer::OptimizationRemarkHandler( 536 const llvm::DiagnosticInfoOptimizationRemark &D) { 537 // Optimization remarks are active only if the -Rpass flag has a regular 538 // expression that matches the name of the pass name in \p D. 539 if (CodeGenOpts.OptimizationRemarkPattern && 540 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) 541 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark); 542 } 543 544 void BackendConsumer::OptimizationRemarkHandler( 545 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) { 546 // Missed optimization remarks are active only if the -Rpass-missed 547 // flag has a regular expression that matches the name of the pass 548 // name in \p D. 549 if (CodeGenOpts.OptimizationRemarkMissedPattern && 550 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName())) 551 EmitOptimizationMessage(D, 552 diag::remark_fe_backend_optimization_remark_missed); 553 } 554 555 void BackendConsumer::OptimizationRemarkHandler( 556 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) { 557 // Optimization analysis remarks are active if the pass name is set to 558 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 559 // regular expression that matches the name of the pass name in \p D. 560 561 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint || 562 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 563 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 564 EmitOptimizationMessage( 565 D, diag::remark_fe_backend_optimization_remark_analysis); 566 } 567 568 void BackendConsumer::OptimizationRemarkHandler( 569 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) { 570 // Optimization analysis remarks are active if the pass name is set to 571 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 572 // regular expression that matches the name of the pass name in \p D. 573 574 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint || 575 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 576 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 577 EmitOptimizationMessage( 578 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute); 579 } 580 581 void BackendConsumer::OptimizationRemarkHandler( 582 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) { 583 // Optimization analysis remarks are active if the pass name is set to 584 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a 585 // regular expression that matches the name of the pass name in \p D. 586 587 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint || 588 (CodeGenOpts.OptimizationRemarkAnalysisPattern && 589 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))) 590 EmitOptimizationMessage( 591 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing); 592 } 593 594 void BackendConsumer::OptimizationFailureHandler( 595 const llvm::DiagnosticInfoOptimizationFailure &D) { 596 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure); 597 } 598 599 /// \brief This function is invoked when the backend needs 600 /// to report something to the user. 601 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) { 602 unsigned DiagID = diag::err_fe_inline_asm; 603 llvm::DiagnosticSeverity Severity = DI.getSeverity(); 604 // Get the diagnostic ID based. 605 switch (DI.getKind()) { 606 case llvm::DK_InlineAsm: 607 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI))) 608 return; 609 ComputeDiagID(Severity, inline_asm, DiagID); 610 break; 611 case llvm::DK_StackSize: 612 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI))) 613 return; 614 ComputeDiagID(Severity, backend_frame_larger_than, DiagID); 615 break; 616 case DK_Linker: 617 assert(CurLinkModule); 618 // FIXME: stop eating the warnings and notes. 619 if (Severity != DS_Error) 620 return; 621 DiagID = diag::err_fe_cannot_link_module; 622 break; 623 case llvm::DK_OptimizationRemark: 624 // Optimization remarks are always handled completely by this 625 // handler. There is no generic way of emitting them. 626 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI)); 627 return; 628 case llvm::DK_OptimizationRemarkMissed: 629 // Optimization remarks are always handled completely by this 630 // handler. There is no generic way of emitting them. 631 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI)); 632 return; 633 case llvm::DK_OptimizationRemarkAnalysis: 634 // Optimization remarks are always handled completely by this 635 // handler. There is no generic way of emitting them. 636 OptimizationRemarkHandler( 637 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI)); 638 return; 639 case llvm::DK_OptimizationRemarkAnalysisFPCommute: 640 // Optimization remarks are always handled completely by this 641 // handler. There is no generic way of emitting them. 642 OptimizationRemarkHandler( 643 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI)); 644 return; 645 case llvm::DK_OptimizationRemarkAnalysisAliasing: 646 // Optimization remarks are always handled completely by this 647 // handler. There is no generic way of emitting them. 648 OptimizationRemarkHandler( 649 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI)); 650 return; 651 case llvm::DK_OptimizationFailure: 652 // Optimization failures are always handled completely by this 653 // handler. 654 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI)); 655 return; 656 case llvm::DK_Unsupported: 657 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI)); 658 return; 659 default: 660 // Plugin IDs are not bound to any value as they are set dynamically. 661 ComputeDiagRemarkID(Severity, backend_plugin, DiagID); 662 break; 663 } 664 std::string MsgStorage; 665 { 666 raw_string_ostream Stream(MsgStorage); 667 DiagnosticPrinterRawOStream DP(Stream); 668 DI.print(DP); 669 } 670 671 if (DiagID == diag::err_fe_cannot_link_module) { 672 Diags.Report(diag::err_fe_cannot_link_module) 673 << CurLinkModule->getModuleIdentifier() << MsgStorage; 674 return; 675 } 676 677 // Report the backend message using the usual diagnostic mechanism. 678 FullSourceLoc Loc; 679 Diags.Report(Loc, DiagID).AddString(MsgStorage); 680 } 681 #undef ComputeDiagID 682 683 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext) 684 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext), 685 OwnsVMContext(!_VMContext) {} 686 687 CodeGenAction::~CodeGenAction() { 688 TheModule.reset(); 689 if (OwnsVMContext) 690 delete VMContext; 691 } 692 693 bool CodeGenAction::hasIRSupport() const { return true; } 694 695 void CodeGenAction::EndSourceFileAction() { 696 // If the consumer creation failed, do nothing. 697 if (!getCompilerInstance().hasASTConsumer()) 698 return; 699 700 // Take back ownership of link modules we passed to consumer. 701 if (!LinkModules.empty()) 702 BEConsumer->releaseLinkModules(); 703 704 // Steal the module from the consumer. 705 TheModule = BEConsumer->takeModule(); 706 } 707 708 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() { 709 return std::move(TheModule); 710 } 711 712 llvm::LLVMContext *CodeGenAction::takeLLVMContext() { 713 OwnsVMContext = false; 714 return VMContext; 715 } 716 717 static raw_pwrite_stream * 718 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) { 719 switch (Action) { 720 case Backend_EmitAssembly: 721 return CI.createDefaultOutputFile(false, InFile, "s"); 722 case Backend_EmitLL: 723 return CI.createDefaultOutputFile(false, InFile, "ll"); 724 case Backend_EmitBC: 725 return CI.createDefaultOutputFile(true, InFile, "bc"); 726 case Backend_EmitNothing: 727 return nullptr; 728 case Backend_EmitMCNull: 729 return CI.createNullOutputFile(); 730 case Backend_EmitObj: 731 return CI.createDefaultOutputFile(true, InFile, "o"); 732 } 733 734 llvm_unreachable("Invalid action!"); 735 } 736 737 std::unique_ptr<ASTConsumer> 738 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 739 BackendAction BA = static_cast<BackendAction>(Act); 740 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA); 741 if (BA != Backend_EmitNothing && !OS) 742 return nullptr; 743 744 // Load bitcode modules to link with, if we need to. 745 if (LinkModules.empty()) 746 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) { 747 const std::string &LinkBCFile = I.second; 748 749 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile); 750 if (!BCBuf) { 751 CI.getDiagnostics().Report(diag::err_cannot_open_file) 752 << LinkBCFile << BCBuf.getError().message(); 753 LinkModules.clear(); 754 return nullptr; 755 } 756 757 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr = 758 getLazyBitcodeModule(std::move(*BCBuf), *VMContext); 759 if (std::error_code EC = ModuleOrErr.getError()) { 760 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile 761 << EC.message(); 762 LinkModules.clear(); 763 return nullptr; 764 } 765 addLinkModule(ModuleOrErr.get().release(), I.first); 766 } 767 768 CoverageSourceInfo *CoverageInfo = nullptr; 769 // Add the preprocessor callback only when the coverage mapping is generated. 770 if (CI.getCodeGenOpts().CoverageMapping) { 771 CoverageInfo = new CoverageSourceInfo; 772 CI.getPreprocessor().addPPCallbacks( 773 std::unique_ptr<PPCallbacks>(CoverageInfo)); 774 } 775 776 std::unique_ptr<BackendConsumer> Result(new BackendConsumer( 777 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(), 778 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(), 779 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules, 780 OS, *VMContext, CoverageInfo)); 781 BEConsumer = Result.get(); 782 return std::move(Result); 783 } 784 785 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM, 786 void *Context, 787 unsigned LocCookie) { 788 SM.print(nullptr, llvm::errs()); 789 } 790 791 void CodeGenAction::ExecuteAction() { 792 // If this is an IR file, we have to treat it specially. 793 if (getCurrentFileKind() == IK_LLVM_IR) { 794 BackendAction BA = static_cast<BackendAction>(Act); 795 CompilerInstance &CI = getCompilerInstance(); 796 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA); 797 if (BA != Backend_EmitNothing && !OS) 798 return; 799 800 bool Invalid; 801 SourceManager &SM = CI.getSourceManager(); 802 FileID FID = SM.getMainFileID(); 803 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid); 804 if (Invalid) 805 return; 806 807 llvm::SMDiagnostic Err; 808 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext); 809 if (!TheModule) { 810 // Translate from the diagnostic info to the SourceManager location if 811 // available. 812 // TODO: Unify this with ConvertBackendLocation() 813 SourceLocation Loc; 814 if (Err.getLineNo() > 0) { 815 assert(Err.getColumnNo() >= 0); 816 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID), 817 Err.getLineNo(), Err.getColumnNo() + 1); 818 } 819 820 // Strip off a leading diagnostic code if there is one. 821 StringRef Msg = Err.getMessage(); 822 if (Msg.startswith("error: ")) 823 Msg = Msg.substr(7); 824 825 unsigned DiagID = 826 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 827 828 CI.getDiagnostics().Report(Loc, DiagID) << Msg; 829 return; 830 } 831 const TargetOptions &TargetOpts = CI.getTargetOpts(); 832 if (TheModule->getTargetTriple() != TargetOpts.Triple) { 833 CI.getDiagnostics().Report(SourceLocation(), 834 diag::warn_fe_override_module) 835 << TargetOpts.Triple; 836 TheModule->setTargetTriple(TargetOpts.Triple); 837 } 838 839 LLVMContext &Ctx = TheModule->getContext(); 840 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler); 841 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts, 842 CI.getLangOpts(), CI.getTarget().getDataLayoutString(), 843 TheModule.get(), BA, OS); 844 return; 845 } 846 847 // Otherwise follow the normal AST path. 848 this->ASTFrontendAction::ExecuteAction(); 849 } 850 851 // 852 853 void EmitAssemblyAction::anchor() { } 854 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext) 855 : CodeGenAction(Backend_EmitAssembly, _VMContext) {} 856 857 void EmitBCAction::anchor() { } 858 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext) 859 : CodeGenAction(Backend_EmitBC, _VMContext) {} 860 861 void EmitLLVMAction::anchor() { } 862 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext) 863 : CodeGenAction(Backend_EmitLL, _VMContext) {} 864 865 void EmitLLVMOnlyAction::anchor() { } 866 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext) 867 : CodeGenAction(Backend_EmitNothing, _VMContext) {} 868 869 void EmitCodeGenOnlyAction::anchor() { } 870 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext) 871 : CodeGenAction(Backend_EmitMCNull, _VMContext) {} 872 873 void EmitObjAction::anchor() { } 874 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext) 875 : CodeGenAction(Backend_EmitObj, _VMContext) {} 876