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