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/DiagnosticFrontend.h"
18 #include "clang/Basic/FileManager.h"
19 #include "clang/Basic/LangStandard.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/CodeGen/BackendUtil.h"
23 #include "clang/CodeGen/ModuleBuilder.h"
24 #include "clang/Driver/DriverDiagnostic.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/FrontendDiagnostic.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "llvm/Bitcode/BitcodeReader.h"
29 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/LLVMRemarkStreamer.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/Linker/Linker.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TimeProfiler.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Support/YAMLTraits.h"
46 #include "llvm/Transforms/IPO/Internalize.h"
49 using namespace clang;
53 class BackendConsumer;
54 class ClangDiagnosticHandler final : public DiagnosticHandler {
56 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
57 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
59 bool handleDiagnostics(const DiagnosticInfo &DI) override;
61 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
62 return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
63 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
65 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
66 return (CodeGenOpts.OptimizationRemarkMissedPattern &&
67 CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
69 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
70 return (CodeGenOpts.OptimizationRemarkPattern &&
71 CodeGenOpts.OptimizationRemarkPattern->match(PassName));
74 bool isAnyRemarkEnabled() const override {
75 return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
76 CodeGenOpts.OptimizationRemarkMissedPattern ||
77 CodeGenOpts.OptimizationRemarkPattern);
81 const CodeGenOptions &CodeGenOpts;
82 BackendConsumer *BackendCon;
85 static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
86 const CodeGenOptions CodeGenOpts) {
89 [&](const LLVMRemarkSetupFileError &E) {
90 Diags.Report(diag::err_cannot_open_file)
91 << CodeGenOpts.OptRecordFile << E.message();
93 [&](const LLVMRemarkSetupPatternError &E) {
94 Diags.Report(diag::err_drv_optimization_remark_pattern)
95 << E.message() << CodeGenOpts.OptRecordPasses;
97 [&](const LLVMRemarkSetupFormatError &E) {
98 Diags.Report(diag::err_drv_optimization_remark_format)
99 << CodeGenOpts.OptRecordFormat;
103 class BackendConsumer : public ASTConsumer {
104 using LinkModule = CodeGenAction::LinkModule;
106 virtual void anchor();
107 DiagnosticsEngine &Diags;
108 BackendAction Action;
109 const HeaderSearchOptions &HeaderSearchOpts;
110 const CodeGenOptions &CodeGenOpts;
111 const TargetOptions &TargetOpts;
112 const LangOptions &LangOpts;
113 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
116 Timer LLVMIRGeneration;
117 unsigned LLVMIRGenerationRefCount;
119 /// True if we've finished generating IR. This prevents us from generating
120 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
121 /// can happen when Clang plugins trigger additional AST deserialization.
122 bool IRGenFinished = false;
124 std::unique_ptr<CodeGenerator> Gen;
126 SmallVector<LinkModule, 4> LinkModules;
128 // This is here so that the diagnostic printer knows the module a diagnostic
130 llvm::Module *CurLinkModule = nullptr;
133 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
134 const HeaderSearchOptions &HeaderSearchOpts,
135 const PreprocessorOptions &PPOpts,
136 const CodeGenOptions &CodeGenOpts,
137 const TargetOptions &TargetOpts,
138 const LangOptions &LangOpts, bool TimePasses,
139 const std::string &InFile,
140 SmallVector<LinkModule, 4> LinkModules,
141 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
142 CoverageSourceInfo *CoverageInfo = nullptr)
143 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
144 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
145 AsmOutStream(std::move(OS)), Context(nullptr),
146 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
147 LLVMIRGenerationRefCount(0),
148 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
149 CodeGenOpts, C, CoverageInfo)),
150 LinkModules(std::move(LinkModules)) {
151 FrontendTimesIsEnabled = TimePasses;
152 llvm::TimePassesIsEnabled = TimePasses;
155 // This constructor is used in installing an empty BackendConsumer
156 // to use the clang diagnostic handler for IR input files. It avoids
157 // initializing the OS field.
158 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
159 const HeaderSearchOptions &HeaderSearchOpts,
160 const PreprocessorOptions &PPOpts,
161 const CodeGenOptions &CodeGenOpts,
162 const TargetOptions &TargetOpts,
163 const LangOptions &LangOpts, bool TimePasses,
164 SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
165 CoverageSourceInfo *CoverageInfo = nullptr)
166 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
167 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
169 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
170 LLVMIRGenerationRefCount(0),
171 Gen(CreateLLVMCodeGen(Diags, "", HeaderSearchOpts, PPOpts,
172 CodeGenOpts, C, CoverageInfo)),
173 LinkModules(std::move(LinkModules)) {
174 FrontendTimesIsEnabled = TimePasses;
175 llvm::TimePassesIsEnabled = TimePasses;
177 llvm::Module *getModule() const { return Gen->GetModule(); }
178 std::unique_ptr<llvm::Module> takeModule() {
179 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
182 CodeGenerator *getCodeGenerator() { return Gen.get(); }
184 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
185 Gen->HandleCXXStaticMemberVarInstantiation(VD);
188 void Initialize(ASTContext &Ctx) override {
189 assert(!Context && "initialized multiple times");
193 if (FrontendTimesIsEnabled)
194 LLVMIRGeneration.startTimer();
196 Gen->Initialize(Ctx);
198 if (FrontendTimesIsEnabled)
199 LLVMIRGeneration.stopTimer();
202 bool HandleTopLevelDecl(DeclGroupRef D) override {
203 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
204 Context->getSourceManager(),
205 "LLVM IR generation of declaration");
208 if (FrontendTimesIsEnabled) {
209 LLVMIRGenerationRefCount += 1;
210 if (LLVMIRGenerationRefCount == 1)
211 LLVMIRGeneration.startTimer();
214 Gen->HandleTopLevelDecl(D);
216 if (FrontendTimesIsEnabled) {
217 LLVMIRGenerationRefCount -= 1;
218 if (LLVMIRGenerationRefCount == 0)
219 LLVMIRGeneration.stopTimer();
225 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
226 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
227 Context->getSourceManager(),
228 "LLVM IR generation of inline function");
229 if (FrontendTimesIsEnabled)
230 LLVMIRGeneration.startTimer();
232 Gen->HandleInlineFunctionDefinition(D);
234 if (FrontendTimesIsEnabled)
235 LLVMIRGeneration.stopTimer();
238 void HandleInterestingDecl(DeclGroupRef D) override {
239 // Ignore interesting decls from the AST reader after IRGen is finished.
241 HandleTopLevelDecl(D);
244 // Links each entry in LinkModules into our module. Returns true on error.
245 bool LinkInModules() {
246 for (auto &LM : LinkModules) {
247 if (LM.PropagateAttrs)
248 for (Function &F : *LM.Module)
249 Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
251 CurLinkModule = LM.Module.get();
254 if (LM.Internalize) {
255 Err = Linker::linkModules(
256 *getModule(), std::move(LM.Module), LM.LinkFlags,
257 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
258 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
259 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
263 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
270 return false; // success
273 void HandleTranslationUnit(ASTContext &C) override {
275 llvm::TimeTraceScope TimeScope("Frontend");
276 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
277 if (FrontendTimesIsEnabled) {
278 LLVMIRGenerationRefCount += 1;
279 if (LLVMIRGenerationRefCount == 1)
280 LLVMIRGeneration.startTimer();
283 Gen->HandleTranslationUnit(C);
285 if (FrontendTimesIsEnabled) {
286 LLVMIRGenerationRefCount -= 1;
287 if (LLVMIRGenerationRefCount == 0)
288 LLVMIRGeneration.stopTimer();
291 IRGenFinished = true;
294 // Silently ignore if we weren't initialized for some reason.
298 // Install an inline asm handler so that diagnostics get printed through
299 // our diagnostics hooks.
300 LLVMContext &Ctx = getModule()->getContext();
301 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
302 Ctx.getInlineAsmDiagnosticHandler();
303 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
304 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
306 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
307 Ctx.getDiagnosticHandler();
308 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
311 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
312 setupLLVMOptimizationRemarks(
313 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
314 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
315 CodeGenOpts.DiagnosticsHotnessThreshold);
317 if (Error E = OptRecordFileOrErr.takeError()) {
318 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
322 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
323 std::move(*OptRecordFileOrErr);
326 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
327 Ctx.setDiagnosticsHotnessRequested(true);
329 // Link each LinkModule into our module.
333 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
335 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
336 LangOpts, C.getTargetInfo().getDataLayout(),
337 getModule(), Action, std::move(AsmOutStream));
339 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
341 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
344 OptRecordFile->keep();
347 void HandleTagDeclDefinition(TagDecl *D) override {
348 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
349 Context->getSourceManager(),
350 "LLVM IR generation of declaration");
351 Gen->HandleTagDeclDefinition(D);
354 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
355 Gen->HandleTagDeclRequiredDefinition(D);
358 void CompleteTentativeDefinition(VarDecl *D) override {
359 Gen->CompleteTentativeDefinition(D);
362 void CompleteExternalDeclaration(VarDecl *D) override {
363 Gen->CompleteExternalDeclaration(D);
366 void AssignInheritanceModel(CXXRecordDecl *RD) override {
367 Gen->AssignInheritanceModel(RD);
370 void HandleVTable(CXXRecordDecl *RD) override {
371 Gen->HandleVTable(RD);
374 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
375 unsigned LocCookie) {
376 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
377 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
380 /// Get the best possible source location to represent a diagnostic that
381 /// may have associated debug info.
383 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
384 bool &BadDebugInfo, StringRef &Filename,
385 unsigned &Line, unsigned &Column) const;
387 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
388 SourceLocation LocCookie);
390 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
391 /// Specialized handler for InlineAsm diagnostic.
392 /// \return True if the diagnostic has been successfully reported, false
394 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
395 /// Specialized handler for StackSize diagnostic.
396 /// \return True if the diagnostic has been successfully reported, false
398 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
399 /// Specialized handler for unsupported backend feature diagnostic.
400 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
401 /// Specialized handler for misexpect warnings.
402 /// Note that misexpect remarks are emitted through ORE
403 void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D);
404 /// Specialized handlers for optimization remarks.
405 /// Note that these handlers only accept remarks and they always handle
407 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
410 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
411 void OptimizationRemarkHandler(
412 const llvm::OptimizationRemarkAnalysisFPCommute &D);
413 void OptimizationRemarkHandler(
414 const llvm::OptimizationRemarkAnalysisAliasing &D);
415 void OptimizationFailureHandler(
416 const llvm::DiagnosticInfoOptimizationFailure &D);
419 void BackendConsumer::anchor() {}
422 bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
423 BackendCon->DiagnosticHandlerImpl(DI);
427 /// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
428 /// buffer to be a valid FullSourceLoc.
429 static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
430 SourceManager &CSM) {
431 // Get both the clang and llvm source managers. The location is relative to
432 // a memory buffer that the LLVM Source Manager is handling, we need to add
433 // a copy to the Clang source manager.
434 const llvm::SourceMgr &LSM = *D.getSourceMgr();
436 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
437 // already owns its one and clang::SourceManager wants to own its one.
438 const MemoryBuffer *LBuf =
439 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
441 // Create the copy and transfer ownership to clang::SourceManager.
442 // TODO: Avoid copying files into memory.
443 std::unique_ptr<llvm::MemoryBuffer> CBuf =
444 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
445 LBuf->getBufferIdentifier());
446 // FIXME: Keep a file ID map instead of creating new IDs for each location.
447 FileID FID = CSM.createFileID(std::move(CBuf));
449 // Translate the offset into the file.
450 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
451 SourceLocation NewLoc =
452 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
453 return FullSourceLoc(NewLoc, CSM);
457 /// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
458 /// error parsing inline asm. The SMDiagnostic indicates the error relative to
459 /// the temporary memory buffer that the inline asm parser has set up.
460 void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
461 SourceLocation LocCookie) {
462 // There are a couple of different kinds of errors we could get here. First,
463 // we re-format the SMDiagnostic in terms of a clang diagnostic.
465 // Strip "error: " off the start of the message string.
466 StringRef Message = D.getMessage();
467 if (Message.startswith("error: "))
468 Message = Message.substr(7);
470 // If the SMDiagnostic has an inline asm source location, translate it.
472 if (D.getLoc() != SMLoc())
473 Loc = ConvertBackendLocation(D, Context->getSourceManager());
476 switch (D.getKind()) {
477 case llvm::SourceMgr::DK_Error:
478 DiagID = diag::err_fe_inline_asm;
480 case llvm::SourceMgr::DK_Warning:
481 DiagID = diag::warn_fe_inline_asm;
483 case llvm::SourceMgr::DK_Note:
484 DiagID = diag::note_fe_inline_asm;
486 case llvm::SourceMgr::DK_Remark:
487 llvm_unreachable("remarks unexpected");
489 // If this problem has clang-level source location information, report the
490 // issue in the source with a note showing the instantiated
492 if (LocCookie.isValid()) {
493 Diags.Report(LocCookie, DiagID).AddString(Message);
495 if (D.getLoc().isValid()) {
496 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
497 // Convert the SMDiagnostic ranges into SourceRange and attach them
498 // to the diagnostic.
499 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
500 unsigned Column = D.getColumnNo();
501 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
502 Loc.getLocWithOffset(Range.second - Column));
508 // Otherwise, report the backend issue as occurring in the generated .s file.
509 // If Loc is invalid, we still need to report the issue, it just gets no
511 Diags.Report(Loc, DiagID).AddString(Message);
514 #define ComputeDiagID(Severity, GroupName, DiagID) \
516 switch (Severity) { \
517 case llvm::DS_Error: \
518 DiagID = diag::err_fe_##GroupName; \
520 case llvm::DS_Warning: \
521 DiagID = diag::warn_fe_##GroupName; \
523 case llvm::DS_Remark: \
524 llvm_unreachable("'remark' severity not expected"); \
526 case llvm::DS_Note: \
527 DiagID = diag::note_fe_##GroupName; \
532 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
534 switch (Severity) { \
535 case llvm::DS_Error: \
536 DiagID = diag::err_fe_##GroupName; \
538 case llvm::DS_Warning: \
539 DiagID = diag::warn_fe_##GroupName; \
541 case llvm::DS_Remark: \
542 DiagID = diag::remark_fe_##GroupName; \
544 case llvm::DS_Note: \
545 DiagID = diag::note_fe_##GroupName; \
551 BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
553 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
554 std::string Message = D.getMsgStr().str();
556 // If this problem has clang-level source location information, report the
557 // issue as being a problem in the source with a note showing the instantiated
559 SourceLocation LocCookie =
560 SourceLocation::getFromRawEncoding(D.getLocCookie());
561 if (LocCookie.isValid())
562 Diags.Report(LocCookie, DiagID).AddString(Message);
564 // Otherwise, report the backend diagnostic as occurring in the generated
566 // If Loc is invalid, we still need to report the diagnostic, it just gets
569 Diags.Report(Loc, DiagID).AddString(Message);
571 // We handled all the possible severities.
576 BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
577 if (D.getSeverity() != llvm::DS_Warning)
578 // For now, the only support we have for StackSize diagnostic is warning.
579 // We do not know how to format other severities.
582 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
583 // FIXME: Shouldn't need to truncate to uint32_t
584 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
585 diag::warn_fe_frame_larger_than)
586 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
593 const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
594 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
595 StringRef &Filename, unsigned &Line, unsigned &Column) const {
596 SourceManager &SourceMgr = Context->getSourceManager();
597 FileManager &FileMgr = SourceMgr.getFileManager();
598 SourceLocation DILoc;
600 if (D.isLocationAvailable()) {
601 D.getLocation(Filename, Line, Column);
603 auto FE = FileMgr.getFile(Filename);
605 FE = FileMgr.getFile(D.getAbsolutePath());
607 // If -gcolumn-info was not used, Column will be 0. This upsets the
608 // source manager, so pass 1 if Column is not set.
609 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
612 BadDebugInfo = DILoc.isInvalid();
615 // If a location isn't available, try to approximate it using the associated
616 // function definition. We use the definition's right brace to differentiate
617 // from diagnostics that genuinely relate to the function itself.
618 FullSourceLoc Loc(DILoc, SourceMgr);
620 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
621 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
623 if (DILoc.isInvalid() && D.isLocationAvailable())
624 // If we were not able to translate the file:line:col information
625 // back to a SourceLocation, at least emit a note stating that
626 // we could not translate this location. This can happen in the
627 // case of #line directives.
628 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
629 << Filename << Line << Column;
634 void BackendConsumer::UnsupportedDiagHandler(
635 const llvm::DiagnosticInfoUnsupported &D) {
636 // We only support warnings or errors.
637 assert(D.getSeverity() == llvm::DS_Error ||
638 D.getSeverity() == llvm::DS_Warning);
641 unsigned Line, Column;
642 bool BadDebugInfo = false;
645 raw_string_ostream MsgStream(Msg);
647 // Context will be nullptr for IR input files, we will construct the diag
648 // message from llvm::DiagnosticInfoUnsupported.
649 if (Context != nullptr) {
650 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
651 MsgStream << D.getMessage();
653 DiagnosticPrinterRawOStream DP(MsgStream);
657 auto DiagType = D.getSeverity() == llvm::DS_Error
658 ? diag::err_fe_backend_unsupported
659 : diag::warn_fe_backend_unsupported;
660 Diags.Report(Loc, DiagType) << MsgStream.str();
663 // If we were not able to translate the file:line:col information
664 // back to a SourceLocation, at least emit a note stating that
665 // we could not translate this location. This can happen in the
666 // case of #line directives.
667 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
668 << Filename << Line << Column;
671 void BackendConsumer::MisExpectDiagHandler(
672 const llvm::DiagnosticInfoMisExpect &D) {
674 unsigned Line, Column;
675 bool BadDebugInfo = false;
678 raw_string_ostream MsgStream(Msg);
679 DiagnosticPrinterRawOStream DP(MsgStream);
681 // Context will be nullptr for IR input files, we will construct the diag
682 // message from llvm::DiagnosticInfoMisExpect.
683 if (Context != nullptr) {
684 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
685 MsgStream << D.getMsg();
687 DiagnosticPrinterRawOStream DP(MsgStream);
690 Diags.Report(Loc, diag::warn_profile_data_misexpect) << MsgStream.str();
693 // If we were not able to translate the file:line:col information
694 // back to a SourceLocation, at least emit a note stating that
695 // we could not translate this location. This can happen in the
696 // case of #line directives.
697 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
698 << Filename << Line << Column;
701 void BackendConsumer::EmitOptimizationMessage(
702 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
703 // We only support warnings and remarks.
704 assert(D.getSeverity() == llvm::DS_Remark ||
705 D.getSeverity() == llvm::DS_Warning);
708 unsigned Line, Column;
709 bool BadDebugInfo = false;
712 raw_string_ostream MsgStream(Msg);
714 // Context will be nullptr for IR input files, we will construct the remark
715 // message from llvm::DiagnosticInfoOptimizationBase.
716 if (Context != nullptr) {
717 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
718 MsgStream << D.getMsg();
720 DiagnosticPrinterRawOStream DP(MsgStream);
725 MsgStream << " (hotness: " << *D.getHotness() << ")";
727 Diags.Report(Loc, DiagID)
728 << AddFlagValue(D.getPassName())
732 // If we were not able to translate the file:line:col information
733 // back to a SourceLocation, at least emit a note stating that
734 // we could not translate this location. This can happen in the
735 // case of #line directives.
736 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
737 << Filename << Line << Column;
740 void BackendConsumer::OptimizationRemarkHandler(
741 const llvm::DiagnosticInfoOptimizationBase &D) {
742 // Without hotness information, don't show noisy remarks.
743 if (D.isVerbose() && !D.getHotness())
747 // Optimization remarks are active only if the -Rpass flag has a regular
748 // expression that matches the name of the pass name in \p D.
749 if (CodeGenOpts.OptimizationRemarkPattern &&
750 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
751 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
752 } else if (D.isMissed()) {
753 // Missed optimization remarks are active only if the -Rpass-missed
754 // flag has a regular expression that matches the name of the pass
756 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
757 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
758 EmitOptimizationMessage(
759 D, diag::remark_fe_backend_optimization_remark_missed);
761 assert(D.isAnalysis() && "Unknown remark type");
763 bool ShouldAlwaysPrint = false;
764 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
765 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
767 if (ShouldAlwaysPrint ||
768 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
769 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
770 EmitOptimizationMessage(
771 D, diag::remark_fe_backend_optimization_remark_analysis);
775 void BackendConsumer::OptimizationRemarkHandler(
776 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
777 // Optimization analysis remarks are active if the pass name is set to
778 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
779 // regular expression that matches the name of the pass name in \p D.
781 if (D.shouldAlwaysPrint() ||
782 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
783 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
784 EmitOptimizationMessage(
785 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
788 void BackendConsumer::OptimizationRemarkHandler(
789 const llvm::OptimizationRemarkAnalysisAliasing &D) {
790 // Optimization analysis remarks are active if the pass name is set to
791 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
792 // regular expression that matches the name of the pass name in \p D.
794 if (D.shouldAlwaysPrint() ||
795 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
796 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
797 EmitOptimizationMessage(
798 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
801 void BackendConsumer::OptimizationFailureHandler(
802 const llvm::DiagnosticInfoOptimizationFailure &D) {
803 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
806 /// This function is invoked when the backend needs
807 /// to report something to the user.
808 void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
809 unsigned DiagID = diag::err_fe_inline_asm;
810 llvm::DiagnosticSeverity Severity = DI.getSeverity();
811 // Get the diagnostic ID based.
812 switch (DI.getKind()) {
813 case llvm::DK_InlineAsm:
814 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
816 ComputeDiagID(Severity, inline_asm, DiagID);
818 case llvm::DK_StackSize:
819 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
821 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
824 assert(CurLinkModule);
825 // FIXME: stop eating the warnings and notes.
826 if (Severity != DS_Error)
828 DiagID = diag::err_fe_cannot_link_module;
830 case llvm::DK_OptimizationRemark:
831 // Optimization remarks are always handled completely by this
832 // handler. There is no generic way of emitting them.
833 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
835 case llvm::DK_OptimizationRemarkMissed:
836 // Optimization remarks are always handled completely by this
837 // handler. There is no generic way of emitting them.
838 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
840 case llvm::DK_OptimizationRemarkAnalysis:
841 // Optimization remarks are always handled completely by this
842 // handler. There is no generic way of emitting them.
843 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
845 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
846 // Optimization remarks are always handled completely by this
847 // handler. There is no generic way of emitting them.
848 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
850 case llvm::DK_OptimizationRemarkAnalysisAliasing:
851 // Optimization remarks are always handled completely by this
852 // handler. There is no generic way of emitting them.
853 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
855 case llvm::DK_MachineOptimizationRemark:
856 // Optimization remarks are always handled completely by this
857 // handler. There is no generic way of emitting them.
858 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
860 case llvm::DK_MachineOptimizationRemarkMissed:
861 // Optimization remarks are always handled completely by this
862 // handler. There is no generic way of emitting them.
863 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
865 case llvm::DK_MachineOptimizationRemarkAnalysis:
866 // Optimization remarks are always handled completely by this
867 // handler. There is no generic way of emitting them.
868 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
870 case llvm::DK_OptimizationFailure:
871 // Optimization failures are always handled completely by this
873 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
875 case llvm::DK_Unsupported:
876 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
878 case llvm::DK_MisExpect:
879 MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
882 // Plugin IDs are not bound to any value as they are set dynamically.
883 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
886 std::string MsgStorage;
888 raw_string_ostream Stream(MsgStorage);
889 DiagnosticPrinterRawOStream DP(Stream);
893 if (DiagID == diag::err_fe_cannot_link_module) {
894 Diags.Report(diag::err_fe_cannot_link_module)
895 << CurLinkModule->getModuleIdentifier() << MsgStorage;
899 // Report the backend message using the usual diagnostic mechanism.
901 Diags.Report(Loc, DiagID).AddString(MsgStorage);
905 CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
906 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
907 OwnsVMContext(!_VMContext) {}
909 CodeGenAction::~CodeGenAction() {
915 bool CodeGenAction::hasIRSupport() const { return true; }
917 void CodeGenAction::EndSourceFileAction() {
918 // If the consumer creation failed, do nothing.
919 if (!getCompilerInstance().hasASTConsumer())
922 // Steal the module from the consumer.
923 TheModule = BEConsumer->takeModule();
926 std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
927 return std::move(TheModule);
930 llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
931 OwnsVMContext = false;
935 static std::unique_ptr<raw_pwrite_stream>
936 GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
938 case Backend_EmitAssembly:
939 return CI.createDefaultOutputFile(false, InFile, "s");
941 return CI.createDefaultOutputFile(false, InFile, "ll");
943 return CI.createDefaultOutputFile(true, InFile, "bc");
944 case Backend_EmitNothing:
946 case Backend_EmitMCNull:
947 return CI.createNullOutputFile();
948 case Backend_EmitObj:
949 return CI.createDefaultOutputFile(true, InFile, "o");
952 llvm_unreachable("Invalid action!");
955 std::unique_ptr<ASTConsumer>
956 CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
957 BackendAction BA = static_cast<BackendAction>(Act);
958 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
960 OS = GetOutputStream(CI, InFile, BA);
962 if (BA != Backend_EmitNothing && !OS)
965 // Load bitcode modules to link with, if we need to.
966 if (LinkModules.empty())
967 for (const CodeGenOptions::BitcodeFileToLink &F :
968 CI.getCodeGenOpts().LinkBitcodeFiles) {
969 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
971 CI.getDiagnostics().Report(diag::err_cannot_open_file)
972 << F.Filename << BCBuf.getError().message();
977 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
978 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
980 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
981 CI.getDiagnostics().Report(diag::err_cannot_open_file)
982 << F.Filename << EIB.message();
987 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
988 F.Internalize, F.LinkFlags});
991 CoverageSourceInfo *CoverageInfo = nullptr;
992 // Add the preprocessor callback only when the coverage mapping is generated.
993 if (CI.getCodeGenOpts().CoverageMapping) {
994 CoverageInfo = new CoverageSourceInfo;
995 CI.getPreprocessor().addPPCallbacks(
996 std::unique_ptr<PPCallbacks>(CoverageInfo));
999 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1000 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1001 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
1002 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, std::string(InFile),
1003 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
1004 BEConsumer = Result.get();
1006 // Enable generating macro debug info only when debug info is not disabled and
1007 // also macro debug info is enabled.
1008 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1009 CI.getCodeGenOpts().MacroDebugInfo) {
1010 std::unique_ptr<PPCallbacks> Callbacks =
1011 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1012 CI.getPreprocessor());
1013 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1016 return std::move(Result);
1019 static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
1021 unsigned LocCookie) {
1022 SM.print(nullptr, llvm::errs());
1024 auto Diags = static_cast<DiagnosticsEngine *>(Context);
1026 switch (SM.getKind()) {
1027 case llvm::SourceMgr::DK_Error:
1028 DiagID = diag::err_fe_inline_asm;
1030 case llvm::SourceMgr::DK_Warning:
1031 DiagID = diag::warn_fe_inline_asm;
1033 case llvm::SourceMgr::DK_Note:
1034 DiagID = diag::note_fe_inline_asm;
1036 case llvm::SourceMgr::DK_Remark:
1037 llvm_unreachable("remarks unexpected");
1040 Diags->Report(DiagID).AddString("cannot compile inline asm");
1043 std::unique_ptr<llvm::Module>
1044 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1045 CompilerInstance &CI = getCompilerInstance();
1046 SourceManager &SM = CI.getSourceManager();
1048 // For ThinLTO backend invocations, ensure that the context
1049 // merges types based on ODR identifiers. We also need to read
1050 // the correct module out of a multi-module bitcode file.
1051 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1052 VMContext->enableDebugTypeODRUniquing();
1054 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1056 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1057 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1058 CI.getDiagnostics().Report(DiagID) << EIB.message();
1063 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1065 return DiagErrors(BMsOrErr.takeError());
1066 BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
1067 // We have nothing to do if the file contains no ThinLTO module. This is
1068 // possible if ThinLTO compilation was not able to split module. Content of
1069 // the file was already processed by indexing and will be passed to the
1070 // linker using merged object file.
1072 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1073 M->setTargetTriple(CI.getTargetOpts().Triple);
1076 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1077 Bm->parseModule(*VMContext);
1079 return DiagErrors(MOrErr.takeError());
1080 return std::move(*MOrErr);
1083 llvm::SMDiagnostic Err;
1084 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1087 // Translate from the diagnostic info to the SourceManager location if
1089 // TODO: Unify this with ConvertBackendLocation()
1091 if (Err.getLineNo() > 0) {
1092 assert(Err.getColumnNo() >= 0);
1093 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1094 Err.getLineNo(), Err.getColumnNo() + 1);
1097 // Strip off a leading diagnostic code if there is one.
1098 StringRef Msg = Err.getMessage();
1099 if (Msg.startswith("error: "))
1100 Msg = Msg.substr(7);
1103 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1105 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1109 void CodeGenAction::ExecuteAction() {
1110 // If this is an IR file, we have to treat it specially.
1111 if (getCurrentFileKind().getLanguage() == Language::LLVM_IR) {
1112 BackendAction BA = static_cast<BackendAction>(Act);
1113 CompilerInstance &CI = getCompilerInstance();
1114 auto &CodeGenOpts = CI.getCodeGenOpts();
1115 auto &Diagnostics = CI.getDiagnostics();
1116 std::unique_ptr<raw_pwrite_stream> OS =
1117 GetOutputStream(CI, getCurrentFile(), BA);
1118 if (BA != Backend_EmitNothing && !OS)
1122 SourceManager &SM = CI.getSourceManager();
1123 FileID FID = SM.getMainFileID();
1124 const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
1128 TheModule = loadModule(*MainFile);
1132 const TargetOptions &TargetOpts = CI.getTargetOpts();
1133 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1134 Diagnostics.Report(SourceLocation(),
1135 diag::warn_fe_override_module)
1136 << TargetOpts.Triple;
1137 TheModule->setTargetTriple(TargetOpts.Triple);
1140 EmbedBitcode(TheModule.get(), CodeGenOpts,
1141 MainFile->getMemBufferRef());
1143 LLVMContext &Ctx = TheModule->getContext();
1144 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1147 // Set clang diagnostic handler. To do this we need to create a fake
1149 BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1150 CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
1151 CI.getTargetOpts(), CI.getLangOpts(),
1152 CI.getFrontendOpts().ShowTimers,
1153 std::move(LinkModules), *VMContext, nullptr);
1154 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1155 // true here because the valued names are needed for reading textual IR.
1156 Ctx.setDiscardValueNames(false);
1157 Ctx.setDiagnosticHandler(
1158 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1160 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
1161 setupLLVMOptimizationRemarks(
1162 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1163 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1164 CodeGenOpts.DiagnosticsHotnessThreshold);
1166 if (Error E = OptRecordFileOrErr.takeError()) {
1167 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1170 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1171 std::move(*OptRecordFileOrErr);
1173 EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1174 TargetOpts, CI.getLangOpts(),
1175 CI.getTarget().getDataLayout(), TheModule.get(), BA,
1179 OptRecordFile->keep();
1183 // Otherwise follow the normal AST path.
1184 this->ASTFrontendAction::ExecuteAction();
1189 void EmitAssemblyAction::anchor() { }
1190 EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1191 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1193 void EmitBCAction::anchor() { }
1194 EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1195 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1197 void EmitLLVMAction::anchor() { }
1198 EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1199 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1201 void EmitLLVMOnlyAction::anchor() { }
1202 EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1203 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1205 void EmitCodeGenOnlyAction::anchor() { }
1206 EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1207 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1209 void EmitObjAction::anchor() { }
1210 EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1211 : CodeGenAction(Backend_EmitObj, _VMContext) {}