1 //===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "clang/CodeGen/CodeGenAction.h"
10 #include "CodeGenModule.h"
11 #include "CoverageMappingGen.h"
12 #include "MacroPPCallbacks.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclGroup.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/CodeGen/BackendUtil.h"
21 #include "clang/CodeGen/ModuleBuilder.h"
22 #include "clang/Driver/DriverDiagnostic.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/IR/RemarkStreamer.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/Linker/Linker.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/YAMLTraits.h"
43 #include "llvm/Transforms/IPO/Internalize.h"
46 using namespace clang;
50 class BackendConsumer;
51 class ClangDiagnosticHandler final : public DiagnosticHandler {
53 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
54 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
56 bool handleDiagnostics(const DiagnosticInfo &DI) override;
58 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
59 return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
60 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
62 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
63 return (CodeGenOpts.OptimizationRemarkMissedPattern &&
64 CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
66 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
67 return (CodeGenOpts.OptimizationRemarkPattern &&
68 CodeGenOpts.OptimizationRemarkPattern->match(PassName));
71 bool isAnyRemarkEnabled() const override {
72 return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
73 CodeGenOpts.OptimizationRemarkMissedPattern ||
74 CodeGenOpts.OptimizationRemarkPattern);
78 const CodeGenOptions &CodeGenOpts;
79 BackendConsumer *BackendCon;
82 class BackendConsumer : public ASTConsumer {
83 using LinkModule = CodeGenAction::LinkModule;
85 virtual void anchor();
86 DiagnosticsEngine &Diags;
88 const HeaderSearchOptions &HeaderSearchOpts;
89 const CodeGenOptions &CodeGenOpts;
90 const TargetOptions &TargetOpts;
91 const LangOptions &LangOpts;
92 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
95 Timer LLVMIRGeneration;
96 unsigned LLVMIRGenerationRefCount;
98 /// True if we've finished generating IR. This prevents us from generating
99 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
100 /// can happen when Clang plugins trigger additional AST deserialization.
101 bool IRGenFinished = false;
103 std::unique_ptr<CodeGenerator> Gen;
105 SmallVector<LinkModule, 4> LinkModules;
107 // This is here so that the diagnostic printer knows the module a diagnostic
109 llvm::Module *CurLinkModule = nullptr;
112 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
113 const HeaderSearchOptions &HeaderSearchOpts,
114 const PreprocessorOptions &PPOpts,
115 const CodeGenOptions &CodeGenOpts,
116 const TargetOptions &TargetOpts,
117 const LangOptions &LangOpts, bool TimePasses,
118 const std::string &InFile,
119 SmallVector<LinkModule, 4> LinkModules,
120 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
121 CoverageSourceInfo *CoverageInfo = nullptr)
122 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
123 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
124 AsmOutStream(std::move(OS)), Context(nullptr),
125 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
126 LLVMIRGenerationRefCount(0),
127 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
128 CodeGenOpts, C, CoverageInfo)),
129 LinkModules(std::move(LinkModules)) {
130 FrontendTimesIsEnabled = TimePasses;
131 llvm::TimePassesIsEnabled = TimePasses;
133 llvm::Module *getModule() const { return Gen->GetModule(); }
134 std::unique_ptr<llvm::Module> takeModule() {
135 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
138 CodeGenerator *getCodeGenerator() { return Gen.get(); }
140 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
141 Gen->HandleCXXStaticMemberVarInstantiation(VD);
144 void Initialize(ASTContext &Ctx) override {
145 assert(!Context && "initialized multiple times");
149 if (FrontendTimesIsEnabled)
150 LLVMIRGeneration.startTimer();
152 Gen->Initialize(Ctx);
154 if (FrontendTimesIsEnabled)
155 LLVMIRGeneration.stopTimer();
158 bool HandleTopLevelDecl(DeclGroupRef D) override {
159 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
160 Context->getSourceManager(),
161 "LLVM IR generation of declaration");
164 if (FrontendTimesIsEnabled) {
165 LLVMIRGenerationRefCount += 1;
166 if (LLVMIRGenerationRefCount == 1)
167 LLVMIRGeneration.startTimer();
170 Gen->HandleTopLevelDecl(D);
172 if (FrontendTimesIsEnabled) {
173 LLVMIRGenerationRefCount -= 1;
174 if (LLVMIRGenerationRefCount == 0)
175 LLVMIRGeneration.stopTimer();
181 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
182 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
183 Context->getSourceManager(),
184 "LLVM IR generation of inline function");
185 if (FrontendTimesIsEnabled)
186 LLVMIRGeneration.startTimer();
188 Gen->HandleInlineFunctionDefinition(D);
190 if (FrontendTimesIsEnabled)
191 LLVMIRGeneration.stopTimer();
194 void HandleInterestingDecl(DeclGroupRef D) override {
195 // Ignore interesting decls from the AST reader after IRGen is finished.
197 HandleTopLevelDecl(D);
200 // Links each entry in LinkModules into our module. Returns true on error.
201 bool LinkInModules() {
202 for (auto &LM : LinkModules) {
203 if (LM.PropagateAttrs)
204 for (Function &F : *LM.Module)
205 Gen->CGM().AddDefaultFnAttrs(F);
207 CurLinkModule = LM.Module.get();
210 if (LM.Internalize) {
211 Err = Linker::linkModules(
212 *getModule(), std::move(LM.Module), LM.LinkFlags,
213 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
214 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
215 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
219 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
226 return false; // success
229 void HandleTranslationUnit(ASTContext &C) override {
231 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
232 if (FrontendTimesIsEnabled) {
233 LLVMIRGenerationRefCount += 1;
234 if (LLVMIRGenerationRefCount == 1)
235 LLVMIRGeneration.startTimer();
238 Gen->HandleTranslationUnit(C);
240 if (FrontendTimesIsEnabled) {
241 LLVMIRGenerationRefCount -= 1;
242 if (LLVMIRGenerationRefCount == 0)
243 LLVMIRGeneration.stopTimer();
246 IRGenFinished = true;
249 // Silently ignore if we weren't initialized for some reason.
253 // Install an inline asm handler so that diagnostics get printed through
254 // our diagnostics hooks.
255 LLVMContext &Ctx = getModule()->getContext();
256 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
257 Ctx.getInlineAsmDiagnosticHandler();
258 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
259 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
261 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
262 Ctx.getDiagnosticHandler();
263 Ctx.setDiagnosticHandler(llvm::make_unique<ClangDiagnosticHandler>(
266 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
267 setupOptimizationRemarks(Ctx, CodeGenOpts.OptRecordFile,
268 CodeGenOpts.OptRecordPasses,
269 CodeGenOpts.OptRecordFormat,
270 CodeGenOpts.DiagnosticsWithHotness,
271 CodeGenOpts.DiagnosticsHotnessThreshold);
273 if (Error E = OptRecordFileOrErr.takeError()) {
276 [&](const RemarkSetupFileError &E) {
277 Diags.Report(diag::err_cannot_open_file)
278 << CodeGenOpts.OptRecordFile << E.message();
280 [&](const RemarkSetupPatternError &E) {
281 Diags.Report(diag::err_drv_optimization_remark_pattern)
282 << E.message() << CodeGenOpts.OptRecordPasses;
284 [&](const RemarkSetupFormatError &E) {
285 Diags.Report(diag::err_drv_optimization_remark_format)
286 << CodeGenOpts.OptRecordFormat;
290 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
291 std::move(*OptRecordFileOrErr);
294 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
295 Ctx.setDiagnosticsHotnessRequested(true);
297 // Link each LinkModule into our module.
301 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
303 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
304 LangOpts, C.getTargetInfo().getDataLayout(),
305 getModule(), Action, std::move(AsmOutStream));
307 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
309 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
312 OptRecordFile->keep();
315 void HandleTagDeclDefinition(TagDecl *D) override {
316 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
317 Context->getSourceManager(),
318 "LLVM IR generation of declaration");
319 Gen->HandleTagDeclDefinition(D);
322 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
323 Gen->HandleTagDeclRequiredDefinition(D);
326 void CompleteTentativeDefinition(VarDecl *D) override {
327 Gen->CompleteTentativeDefinition(D);
330 void AssignInheritanceModel(CXXRecordDecl *RD) override {
331 Gen->AssignInheritanceModel(RD);
334 void HandleVTable(CXXRecordDecl *RD) override {
335 Gen->HandleVTable(RD);
338 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
339 unsigned LocCookie) {
340 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
341 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
344 /// Get the best possible source location to represent a diagnostic that
345 /// may have associated debug info.
347 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
348 bool &BadDebugInfo, StringRef &Filename,
349 unsigned &Line, unsigned &Column) const;
351 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
352 SourceLocation LocCookie);
354 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
355 /// Specialized handler for InlineAsm diagnostic.
356 /// \return True if the diagnostic has been successfully reported, false
358 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
359 /// Specialized handler for StackSize diagnostic.
360 /// \return True if the diagnostic has been successfully reported, false
362 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
363 /// Specialized handler for unsupported backend feature diagnostic.
364 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
365 /// Specialized handlers for optimization remarks.
366 /// Note that these handlers only accept remarks and they always handle
368 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
371 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
372 void OptimizationRemarkHandler(
373 const llvm::OptimizationRemarkAnalysisFPCommute &D);
374 void OptimizationRemarkHandler(
375 const llvm::OptimizationRemarkAnalysisAliasing &D);
376 void OptimizationFailureHandler(
377 const llvm::DiagnosticInfoOptimizationFailure &D);
380 void BackendConsumer::anchor() {}
383 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
384 BackendCon->DiagnosticHandlerImpl(DI);
388 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
389 /// buffer to be a valid FullSourceLoc.
390 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
391 SourceManager &CSM) {
392 // Get both the clang and llvm source managers. The location is relative to
393 // a memory buffer that the LLVM Source Manager is handling, we need to add
394 // a copy to the Clang source manager.
395 const llvm::SourceMgr &LSM = *D.getSourceMgr();
397 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
398 // already owns its one and clang::SourceManager wants to own its one.
399 const MemoryBuffer *LBuf =
400 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
402 // Create the copy and transfer ownership to clang::SourceManager.
403 // TODO: Avoid copying files into memory.
404 std::unique_ptr<llvm::MemoryBuffer> CBuf =
405 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
406 LBuf->getBufferIdentifier());
407 // FIXME: Keep a file ID map instead of creating new IDs for each location.
408 FileID FID = CSM.createFileID(std::move(CBuf));
410 // Translate the offset into the file.
411 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
412 SourceLocation NewLoc =
413 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
414 return FullSourceLoc(NewLoc, CSM);
418 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
419 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
420 /// the temporary memory buffer that the inline asm parser has set up.
421 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
422 SourceLocation LocCookie) {
423 // There are a couple of different kinds of errors we could get here. First,
424 // we re-format the SMDiagnostic in terms of a clang diagnostic.
426 // Strip "error: " off the start of the message string.
427 StringRef Message = D.getMessage();
428 if (Message.startswith("error: "))
429 Message = Message.substr(7);
431 // If the SMDiagnostic has an inline asm source location, translate it.
433 if (D.getLoc() != SMLoc())
434 Loc = ConvertBackendLocation(D, Context->getSourceManager());
437 switch (D.getKind()) {
438 case llvm::SourceMgr::DK_Error:
439 DiagID = diag::err_fe_inline_asm;
441 case llvm::SourceMgr::DK_Warning:
442 DiagID = diag::warn_fe_inline_asm;
444 case llvm::SourceMgr::DK_Note:
445 DiagID = diag::note_fe_inline_asm;
447 case llvm::SourceMgr::DK_Remark:
448 llvm_unreachable("remarks unexpected");
450 // If this problem has clang-level source location information, report the
451 // issue in the source with a note showing the instantiated
453 if (LocCookie.isValid()) {
454 Diags.Report(LocCookie, DiagID).AddString(Message);
456 if (D.getLoc().isValid()) {
457 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
458 // Convert the SMDiagnostic ranges into SourceRange and attach them
459 // to the diagnostic.
460 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
461 unsigned Column = D.getColumnNo();
462 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
463 Loc.getLocWithOffset(Range.second - Column));
469 // Otherwise, report the backend issue as occurring in the generated .s file.
470 // If Loc is invalid, we still need to report the issue, it just gets no
472 Diags.Report(Loc, DiagID).AddString(Message);
475 #define ComputeDiagID(Severity, GroupName, DiagID) \
477 switch (Severity) { \
478 case llvm::DS_Error: \
479 DiagID = diag::err_fe_##GroupName; \
481 case llvm::DS_Warning: \
482 DiagID = diag::warn_fe_##GroupName; \
484 case llvm::DS_Remark: \
485 llvm_unreachable("'remark' severity not expected"); \
487 case llvm::DS_Note: \
488 DiagID = diag::note_fe_##GroupName; \
493 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
495 switch (Severity) { \
496 case llvm::DS_Error: \
497 DiagID = diag::err_fe_##GroupName; \
499 case llvm::DS_Warning: \
500 DiagID = diag::warn_fe_##GroupName; \
502 case llvm::DS_Remark: \
503 DiagID = diag::remark_fe_##GroupName; \
505 case llvm::DS_Note: \
506 DiagID = diag::note_fe_##GroupName; \
512 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
514 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
515 std::string Message = D.getMsgStr().str();
517 // If this problem has clang-level source location information, report the
518 // issue as being a problem in the source with a note showing the instantiated
520 SourceLocation LocCookie =
521 SourceLocation::getFromRawEncoding(D.getLocCookie());
522 if (LocCookie.isValid())
523 Diags.Report(LocCookie, DiagID).AddString(Message);
525 // Otherwise, report the backend diagnostic as occurring in the generated
527 // If Loc is invalid, we still need to report the diagnostic, it just gets
530 Diags.Report(Loc, DiagID).AddString(Message);
532 // We handled all the possible severities.
537 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
538 if (D.getSeverity() != llvm::DS_Warning)
539 // For now, the only support we have for StackSize diagnostic is warning.
540 // We do not know how to format other severities.
543 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
544 // FIXME: Shouldn't need to truncate to uint32_t
545 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
546 diag::warn_fe_frame_larger_than)
547 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
554 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
555 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
556 StringRef &Filename, unsigned &Line, unsigned &Column) const {
557 SourceManager &SourceMgr = Context->getSourceManager();
558 FileManager &FileMgr = SourceMgr.getFileManager();
559 SourceLocation DILoc;
561 if (D.isLocationAvailable()) {
562 D.getLocation(Filename, Line, Column);
564 const FileEntry *FE = FileMgr.getFile(Filename);
566 FE = FileMgr.getFile(D.getAbsolutePath());
568 // If -gcolumn-info was not used, Column will be 0. This upsets the
569 // source manager, so pass 1 if Column is not set.
570 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
573 BadDebugInfo = DILoc.isInvalid();
576 // If a location isn't available, try to approximate it using the associated
577 // function definition. We use the definition's right brace to differentiate
578 // from diagnostics that genuinely relate to the function itself.
579 FullSourceLoc Loc(DILoc, SourceMgr);
581 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
582 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
584 if (DILoc.isInvalid() && D.isLocationAvailable())
585 // If we were not able to translate the file:line:col information
586 // back to a SourceLocation, at least emit a note stating that
587 // we could not translate this location. This can happen in the
588 // case of #line directives.
589 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
590 << Filename << Line << Column;
595 void BackendConsumer::UnsupportedDiagHandler(
596 const llvm::DiagnosticInfoUnsupported &D) {
597 // We only support errors.
598 assert(D.getSeverity() == llvm::DS_Error);
601 unsigned Line, Column;
602 bool BadDebugInfo = false;
604 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
606 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
609 // If we were not able to translate the file:line:col information
610 // back to a SourceLocation, at least emit a note stating that
611 // we could not translate this location. This can happen in the
612 // case of #line directives.
613 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
614 << Filename << Line << Column;
617 void BackendConsumer::EmitOptimizationMessage(
618 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
619 // We only support warnings and remarks.
620 assert(D.getSeverity() == llvm::DS_Remark ||
621 D.getSeverity() == llvm::DS_Warning);
624 unsigned Line, Column;
625 bool BadDebugInfo = false;
627 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
630 raw_string_ostream MsgStream(Msg);
631 MsgStream << D.getMsg();
634 MsgStream << " (hotness: " << *D.getHotness() << ")";
636 Diags.Report(Loc, DiagID)
637 << AddFlagValue(D.getPassName())
641 // If we were not able to translate the file:line:col information
642 // back to a SourceLocation, at least emit a note stating that
643 // we could not translate this location. This can happen in the
644 // case of #line directives.
645 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
646 << Filename << Line << Column;
649 void BackendConsumer::OptimizationRemarkHandler(
650 const llvm::DiagnosticInfoOptimizationBase &D) {
651 // Without hotness information, don't show noisy remarks.
652 if (D.isVerbose() && !D.getHotness())
656 // Optimization remarks are active only if the -Rpass flag has a regular
657 // expression that matches the name of the pass name in \p D.
658 if (CodeGenOpts.OptimizationRemarkPattern &&
659 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
660 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
661 } else if (D.isMissed()) {
662 // Missed optimization remarks are active only if the -Rpass-missed
663 // flag has a regular expression that matches the name of the pass
665 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
666 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
667 EmitOptimizationMessage(
668 D, diag::remark_fe_backend_optimization_remark_missed);
670 assert(D.isAnalysis() && "Unknown remark type");
672 bool ShouldAlwaysPrint = false;
673 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
674 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
676 if (ShouldAlwaysPrint ||
677 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
678 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
679 EmitOptimizationMessage(
680 D, diag::remark_fe_backend_optimization_remark_analysis);
684 void BackendConsumer::OptimizationRemarkHandler(
685 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
686 // Optimization analysis remarks are active if the pass name is set to
687 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
688 // regular expression that matches the name of the pass name in \p D.
690 if (D.shouldAlwaysPrint() ||
691 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
692 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
693 EmitOptimizationMessage(
694 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
697 void BackendConsumer::OptimizationRemarkHandler(
698 const llvm::OptimizationRemarkAnalysisAliasing &D) {
699 // Optimization analysis remarks are active if the pass name is set to
700 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
701 // regular expression that matches the name of the pass name in \p D.
703 if (D.shouldAlwaysPrint() ||
704 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
705 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
706 EmitOptimizationMessage(
707 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
710 void BackendConsumer::OptimizationFailureHandler(
711 const llvm::DiagnosticInfoOptimizationFailure &D) {
712 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
715 /// This function is invoked when the backend needs
716 /// to report something to the user.
717 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
718 unsigned DiagID = diag::err_fe_inline_asm;
719 llvm::DiagnosticSeverity Severity = DI.getSeverity();
720 // Get the diagnostic ID based.
721 switch (DI.getKind()) {
722 case llvm::DK_InlineAsm:
723 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
725 ComputeDiagID(Severity, inline_asm, DiagID);
727 case llvm::DK_StackSize:
728 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
730 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
733 assert(CurLinkModule);
734 // FIXME: stop eating the warnings and notes.
735 if (Severity != DS_Error)
737 DiagID = diag::err_fe_cannot_link_module;
739 case llvm::DK_OptimizationRemark:
740 // Optimization remarks are always handled completely by this
741 // handler. There is no generic way of emitting them.
742 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
744 case llvm::DK_OptimizationRemarkMissed:
745 // Optimization remarks are always handled completely by this
746 // handler. There is no generic way of emitting them.
747 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
749 case llvm::DK_OptimizationRemarkAnalysis:
750 // Optimization remarks are always handled completely by this
751 // handler. There is no generic way of emitting them.
752 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
754 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
755 // Optimization remarks are always handled completely by this
756 // handler. There is no generic way of emitting them.
757 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
759 case llvm::DK_OptimizationRemarkAnalysisAliasing:
760 // Optimization remarks are always handled completely by this
761 // handler. There is no generic way of emitting them.
762 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
764 case llvm::DK_MachineOptimizationRemark:
765 // Optimization remarks are always handled completely by this
766 // handler. There is no generic way of emitting them.
767 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
769 case llvm::DK_MachineOptimizationRemarkMissed:
770 // Optimization remarks are always handled completely by this
771 // handler. There is no generic way of emitting them.
772 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
774 case llvm::DK_MachineOptimizationRemarkAnalysis:
775 // Optimization remarks are always handled completely by this
776 // handler. There is no generic way of emitting them.
777 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
779 case llvm::DK_OptimizationFailure:
780 // Optimization failures are always handled completely by this
782 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
784 case llvm::DK_Unsupported:
785 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
788 // Plugin IDs are not bound to any value as they are set dynamically.
789 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
792 std::string MsgStorage;
794 raw_string_ostream Stream(MsgStorage);
795 DiagnosticPrinterRawOStream DP(Stream);
799 if (DiagID == diag::err_fe_cannot_link_module) {
800 Diags.Report(diag::err_fe_cannot_link_module)
801 << CurLinkModule->getModuleIdentifier() << MsgStorage;
805 // Report the backend message using the usual diagnostic mechanism.
807 Diags.Report(Loc, DiagID).AddString(MsgStorage);
811 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
812 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
813 OwnsVMContext(!_VMContext) {}
815 CodeGenAction::~CodeGenAction() {
821 bool CodeGenAction::hasIRSupport() const { return true; }
823 void CodeGenAction::EndSourceFileAction() {
824 // If the consumer creation failed, do nothing.
825 if (!getCompilerInstance().hasASTConsumer())
828 // Steal the module from the consumer.
829 TheModule = BEConsumer->takeModule();
832 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
833 return std::move(TheModule);
836 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
837 OwnsVMContext = false;
841 static std::unique_ptr<raw_pwrite_stream>
842 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
844 case Backend_EmitAssembly:
845 return CI.createDefaultOutputFile(false, InFile, "s");
847 return CI.createDefaultOutputFile(false, InFile, "ll");
849 return CI.createDefaultOutputFile(true, InFile, "bc");
850 case Backend_EmitNothing:
852 case Backend_EmitMCNull:
853 return CI.createNullOutputFile();
854 case Backend_EmitObj:
855 return CI.createDefaultOutputFile(true, InFile, "o");
858 llvm_unreachable("Invalid action!");
861 std::unique_ptr<ASTConsumer>
862 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
863 BackendAction BA = static_cast<BackendAction>(Act);
864 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
866 OS = GetOutputStream(CI, InFile, BA);
868 if (BA != Backend_EmitNothing && !OS)
871 // Load bitcode modules to link with, if we need to.
872 if (LinkModules.empty())
873 for (const CodeGenOptions::BitcodeFileToLink &F :
874 CI.getCodeGenOpts().LinkBitcodeFiles) {
875 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
877 CI.getDiagnostics().Report(diag::err_cannot_open_file)
878 << F.Filename << BCBuf.getError().message();
883 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
884 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
886 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
887 CI.getDiagnostics().Report(diag::err_cannot_open_file)
888 << F.Filename << EIB.message();
893 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
894 F.Internalize, F.LinkFlags});
897 CoverageSourceInfo *CoverageInfo = nullptr;
898 // Add the preprocessor callback only when the coverage mapping is generated.
899 if (CI.getCodeGenOpts().CoverageMapping) {
900 CoverageInfo = new CoverageSourceInfo;
901 CI.getPreprocessor().addPPCallbacks(
902 std::unique_ptr<PPCallbacks>(CoverageInfo));
905 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
906 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
907 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
908 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
909 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
910 BEConsumer = Result.get();
912 // Enable generating macro debug info only when debug info is not disabled and
913 // also macro debug info is enabled.
914 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
915 CI.getCodeGenOpts().MacroDebugInfo) {
916 std::unique_ptr<PPCallbacks> Callbacks =
917 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
918 CI.getPreprocessor());
919 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
922 return std::move(Result);
925 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
927 unsigned LocCookie) {
928 SM.print(nullptr, llvm::errs());
930 auto Diags = static_cast<DiagnosticsEngine *>(Context);
932 switch (SM.getKind()) {
933 case llvm::SourceMgr::DK_Error:
934 DiagID = diag::err_fe_inline_asm;
936 case llvm::SourceMgr::DK_Warning:
937 DiagID = diag::warn_fe_inline_asm;
939 case llvm::SourceMgr::DK_Note:
940 DiagID = diag::note_fe_inline_asm;
942 case llvm::SourceMgr::DK_Remark:
943 llvm_unreachable("remarks unexpected");
946 Diags->Report(DiagID).AddString("cannot compile inline asm");
949 std::unique_ptr<llvm::Module>
950 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
951 CompilerInstance &CI = getCompilerInstance();
952 SourceManager &SM = CI.getSourceManager();
954 // For ThinLTO backend invocations, ensure that the context
955 // merges types based on ODR identifiers. We also need to read
956 // the correct module out of a multi-module bitcode file.
957 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
958 VMContext->enableDebugTypeODRUniquing();
960 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
962 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
963 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
964 CI.getDiagnostics().Report(DiagID) << EIB.message();
969 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
971 return DiagErrors(BMsOrErr.takeError());
972 BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
973 // We have nothing to do if the file contains no ThinLTO module. This is
974 // possible if ThinLTO compilation was not able to split module. Content of
975 // the file was already processed by indexing and will be passed to the
976 // linker using merged object file.
978 auto M = llvm::make_unique<llvm::Module>("empty", *VMContext);
979 M->setTargetTriple(CI.getTargetOpts().Triple);
982 Expected<std::unique_ptr<llvm::Module>> MOrErr =
983 Bm->parseModule(*VMContext);
985 return DiagErrors(MOrErr.takeError());
986 return std::move(*MOrErr);
989 llvm::SMDiagnostic Err;
990 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
993 // Translate from the diagnostic info to the SourceManager location if
995 // TODO: Unify this with ConvertBackendLocation()
997 if (Err.getLineNo() > 0) {
998 assert(Err.getColumnNo() >= 0);
999 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1000 Err.getLineNo(), Err.getColumnNo() + 1);
1003 // Strip off a leading diagnostic code if there is one.
1004 StringRef Msg = Err.getMessage();
1005 if (Msg.startswith("error: "))
1006 Msg = Msg.substr(7);
1009 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1011 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1015 void CodeGenAction::ExecuteAction() {
1016 // If this is an IR file, we have to treat it specially.
1017 if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
1018 BackendAction BA = static_cast<BackendAction>(Act);
1019 CompilerInstance &CI = getCompilerInstance();
1020 std::unique_ptr<raw_pwrite_stream> OS =
1021 GetOutputStream(CI, getCurrentFile(), BA);
1022 if (BA != Backend_EmitNothing && !OS)
1026 SourceManager &SM = CI.getSourceManager();
1027 FileID FID = SM.getMainFileID();
1028 const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
1032 TheModule = loadModule(*MainFile);
1036 const TargetOptions &TargetOpts = CI.getTargetOpts();
1037 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1038 CI.getDiagnostics().Report(SourceLocation(),
1039 diag::warn_fe_override_module)
1040 << TargetOpts.Triple;
1041 TheModule->setTargetTriple(TargetOpts.Triple);
1044 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
1045 MainFile->getMemBufferRef());
1047 LLVMContext &Ctx = TheModule->getContext();
1048 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1049 &CI.getDiagnostics());
1051 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1052 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
1053 CI.getTarget().getDataLayout(), TheModule.get(), BA,
1058 // Otherwise follow the normal AST path.
1059 this->ASTFrontendAction::ExecuteAction();
1064 void EmitAssemblyAction::anchor() { }
1065 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1066 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1068 void EmitBCAction::anchor() { }
1069 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1070 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1072 void EmitLLVMAction::anchor() { }
1073 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1074 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1076 void EmitLLVMOnlyAction::anchor() { }
1077 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1078 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1080 void EmitCodeGenOnlyAction::anchor() { }
1081 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1082 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1084 void EmitObjAction::anchor() { }
1085 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1086 : CodeGenAction(Backend_EmitObj, _VMContext) {}