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/Bitcode/BitcodeReader.h"
25 #include "llvm/IR/DebugInfo.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IRReader/IRReader.h"
31 #include "llvm/Linker/Linker.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/Timer.h"
36 #include "llvm/Support/ToolOutputFile.h"
37 #include "llvm/Support/YAMLTraits.h"
39 using namespace clang;
43 class BackendConsumer : public ASTConsumer {
44 virtual void anchor();
45 DiagnosticsEngine &Diags;
47 const CodeGenOptions &CodeGenOpts;
48 const TargetOptions &TargetOpts;
49 const LangOptions &LangOpts;
50 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
53 Timer LLVMIRGeneration;
54 unsigned LLVMIRGenerationRefCount;
56 /// True if we've finished generating IR. This prevents us from generating
57 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
58 /// can happen when Clang plugins trigger additional AST deserialization.
59 bool IRGenFinished = false;
61 std::unique_ptr<CodeGenerator> Gen;
63 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
66 // This is here so that the diagnostic printer knows the module a diagnostic
68 llvm::Module *CurLinkModule = nullptr;
72 BackendAction Action, DiagnosticsEngine &Diags,
73 const HeaderSearchOptions &HeaderSearchOpts,
74 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
75 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
76 bool TimePasses, const std::string &InFile,
77 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
78 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
79 CoverageSourceInfo *CoverageInfo = nullptr)
80 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
81 TargetOpts(TargetOpts), LangOpts(LangOpts),
82 AsmOutStream(std::move(OS)), Context(nullptr),
83 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
84 LLVMIRGenerationRefCount(0),
85 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
86 CodeGenOpts, C, CoverageInfo)) {
87 llvm::TimePassesIsEnabled = TimePasses;
88 for (auto &I : LinkModules)
89 this->LinkModules.push_back(
90 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
92 llvm::Module *getModule() const { return Gen->GetModule(); }
93 std::unique_ptr<llvm::Module> takeModule() {
94 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
96 void releaseLinkModules() {
97 for (auto &I : LinkModules)
101 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
102 Gen->HandleCXXStaticMemberVarInstantiation(VD);
105 void Initialize(ASTContext &Ctx) override {
106 assert(!Context && "initialized multiple times");
110 if (llvm::TimePassesIsEnabled)
111 LLVMIRGeneration.startTimer();
113 Gen->Initialize(Ctx);
115 if (llvm::TimePassesIsEnabled)
116 LLVMIRGeneration.stopTimer();
119 bool HandleTopLevelDecl(DeclGroupRef D) override {
120 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
121 Context->getSourceManager(),
122 "LLVM IR generation of declaration");
125 if (llvm::TimePassesIsEnabled) {
126 LLVMIRGenerationRefCount += 1;
127 if (LLVMIRGenerationRefCount == 1)
128 LLVMIRGeneration.startTimer();
131 Gen->HandleTopLevelDecl(D);
133 if (llvm::TimePassesIsEnabled) {
134 LLVMIRGenerationRefCount -= 1;
135 if (LLVMIRGenerationRefCount == 0)
136 LLVMIRGeneration.stopTimer();
142 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
143 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
144 Context->getSourceManager(),
145 "LLVM IR generation of inline function");
146 if (llvm::TimePassesIsEnabled)
147 LLVMIRGeneration.startTimer();
149 Gen->HandleInlineFunctionDefinition(D);
151 if (llvm::TimePassesIsEnabled)
152 LLVMIRGeneration.stopTimer();
155 void HandleInterestingDecl(DeclGroupRef D) override {
156 // Ignore interesting decls from the AST reader after IRGen is finished.
158 HandleTopLevelDecl(D);
161 void HandleTranslationUnit(ASTContext &C) override {
163 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
164 if (llvm::TimePassesIsEnabled) {
165 LLVMIRGenerationRefCount += 1;
166 if (LLVMIRGenerationRefCount == 1)
167 LLVMIRGeneration.startTimer();
170 Gen->HandleTranslationUnit(C);
172 if (llvm::TimePassesIsEnabled) {
173 LLVMIRGenerationRefCount -= 1;
174 if (LLVMIRGenerationRefCount == 0)
175 LLVMIRGeneration.stopTimer();
178 IRGenFinished = true;
181 // Silently ignore if we weren't initialized for some reason.
185 // Install an inline asm handler so that diagnostics get printed through
186 // our diagnostics hooks.
187 LLVMContext &Ctx = getModule()->getContext();
188 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
189 Ctx.getInlineAsmDiagnosticHandler();
190 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
191 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
193 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
194 Ctx.getDiagnosticHandler();
195 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
196 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
197 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
199 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
200 if (!CodeGenOpts.OptRecordFile.empty()) {
203 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
204 EC, sys::fs::F_None);
206 Diags.Report(diag::err_cannot_open_file) <<
207 CodeGenOpts.OptRecordFile << EC.message();
211 Ctx.setDiagnosticsOutputFile(
212 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
214 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
215 Ctx.setDiagnosticHotnessRequested(true);
218 // Link LinkModule into this module if present, preserving its validity.
219 for (auto &I : LinkModules) {
220 unsigned LinkFlags = I.first;
221 CurLinkModule = I.second.get();
222 if (Linker::linkModules(*getModule(), std::move(I.second), LinkFlags))
226 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
228 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
229 C.getTargetInfo().getDataLayout(),
230 getModule(), Action, std::move(AsmOutStream));
232 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
234 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
237 OptRecordFile->keep();
240 void HandleTagDeclDefinition(TagDecl *D) override {
241 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
242 Context->getSourceManager(),
243 "LLVM IR generation of declaration");
244 Gen->HandleTagDeclDefinition(D);
247 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
248 Gen->HandleTagDeclRequiredDefinition(D);
251 void CompleteTentativeDefinition(VarDecl *D) override {
252 Gen->CompleteTentativeDefinition(D);
255 void AssignInheritanceModel(CXXRecordDecl *RD) override {
256 Gen->AssignInheritanceModel(RD);
259 void HandleVTable(CXXRecordDecl *RD) override {
260 Gen->HandleVTable(RD);
263 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
264 unsigned LocCookie) {
265 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
266 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
269 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
271 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
274 /// Get the best possible source location to represent a diagnostic that
275 /// may have associated debug info.
277 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
278 bool &BadDebugInfo, StringRef &Filename,
279 unsigned &Line, unsigned &Column) const;
281 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
282 SourceLocation LocCookie);
284 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
285 /// \brief Specialized handler for InlineAsm diagnostic.
286 /// \return True if the diagnostic has been successfully reported, false
288 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
289 /// \brief Specialized handler for StackSize diagnostic.
290 /// \return True if the diagnostic has been successfully reported, false
292 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
293 /// \brief Specialized handler for unsupported backend feature diagnostic.
294 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
295 /// \brief Specialized handlers for optimization remarks.
296 /// Note that these handlers only accept remarks and they always handle
298 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
300 void OptimizationRemarkHandler(const llvm::OptimizationRemark &D);
301 void OptimizationRemarkHandler(const llvm::OptimizationRemarkMissed &D);
302 void OptimizationRemarkHandler(const llvm::OptimizationRemarkAnalysis &D);
303 void OptimizationRemarkHandler(
304 const llvm::OptimizationRemarkAnalysisFPCommute &D);
305 void OptimizationRemarkHandler(
306 const llvm::OptimizationRemarkAnalysisAliasing &D);
307 void OptimizationFailureHandler(
308 const llvm::DiagnosticInfoOptimizationFailure &D);
311 void BackendConsumer::anchor() {}
314 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
315 /// buffer to be a valid FullSourceLoc.
316 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
317 SourceManager &CSM) {
318 // Get both the clang and llvm source managers. The location is relative to
319 // a memory buffer that the LLVM Source Manager is handling, we need to add
320 // a copy to the Clang source manager.
321 const llvm::SourceMgr &LSM = *D.getSourceMgr();
323 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
324 // already owns its one and clang::SourceManager wants to own its one.
325 const MemoryBuffer *LBuf =
326 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
328 // Create the copy and transfer ownership to clang::SourceManager.
329 // TODO: Avoid copying files into memory.
330 std::unique_ptr<llvm::MemoryBuffer> CBuf =
331 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
332 LBuf->getBufferIdentifier());
333 // FIXME: Keep a file ID map instead of creating new IDs for each location.
334 FileID FID = CSM.createFileID(std::move(CBuf));
336 // Translate the offset into the file.
337 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
338 SourceLocation NewLoc =
339 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
340 return FullSourceLoc(NewLoc, CSM);
344 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
345 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
346 /// the temporary memory buffer that the inline asm parser has set up.
347 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
348 SourceLocation LocCookie) {
349 // There are a couple of different kinds of errors we could get here. First,
350 // we re-format the SMDiagnostic in terms of a clang diagnostic.
352 // Strip "error: " off the start of the message string.
353 StringRef Message = D.getMessage();
354 if (Message.startswith("error: "))
355 Message = Message.substr(7);
357 // If the SMDiagnostic has an inline asm source location, translate it.
359 if (D.getLoc() != SMLoc())
360 Loc = ConvertBackendLocation(D, Context->getSourceManager());
363 switch (D.getKind()) {
364 case llvm::SourceMgr::DK_Error:
365 DiagID = diag::err_fe_inline_asm;
367 case llvm::SourceMgr::DK_Warning:
368 DiagID = diag::warn_fe_inline_asm;
370 case llvm::SourceMgr::DK_Note:
371 DiagID = diag::note_fe_inline_asm;
374 // If this problem has clang-level source location information, report the
375 // issue in the source with a note showing the instantiated
377 if (LocCookie.isValid()) {
378 Diags.Report(LocCookie, DiagID).AddString(Message);
380 if (D.getLoc().isValid()) {
381 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
382 // Convert the SMDiagnostic ranges into SourceRange and attach them
383 // to the diagnostic.
384 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
385 unsigned Column = D.getColumnNo();
386 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
387 Loc.getLocWithOffset(Range.second - Column));
393 // Otherwise, report the backend issue as occurring in the generated .s file.
394 // If Loc is invalid, we still need to report the issue, it just gets no
396 Diags.Report(Loc, DiagID).AddString(Message);
399 #define ComputeDiagID(Severity, GroupName, DiagID) \
401 switch (Severity) { \
402 case llvm::DS_Error: \
403 DiagID = diag::err_fe_##GroupName; \
405 case llvm::DS_Warning: \
406 DiagID = diag::warn_fe_##GroupName; \
408 case llvm::DS_Remark: \
409 llvm_unreachable("'remark' severity not expected"); \
411 case llvm::DS_Note: \
412 DiagID = diag::note_fe_##GroupName; \
417 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
419 switch (Severity) { \
420 case llvm::DS_Error: \
421 DiagID = diag::err_fe_##GroupName; \
423 case llvm::DS_Warning: \
424 DiagID = diag::warn_fe_##GroupName; \
426 case llvm::DS_Remark: \
427 DiagID = diag::remark_fe_##GroupName; \
429 case llvm::DS_Note: \
430 DiagID = diag::note_fe_##GroupName; \
436 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
438 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
439 std::string Message = D.getMsgStr().str();
441 // If this problem has clang-level source location information, report the
442 // issue as being a problem in the source with a note showing the instantiated
444 SourceLocation LocCookie =
445 SourceLocation::getFromRawEncoding(D.getLocCookie());
446 if (LocCookie.isValid())
447 Diags.Report(LocCookie, DiagID).AddString(Message);
449 // Otherwise, report the backend diagnostic as occurring in the generated
451 // If Loc is invalid, we still need to report the diagnostic, it just gets
454 Diags.Report(Loc, DiagID).AddString(Message);
456 // We handled all the possible severities.
461 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
462 if (D.getSeverity() != llvm::DS_Warning)
463 // For now, the only support we have for StackSize diagnostic is warning.
464 // We do not know how to format other severities.
467 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
468 // FIXME: Shouldn't need to truncate to uint32_t
469 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
470 diag::warn_fe_frame_larger_than)
471 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
478 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
479 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
480 unsigned &Line, unsigned &Column) const {
481 SourceManager &SourceMgr = Context->getSourceManager();
482 FileManager &FileMgr = SourceMgr.getFileManager();
483 SourceLocation DILoc;
485 if (D.isLocationAvailable()) {
486 D.getLocation(&Filename, &Line, &Column);
487 const FileEntry *FE = FileMgr.getFile(Filename);
488 if (FE && Line > 0) {
489 // If -gcolumn-info was not used, Column will be 0. This upsets the
490 // source manager, so pass 1 if Column is not set.
491 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
493 BadDebugInfo = DILoc.isInvalid();
496 // If a location isn't available, try to approximate it using the associated
497 // function definition. We use the definition's right brace to differentiate
498 // from diagnostics that genuinely relate to the function itself.
499 FullSourceLoc Loc(DILoc, SourceMgr);
501 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
502 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
504 if (DILoc.isInvalid() && D.isLocationAvailable())
505 // If we were not able to translate the file:line:col information
506 // back to a SourceLocation, at least emit a note stating that
507 // we could not translate this location. This can happen in the
508 // case of #line directives.
509 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
510 << Filename << Line << Column;
515 void BackendConsumer::UnsupportedDiagHandler(
516 const llvm::DiagnosticInfoUnsupported &D) {
517 // We only support errors.
518 assert(D.getSeverity() == llvm::DS_Error);
521 unsigned Line, Column;
523 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
526 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
529 // If we were not able to translate the file:line:col information
530 // back to a SourceLocation, at least emit a note stating that
531 // we could not translate this location. This can happen in the
532 // case of #line directives.
533 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
534 << Filename << Line << Column;
537 void BackendConsumer::EmitOptimizationMessage(
538 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
539 // We only support warnings and remarks.
540 assert(D.getSeverity() == llvm::DS_Remark ||
541 D.getSeverity() == llvm::DS_Warning);
544 unsigned Line, Column;
545 bool BadDebugInfo = false;
546 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
550 raw_string_ostream MsgStream(Msg);
551 MsgStream << D.getMsg();
554 MsgStream << " (hotness: " << *D.getHotness() << ")";
556 Diags.Report(Loc, DiagID)
557 << AddFlagValue(D.getPassName())
561 // If we were not able to translate the file:line:col information
562 // back to a SourceLocation, at least emit a note stating that
563 // we could not translate this location. This can happen in the
564 // case of #line directives.
565 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
566 << Filename << Line << Column;
569 void BackendConsumer::OptimizationRemarkHandler(
570 const llvm::OptimizationRemark &D) {
571 // Optimization remarks are active only if the -Rpass flag has a regular
572 // expression that matches the name of the pass name in \p D.
573 if (CodeGenOpts.OptimizationRemarkPattern &&
574 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
575 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
578 void BackendConsumer::OptimizationRemarkHandler(
579 const llvm::OptimizationRemarkMissed &D) {
580 // Missed optimization remarks are active only if the -Rpass-missed
581 // flag has a regular expression that matches the name of the pass
583 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
584 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
585 EmitOptimizationMessage(D,
586 diag::remark_fe_backend_optimization_remark_missed);
589 void BackendConsumer::OptimizationRemarkHandler(
590 const llvm::OptimizationRemarkAnalysis &D) {
591 // Optimization analysis remarks are active if the pass name is set to
592 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
593 // regular expression that matches the name of the pass name in \p D.
595 if (D.shouldAlwaysPrint() ||
596 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
597 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
598 EmitOptimizationMessage(
599 D, diag::remark_fe_backend_optimization_remark_analysis);
602 void BackendConsumer::OptimizationRemarkHandler(
603 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
604 // Optimization analysis remarks are active if the pass name is set to
605 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
606 // regular expression that matches the name of the pass name in \p D.
608 if (D.shouldAlwaysPrint() ||
609 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
610 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
611 EmitOptimizationMessage(
612 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
615 void BackendConsumer::OptimizationRemarkHandler(
616 const llvm::OptimizationRemarkAnalysisAliasing &D) {
617 // Optimization analysis remarks are active if the pass name is set to
618 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
619 // regular expression that matches the name of the pass name in \p D.
621 if (D.shouldAlwaysPrint() ||
622 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
623 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
624 EmitOptimizationMessage(
625 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
628 void BackendConsumer::OptimizationFailureHandler(
629 const llvm::DiagnosticInfoOptimizationFailure &D) {
630 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
633 /// \brief This function is invoked when the backend needs
634 /// to report something to the user.
635 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
636 unsigned DiagID = diag::err_fe_inline_asm;
637 llvm::DiagnosticSeverity Severity = DI.getSeverity();
638 // Get the diagnostic ID based.
639 switch (DI.getKind()) {
640 case llvm::DK_InlineAsm:
641 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
643 ComputeDiagID(Severity, inline_asm, DiagID);
645 case llvm::DK_StackSize:
646 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
648 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
651 assert(CurLinkModule);
652 // FIXME: stop eating the warnings and notes.
653 if (Severity != DS_Error)
655 DiagID = diag::err_fe_cannot_link_module;
657 case llvm::DK_OptimizationRemark:
658 // Optimization remarks are always handled completely by this
659 // handler. There is no generic way of emitting them.
660 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
662 case llvm::DK_OptimizationRemarkMissed:
663 // Optimization remarks are always handled completely by this
664 // handler. There is no generic way of emitting them.
665 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
667 case llvm::DK_OptimizationRemarkAnalysis:
668 // Optimization remarks are always handled completely by this
669 // handler. There is no generic way of emitting them.
670 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
672 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
673 // Optimization remarks are always handled completely by this
674 // handler. There is no generic way of emitting them.
675 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
677 case llvm::DK_OptimizationRemarkAnalysisAliasing:
678 // Optimization remarks are always handled completely by this
679 // handler. There is no generic way of emitting them.
680 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
682 case llvm::DK_OptimizationFailure:
683 // Optimization failures are always handled completely by this
685 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
687 case llvm::DK_Unsupported:
688 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
691 // Plugin IDs are not bound to any value as they are set dynamically.
692 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
695 std::string MsgStorage;
697 raw_string_ostream Stream(MsgStorage);
698 DiagnosticPrinterRawOStream DP(Stream);
702 if (DiagID == diag::err_fe_cannot_link_module) {
703 Diags.Report(diag::err_fe_cannot_link_module)
704 << CurLinkModule->getModuleIdentifier() << MsgStorage;
708 // Report the backend message using the usual diagnostic mechanism.
710 Diags.Report(Loc, DiagID).AddString(MsgStorage);
714 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
715 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
716 OwnsVMContext(!_VMContext) {}
718 CodeGenAction::~CodeGenAction() {
724 bool CodeGenAction::hasIRSupport() const { return true; }
726 void CodeGenAction::EndSourceFileAction() {
727 // If the consumer creation failed, do nothing.
728 if (!getCompilerInstance().hasASTConsumer())
731 // Take back ownership of link modules we passed to consumer.
732 if (!LinkModules.empty())
733 BEConsumer->releaseLinkModules();
735 // Steal the module from the consumer.
736 TheModule = BEConsumer->takeModule();
739 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
740 return std::move(TheModule);
743 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
744 OwnsVMContext = false;
748 static std::unique_ptr<raw_pwrite_stream>
749 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
751 case Backend_EmitAssembly:
752 return CI.createDefaultOutputFile(false, InFile, "s");
754 return CI.createDefaultOutputFile(false, InFile, "ll");
756 return CI.createDefaultOutputFile(true, InFile, "bc");
757 case Backend_EmitNothing:
759 case Backend_EmitMCNull:
760 return CI.createNullOutputFile();
761 case Backend_EmitObj:
762 return CI.createDefaultOutputFile(true, InFile, "o");
765 llvm_unreachable("Invalid action!");
768 std::unique_ptr<ASTConsumer>
769 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
770 BackendAction BA = static_cast<BackendAction>(Act);
771 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
772 if (BA != Backend_EmitNothing && !OS)
775 // Load bitcode modules to link with, if we need to.
776 if (LinkModules.empty())
777 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
778 const std::string &LinkBCFile = I.second;
780 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
782 CI.getDiagnostics().Report(diag::err_cannot_open_file)
783 << LinkBCFile << BCBuf.getError().message();
788 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
789 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
791 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
792 CI.getDiagnostics().Report(diag::err_cannot_open_file)
793 << LinkBCFile << EIB.message();
798 addLinkModule(ModuleOrErr.get().release(), I.first);
801 CoverageSourceInfo *CoverageInfo = nullptr;
802 // Add the preprocessor callback only when the coverage mapping is generated.
803 if (CI.getCodeGenOpts().CoverageMapping) {
804 CoverageInfo = new CoverageSourceInfo;
805 CI.getPreprocessor().addPPCallbacks(
806 std::unique_ptr<PPCallbacks>(CoverageInfo));
809 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
810 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
811 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
812 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
813 std::move(OS), *VMContext, CoverageInfo));
814 BEConsumer = Result.get();
815 return std::move(Result);
818 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
820 unsigned LocCookie) {
821 SM.print(nullptr, llvm::errs());
823 auto Diags = static_cast<DiagnosticsEngine *>(Context);
825 switch (SM.getKind()) {
826 case llvm::SourceMgr::DK_Error:
827 DiagID = diag::err_fe_inline_asm;
829 case llvm::SourceMgr::DK_Warning:
830 DiagID = diag::warn_fe_inline_asm;
832 case llvm::SourceMgr::DK_Note:
833 DiagID = diag::note_fe_inline_asm;
837 Diags->Report(DiagID).AddString("cannot compile inline asm");
840 void CodeGenAction::ExecuteAction() {
841 // If this is an IR file, we have to treat it specially.
842 if (getCurrentFileKind() == IK_LLVM_IR) {
843 BackendAction BA = static_cast<BackendAction>(Act);
844 CompilerInstance &CI = getCompilerInstance();
845 std::unique_ptr<raw_pwrite_stream> OS =
846 GetOutputStream(CI, getCurrentFile(), BA);
847 if (BA != Backend_EmitNothing && !OS)
851 SourceManager &SM = CI.getSourceManager();
852 FileID FID = SM.getMainFileID();
853 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
857 // For ThinLTO backend invocations, ensure that the context
858 // merges types based on ODR identifiers.
859 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
860 VMContext->enableDebugTypeODRUniquing();
862 llvm::SMDiagnostic Err;
863 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
865 // Translate from the diagnostic info to the SourceManager location if
867 // TODO: Unify this with ConvertBackendLocation()
869 if (Err.getLineNo() > 0) {
870 assert(Err.getColumnNo() >= 0);
871 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
872 Err.getLineNo(), Err.getColumnNo() + 1);
875 // Strip off a leading diagnostic code if there is one.
876 StringRef Msg = Err.getMessage();
877 if (Msg.startswith("error: "))
881 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
883 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
886 const TargetOptions &TargetOpts = CI.getTargetOpts();
887 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
888 CI.getDiagnostics().Report(SourceLocation(),
889 diag::warn_fe_override_module)
890 << TargetOpts.Triple;
891 TheModule->setTargetTriple(TargetOpts.Triple);
894 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
895 MainFile->getMemBufferRef());
897 LLVMContext &Ctx = TheModule->getContext();
898 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
899 &CI.getDiagnostics());
901 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
902 CI.getLangOpts(), CI.getTarget().getDataLayout(),
903 TheModule.get(), BA, std::move(OS));
907 // Otherwise follow the normal AST path.
908 this->ASTFrontendAction::ExecuteAction();
913 void EmitAssemblyAction::anchor() { }
914 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
915 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
917 void EmitBCAction::anchor() { }
918 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
919 : CodeGenAction(Backend_EmitBC, _VMContext) {}
921 void EmitLLVMAction::anchor() { }
922 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
923 : CodeGenAction(Backend_EmitLL, _VMContext) {}
925 void EmitLLVMOnlyAction::anchor() { }
926 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
927 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
929 void EmitCodeGenOnlyAction::anchor() { }
930 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
931 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
933 void EmitObjAction::anchor() { }
934 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
935 : CodeGenAction(Backend_EmitObj, _VMContext) {}