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/FunctionInfo.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IRReader/IRReader.h"
33 #include "llvm/Linker/Linker.h"
34 #include "llvm/Object/FunctionIndexObjectFile.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/Timer.h"
40 using namespace clang;
44 class BackendConsumer : public ASTConsumer {
45 virtual void anchor();
46 DiagnosticsEngine &Diags;
48 const CodeGenOptions &CodeGenOpts;
49 const TargetOptions &TargetOpts;
50 const LangOptions &LangOpts;
51 raw_pwrite_stream *AsmOutStream;
54 Timer LLVMIRGeneration;
56 std::unique_ptr<CodeGenerator> Gen;
58 std::unique_ptr<llvm::Module> TheModule;
59 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
62 // This is here so that the diagnostic printer knows the module a diagnostic
64 llvm::Module *CurLinkModule = nullptr;
68 BackendAction Action, DiagnosticsEngine &Diags,
69 const HeaderSearchOptions &HeaderSearchOpts,
70 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
71 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
72 bool TimePasses, const std::string &InFile,
73 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
74 raw_pwrite_stream *OS, LLVMContext &C,
75 CoverageSourceInfo *CoverageInfo = nullptr)
76 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
77 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
78 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
79 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
80 CodeGenOpts, C, CoverageInfo)) {
81 llvm::TimePassesIsEnabled = TimePasses;
82 for (auto &I : LinkModules)
83 this->LinkModules.push_back(
84 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
86 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
87 void releaseLinkModules() {
88 for (auto &I : LinkModules)
92 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
93 Gen->HandleCXXStaticMemberVarInstantiation(VD);
96 void Initialize(ASTContext &Ctx) override {
97 assert(!Context && "initialized multiple times");
101 if (llvm::TimePassesIsEnabled)
102 LLVMIRGeneration.startTimer();
104 Gen->Initialize(Ctx);
106 TheModule.reset(Gen->GetModule());
108 if (llvm::TimePassesIsEnabled)
109 LLVMIRGeneration.stopTimer();
112 bool HandleTopLevelDecl(DeclGroupRef D) override {
113 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
114 Context->getSourceManager(),
115 "LLVM IR generation of declaration");
117 if (llvm::TimePassesIsEnabled)
118 LLVMIRGeneration.startTimer();
120 Gen->HandleTopLevelDecl(D);
122 if (llvm::TimePassesIsEnabled)
123 LLVMIRGeneration.stopTimer();
128 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
129 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
130 Context->getSourceManager(),
131 "LLVM IR generation of inline method");
132 if (llvm::TimePassesIsEnabled)
133 LLVMIRGeneration.startTimer();
135 Gen->HandleInlineMethodDefinition(D);
137 if (llvm::TimePassesIsEnabled)
138 LLVMIRGeneration.stopTimer();
141 void HandleTranslationUnit(ASTContext &C) override {
143 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
144 if (llvm::TimePassesIsEnabled)
145 LLVMIRGeneration.startTimer();
147 Gen->HandleTranslationUnit(C);
149 if (llvm::TimePassesIsEnabled)
150 LLVMIRGeneration.stopTimer();
153 // Silently ignore if we weren't initialized for some reason.
157 // Make sure IR generation is happy with the module. This is released by
158 // the module provider.
159 llvm::Module *M = Gen->ReleaseModule();
161 // The module has been released by IR gen on failures, do not double
167 assert(TheModule.get() == M &&
168 "Unexpected module change during IR generation");
170 // Install an inline asm handler so that diagnostics get printed through
171 // our diagnostics hooks.
172 LLVMContext &Ctx = TheModule->getContext();
173 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
174 Ctx.getInlineAsmDiagnosticHandler();
175 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
176 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
178 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
179 Ctx.getDiagnosticHandler();
180 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
181 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
183 // Link LinkModule into this module if present, preserving its validity.
184 for (auto &I : LinkModules) {
185 unsigned LinkFlags = I.first;
186 CurLinkModule = I.second.get();
187 if (Linker::linkModules(*M, std::move(I.second), LinkFlags))
191 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
192 C.getTargetInfo().getDataLayoutString(),
193 TheModule.get(), Action, AsmOutStream);
195 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
197 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
200 void HandleTagDeclDefinition(TagDecl *D) override {
201 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
202 Context->getSourceManager(),
203 "LLVM IR generation of declaration");
204 Gen->HandleTagDeclDefinition(D);
207 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
208 Gen->HandleTagDeclRequiredDefinition(D);
211 void CompleteTentativeDefinition(VarDecl *D) override {
212 Gen->CompleteTentativeDefinition(D);
215 void HandleVTable(CXXRecordDecl *RD) override {
216 Gen->HandleVTable(RD);
219 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
220 Gen->HandleLinkerOptionPragma(Opts);
223 void HandleDetectMismatch(llvm::StringRef Name,
224 llvm::StringRef Value) override {
225 Gen->HandleDetectMismatch(Name, Value);
228 void HandleDependentLibrary(llvm::StringRef Opts) override {
229 Gen->HandleDependentLibrary(Opts);
232 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
233 unsigned LocCookie) {
234 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
235 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
238 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
240 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
243 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
244 SourceLocation LocCookie);
246 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
247 /// \brief Specialized handler for InlineAsm diagnostic.
248 /// \return True if the diagnostic has been successfully reported, false
250 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
251 /// \brief Specialized handler for StackSize diagnostic.
252 /// \return True if the diagnostic has been successfully reported, false
254 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
255 /// \brief Specialized handlers for optimization remarks.
256 /// Note that these handlers only accept remarks and they always handle
258 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
261 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
262 void OptimizationRemarkHandler(
263 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
264 void OptimizationRemarkHandler(
265 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
266 void OptimizationRemarkHandler(
267 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
268 void OptimizationRemarkHandler(
269 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
270 void OptimizationFailureHandler(
271 const llvm::DiagnosticInfoOptimizationFailure &D);
274 void BackendConsumer::anchor() {}
277 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
278 /// buffer to be a valid FullSourceLoc.
279 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
280 SourceManager &CSM) {
281 // Get both the clang and llvm source managers. The location is relative to
282 // a memory buffer that the LLVM Source Manager is handling, we need to add
283 // a copy to the Clang source manager.
284 const llvm::SourceMgr &LSM = *D.getSourceMgr();
286 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
287 // already owns its one and clang::SourceManager wants to own its one.
288 const MemoryBuffer *LBuf =
289 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
291 // Create the copy and transfer ownership to clang::SourceManager.
292 // TODO: Avoid copying files into memory.
293 std::unique_ptr<llvm::MemoryBuffer> CBuf =
294 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
295 LBuf->getBufferIdentifier());
296 // FIXME: Keep a file ID map instead of creating new IDs for each location.
297 FileID FID = CSM.createFileID(std::move(CBuf));
299 // Translate the offset into the file.
300 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
301 SourceLocation NewLoc =
302 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
303 return FullSourceLoc(NewLoc, CSM);
307 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
308 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
309 /// the temporary memory buffer that the inline asm parser has set up.
310 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
311 SourceLocation LocCookie) {
312 // There are a couple of different kinds of errors we could get here. First,
313 // we re-format the SMDiagnostic in terms of a clang diagnostic.
315 // Strip "error: " off the start of the message string.
316 StringRef Message = D.getMessage();
317 if (Message.startswith("error: "))
318 Message = Message.substr(7);
320 // If the SMDiagnostic has an inline asm source location, translate it.
322 if (D.getLoc() != SMLoc())
323 Loc = ConvertBackendLocation(D, Context->getSourceManager());
326 switch (D.getKind()) {
327 case llvm::SourceMgr::DK_Error:
328 DiagID = diag::err_fe_inline_asm;
330 case llvm::SourceMgr::DK_Warning:
331 DiagID = diag::warn_fe_inline_asm;
333 case llvm::SourceMgr::DK_Note:
334 DiagID = diag::note_fe_inline_asm;
337 // If this problem has clang-level source location information, report the
338 // issue in the source with a note showing the instantiated
340 if (LocCookie.isValid()) {
341 Diags.Report(LocCookie, DiagID).AddString(Message);
343 if (D.getLoc().isValid()) {
344 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
345 // Convert the SMDiagnostic ranges into SourceRange and attach them
346 // to the diagnostic.
347 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
348 unsigned Column = D.getColumnNo();
349 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
350 Loc.getLocWithOffset(Range.second - Column));
356 // Otherwise, report the backend issue as occurring in the generated .s file.
357 // If Loc is invalid, we still need to report the issue, it just gets no
359 Diags.Report(Loc, DiagID).AddString(Message);
362 #define ComputeDiagID(Severity, GroupName, DiagID) \
364 switch (Severity) { \
365 case llvm::DS_Error: \
366 DiagID = diag::err_fe_##GroupName; \
368 case llvm::DS_Warning: \
369 DiagID = diag::warn_fe_##GroupName; \
371 case llvm::DS_Remark: \
372 llvm_unreachable("'remark' severity not expected"); \
374 case llvm::DS_Note: \
375 DiagID = diag::note_fe_##GroupName; \
380 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
382 switch (Severity) { \
383 case llvm::DS_Error: \
384 DiagID = diag::err_fe_##GroupName; \
386 case llvm::DS_Warning: \
387 DiagID = diag::warn_fe_##GroupName; \
389 case llvm::DS_Remark: \
390 DiagID = diag::remark_fe_##GroupName; \
392 case llvm::DS_Note: \
393 DiagID = diag::note_fe_##GroupName; \
399 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
401 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
402 std::string Message = D.getMsgStr().str();
404 // If this problem has clang-level source location information, report the
405 // issue as being a problem in the source with a note showing the instantiated
407 SourceLocation LocCookie =
408 SourceLocation::getFromRawEncoding(D.getLocCookie());
409 if (LocCookie.isValid())
410 Diags.Report(LocCookie, DiagID).AddString(Message);
412 // Otherwise, report the backend diagnostic as occurring in the generated
414 // If Loc is invalid, we still need to report the diagnostic, it just gets
417 Diags.Report(Loc, DiagID).AddString(Message);
419 // We handled all the possible severities.
424 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
425 if (D.getSeverity() != llvm::DS_Warning)
426 // For now, the only support we have for StackSize diagnostic is warning.
427 // We do not know how to format other severities.
430 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
431 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
432 diag::warn_fe_frame_larger_than)
433 << D.getStackSize() << Decl::castToDeclContext(ND);
440 void BackendConsumer::EmitOptimizationMessage(
441 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
442 // We only support warnings and remarks.
443 assert(D.getSeverity() == llvm::DS_Remark ||
444 D.getSeverity() == llvm::DS_Warning);
446 SourceManager &SourceMgr = Context->getSourceManager();
447 FileManager &FileMgr = SourceMgr.getFileManager();
449 unsigned Line, Column;
450 SourceLocation DILoc;
452 if (D.isLocationAvailable()) {
453 D.getLocation(&Filename, &Line, &Column);
454 const FileEntry *FE = FileMgr.getFile(Filename);
455 if (FE && Line > 0) {
456 // If -gcolumn-info was not used, Column will be 0. This upsets the
457 // source manager, so pass 1 if Column is not set.
458 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
462 // If a location isn't available, try to approximate it using the associated
463 // function definition. We use the definition's right brace to differentiate
464 // from diagnostics that genuinely relate to the function itself.
465 FullSourceLoc Loc(DILoc, SourceMgr);
467 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
468 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
470 Diags.Report(Loc, DiagID)
471 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
474 if (DILoc.isInvalid() && D.isLocationAvailable())
475 // If we were not able to translate the file:line:col information
476 // back to a SourceLocation, at least emit a note stating that
477 // we could not translate this location. This can happen in the
478 // case of #line directives.
479 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
480 << Filename << Line << Column;
483 void BackendConsumer::OptimizationRemarkHandler(
484 const llvm::DiagnosticInfoOptimizationRemark &D) {
485 // Optimization remarks are active only if the -Rpass flag has a regular
486 // expression that matches the name of the pass name in \p D.
487 if (CodeGenOpts.OptimizationRemarkPattern &&
488 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
489 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
492 void BackendConsumer::OptimizationRemarkHandler(
493 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
494 // Missed optimization remarks are active only if the -Rpass-missed
495 // flag has a regular expression that matches the name of the pass
497 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
498 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
499 EmitOptimizationMessage(D,
500 diag::remark_fe_backend_optimization_remark_missed);
503 void BackendConsumer::OptimizationRemarkHandler(
504 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
505 // Optimization analysis remarks are active if the pass name is set to
506 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
507 // regular expression that matches the name of the pass name in \p D.
509 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
510 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
511 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
512 EmitOptimizationMessage(
513 D, diag::remark_fe_backend_optimization_remark_analysis);
516 void BackendConsumer::OptimizationRemarkHandler(
517 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
518 // Optimization analysis remarks are active if the pass name is set to
519 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
520 // regular expression that matches the name of the pass name in \p D.
522 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
523 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
524 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
525 EmitOptimizationMessage(
526 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
529 void BackendConsumer::OptimizationRemarkHandler(
530 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
531 // Optimization analysis remarks are active if the pass name is set to
532 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
533 // regular expression that matches the name of the pass name in \p D.
535 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
536 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
537 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
538 EmitOptimizationMessage(
539 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
542 void BackendConsumer::OptimizationFailureHandler(
543 const llvm::DiagnosticInfoOptimizationFailure &D) {
544 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
547 /// \brief This function is invoked when the backend needs
548 /// to report something to the user.
549 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
550 unsigned DiagID = diag::err_fe_inline_asm;
551 llvm::DiagnosticSeverity Severity = DI.getSeverity();
552 // Get the diagnostic ID based.
553 switch (DI.getKind()) {
554 case llvm::DK_InlineAsm:
555 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
557 ComputeDiagID(Severity, inline_asm, DiagID);
559 case llvm::DK_StackSize:
560 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
562 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
565 assert(CurLinkModule);
566 // FIXME: stop eating the warnings and notes.
567 if (Severity != DS_Error)
569 DiagID = diag::err_fe_cannot_link_module;
571 case llvm::DK_OptimizationRemark:
572 // Optimization remarks are always handled completely by this
573 // handler. There is no generic way of emitting them.
574 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
576 case llvm::DK_OptimizationRemarkMissed:
577 // Optimization remarks are always handled completely by this
578 // handler. There is no generic way of emitting them.
579 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
581 case llvm::DK_OptimizationRemarkAnalysis:
582 // Optimization remarks are always handled completely by this
583 // handler. There is no generic way of emitting them.
584 OptimizationRemarkHandler(
585 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
587 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
588 // Optimization remarks are always handled completely by this
589 // handler. There is no generic way of emitting them.
590 OptimizationRemarkHandler(
591 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
593 case llvm::DK_OptimizationRemarkAnalysisAliasing:
594 // Optimization remarks are always handled completely by this
595 // handler. There is no generic way of emitting them.
596 OptimizationRemarkHandler(
597 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
599 case llvm::DK_OptimizationFailure:
600 // Optimization failures are always handled completely by this
602 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
605 // Plugin IDs are not bound to any value as they are set dynamically.
606 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
609 std::string MsgStorage;
611 raw_string_ostream Stream(MsgStorage);
612 DiagnosticPrinterRawOStream DP(Stream);
616 if (DiagID == diag::err_fe_cannot_link_module) {
617 Diags.Report(diag::err_fe_cannot_link_module)
618 << CurLinkModule->getModuleIdentifier() << MsgStorage;
622 // Report the backend message using the usual diagnostic mechanism.
624 Diags.Report(Loc, DiagID).AddString(MsgStorage);
628 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
629 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
630 OwnsVMContext(!_VMContext) {}
632 CodeGenAction::~CodeGenAction() {
638 bool CodeGenAction::hasIRSupport() const { return true; }
640 void CodeGenAction::EndSourceFileAction() {
641 // If the consumer creation failed, do nothing.
642 if (!getCompilerInstance().hasASTConsumer())
645 // Take back ownership of link modules we passed to consumer.
646 if (!LinkModules.empty())
647 BEConsumer->releaseLinkModules();
649 // Steal the module from the consumer.
650 TheModule = BEConsumer->takeModule();
653 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
654 return std::move(TheModule);
657 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
658 OwnsVMContext = false;
662 static raw_pwrite_stream *
663 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
665 case Backend_EmitAssembly:
666 return CI.createDefaultOutputFile(false, InFile, "s");
668 return CI.createDefaultOutputFile(false, InFile, "ll");
670 return CI.createDefaultOutputFile(true, InFile, "bc");
671 case Backend_EmitNothing:
673 case Backend_EmitMCNull:
674 return CI.createNullOutputFile();
675 case Backend_EmitObj:
676 return CI.createDefaultOutputFile(true, InFile, "o");
679 llvm_unreachable("Invalid action!");
682 std::unique_ptr<ASTConsumer>
683 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
684 BackendAction BA = static_cast<BackendAction>(Act);
685 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
686 if (BA != Backend_EmitNothing && !OS)
689 // Load bitcode modules to link with, if we need to.
690 if (LinkModules.empty())
691 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
692 const std::string &LinkBCFile = I.second;
694 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
696 CI.getDiagnostics().Report(diag::err_cannot_open_file)
697 << LinkBCFile << BCBuf.getError().message();
702 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
703 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
704 if (std::error_code EC = ModuleOrErr.getError()) {
705 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
710 addLinkModule(ModuleOrErr.get().release(), I.first);
713 CoverageSourceInfo *CoverageInfo = nullptr;
714 // Add the preprocessor callback only when the coverage mapping is generated.
715 if (CI.getCodeGenOpts().CoverageMapping) {
716 CoverageInfo = new CoverageSourceInfo;
717 CI.getPreprocessor().addPPCallbacks(
718 std::unique_ptr<PPCallbacks>(CoverageInfo));
721 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
722 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
723 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
724 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
725 OS, *VMContext, CoverageInfo));
726 BEConsumer = Result.get();
727 return std::move(Result);
730 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
732 unsigned LocCookie) {
733 SM.print(nullptr, llvm::errs());
736 void CodeGenAction::ExecuteAction() {
737 // If this is an IR file, we have to treat it specially.
738 if (getCurrentFileKind() == IK_LLVM_IR) {
739 BackendAction BA = static_cast<BackendAction>(Act);
740 CompilerInstance &CI = getCompilerInstance();
741 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
742 if (BA != Backend_EmitNothing && !OS)
746 SourceManager &SM = CI.getSourceManager();
747 FileID FID = SM.getMainFileID();
748 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
752 llvm::SMDiagnostic Err;
753 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
755 // Translate from the diagnostic info to the SourceManager location if
757 // TODO: Unify this with ConvertBackendLocation()
759 if (Err.getLineNo() > 0) {
760 assert(Err.getColumnNo() >= 0);
761 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
762 Err.getLineNo(), Err.getColumnNo() + 1);
765 // Strip off a leading diagnostic code if there is one.
766 StringRef Msg = Err.getMessage();
767 if (Msg.startswith("error: "))
771 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
773 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
776 const TargetOptions &TargetOpts = CI.getTargetOpts();
777 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
778 CI.getDiagnostics().Report(SourceLocation(),
779 diag::warn_fe_override_module)
780 << TargetOpts.Triple;
781 TheModule->setTargetTriple(TargetOpts.Triple);
784 auto DiagHandler = [&](const DiagnosticInfo &DI) {
785 TheModule->getContext().diagnose(DI);
788 // If we are performing ThinLTO importing compilation (indicated by
789 // a non-empty index file option), then we need promote to global scope
790 // and rename any local values that are potentially exported to other
791 // modules. Do this early so that the rest of the compilation sees the
793 std::unique_ptr<FunctionInfoIndex> Index;
794 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
795 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
796 llvm::getFunctionIndexForFile(CI.getCodeGenOpts().ThinLTOIndexFile,
798 if (std::error_code EC = IndexOrErr.getError()) {
799 std::string Error = EC.message();
800 errs() << "Error loading index file '"
801 << CI.getCodeGenOpts().ThinLTOIndexFile << "': " << Error
805 Index = std::move(IndexOrErr.get());
807 // Currently this requires creating a new Module object.
808 std::unique_ptr<llvm::Module> RenamedModule =
809 renameModuleForThinLTO(std::move(TheModule), Index.get());
813 TheModule = std::move(RenamedModule);
816 LLVMContext &Ctx = TheModule->getContext();
817 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
818 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
819 CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
820 TheModule.get(), BA, OS, std::move(Index));
824 // Otherwise follow the normal AST path.
825 this->ASTFrontendAction::ExecuteAction();
830 void EmitAssemblyAction::anchor() { }
831 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
832 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
834 void EmitBCAction::anchor() { }
835 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
836 : CodeGenAction(Backend_EmitBC, _VMContext) {}
838 void EmitLLVMAction::anchor() { }
839 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
840 : CodeGenAction(Backend_EmitLL, _VMContext) {}
842 void EmitLLVMOnlyAction::anchor() { }
843 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
844 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
846 void EmitCodeGenOnlyAction::anchor() { }
847 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
848 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
850 void EmitObjAction::anchor() { }
851 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
852 : CodeGenAction(Backend_EmitObj, _VMContext) {}