1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
38 using namespace clang;
42 class BackendConsumer : public ASTConsumer {
43 virtual void anchor();
44 DiagnosticsEngine &Diags;
46 const CodeGenOptions &CodeGenOpts;
47 const TargetOptions &TargetOpts;
48 const LangOptions &LangOpts;
49 raw_ostream *AsmOutStream;
52 Timer LLVMIRGeneration;
54 std::unique_ptr<CodeGenerator> Gen;
56 std::unique_ptr<llvm::Module> TheModule, LinkModule;
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(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
69 Gen(CreateLLVMCodeGen(Diags, infile, compopts,
70 targetopts, C, CoverageInfo)),
71 LinkModule(LinkModule) {
72 llvm::TimePassesIsEnabled = TimePasses;
75 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
76 llvm::Module *takeLinkModule() { return LinkModule.release(); }
78 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
79 Gen->HandleCXXStaticMemberVarInstantiation(VD);
82 void Initialize(ASTContext &Ctx) override {
85 if (llvm::TimePassesIsEnabled)
86 LLVMIRGeneration.startTimer();
90 TheModule.reset(Gen->GetModule());
92 if (llvm::TimePassesIsEnabled)
93 LLVMIRGeneration.stopTimer();
96 bool HandleTopLevelDecl(DeclGroupRef D) override {
97 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
98 Context->getSourceManager(),
99 "LLVM IR generation of declaration");
101 if (llvm::TimePassesIsEnabled)
102 LLVMIRGeneration.startTimer();
104 Gen->HandleTopLevelDecl(D);
106 if (llvm::TimePassesIsEnabled)
107 LLVMIRGeneration.stopTimer();
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();
119 Gen->HandleInlineMethodDefinition(D);
121 if (llvm::TimePassesIsEnabled)
122 LLVMIRGeneration.stopTimer();
125 void HandleTranslationUnit(ASTContext &C) override {
127 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
128 if (llvm::TimePassesIsEnabled)
129 LLVMIRGeneration.startTimer();
131 Gen->HandleTranslationUnit(C);
133 if (llvm::TimePassesIsEnabled)
134 LLVMIRGeneration.stopTimer();
137 // Silently ignore if we weren't initialized for some reason.
141 // Make sure IR generation is happy with the module. This is released by
142 // the module provider.
143 llvm::Module *M = Gen->ReleaseModule();
145 // The module has been released by IR gen on failures, do not double
151 assert(TheModule.get() == M &&
152 "Unexpected module change during IR generation");
154 // Link LinkModule into this module if present, preserving its validity.
156 if (Linker::LinkModules(
158 [=](const DiagnosticInfo &DI) { linkerDiagnosticHandler(DI); }))
162 // Install an inline asm handler so that diagnostics get printed through
163 // our diagnostics hooks.
164 LLVMContext &Ctx = TheModule->getContext();
165 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
166 Ctx.getInlineAsmDiagnosticHandler();
167 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
168 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
170 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
171 Ctx.getDiagnosticHandler();
172 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
173 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
175 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
176 C.getTargetInfo().getTargetDescription(),
177 TheModule.get(), Action, AsmOutStream);
179 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
181 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
184 void HandleTagDeclDefinition(TagDecl *D) override {
185 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
186 Context->getSourceManager(),
187 "LLVM IR generation of declaration");
188 Gen->HandleTagDeclDefinition(D);
191 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
192 Gen->HandleTagDeclRequiredDefinition(D);
195 void CompleteTentativeDefinition(VarDecl *D) override {
196 Gen->CompleteTentativeDefinition(D);
199 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
200 Gen->HandleVTable(RD, DefinitionRequired);
203 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
204 Gen->HandleLinkerOptionPragma(Opts);
207 void HandleDetectMismatch(llvm::StringRef Name,
208 llvm::StringRef Value) override {
209 Gen->HandleDetectMismatch(Name, Value);
212 void HandleDependentLibrary(llvm::StringRef Opts) override {
213 Gen->HandleDependentLibrary(Opts);
216 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
217 unsigned LocCookie) {
218 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
219 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
222 void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI);
224 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
226 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
229 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
230 SourceLocation LocCookie);
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
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
240 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
241 /// \brief Specialized handlers for optimization remarks.
242 /// Note that these handlers only accept remarks and they always handle
244 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
247 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
248 void OptimizationRemarkHandler(
249 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
250 void OptimizationRemarkHandler(
251 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
252 void OptimizationFailureHandler(
253 const llvm::DiagnosticInfoOptimizationFailure &D);
256 void BackendConsumer::anchor() {}
259 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
260 /// buffer to be a valid FullSourceLoc.
261 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
262 SourceManager &CSM) {
263 // Get both the clang and llvm source managers. The location is relative to
264 // a memory buffer that the LLVM Source Manager is handling, we need to add
265 // a copy to the Clang source manager.
266 const llvm::SourceMgr &LSM = *D.getSourceMgr();
268 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
269 // already owns its one and clang::SourceManager wants to own its one.
270 const MemoryBuffer *LBuf =
271 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
273 // Create the copy and transfer ownership to clang::SourceManager.
274 // TODO: Avoid copying files into memory.
275 std::unique_ptr<llvm::MemoryBuffer> CBuf =
276 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
277 LBuf->getBufferIdentifier());
278 // FIXME: Keep a file ID map instead of creating new IDs for each location.
279 FileID FID = CSM.createFileID(std::move(CBuf));
281 // Translate the offset into the file.
282 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
283 SourceLocation NewLoc =
284 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
285 return FullSourceLoc(NewLoc, CSM);
289 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
290 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
291 /// the temporary memory buffer that the inline asm parser has set up.
292 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
293 SourceLocation LocCookie) {
294 // There are a couple of different kinds of errors we could get here. First,
295 // we re-format the SMDiagnostic in terms of a clang diagnostic.
297 // Strip "error: " off the start of the message string.
298 StringRef Message = D.getMessage();
299 if (Message.startswith("error: "))
300 Message = Message.substr(7);
302 // If the SMDiagnostic has an inline asm source location, translate it.
304 if (D.getLoc() != SMLoc())
305 Loc = ConvertBackendLocation(D, Context->getSourceManager());
308 switch (D.getKind()) {
309 case llvm::SourceMgr::DK_Error:
310 DiagID = diag::err_fe_inline_asm;
312 case llvm::SourceMgr::DK_Warning:
313 DiagID = diag::warn_fe_inline_asm;
315 case llvm::SourceMgr::DK_Note:
316 DiagID = diag::note_fe_inline_asm;
319 // If this problem has clang-level source location information, report the
320 // issue in the source with a note showing the instantiated
322 if (LocCookie.isValid()) {
323 Diags.Report(LocCookie, DiagID).AddString(Message);
325 if (D.getLoc().isValid()) {
326 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
327 // Convert the SMDiagnostic ranges into SourceRange and attach them
328 // to the diagnostic.
329 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
330 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
331 unsigned Column = D.getColumnNo();
332 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
333 Loc.getLocWithOffset(Range.second - Column));
339 // Otherwise, report the backend issue as occurring in the generated .s file.
340 // If Loc is invalid, we still need to report the issue, it just gets no
342 Diags.Report(Loc, DiagID).AddString(Message);
345 #define ComputeDiagID(Severity, GroupName, DiagID) \
347 switch (Severity) { \
348 case llvm::DS_Error: \
349 DiagID = diag::err_fe_##GroupName; \
351 case llvm::DS_Warning: \
352 DiagID = diag::warn_fe_##GroupName; \
354 case llvm::DS_Remark: \
355 llvm_unreachable("'remark' severity not expected"); \
357 case llvm::DS_Note: \
358 DiagID = diag::note_fe_##GroupName; \
363 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
365 switch (Severity) { \
366 case llvm::DS_Error: \
367 DiagID = diag::err_fe_##GroupName; \
369 case llvm::DS_Warning: \
370 DiagID = diag::warn_fe_##GroupName; \
372 case llvm::DS_Remark: \
373 DiagID = diag::remark_fe_##GroupName; \
375 case llvm::DS_Note: \
376 DiagID = diag::note_fe_##GroupName; \
382 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
384 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
385 std::string Message = D.getMsgStr().str();
387 // If this problem has clang-level source location information, report the
388 // issue as being a problem in the source with a note showing the instantiated
390 SourceLocation LocCookie =
391 SourceLocation::getFromRawEncoding(D.getLocCookie());
392 if (LocCookie.isValid())
393 Diags.Report(LocCookie, DiagID).AddString(Message);
395 // Otherwise, report the backend diagnostic as occurring in the generated
397 // If Loc is invalid, we still need to report the diagnostic, it just gets
400 Diags.Report(Loc, DiagID).AddString(Message);
402 // We handled all the possible severities.
407 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
408 if (D.getSeverity() != llvm::DS_Warning)
409 // For now, the only support we have for StackSize diagnostic is warning.
410 // We do not know how to format other severities.
413 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
414 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
415 diag::warn_fe_frame_larger_than)
416 << D.getStackSize() << Decl::castToDeclContext(ND);
423 void BackendConsumer::EmitOptimizationMessage(
424 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
425 // We only support warnings and remarks.
426 assert(D.getSeverity() == llvm::DS_Remark ||
427 D.getSeverity() == llvm::DS_Warning);
429 SourceManager &SourceMgr = Context->getSourceManager();
430 FileManager &FileMgr = SourceMgr.getFileManager();
432 unsigned Line, Column;
433 D.getLocation(&Filename, &Line, &Column);
434 SourceLocation DILoc;
435 const FileEntry *FE = FileMgr.getFile(Filename);
436 if (FE && Line > 0) {
437 // If -gcolumn-info was not used, Column will be 0. This upsets the
438 // source manager, so pass 1 if Column is not set.
439 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
442 // If a location isn't available, try to approximate it using the associated
443 // function definition. We use the definition's right brace to differentiate
444 // from diagnostics that genuinely relate to the function itself.
445 FullSourceLoc Loc(DILoc, SourceMgr);
447 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
448 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
450 Diags.Report(Loc, DiagID)
451 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
454 if (DILoc.isInvalid())
455 // If we were not able to translate the file:line:col information
456 // back to a SourceLocation, at least emit a note stating that
457 // we could not translate this location. This can happen in the
458 // case of #line directives.
459 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
460 << Filename << Line << Column;
463 void BackendConsumer::OptimizationRemarkHandler(
464 const llvm::DiagnosticInfoOptimizationRemark &D) {
465 // Optimization remarks are active only if the -Rpass flag has a regular
466 // expression that matches the name of the pass name in \p D.
467 if (CodeGenOpts.OptimizationRemarkPattern &&
468 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
469 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
472 void BackendConsumer::OptimizationRemarkHandler(
473 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
474 // Missed optimization remarks are active only if the -Rpass-missed
475 // flag has a regular expression that matches the name of the pass
477 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
478 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
479 EmitOptimizationMessage(D,
480 diag::remark_fe_backend_optimization_remark_missed);
483 void BackendConsumer::OptimizationRemarkHandler(
484 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
485 // Optimization analysis remarks are active only if the -Rpass-analysis
486 // flag has a regular expression that matches the name of the pass
488 if (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
489 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName()))
490 EmitOptimizationMessage(
491 D, diag::remark_fe_backend_optimization_remark_analysis);
494 void BackendConsumer::OptimizationFailureHandler(
495 const llvm::DiagnosticInfoOptimizationFailure &D) {
496 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
499 void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI) {
500 if (DI.getSeverity() != DS_Error)
503 std::string MsgStorage;
505 raw_string_ostream Stream(MsgStorage);
506 DiagnosticPrinterRawOStream DP(Stream);
510 Diags.Report(diag::err_fe_cannot_link_module)
511 << LinkModule->getModuleIdentifier() << MsgStorage;
514 /// \brief This function is invoked when the backend needs
515 /// to report something to the user.
516 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
517 unsigned DiagID = diag::err_fe_inline_asm;
518 llvm::DiagnosticSeverity Severity = DI.getSeverity();
519 // Get the diagnostic ID based.
520 switch (DI.getKind()) {
521 case llvm::DK_InlineAsm:
522 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
524 ComputeDiagID(Severity, inline_asm, DiagID);
526 case llvm::DK_StackSize:
527 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
529 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
531 case llvm::DK_OptimizationRemark:
532 // Optimization remarks are always handled completely by this
533 // handler. There is no generic way of emitting them.
534 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
536 case llvm::DK_OptimizationRemarkMissed:
537 // Optimization remarks are always handled completely by this
538 // handler. There is no generic way of emitting them.
539 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
541 case llvm::DK_OptimizationRemarkAnalysis:
542 // Optimization remarks are always handled completely by this
543 // handler. There is no generic way of emitting them.
544 OptimizationRemarkHandler(
545 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
547 case llvm::DK_OptimizationFailure:
548 // Optimization failures are always handled completely by this
550 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
553 // Plugin IDs are not bound to any value as they are set dynamically.
554 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
557 std::string MsgStorage;
559 raw_string_ostream Stream(MsgStorage);
560 DiagnosticPrinterRawOStream DP(Stream);
564 // Report the backend message using the usual diagnostic mechanism.
566 Diags.Report(Loc, DiagID).AddString(MsgStorage);
570 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
571 : Act(_Act), LinkModule(nullptr),
572 VMContext(_VMContext ? _VMContext : new LLVMContext),
573 OwnsVMContext(!_VMContext) {}
575 CodeGenAction::~CodeGenAction() {
581 bool CodeGenAction::hasIRSupport() const { return true; }
583 void CodeGenAction::EndSourceFileAction() {
584 // If the consumer creation failed, do nothing.
585 if (!getCompilerInstance().hasASTConsumer())
588 // If we were given a link module, release consumer's ownership of it.
590 BEConsumer->takeLinkModule();
592 // Steal the module from the consumer.
593 TheModule = BEConsumer->takeModule();
596 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
597 return std::move(TheModule);
600 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
601 OwnsVMContext = false;
605 static raw_ostream *GetOutputStream(CompilerInstance &CI,
607 BackendAction Action) {
609 case Backend_EmitAssembly:
610 return CI.createDefaultOutputFile(false, InFile, "s");
612 return CI.createDefaultOutputFile(false, InFile, "ll");
614 return CI.createDefaultOutputFile(true, InFile, "bc");
615 case Backend_EmitNothing:
617 case Backend_EmitMCNull:
618 return CI.createNullOutputFile();
619 case Backend_EmitObj:
620 return CI.createDefaultOutputFile(true, InFile, "o");
623 llvm_unreachable("Invalid action!");
626 std::unique_ptr<ASTConsumer>
627 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
628 BackendAction BA = static_cast<BackendAction>(Act);
629 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
630 if (BA != Backend_EmitNothing && !OS)
633 llvm::Module *LinkModuleToUse = LinkModule;
635 // If we were not given a link module, and the user requested that one be
636 // loaded from bitcode, do so now.
637 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
638 if (!LinkModuleToUse && !LinkBCFile.empty()) {
639 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
641 CI.getDiagnostics().Report(diag::err_cannot_open_file)
642 << LinkBCFile << BCBuf.getError().message();
646 ErrorOr<llvm::Module *> ModuleOrErr =
647 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
648 if (std::error_code EC = ModuleOrErr.getError()) {
649 CI.getDiagnostics().Report(diag::err_cannot_open_file)
650 << LinkBCFile << EC.message();
653 LinkModuleToUse = ModuleOrErr.get();
656 CoverageSourceInfo *CoverageInfo = nullptr;
657 // Add the preprocessor callback only when the coverage mapping is generated.
658 if (CI.getCodeGenOpts().CoverageMapping) {
659 CoverageInfo = new CoverageSourceInfo;
660 CI.getPreprocessor().addPPCallbacks(
661 std::unique_ptr<PPCallbacks>(CoverageInfo));
663 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
664 BA, CI.getDiagnostics(), CI.getCodeGenOpts(), CI.getTargetOpts(),
665 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
666 LinkModuleToUse, OS.release(), *VMContext, CoverageInfo));
667 BEConsumer = Result.get();
668 return std::move(Result);
671 void CodeGenAction::ExecuteAction() {
672 // If this is an IR file, we have to treat it specially.
673 if (getCurrentFileKind() == IK_LLVM_IR) {
674 BackendAction BA = static_cast<BackendAction>(Act);
675 CompilerInstance &CI = getCompilerInstance();
676 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
677 if (BA != Backend_EmitNothing && !OS)
681 SourceManager &SM = CI.getSourceManager();
682 FileID FID = SM.getMainFileID();
683 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
687 llvm::SMDiagnostic Err;
688 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
690 // Translate from the diagnostic info to the SourceManager location if
692 // TODO: Unify this with ConvertBackendLocation()
694 if (Err.getLineNo() > 0) {
695 assert(Err.getColumnNo() >= 0);
696 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
697 Err.getLineNo(), Err.getColumnNo() + 1);
700 // Strip off a leading diagnostic code if there is one.
701 StringRef Msg = Err.getMessage();
702 if (Msg.startswith("error: "))
706 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
708 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
711 const TargetOptions &TargetOpts = CI.getTargetOpts();
712 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
713 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
714 DiagnosticsEngine::Warning,
715 "overriding the module target triple with %0");
717 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
718 TheModule->setTargetTriple(TargetOpts.Triple);
721 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
722 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
723 TheModule.get(), BA, OS);
727 // Otherwise follow the normal AST path.
728 this->ASTFrontendAction::ExecuteAction();
733 void EmitAssemblyAction::anchor() { }
734 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
735 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
737 void EmitBCAction::anchor() { }
738 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
739 : CodeGenAction(Backend_EmitBC, _VMContext) {}
741 void EmitLLVMAction::anchor() { }
742 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
743 : CodeGenAction(Backend_EmitLL, _VMContext) {}
745 void EmitLLVMOnlyAction::anchor() { }
746 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
747 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
749 void EmitCodeGenOnlyAction::anchor() { }
750 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
751 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
753 void EmitObjAction::anchor() { }
754 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
755 : CodeGenAction(Backend_EmitObj, _VMContext) {}