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