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 "clang/CodeGen/CodeGenAction.h"
11 #include "CodeGenModule.h"
12 #include "CoverageMappingGen.h"
13 #include "MacroPPCallbacks.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclGroup.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/CodeGen/BackendUtil.h"
22 #include "clang/CodeGen/ModuleBuilder.h"
23 #include "clang/Frontend/CompilerInstance.h"
24 #include "clang/Frontend/FrontendDiagnostic.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IRReader/IRReader.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/Timer.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/YAMLTraits.h"
42 #include "llvm/Transforms/IPO/Internalize.h"
45 using namespace clang;
49 class BackendConsumer : public ASTConsumer {
50 using LinkModule = CodeGenAction::LinkModule;
52 virtual void anchor();
53 DiagnosticsEngine &Diags;
55 const HeaderSearchOptions &HeaderSearchOpts;
56 const CodeGenOptions &CodeGenOpts;
57 const TargetOptions &TargetOpts;
58 const LangOptions &LangOpts;
59 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
62 Timer LLVMIRGeneration;
63 unsigned LLVMIRGenerationRefCount;
65 /// True if we've finished generating IR. This prevents us from generating
66 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
67 /// can happen when Clang plugins trigger additional AST deserialization.
68 bool IRGenFinished = false;
70 std::unique_ptr<CodeGenerator> Gen;
72 SmallVector<LinkModule, 4> LinkModules;
74 // This is here so that the diagnostic printer knows the module a diagnostic
76 llvm::Module *CurLinkModule = nullptr;
79 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
80 const HeaderSearchOptions &HeaderSearchOpts,
81 const PreprocessorOptions &PPOpts,
82 const CodeGenOptions &CodeGenOpts,
83 const TargetOptions &TargetOpts,
84 const LangOptions &LangOpts, bool TimePasses,
85 const std::string &InFile,
86 SmallVector<LinkModule, 4> LinkModules,
87 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
88 CoverageSourceInfo *CoverageInfo = nullptr)
89 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
90 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
91 AsmOutStream(std::move(OS)), Context(nullptr),
92 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
93 LLVMIRGenerationRefCount(0),
94 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
95 CodeGenOpts, C, CoverageInfo)),
96 LinkModules(std::move(LinkModules)) {
97 llvm::TimePassesIsEnabled = TimePasses;
99 llvm::Module *getModule() const { return Gen->GetModule(); }
100 std::unique_ptr<llvm::Module> takeModule() {
101 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
104 CodeGenerator *getCodeGenerator() { return Gen.get(); }
106 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
107 Gen->HandleCXXStaticMemberVarInstantiation(VD);
110 void Initialize(ASTContext &Ctx) override {
111 assert(!Context && "initialized multiple times");
115 if (llvm::TimePassesIsEnabled)
116 LLVMIRGeneration.startTimer();
118 Gen->Initialize(Ctx);
120 if (llvm::TimePassesIsEnabled)
121 LLVMIRGeneration.stopTimer();
124 bool HandleTopLevelDecl(DeclGroupRef D) override {
125 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
126 Context->getSourceManager(),
127 "LLVM IR generation of declaration");
130 if (llvm::TimePassesIsEnabled) {
131 LLVMIRGenerationRefCount += 1;
132 if (LLVMIRGenerationRefCount == 1)
133 LLVMIRGeneration.startTimer();
136 Gen->HandleTopLevelDecl(D);
138 if (llvm::TimePassesIsEnabled) {
139 LLVMIRGenerationRefCount -= 1;
140 if (LLVMIRGenerationRefCount == 0)
141 LLVMIRGeneration.stopTimer();
147 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
148 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
149 Context->getSourceManager(),
150 "LLVM IR generation of inline function");
151 if (llvm::TimePassesIsEnabled)
152 LLVMIRGeneration.startTimer();
154 Gen->HandleInlineFunctionDefinition(D);
156 if (llvm::TimePassesIsEnabled)
157 LLVMIRGeneration.stopTimer();
160 void HandleInterestingDecl(DeclGroupRef D) override {
161 // Ignore interesting decls from the AST reader after IRGen is finished.
163 HandleTopLevelDecl(D);
166 // Links each entry in LinkModules into our module. Returns true on error.
167 bool LinkInModules() {
168 for (auto &LM : LinkModules) {
169 if (LM.PropagateAttrs)
170 for (Function &F : *LM.Module)
171 Gen->CGM().AddDefaultFnAttrs(F);
173 CurLinkModule = LM.Module.get();
176 if (LM.Internalize) {
177 Err = Linker::linkModules(
178 *getModule(), std::move(LM.Module), LM.LinkFlags,
179 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
180 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
181 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
185 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
192 return false; // success
195 void HandleTranslationUnit(ASTContext &C) override {
197 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
198 if (llvm::TimePassesIsEnabled) {
199 LLVMIRGenerationRefCount += 1;
200 if (LLVMIRGenerationRefCount == 1)
201 LLVMIRGeneration.startTimer();
204 Gen->HandleTranslationUnit(C);
206 if (llvm::TimePassesIsEnabled) {
207 LLVMIRGenerationRefCount -= 1;
208 if (LLVMIRGenerationRefCount == 0)
209 LLVMIRGeneration.stopTimer();
212 IRGenFinished = true;
215 // Silently ignore if we weren't initialized for some reason.
219 // Install an inline asm handler so that diagnostics get printed through
220 // our diagnostics hooks.
221 LLVMContext &Ctx = getModule()->getContext();
222 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
223 Ctx.getInlineAsmDiagnosticHandler();
224 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
225 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
227 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
228 Ctx.getDiagnosticHandler();
229 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
230 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
231 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
233 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
234 if (!CodeGenOpts.OptRecordFile.empty()) {
237 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
238 EC, sys::fs::F_None);
240 Diags.Report(diag::err_cannot_open_file) <<
241 CodeGenOpts.OptRecordFile << EC.message();
245 Ctx.setDiagnosticsOutputFile(
246 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
248 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
249 Ctx.setDiagnosticHotnessRequested(true);
252 // Link each LinkModule into our module.
256 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
258 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
259 LangOpts, C.getTargetInfo().getDataLayout(),
260 getModule(), Action, std::move(AsmOutStream));
262 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
264 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
267 OptRecordFile->keep();
270 void HandleTagDeclDefinition(TagDecl *D) override {
271 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
272 Context->getSourceManager(),
273 "LLVM IR generation of declaration");
274 Gen->HandleTagDeclDefinition(D);
277 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
278 Gen->HandleTagDeclRequiredDefinition(D);
281 void CompleteTentativeDefinition(VarDecl *D) override {
282 Gen->CompleteTentativeDefinition(D);
285 void AssignInheritanceModel(CXXRecordDecl *RD) override {
286 Gen->AssignInheritanceModel(RD);
289 void HandleVTable(CXXRecordDecl *RD) override {
290 Gen->HandleVTable(RD);
293 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
294 unsigned LocCookie) {
295 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
296 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
299 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
301 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
304 /// Get the best possible source location to represent a diagnostic that
305 /// may have associated debug info.
307 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
308 bool &BadDebugInfo, StringRef &Filename,
309 unsigned &Line, unsigned &Column) const;
311 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
312 SourceLocation LocCookie);
314 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
315 /// \brief Specialized handler for InlineAsm diagnostic.
316 /// \return True if the diagnostic has been successfully reported, false
318 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
319 /// \brief Specialized handler for StackSize diagnostic.
320 /// \return True if the diagnostic has been successfully reported, false
322 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
323 /// \brief Specialized handler for unsupported backend feature diagnostic.
324 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
325 /// \brief Specialized handlers for optimization remarks.
326 /// Note that these handlers only accept remarks and they always handle
328 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
331 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
332 void OptimizationRemarkHandler(
333 const llvm::OptimizationRemarkAnalysisFPCommute &D);
334 void OptimizationRemarkHandler(
335 const llvm::OptimizationRemarkAnalysisAliasing &D);
336 void OptimizationFailureHandler(
337 const llvm::DiagnosticInfoOptimizationFailure &D);
340 void BackendConsumer::anchor() {}
343 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
344 /// buffer to be a valid FullSourceLoc.
345 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
346 SourceManager &CSM) {
347 // Get both the clang and llvm source managers. The location is relative to
348 // a memory buffer that the LLVM Source Manager is handling, we need to add
349 // a copy to the Clang source manager.
350 const llvm::SourceMgr &LSM = *D.getSourceMgr();
352 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
353 // already owns its one and clang::SourceManager wants to own its one.
354 const MemoryBuffer *LBuf =
355 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
357 // Create the copy and transfer ownership to clang::SourceManager.
358 // TODO: Avoid copying files into memory.
359 std::unique_ptr<llvm::MemoryBuffer> CBuf =
360 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
361 LBuf->getBufferIdentifier());
362 // FIXME: Keep a file ID map instead of creating new IDs for each location.
363 FileID FID = CSM.createFileID(std::move(CBuf));
365 // Translate the offset into the file.
366 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
367 SourceLocation NewLoc =
368 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
369 return FullSourceLoc(NewLoc, CSM);
373 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
374 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
375 /// the temporary memory buffer that the inline asm parser has set up.
376 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
377 SourceLocation LocCookie) {
378 // There are a couple of different kinds of errors we could get here. First,
379 // we re-format the SMDiagnostic in terms of a clang diagnostic.
381 // Strip "error: " off the start of the message string.
382 StringRef Message = D.getMessage();
383 if (Message.startswith("error: "))
384 Message = Message.substr(7);
386 // If the SMDiagnostic has an inline asm source location, translate it.
388 if (D.getLoc() != SMLoc())
389 Loc = ConvertBackendLocation(D, Context->getSourceManager());
392 switch (D.getKind()) {
393 case llvm::SourceMgr::DK_Error:
394 DiagID = diag::err_fe_inline_asm;
396 case llvm::SourceMgr::DK_Warning:
397 DiagID = diag::warn_fe_inline_asm;
399 case llvm::SourceMgr::DK_Note:
400 DiagID = diag::note_fe_inline_asm;
403 // If this problem has clang-level source location information, report the
404 // issue in the source with a note showing the instantiated
406 if (LocCookie.isValid()) {
407 Diags.Report(LocCookie, DiagID).AddString(Message);
409 if (D.getLoc().isValid()) {
410 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
411 // Convert the SMDiagnostic ranges into SourceRange and attach them
412 // to the diagnostic.
413 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
414 unsigned Column = D.getColumnNo();
415 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
416 Loc.getLocWithOffset(Range.second - Column));
422 // Otherwise, report the backend issue as occurring in the generated .s file.
423 // If Loc is invalid, we still need to report the issue, it just gets no
425 Diags.Report(Loc, DiagID).AddString(Message);
428 #define ComputeDiagID(Severity, GroupName, DiagID) \
430 switch (Severity) { \
431 case llvm::DS_Error: \
432 DiagID = diag::err_fe_##GroupName; \
434 case llvm::DS_Warning: \
435 DiagID = diag::warn_fe_##GroupName; \
437 case llvm::DS_Remark: \
438 llvm_unreachable("'remark' severity not expected"); \
440 case llvm::DS_Note: \
441 DiagID = diag::note_fe_##GroupName; \
446 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
448 switch (Severity) { \
449 case llvm::DS_Error: \
450 DiagID = diag::err_fe_##GroupName; \
452 case llvm::DS_Warning: \
453 DiagID = diag::warn_fe_##GroupName; \
455 case llvm::DS_Remark: \
456 DiagID = diag::remark_fe_##GroupName; \
458 case llvm::DS_Note: \
459 DiagID = diag::note_fe_##GroupName; \
465 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
467 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
468 std::string Message = D.getMsgStr().str();
470 // If this problem has clang-level source location information, report the
471 // issue as being a problem in the source with a note showing the instantiated
473 SourceLocation LocCookie =
474 SourceLocation::getFromRawEncoding(D.getLocCookie());
475 if (LocCookie.isValid())
476 Diags.Report(LocCookie, DiagID).AddString(Message);
478 // Otherwise, report the backend diagnostic as occurring in the generated
480 // If Loc is invalid, we still need to report the diagnostic, it just gets
483 Diags.Report(Loc, DiagID).AddString(Message);
485 // We handled all the possible severities.
490 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
491 if (D.getSeverity() != llvm::DS_Warning)
492 // For now, the only support we have for StackSize diagnostic is warning.
493 // We do not know how to format other severities.
496 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
497 // FIXME: Shouldn't need to truncate to uint32_t
498 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
499 diag::warn_fe_frame_larger_than)
500 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
507 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
508 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
509 StringRef &Filename, unsigned &Line, unsigned &Column) const {
510 SourceManager &SourceMgr = Context->getSourceManager();
511 FileManager &FileMgr = SourceMgr.getFileManager();
512 SourceLocation DILoc;
514 if (D.isLocationAvailable()) {
515 D.getLocation(&Filename, &Line, &Column);
516 const FileEntry *FE = FileMgr.getFile(Filename);
517 if (FE && Line > 0) {
518 // If -gcolumn-info was not used, Column will be 0. This upsets the
519 // source manager, so pass 1 if Column is not set.
520 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
522 BadDebugInfo = DILoc.isInvalid();
525 // If a location isn't available, try to approximate it using the associated
526 // function definition. We use the definition's right brace to differentiate
527 // from diagnostics that genuinely relate to the function itself.
528 FullSourceLoc Loc(DILoc, SourceMgr);
530 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
531 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
533 if (DILoc.isInvalid() && D.isLocationAvailable())
534 // If we were not able to translate the file:line:col information
535 // back to a SourceLocation, at least emit a note stating that
536 // we could not translate this location. This can happen in the
537 // case of #line directives.
538 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
539 << Filename << Line << Column;
544 void BackendConsumer::UnsupportedDiagHandler(
545 const llvm::DiagnosticInfoUnsupported &D) {
546 // We only support errors.
547 assert(D.getSeverity() == llvm::DS_Error);
550 unsigned Line, Column;
552 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
555 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
558 // If we were not able to translate the file:line:col information
559 // back to a SourceLocation, at least emit a note stating that
560 // we could not translate this location. This can happen in the
561 // case of #line directives.
562 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
563 << Filename << Line << Column;
566 void BackendConsumer::EmitOptimizationMessage(
567 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
568 // We only support warnings and remarks.
569 assert(D.getSeverity() == llvm::DS_Remark ||
570 D.getSeverity() == llvm::DS_Warning);
573 unsigned Line, Column;
574 bool BadDebugInfo = false;
575 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
579 raw_string_ostream MsgStream(Msg);
580 MsgStream << D.getMsg();
583 MsgStream << " (hotness: " << *D.getHotness() << ")";
585 Diags.Report(Loc, DiagID)
586 << AddFlagValue(D.getPassName())
590 // If we were not able to translate the file:line:col information
591 // back to a SourceLocation, at least emit a note stating that
592 // we could not translate this location. This can happen in the
593 // case of #line directives.
594 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
595 << Filename << Line << Column;
598 void BackendConsumer::OptimizationRemarkHandler(
599 const llvm::DiagnosticInfoOptimizationBase &D) {
601 // Optimization remarks are active only if the -Rpass flag has a regular
602 // expression that matches the name of the pass name in \p D.
603 if (CodeGenOpts.OptimizationRemarkPattern &&
604 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
605 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
606 } else if (D.isMissed()) {
607 // Missed optimization remarks are active only if the -Rpass-missed
608 // flag has a regular expression that matches the name of the pass
610 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
611 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
612 EmitOptimizationMessage(
613 D, diag::remark_fe_backend_optimization_remark_missed);
615 assert(D.isAnalysis() && "Unknown remark type");
617 bool ShouldAlwaysPrint = false;
618 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
619 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
621 if (ShouldAlwaysPrint ||
622 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
623 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
624 EmitOptimizationMessage(
625 D, diag::remark_fe_backend_optimization_remark_analysis);
629 void BackendConsumer::OptimizationRemarkHandler(
630 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
631 // Optimization analysis remarks are active if the pass name is set to
632 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
633 // regular expression that matches the name of the pass name in \p D.
635 if (D.shouldAlwaysPrint() ||
636 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
637 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
638 EmitOptimizationMessage(
639 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
642 void BackendConsumer::OptimizationRemarkHandler(
643 const llvm::OptimizationRemarkAnalysisAliasing &D) {
644 // Optimization analysis remarks are active if the pass name is set to
645 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
646 // regular expression that matches the name of the pass name in \p D.
648 if (D.shouldAlwaysPrint() ||
649 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
650 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
651 EmitOptimizationMessage(
652 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
655 void BackendConsumer::OptimizationFailureHandler(
656 const llvm::DiagnosticInfoOptimizationFailure &D) {
657 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
660 /// \brief This function is invoked when the backend needs
661 /// to report something to the user.
662 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
663 unsigned DiagID = diag::err_fe_inline_asm;
664 llvm::DiagnosticSeverity Severity = DI.getSeverity();
665 // Get the diagnostic ID based.
666 switch (DI.getKind()) {
667 case llvm::DK_InlineAsm:
668 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
670 ComputeDiagID(Severity, inline_asm, DiagID);
672 case llvm::DK_StackSize:
673 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
675 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
678 assert(CurLinkModule);
679 // FIXME: stop eating the warnings and notes.
680 if (Severity != DS_Error)
682 DiagID = diag::err_fe_cannot_link_module;
684 case llvm::DK_OptimizationRemark:
685 // Optimization remarks are always handled completely by this
686 // handler. There is no generic way of emitting them.
687 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
689 case llvm::DK_OptimizationRemarkMissed:
690 // Optimization remarks are always handled completely by this
691 // handler. There is no generic way of emitting them.
692 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
694 case llvm::DK_OptimizationRemarkAnalysis:
695 // Optimization remarks are always handled completely by this
696 // handler. There is no generic way of emitting them.
697 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
699 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
700 // Optimization remarks are always handled completely by this
701 // handler. There is no generic way of emitting them.
702 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
704 case llvm::DK_OptimizationRemarkAnalysisAliasing:
705 // Optimization remarks are always handled completely by this
706 // handler. There is no generic way of emitting them.
707 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
709 case llvm::DK_MachineOptimizationRemark:
710 // Optimization remarks are always handled completely by this
711 // handler. There is no generic way of emitting them.
712 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
714 case llvm::DK_MachineOptimizationRemarkMissed:
715 // Optimization remarks are always handled completely by this
716 // handler. There is no generic way of emitting them.
717 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
719 case llvm::DK_MachineOptimizationRemarkAnalysis:
720 // Optimization remarks are always handled completely by this
721 // handler. There is no generic way of emitting them.
722 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
724 case llvm::DK_OptimizationFailure:
725 // Optimization failures are always handled completely by this
727 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
729 case llvm::DK_Unsupported:
730 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
733 // Plugin IDs are not bound to any value as they are set dynamically.
734 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
737 std::string MsgStorage;
739 raw_string_ostream Stream(MsgStorage);
740 DiagnosticPrinterRawOStream DP(Stream);
744 if (DiagID == diag::err_fe_cannot_link_module) {
745 Diags.Report(diag::err_fe_cannot_link_module)
746 << CurLinkModule->getModuleIdentifier() << MsgStorage;
750 // Report the backend message using the usual diagnostic mechanism.
752 Diags.Report(Loc, DiagID).AddString(MsgStorage);
756 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
757 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
758 OwnsVMContext(!_VMContext) {}
760 CodeGenAction::~CodeGenAction() {
766 bool CodeGenAction::hasIRSupport() const { return true; }
768 void CodeGenAction::EndSourceFileAction() {
769 // If the consumer creation failed, do nothing.
770 if (!getCompilerInstance().hasASTConsumer())
773 // Steal the module from the consumer.
774 TheModule = BEConsumer->takeModule();
777 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
778 return std::move(TheModule);
781 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
782 OwnsVMContext = false;
786 static std::unique_ptr<raw_pwrite_stream>
787 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
789 case Backend_EmitAssembly:
790 return CI.createDefaultOutputFile(false, InFile, "s");
792 return CI.createDefaultOutputFile(false, InFile, "ll");
794 return CI.createDefaultOutputFile(true, InFile, "bc");
795 case Backend_EmitNothing:
797 case Backend_EmitMCNull:
798 return CI.createNullOutputFile();
799 case Backend_EmitObj:
800 return CI.createDefaultOutputFile(true, InFile, "o");
803 llvm_unreachable("Invalid action!");
806 std::unique_ptr<ASTConsumer>
807 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
808 BackendAction BA = static_cast<BackendAction>(Act);
809 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
810 if (BA != Backend_EmitNothing && !OS)
813 // Load bitcode modules to link with, if we need to.
814 if (LinkModules.empty())
815 for (const CodeGenOptions::BitcodeFileToLink &F :
816 CI.getCodeGenOpts().LinkBitcodeFiles) {
817 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
819 CI.getDiagnostics().Report(diag::err_cannot_open_file)
820 << F.Filename << BCBuf.getError().message();
825 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
826 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
828 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
829 CI.getDiagnostics().Report(diag::err_cannot_open_file)
830 << F.Filename << EIB.message();
835 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
836 F.Internalize, F.LinkFlags});
839 CoverageSourceInfo *CoverageInfo = nullptr;
840 // Add the preprocessor callback only when the coverage mapping is generated.
841 if (CI.getCodeGenOpts().CoverageMapping) {
842 CoverageInfo = new CoverageSourceInfo;
843 CI.getPreprocessor().addPPCallbacks(
844 std::unique_ptr<PPCallbacks>(CoverageInfo));
847 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
848 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
849 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
850 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
851 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
852 BEConsumer = Result.get();
854 // Enable generating macro debug info only when debug info is not disabled and
855 // also macro debug info is enabled.
856 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
857 CI.getCodeGenOpts().MacroDebugInfo) {
858 std::unique_ptr<PPCallbacks> Callbacks =
859 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
860 CI.getPreprocessor());
861 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
864 return std::move(Result);
867 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
869 unsigned LocCookie) {
870 SM.print(nullptr, llvm::errs());
872 auto Diags = static_cast<DiagnosticsEngine *>(Context);
874 switch (SM.getKind()) {
875 case llvm::SourceMgr::DK_Error:
876 DiagID = diag::err_fe_inline_asm;
878 case llvm::SourceMgr::DK_Warning:
879 DiagID = diag::warn_fe_inline_asm;
881 case llvm::SourceMgr::DK_Note:
882 DiagID = diag::note_fe_inline_asm;
886 Diags->Report(DiagID).AddString("cannot compile inline asm");
889 std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
890 CompilerInstance &CI = getCompilerInstance();
891 SourceManager &SM = CI.getSourceManager();
893 // For ThinLTO backend invocations, ensure that the context
894 // merges types based on ODR identifiers. We also need to read
895 // the correct module out of a multi-module bitcode file.
896 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
897 VMContext->enableDebugTypeODRUniquing();
899 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
901 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
902 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
903 CI.getDiagnostics().Report(DiagID) << EIB.message();
908 Expected<llvm::BitcodeModule> BMOrErr = FindThinLTOModule(MBRef);
910 return DiagErrors(BMOrErr.takeError());
912 Expected<std::unique_ptr<llvm::Module>> MOrErr =
913 BMOrErr->parseModule(*VMContext);
915 return DiagErrors(MOrErr.takeError());
916 return std::move(*MOrErr);
919 llvm::SMDiagnostic Err;
920 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
923 // Translate from the diagnostic info to the SourceManager location if
925 // TODO: Unify this with ConvertBackendLocation()
927 if (Err.getLineNo() > 0) {
928 assert(Err.getColumnNo() >= 0);
929 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
930 Err.getLineNo(), Err.getColumnNo() + 1);
933 // Strip off a leading diagnostic code if there is one.
934 StringRef Msg = Err.getMessage();
935 if (Msg.startswith("error: "))
939 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
941 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
945 void CodeGenAction::ExecuteAction() {
946 // If this is an IR file, we have to treat it specially.
947 if (getCurrentFileKind() == IK_LLVM_IR) {
948 BackendAction BA = static_cast<BackendAction>(Act);
949 CompilerInstance &CI = getCompilerInstance();
950 std::unique_ptr<raw_pwrite_stream> OS =
951 GetOutputStream(CI, getCurrentFile(), BA);
952 if (BA != Backend_EmitNothing && !OS)
956 SourceManager &SM = CI.getSourceManager();
957 FileID FID = SM.getMainFileID();
958 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
962 TheModule = loadModule(*MainFile);
966 const TargetOptions &TargetOpts = CI.getTargetOpts();
967 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
968 CI.getDiagnostics().Report(SourceLocation(),
969 diag::warn_fe_override_module)
970 << TargetOpts.Triple;
971 TheModule->setTargetTriple(TargetOpts.Triple);
974 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
975 MainFile->getMemBufferRef());
977 LLVMContext &Ctx = TheModule->getContext();
978 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
979 &CI.getDiagnostics());
981 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
982 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
983 CI.getTarget().getDataLayout(), TheModule.get(), BA,
988 // Otherwise follow the normal AST path.
989 this->ASTFrontendAction::ExecuteAction();
994 void EmitAssemblyAction::anchor() { }
995 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
996 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
998 void EmitBCAction::anchor() { }
999 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1000 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1002 void EmitLLVMAction::anchor() { }
1003 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1004 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1006 void EmitLLVMOnlyAction::anchor() { }
1007 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1008 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1010 void EmitCodeGenOnlyAction::anchor() { }
1011 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1012 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1014 void EmitObjAction::anchor() { }
1015 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1016 : CodeGenAction(Backend_EmitObj, _VMContext) {}