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>
60 // This is here so that the diagnostic printer knows the module a diagnostic
62 llvm::Module *CurLinkModule = nullptr;
66 BackendAction Action, DiagnosticsEngine &Diags,
67 const HeaderSearchOptions &HeaderSearchOpts,
68 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
69 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
70 bool TimePasses, const std::string &InFile,
71 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
72 raw_pwrite_stream *OS, LLVMContext &C,
73 CoverageSourceInfo *CoverageInfo = nullptr)
74 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
75 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
76 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
77 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
78 CodeGenOpts, C, CoverageInfo)) {
79 llvm::TimePassesIsEnabled = TimePasses;
80 for (auto &I : LinkModules)
81 this->LinkModules.push_back(
82 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
84 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
85 void releaseLinkModules() {
86 for (auto &I : LinkModules)
90 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
91 Gen->HandleCXXStaticMemberVarInstantiation(VD);
94 void Initialize(ASTContext &Ctx) override {
95 assert(!Context && "initialized multiple times");
99 if (llvm::TimePassesIsEnabled)
100 LLVMIRGeneration.startTimer();
102 Gen->Initialize(Ctx);
104 TheModule.reset(Gen->GetModule());
106 if (llvm::TimePassesIsEnabled)
107 LLVMIRGeneration.stopTimer();
110 bool HandleTopLevelDecl(DeclGroupRef D) override {
111 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
112 Context->getSourceManager(),
113 "LLVM IR generation of declaration");
115 if (llvm::TimePassesIsEnabled)
116 LLVMIRGeneration.startTimer();
118 Gen->HandleTopLevelDecl(D);
120 if (llvm::TimePassesIsEnabled)
121 LLVMIRGeneration.stopTimer();
126 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
127 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
128 Context->getSourceManager(),
129 "LLVM IR generation of inline method");
130 if (llvm::TimePassesIsEnabled)
131 LLVMIRGeneration.startTimer();
133 Gen->HandleInlineMethodDefinition(D);
135 if (llvm::TimePassesIsEnabled)
136 LLVMIRGeneration.stopTimer();
139 void HandleTranslationUnit(ASTContext &C) override {
141 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
142 if (llvm::TimePassesIsEnabled)
143 LLVMIRGeneration.startTimer();
145 Gen->HandleTranslationUnit(C);
147 if (llvm::TimePassesIsEnabled)
148 LLVMIRGeneration.stopTimer();
151 // Silently ignore if we weren't initialized for some reason.
155 // Make sure IR generation is happy with the module. This is released by
156 // the module provider.
157 llvm::Module *M = Gen->ReleaseModule();
159 // The module has been released by IR gen on failures, do not double
165 assert(TheModule.get() == M &&
166 "Unexpected module change during IR generation");
168 // Install an inline asm handler so that diagnostics get printed through
169 // our diagnostics hooks.
170 LLVMContext &Ctx = TheModule->getContext();
171 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
172 Ctx.getInlineAsmDiagnosticHandler();
173 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
174 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
176 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
177 Ctx.getDiagnosticHandler();
178 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
179 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
181 // Link LinkModule into this module if present, preserving its validity.
182 for (auto &I : LinkModules) {
183 unsigned LinkFlags = I.first;
184 CurLinkModule = I.second.get();
185 if (Linker::linkModules(*M, std::move(I.second), LinkFlags))
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 AssignInheritanceModel(CXXRecordDecl *RD) override {
214 Gen->AssignInheritanceModel(RD);
217 void HandleVTable(CXXRecordDecl *RD) override {
218 Gen->HandleVTable(RD);
221 void HandleLinkerOption(llvm::StringRef Opts) override {
222 Gen->HandleLinkerOption(Opts);
225 void HandleDetectMismatch(llvm::StringRef Name,
226 llvm::StringRef Value) override {
227 Gen->HandleDetectMismatch(Name, Value);
230 void HandleDependentLibrary(llvm::StringRef Opts) override {
231 Gen->HandleDependentLibrary(Opts);
234 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
235 unsigned LocCookie) {
236 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
237 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
240 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
242 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
245 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
246 SourceLocation LocCookie);
248 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
249 /// \brief Specialized handler for InlineAsm diagnostic.
250 /// \return True if the diagnostic has been successfully reported, false
252 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
253 /// \brief Specialized handler for StackSize diagnostic.
254 /// \return True if the diagnostic has been successfully reported, false
256 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
257 /// \brief Specialized handlers for optimization remarks.
258 /// Note that these handlers only accept remarks and they always handle
260 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
263 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
264 void OptimizationRemarkHandler(
265 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
266 void OptimizationRemarkHandler(
267 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
268 void OptimizationRemarkHandler(
269 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
270 void OptimizationRemarkHandler(
271 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
272 void OptimizationFailureHandler(
273 const llvm::DiagnosticInfoOptimizationFailure &D);
276 void BackendConsumer::anchor() {}
279 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
280 /// buffer to be a valid FullSourceLoc.
281 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
282 SourceManager &CSM) {
283 // Get both the clang and llvm source managers. The location is relative to
284 // a memory buffer that the LLVM Source Manager is handling, we need to add
285 // a copy to the Clang source manager.
286 const llvm::SourceMgr &LSM = *D.getSourceMgr();
288 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
289 // already owns its one and clang::SourceManager wants to own its one.
290 const MemoryBuffer *LBuf =
291 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
293 // Create the copy and transfer ownership to clang::SourceManager.
294 // TODO: Avoid copying files into memory.
295 std::unique_ptr<llvm::MemoryBuffer> CBuf =
296 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
297 LBuf->getBufferIdentifier());
298 // FIXME: Keep a file ID map instead of creating new IDs for each location.
299 FileID FID = CSM.createFileID(std::move(CBuf));
301 // Translate the offset into the file.
302 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
303 SourceLocation NewLoc =
304 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
305 return FullSourceLoc(NewLoc, CSM);
309 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
310 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
311 /// the temporary memory buffer that the inline asm parser has set up.
312 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
313 SourceLocation LocCookie) {
314 // There are a couple of different kinds of errors we could get here. First,
315 // we re-format the SMDiagnostic in terms of a clang diagnostic.
317 // Strip "error: " off the start of the message string.
318 StringRef Message = D.getMessage();
319 if (Message.startswith("error: "))
320 Message = Message.substr(7);
322 // If the SMDiagnostic has an inline asm source location, translate it.
324 if (D.getLoc() != SMLoc())
325 Loc = ConvertBackendLocation(D, Context->getSourceManager());
328 switch (D.getKind()) {
329 case llvm::SourceMgr::DK_Error:
330 DiagID = diag::err_fe_inline_asm;
332 case llvm::SourceMgr::DK_Warning:
333 DiagID = diag::warn_fe_inline_asm;
335 case llvm::SourceMgr::DK_Note:
336 DiagID = diag::note_fe_inline_asm;
339 // If this problem has clang-level source location information, report the
340 // issue in the source with a note showing the instantiated
342 if (LocCookie.isValid()) {
343 Diags.Report(LocCookie, DiagID).AddString(Message);
345 if (D.getLoc().isValid()) {
346 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
347 // Convert the SMDiagnostic ranges into SourceRange and attach them
348 // to the diagnostic.
349 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
350 unsigned Column = D.getColumnNo();
351 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
352 Loc.getLocWithOffset(Range.second - Column));
358 // Otherwise, report the backend issue as occurring in the generated .s file.
359 // If Loc is invalid, we still need to report the issue, it just gets no
361 Diags.Report(Loc, DiagID).AddString(Message);
364 #define ComputeDiagID(Severity, GroupName, DiagID) \
366 switch (Severity) { \
367 case llvm::DS_Error: \
368 DiagID = diag::err_fe_##GroupName; \
370 case llvm::DS_Warning: \
371 DiagID = diag::warn_fe_##GroupName; \
373 case llvm::DS_Remark: \
374 llvm_unreachable("'remark' severity not expected"); \
376 case llvm::DS_Note: \
377 DiagID = diag::note_fe_##GroupName; \
382 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
384 switch (Severity) { \
385 case llvm::DS_Error: \
386 DiagID = diag::err_fe_##GroupName; \
388 case llvm::DS_Warning: \
389 DiagID = diag::warn_fe_##GroupName; \
391 case llvm::DS_Remark: \
392 DiagID = diag::remark_fe_##GroupName; \
394 case llvm::DS_Note: \
395 DiagID = diag::note_fe_##GroupName; \
401 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
403 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
404 std::string Message = D.getMsgStr().str();
406 // If this problem has clang-level source location information, report the
407 // issue as being a problem in the source with a note showing the instantiated
409 SourceLocation LocCookie =
410 SourceLocation::getFromRawEncoding(D.getLocCookie());
411 if (LocCookie.isValid())
412 Diags.Report(LocCookie, DiagID).AddString(Message);
414 // Otherwise, report the backend diagnostic as occurring in the generated
416 // If Loc is invalid, we still need to report the diagnostic, it just gets
419 Diags.Report(Loc, DiagID).AddString(Message);
421 // We handled all the possible severities.
426 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
427 if (D.getSeverity() != llvm::DS_Warning)
428 // For now, the only support we have for StackSize diagnostic is warning.
429 // We do not know how to format other severities.
432 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
433 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
434 diag::warn_fe_frame_larger_than)
435 << D.getStackSize() << Decl::castToDeclContext(ND);
442 void BackendConsumer::EmitOptimizationMessage(
443 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
444 // We only support warnings and remarks.
445 assert(D.getSeverity() == llvm::DS_Remark ||
446 D.getSeverity() == llvm::DS_Warning);
448 SourceManager &SourceMgr = Context->getSourceManager();
449 FileManager &FileMgr = SourceMgr.getFileManager();
451 unsigned Line, Column;
452 SourceLocation DILoc;
454 if (D.isLocationAvailable()) {
455 D.getLocation(&Filename, &Line, &Column);
456 const FileEntry *FE = FileMgr.getFile(Filename);
457 if (FE && Line > 0) {
458 // If -gcolumn-info was not used, Column will be 0. This upsets the
459 // source manager, so pass 1 if Column is not set.
460 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
464 // If a location isn't available, try to approximate it using the associated
465 // function definition. We use the definition's right brace to differentiate
466 // from diagnostics that genuinely relate to the function itself.
467 FullSourceLoc Loc(DILoc, SourceMgr);
469 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
470 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
472 Diags.Report(Loc, DiagID)
473 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
476 if (DILoc.isInvalid() && D.isLocationAvailable())
477 // If we were not able to translate the file:line:col information
478 // back to a SourceLocation, at least emit a note stating that
479 // we could not translate this location. This can happen in the
480 // case of #line directives.
481 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
482 << Filename << Line << Column;
485 void BackendConsumer::OptimizationRemarkHandler(
486 const llvm::DiagnosticInfoOptimizationRemark &D) {
487 // Optimization remarks are active only if the -Rpass flag has a regular
488 // expression that matches the name of the pass name in \p D.
489 if (CodeGenOpts.OptimizationRemarkPattern &&
490 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
491 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
494 void BackendConsumer::OptimizationRemarkHandler(
495 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
496 // Missed optimization remarks are active only if the -Rpass-missed
497 // flag has a regular expression that matches the name of the pass
499 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
500 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
501 EmitOptimizationMessage(D,
502 diag::remark_fe_backend_optimization_remark_missed);
505 void BackendConsumer::OptimizationRemarkHandler(
506 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
507 // Optimization analysis remarks are active if the pass name is set to
508 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
509 // regular expression that matches the name of the pass name in \p D.
511 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
512 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
513 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
514 EmitOptimizationMessage(
515 D, diag::remark_fe_backend_optimization_remark_analysis);
518 void BackendConsumer::OptimizationRemarkHandler(
519 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
520 // Optimization analysis remarks are active if the pass name is set to
521 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
522 // regular expression that matches the name of the pass name in \p D.
524 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
525 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
526 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
527 EmitOptimizationMessage(
528 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
531 void BackendConsumer::OptimizationRemarkHandler(
532 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
533 // Optimization analysis remarks are active if the pass name is set to
534 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
535 // regular expression that matches the name of the pass name in \p D.
537 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
538 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
539 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
540 EmitOptimizationMessage(
541 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
544 void BackendConsumer::OptimizationFailureHandler(
545 const llvm::DiagnosticInfoOptimizationFailure &D) {
546 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
549 /// \brief This function is invoked when the backend needs
550 /// to report something to the user.
551 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
552 unsigned DiagID = diag::err_fe_inline_asm;
553 llvm::DiagnosticSeverity Severity = DI.getSeverity();
554 // Get the diagnostic ID based.
555 switch (DI.getKind()) {
556 case llvm::DK_InlineAsm:
557 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
559 ComputeDiagID(Severity, inline_asm, DiagID);
561 case llvm::DK_StackSize:
562 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
564 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
567 assert(CurLinkModule);
568 // FIXME: stop eating the warnings and notes.
569 if (Severity != DS_Error)
571 DiagID = diag::err_fe_cannot_link_module;
573 case llvm::DK_OptimizationRemark:
574 // Optimization remarks are always handled completely by this
575 // handler. There is no generic way of emitting them.
576 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
578 case llvm::DK_OptimizationRemarkMissed:
579 // Optimization remarks are always handled completely by this
580 // handler. There is no generic way of emitting them.
581 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
583 case llvm::DK_OptimizationRemarkAnalysis:
584 // Optimization remarks are always handled completely by this
585 // handler. There is no generic way of emitting them.
586 OptimizationRemarkHandler(
587 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
589 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
590 // Optimization remarks are always handled completely by this
591 // handler. There is no generic way of emitting them.
592 OptimizationRemarkHandler(
593 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
595 case llvm::DK_OptimizationRemarkAnalysisAliasing:
596 // Optimization remarks are always handled completely by this
597 // handler. There is no generic way of emitting them.
598 OptimizationRemarkHandler(
599 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
601 case llvm::DK_OptimizationFailure:
602 // Optimization failures are always handled completely by this
604 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
607 // Plugin IDs are not bound to any value as they are set dynamically.
608 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
611 std::string MsgStorage;
613 raw_string_ostream Stream(MsgStorage);
614 DiagnosticPrinterRawOStream DP(Stream);
618 if (DiagID == diag::err_fe_cannot_link_module) {
619 Diags.Report(diag::err_fe_cannot_link_module)
620 << CurLinkModule->getModuleIdentifier() << MsgStorage;
624 // Report the backend message using the usual diagnostic mechanism.
626 Diags.Report(Loc, DiagID).AddString(MsgStorage);
630 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
631 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
632 OwnsVMContext(!_VMContext) {}
634 CodeGenAction::~CodeGenAction() {
640 bool CodeGenAction::hasIRSupport() const { return true; }
642 void CodeGenAction::EndSourceFileAction() {
643 // If the consumer creation failed, do nothing.
644 if (!getCompilerInstance().hasASTConsumer())
647 // Take back ownership of link modules we passed to consumer.
648 if (!LinkModules.empty())
649 BEConsumer->releaseLinkModules();
651 // Steal the module from the consumer.
652 TheModule = BEConsumer->takeModule();
655 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
656 return std::move(TheModule);
659 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
660 OwnsVMContext = false;
664 static raw_pwrite_stream *
665 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
667 case Backend_EmitAssembly:
668 return CI.createDefaultOutputFile(false, InFile, "s");
670 return CI.createDefaultOutputFile(false, InFile, "ll");
672 return CI.createDefaultOutputFile(true, InFile, "bc");
673 case Backend_EmitNothing:
675 case Backend_EmitMCNull:
676 return CI.createNullOutputFile();
677 case Backend_EmitObj:
678 return CI.createDefaultOutputFile(true, InFile, "o");
681 llvm_unreachable("Invalid action!");
684 std::unique_ptr<ASTConsumer>
685 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
686 BackendAction BA = static_cast<BackendAction>(Act);
687 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
688 if (BA != Backend_EmitNothing && !OS)
691 // Load bitcode modules to link with, if we need to.
692 if (LinkModules.empty())
693 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
694 const std::string &LinkBCFile = I.second;
696 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
698 CI.getDiagnostics().Report(diag::err_cannot_open_file)
699 << LinkBCFile << BCBuf.getError().message();
704 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
705 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
706 if (std::error_code EC = ModuleOrErr.getError()) {
707 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
712 addLinkModule(ModuleOrErr.get().release(), I.first);
715 CoverageSourceInfo *CoverageInfo = nullptr;
716 // Add the preprocessor callback only when the coverage mapping is generated.
717 if (CI.getCodeGenOpts().CoverageMapping) {
718 CoverageInfo = new CoverageSourceInfo;
719 CI.getPreprocessor().addPPCallbacks(
720 std::unique_ptr<PPCallbacks>(CoverageInfo));
723 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
724 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
725 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
726 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
727 OS, *VMContext, CoverageInfo));
728 BEConsumer = Result.get();
729 return std::move(Result);
732 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
734 unsigned LocCookie) {
735 SM.print(nullptr, llvm::errs());
738 void CodeGenAction::ExecuteAction() {
739 // If this is an IR file, we have to treat it specially.
740 if (getCurrentFileKind() == IK_LLVM_IR) {
741 BackendAction BA = static_cast<BackendAction>(Act);
742 CompilerInstance &CI = getCompilerInstance();
743 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
744 if (BA != Backend_EmitNothing && !OS)
748 SourceManager &SM = CI.getSourceManager();
749 FileID FID = SM.getMainFileID();
750 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
754 llvm::SMDiagnostic Err;
755 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
757 // Translate from the diagnostic info to the SourceManager location if
759 // TODO: Unify this with ConvertBackendLocation()
761 if (Err.getLineNo() > 0) {
762 assert(Err.getColumnNo() >= 0);
763 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
764 Err.getLineNo(), Err.getColumnNo() + 1);
767 // Strip off a leading diagnostic code if there is one.
768 StringRef Msg = Err.getMessage();
769 if (Msg.startswith("error: "))
773 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
775 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
778 const TargetOptions &TargetOpts = CI.getTargetOpts();
779 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
780 CI.getDiagnostics().Report(SourceLocation(),
781 diag::warn_fe_override_module)
782 << TargetOpts.Triple;
783 TheModule->setTargetTriple(TargetOpts.Triple);
786 LLVMContext &Ctx = TheModule->getContext();
787 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
788 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
789 CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
790 TheModule.get(), BA, OS);
794 // Otherwise follow the normal AST path.
795 this->ASTFrontendAction::ExecuteAction();
800 void EmitAssemblyAction::anchor() { }
801 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
802 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
804 void EmitBCAction::anchor() { }
805 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
806 : CodeGenAction(Backend_EmitBC, _VMContext) {}
808 void EmitLLVMAction::anchor() { }
809 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
810 : CodeGenAction(Backend_EmitLL, _VMContext) {}
812 void EmitLLVMOnlyAction::anchor() { }
813 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
814 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
816 void EmitCodeGenOnlyAction::anchor() { }
817 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
818 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
820 void EmitObjAction::anchor() { }
821 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
822 : CodeGenAction(Backend_EmitObj, _VMContext) {}