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