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