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