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