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_pwrite_stream *AsmOutStream;
52 Timer LLVMIRGeneration;
54 std::unique_ptr<CodeGenerator> Gen;
56 std::unique_ptr<llvm::Module> TheModule;
57 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
62 BackendAction Action, DiagnosticsEngine &Diags,
63 const HeaderSearchOptions &HeaderSearchOpts,
64 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
65 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
66 bool TimePasses, const std::string &InFile,
67 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
68 raw_pwrite_stream *OS, LLVMContext &C,
69 CoverageSourceInfo *CoverageInfo = nullptr)
70 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
71 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
72 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
73 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
74 CodeGenOpts, C, CoverageInfo)) {
75 llvm::TimePassesIsEnabled = TimePasses;
76 for (auto &I : LinkModules)
77 this->LinkModules.push_back(
78 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
80 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
81 void releaseLinkModules() {
82 for (auto &I : LinkModules)
86 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
87 Gen->HandleCXXStaticMemberVarInstantiation(VD);
90 void Initialize(ASTContext &Ctx) override {
91 assert(!Context && "initialized multiple times");
95 if (llvm::TimePassesIsEnabled)
96 LLVMIRGeneration.startTimer();
100 TheModule.reset(Gen->GetModule());
102 if (llvm::TimePassesIsEnabled)
103 LLVMIRGeneration.stopTimer();
106 bool HandleTopLevelDecl(DeclGroupRef D) override {
107 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
108 Context->getSourceManager(),
109 "LLVM IR generation of declaration");
111 if (llvm::TimePassesIsEnabled)
112 LLVMIRGeneration.startTimer();
114 Gen->HandleTopLevelDecl(D);
116 if (llvm::TimePassesIsEnabled)
117 LLVMIRGeneration.stopTimer();
122 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
123 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
124 Context->getSourceManager(),
125 "LLVM IR generation of inline method");
126 if (llvm::TimePassesIsEnabled)
127 LLVMIRGeneration.startTimer();
129 Gen->HandleInlineMethodDefinition(D);
131 if (llvm::TimePassesIsEnabled)
132 LLVMIRGeneration.stopTimer();
135 void HandleTranslationUnit(ASTContext &C) override {
137 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
138 if (llvm::TimePassesIsEnabled)
139 LLVMIRGeneration.startTimer();
141 Gen->HandleTranslationUnit(C);
143 if (llvm::TimePassesIsEnabled)
144 LLVMIRGeneration.stopTimer();
147 // Silently ignore if we weren't initialized for some reason.
151 // Make sure IR generation is happy with the module. This is released by
152 // the module provider.
153 llvm::Module *M = Gen->ReleaseModule();
155 // The module has been released by IR gen on failures, do not double
161 assert(TheModule.get() == M &&
162 "Unexpected module change during IR generation");
164 // Link LinkModule into this module if present, preserving its validity.
165 for (auto &I : LinkModules) {
166 unsigned LinkFlags = I.first;
167 llvm::Module *LinkModule = I.second.get();
168 if (Linker::linkModules(*M, *LinkModule,
169 [=](const DiagnosticInfo &DI) {
170 linkerDiagnosticHandler(DI, LinkModule);
176 // Install an inline asm handler so that diagnostics get printed through
177 // our diagnostics hooks.
178 LLVMContext &Ctx = TheModule->getContext();
179 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
180 Ctx.getInlineAsmDiagnosticHandler();
181 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
182 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
184 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
185 Ctx.getDiagnosticHandler();
186 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
187 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
189 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
190 C.getTargetInfo().getDataLayoutString(),
191 TheModule.get(), Action, AsmOutStream);
193 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
195 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
198 void HandleTagDeclDefinition(TagDecl *D) override {
199 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
200 Context->getSourceManager(),
201 "LLVM IR generation of declaration");
202 Gen->HandleTagDeclDefinition(D);
205 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
206 Gen->HandleTagDeclRequiredDefinition(D);
209 void CompleteTentativeDefinition(VarDecl *D) override {
210 Gen->CompleteTentativeDefinition(D);
213 void HandleVTable(CXXRecordDecl *RD) override {
214 Gen->HandleVTable(RD);
217 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
218 Gen->HandleLinkerOptionPragma(Opts);
221 void HandleDetectMismatch(llvm::StringRef Name,
222 llvm::StringRef Value) override {
223 Gen->HandleDetectMismatch(Name, Value);
226 void HandleDependentLibrary(llvm::StringRef Opts) override {
227 Gen->HandleDependentLibrary(Opts);
230 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
231 unsigned LocCookie) {
232 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
233 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
236 void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI,
237 const llvm::Module *LinkModule);
239 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
241 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
244 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
245 SourceLocation LocCookie);
247 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
248 /// \brief Specialized handler for InlineAsm diagnostic.
249 /// \return True if the diagnostic has been successfully reported, false
251 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
252 /// \brief Specialized handler for StackSize diagnostic.
253 /// \return True if the diagnostic has been successfully reported, false
255 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
256 /// \brief Specialized handlers for optimization remarks.
257 /// Note that these handlers only accept remarks and they always handle
259 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
262 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
263 void OptimizationRemarkHandler(
264 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
265 void OptimizationRemarkHandler(
266 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
267 void OptimizationRemarkHandler(
268 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
269 void OptimizationRemarkHandler(
270 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
271 void OptimizationFailureHandler(
272 const llvm::DiagnosticInfoOptimizationFailure &D);
275 void BackendConsumer::anchor() {}
278 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
279 /// buffer to be a valid FullSourceLoc.
280 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
281 SourceManager &CSM) {
282 // Get both the clang and llvm source managers. The location is relative to
283 // a memory buffer that the LLVM Source Manager is handling, we need to add
284 // a copy to the Clang source manager.
285 const llvm::SourceMgr &LSM = *D.getSourceMgr();
287 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
288 // already owns its one and clang::SourceManager wants to own its one.
289 const MemoryBuffer *LBuf =
290 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
292 // Create the copy and transfer ownership to clang::SourceManager.
293 // TODO: Avoid copying files into memory.
294 std::unique_ptr<llvm::MemoryBuffer> CBuf =
295 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
296 LBuf->getBufferIdentifier());
297 // FIXME: Keep a file ID map instead of creating new IDs for each location.
298 FileID FID = CSM.createFileID(std::move(CBuf));
300 // Translate the offset into the file.
301 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
302 SourceLocation NewLoc =
303 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
304 return FullSourceLoc(NewLoc, CSM);
308 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
309 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
310 /// the temporary memory buffer that the inline asm parser has set up.
311 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
312 SourceLocation LocCookie) {
313 // There are a couple of different kinds of errors we could get here. First,
314 // we re-format the SMDiagnostic in terms of a clang diagnostic.
316 // Strip "error: " off the start of the message string.
317 StringRef Message = D.getMessage();
318 if (Message.startswith("error: "))
319 Message = Message.substr(7);
321 // If the SMDiagnostic has an inline asm source location, translate it.
323 if (D.getLoc() != SMLoc())
324 Loc = ConvertBackendLocation(D, Context->getSourceManager());
327 switch (D.getKind()) {
328 case llvm::SourceMgr::DK_Error:
329 DiagID = diag::err_fe_inline_asm;
331 case llvm::SourceMgr::DK_Warning:
332 DiagID = diag::warn_fe_inline_asm;
334 case llvm::SourceMgr::DK_Note:
335 DiagID = diag::note_fe_inline_asm;
338 // If this problem has clang-level source location information, report the
339 // issue in the source with a note showing the instantiated
341 if (LocCookie.isValid()) {
342 Diags.Report(LocCookie, DiagID).AddString(Message);
344 if (D.getLoc().isValid()) {
345 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
346 // Convert the SMDiagnostic ranges into SourceRange and attach them
347 // to the diagnostic.
348 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
349 unsigned Column = D.getColumnNo();
350 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
351 Loc.getLocWithOffset(Range.second - Column));
357 // Otherwise, report the backend issue as occurring in the generated .s file.
358 // If Loc is invalid, we still need to report the issue, it just gets no
360 Diags.Report(Loc, DiagID).AddString(Message);
363 #define ComputeDiagID(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 llvm_unreachable("'remark' severity not expected"); \
375 case llvm::DS_Note: \
376 DiagID = diag::note_fe_##GroupName; \
381 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
383 switch (Severity) { \
384 case llvm::DS_Error: \
385 DiagID = diag::err_fe_##GroupName; \
387 case llvm::DS_Warning: \
388 DiagID = diag::warn_fe_##GroupName; \
390 case llvm::DS_Remark: \
391 DiagID = diag::remark_fe_##GroupName; \
393 case llvm::DS_Note: \
394 DiagID = diag::note_fe_##GroupName; \
400 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
402 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
403 std::string Message = D.getMsgStr().str();
405 // If this problem has clang-level source location information, report the
406 // issue as being a problem in the source with a note showing the instantiated
408 SourceLocation LocCookie =
409 SourceLocation::getFromRawEncoding(D.getLocCookie());
410 if (LocCookie.isValid())
411 Diags.Report(LocCookie, DiagID).AddString(Message);
413 // Otherwise, report the backend diagnostic as occurring in the generated
415 // If Loc is invalid, we still need to report the diagnostic, it just gets
418 Diags.Report(Loc, DiagID).AddString(Message);
420 // We handled all the possible severities.
425 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
426 if (D.getSeverity() != llvm::DS_Warning)
427 // For now, the only support we have for StackSize diagnostic is warning.
428 // We do not know how to format other severities.
431 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
432 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
433 diag::warn_fe_frame_larger_than)
434 << D.getStackSize() << Decl::castToDeclContext(ND);
441 void BackendConsumer::EmitOptimizationMessage(
442 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
443 // We only support warnings and remarks.
444 assert(D.getSeverity() == llvm::DS_Remark ||
445 D.getSeverity() == llvm::DS_Warning);
447 SourceManager &SourceMgr = Context->getSourceManager();
448 FileManager &FileMgr = SourceMgr.getFileManager();
450 unsigned Line, Column;
451 SourceLocation DILoc;
453 if (D.isLocationAvailable()) {
454 D.getLocation(&Filename, &Line, &Column);
455 const FileEntry *FE = FileMgr.getFile(Filename);
456 if (FE && Line > 0) {
457 // If -gcolumn-info was not used, Column will be 0. This upsets the
458 // source manager, so pass 1 if Column is not set.
459 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
463 // If a location isn't available, try to approximate it using the associated
464 // function definition. We use the definition's right brace to differentiate
465 // from diagnostics that genuinely relate to the function itself.
466 FullSourceLoc Loc(DILoc, SourceMgr);
468 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
469 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
471 Diags.Report(Loc, DiagID)
472 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
475 if (DILoc.isInvalid() && D.isLocationAvailable())
476 // If we were not able to translate the file:line:col information
477 // back to a SourceLocation, at least emit a note stating that
478 // we could not translate this location. This can happen in the
479 // case of #line directives.
480 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
481 << Filename << Line << Column;
484 void BackendConsumer::OptimizationRemarkHandler(
485 const llvm::DiagnosticInfoOptimizationRemark &D) {
486 // Optimization remarks are active only if the -Rpass flag has a regular
487 // expression that matches the name of the pass name in \p D.
488 if (CodeGenOpts.OptimizationRemarkPattern &&
489 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
490 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
493 void BackendConsumer::OptimizationRemarkHandler(
494 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
495 // Missed optimization remarks are active only if the -Rpass-missed
496 // flag has a regular expression that matches the name of the pass
498 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
499 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
500 EmitOptimizationMessage(D,
501 diag::remark_fe_backend_optimization_remark_missed);
504 void BackendConsumer::OptimizationRemarkHandler(
505 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
506 // Optimization analysis remarks are active if the pass name is set to
507 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
508 // regular expression that matches the name of the pass name in \p D.
510 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
511 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
512 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
513 EmitOptimizationMessage(
514 D, diag::remark_fe_backend_optimization_remark_analysis);
517 void BackendConsumer::OptimizationRemarkHandler(
518 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
519 // Optimization analysis remarks are active if the pass name is set to
520 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
521 // regular expression that matches the name of the pass name in \p D.
523 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
524 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
525 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
526 EmitOptimizationMessage(
527 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
530 void BackendConsumer::OptimizationRemarkHandler(
531 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
532 // Optimization analysis remarks are active if the pass name is set to
533 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
534 // regular expression that matches the name of the pass name in \p D.
536 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
537 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
538 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
539 EmitOptimizationMessage(
540 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
543 void BackendConsumer::OptimizationFailureHandler(
544 const llvm::DiagnosticInfoOptimizationFailure &D) {
545 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
548 void BackendConsumer::linkerDiagnosticHandler(const DiagnosticInfo &DI,
549 const llvm::Module *LinkModule) {
550 if (DI.getSeverity() != DS_Error)
553 std::string MsgStorage;
555 raw_string_ostream Stream(MsgStorage);
556 DiagnosticPrinterRawOStream DP(Stream);
560 Diags.Report(diag::err_fe_cannot_link_module)
561 << LinkModule->getModuleIdentifier() << MsgStorage;
564 /// \brief This function is invoked when the backend needs
565 /// to report something to the user.
566 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
567 unsigned DiagID = diag::err_fe_inline_asm;
568 llvm::DiagnosticSeverity Severity = DI.getSeverity();
569 // Get the diagnostic ID based.
570 switch (DI.getKind()) {
571 case llvm::DK_InlineAsm:
572 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
574 ComputeDiagID(Severity, inline_asm, DiagID);
576 case llvm::DK_StackSize:
577 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
579 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
581 case llvm::DK_OptimizationRemark:
582 // Optimization remarks are always handled completely by this
583 // handler. There is no generic way of emitting them.
584 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
586 case llvm::DK_OptimizationRemarkMissed:
587 // Optimization remarks are always handled completely by this
588 // handler. There is no generic way of emitting them.
589 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
591 case llvm::DK_OptimizationRemarkAnalysis:
592 // Optimization remarks are always handled completely by this
593 // handler. There is no generic way of emitting them.
594 OptimizationRemarkHandler(
595 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
597 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
598 // Optimization remarks are always handled completely by this
599 // handler. There is no generic way of emitting them.
600 OptimizationRemarkHandler(
601 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
603 case llvm::DK_OptimizationRemarkAnalysisAliasing:
604 // Optimization remarks are always handled completely by this
605 // handler. There is no generic way of emitting them.
606 OptimizationRemarkHandler(
607 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
609 case llvm::DK_OptimizationFailure:
610 // Optimization failures are always handled completely by this
612 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
615 // Plugin IDs are not bound to any value as they are set dynamically.
616 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
619 std::string MsgStorage;
621 raw_string_ostream Stream(MsgStorage);
622 DiagnosticPrinterRawOStream DP(Stream);
626 // Report the backend message using the usual diagnostic mechanism.
628 Diags.Report(Loc, DiagID).AddString(MsgStorage);
632 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
633 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
634 OwnsVMContext(!_VMContext) {}
636 CodeGenAction::~CodeGenAction() {
642 bool CodeGenAction::hasIRSupport() const { return true; }
644 void CodeGenAction::EndSourceFileAction() {
645 // If the consumer creation failed, do nothing.
646 if (!getCompilerInstance().hasASTConsumer())
649 // Take back ownership of link modules we passed to consumer.
650 if (!LinkModules.empty())
651 BEConsumer->releaseLinkModules();
653 // Steal the module from the consumer.
654 TheModule = BEConsumer->takeModule();
657 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
658 return std::move(TheModule);
661 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
662 OwnsVMContext = false;
666 static raw_pwrite_stream *
667 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
669 case Backend_EmitAssembly:
670 return CI.createDefaultOutputFile(false, InFile, "s");
672 return CI.createDefaultOutputFile(false, InFile, "ll");
674 return CI.createDefaultOutputFile(true, InFile, "bc");
675 case Backend_EmitNothing:
677 case Backend_EmitMCNull:
678 return CI.createNullOutputFile();
679 case Backend_EmitObj:
680 return CI.createDefaultOutputFile(true, InFile, "o");
683 llvm_unreachable("Invalid action!");
686 std::unique_ptr<ASTConsumer>
687 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
688 BackendAction BA = static_cast<BackendAction>(Act);
689 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
690 if (BA != Backend_EmitNothing && !OS)
693 // Load bitcode modules to link with, if we need to.
694 if (LinkModules.empty())
695 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
696 const std::string &LinkBCFile = I.second;
698 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
700 CI.getDiagnostics().Report(diag::err_cannot_open_file)
701 << LinkBCFile << BCBuf.getError().message();
706 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
707 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
708 if (std::error_code EC = ModuleOrErr.getError()) {
709 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
714 addLinkModule(ModuleOrErr.get().release(), I.first);
717 CoverageSourceInfo *CoverageInfo = nullptr;
718 // Add the preprocessor callback only when the coverage mapping is generated.
719 if (CI.getCodeGenOpts().CoverageMapping) {
720 CoverageInfo = new CoverageSourceInfo;
721 CI.getPreprocessor().addPPCallbacks(
722 std::unique_ptr<PPCallbacks>(CoverageInfo));
725 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
726 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
727 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
728 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
729 OS, *VMContext, CoverageInfo));
730 BEConsumer = Result.get();
731 return std::move(Result);
734 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
736 unsigned LocCookie) {
737 SM.print(nullptr, llvm::errs());
740 void CodeGenAction::ExecuteAction() {
741 // If this is an IR file, we have to treat it specially.
742 if (getCurrentFileKind() == IK_LLVM_IR) {
743 BackendAction BA = static_cast<BackendAction>(Act);
744 CompilerInstance &CI = getCompilerInstance();
745 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
746 if (BA != Backend_EmitNothing && !OS)
750 SourceManager &SM = CI.getSourceManager();
751 FileID FID = SM.getMainFileID();
752 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
756 llvm::SMDiagnostic Err;
757 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
759 // Translate from the diagnostic info to the SourceManager location if
761 // TODO: Unify this with ConvertBackendLocation()
763 if (Err.getLineNo() > 0) {
764 assert(Err.getColumnNo() >= 0);
765 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
766 Err.getLineNo(), Err.getColumnNo() + 1);
769 // Strip off a leading diagnostic code if there is one.
770 StringRef Msg = Err.getMessage();
771 if (Msg.startswith("error: "))
775 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
777 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
780 const TargetOptions &TargetOpts = CI.getTargetOpts();
781 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
782 CI.getDiagnostics().Report(SourceLocation(),
783 diag::warn_fe_override_module)
784 << TargetOpts.Triple;
785 TheModule->setTargetTriple(TargetOpts.Triple);
788 LLVMContext &Ctx = TheModule->getContext();
789 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
790 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
791 CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
792 TheModule.get(), BA, OS);
796 // Otherwise follow the normal AST path.
797 this->ASTFrontendAction::ExecuteAction();
802 void EmitAssemblyAction::anchor() { }
803 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
804 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
806 void EmitBCAction::anchor() { }
807 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
808 : CodeGenAction(Backend_EmitBC, _VMContext) {}
810 void EmitLLVMAction::anchor() { }
811 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
812 : CodeGenAction(Backend_EmitLL, _VMContext) {}
814 void EmitLLVMOnlyAction::anchor() { }
815 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
816 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
818 void EmitCodeGenOnlyAction::anchor() { }
819 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
820 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
822 void EmitObjAction::anchor() { }
823 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
824 : CodeGenAction(Backend_EmitObj, _VMContext) {}