31#include "llvm/ADT/Hashing.h"
32#include "llvm/ADT/ScopeExit.h"
33#include "llvm/Bitcode/BitcodeReader.h"
34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
35#include "llvm/Demangle/Demangle.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DiagnosticInfo.h"
38#include "llvm/IR/DiagnosticPrinter.h"
39#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/LLVMRemarkStreamer.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/PassTimingInfo.h"
44#include "llvm/IR/Verifier.h"
45#include "llvm/IRReader/IRReader.h"
46#include "llvm/LTO/LTOBackend.h"
47#include "llvm/Linker/Linker.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/SourceMgr.h"
51#include "llvm/Support/TimeProfiler.h"
52#include "llvm/Support/Timer.h"
53#include "llvm/Support/ToolOutputFile.h"
54#include "llvm/Transforms/IPO/Internalize.h"
55#include "llvm/Transforms/Utils/Cloning.h"
61#define DEBUG_TYPE "codegenaction"
68 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
73 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
76 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
79 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
83 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
84 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
85 CodeGenOpts.OptimizationRemark.hasValidPattern();
97 [&](
const LLVMRemarkSetupFileError &E) {
98 Diags.
Report(diag::err_cannot_open_file)
101 [&](
const LLVMRemarkSetupPatternError &E) {
102 Diags.
Report(diag::err_drv_optimization_remark_pattern)
105 [&](
const LLVMRemarkSetupFormatError &E) {
106 Diags.
Report(diag::err_drv_optimization_remark_format)
116 std::unique_ptr<raw_pwrite_stream> OS,
118 llvm::Module *CurLinkModule)
119 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
120 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
121 AsmOutStream(
std::move(OS)), FS(VFS), Action(Action),
123 LinkModules(
std::move(LinkModules)), CurLinkModule(CurLinkModule) {
124 TimerIsEnabled = CodeGenOpts.TimePasses;
125 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
126 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
127 if (CodeGenOpts.TimePasses)
128 LLVMIRGeneration.init(
"irgen",
"LLVM IR generation", CI.getTimerGroup());
132 return Gen->GetModule();
136 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
148 assert(!Context &&
"initialized multiple times");
153 LLVMIRGeneration.startTimer();
155 Gen->Initialize(Ctx);
158 LLVMIRGeneration.stopTimer();
163 Context->getSourceManager(),
164 "LLVM IR generation of declaration");
167 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
168 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
170 Gen->HandleTopLevelDecl(D);
172 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
173 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
180 Context->getSourceManager(),
181 "LLVM IR generation of inline function");
183 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
185 Gen->HandleInlineFunctionDefinition(D);
188 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
197 for (
auto &LM : LinkModules) {
198 assert(LM.Module &&
"LinkModule does not actually have a module");
200 if (LM.PropagateAttrs)
207 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
210 CurLinkModule = LM.Module.get();
213 if (LM.Internalize) {
214 Err = Linker::linkModules(
215 *M, std::move(LM.Module), LM.LinkFlags,
216 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
217 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
218 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
222 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
234 llvm::TimeTraceScope TimeScope(
"Frontend");
235 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
236 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
237 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
239 Gen->HandleTranslationUnit(
C);
241 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
242 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
249 LLVMContext &Ctx =
getModule()->getContext();
250 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
251 Ctx.getDiagnosticHandler();
252 llvm::scope_exit RestoreDiagnosticHandler(
253 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
254 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
257 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
258 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features,
","));
261 setupLLVMOptimizationRemarks(
262 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
263 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
264 CodeGenOpts.DiagnosticsHotnessThreshold);
266 if (
Error E = OptRecordFileOrErr.takeError()) {
271 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
273 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
274 llvm::driver::ProfileInstrKind::ProfileNone)
275 Ctx.setDiagnosticsHotnessRequested(
true);
277 if (CodeGenOpts.MisExpect) {
278 Ctx.setMisExpectWarningRequested(
true);
281 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
282 Ctx.setDiagnosticsMisExpectTolerance(
283 CodeGenOpts.DiagnosticsMisExpectTolerance);
290 for (
auto &F :
getModule()->functions()) {
291 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
292 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
295 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
299 if (CodeGenOpts.ClearASTBeforeBackend) {
300 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
308 C.getAllocator().Reset();
314 C.getTargetInfo().getDataLayoutString(),
getModule(),
315 Action, FS, std::move(AsmOutStream),
this);
318 OptRecordFile->keep();
323 Context->getSourceManager(),
324 "LLVM IR generation of declaration");
325 Gen->HandleTagDeclDefinition(D);
329 Gen->HandleTagDeclRequiredDefinition(D);
333 Gen->CompleteTentativeDefinition(D);
337 Gen->CompleteExternalDeclaration(D);
341 Gen->AssignInheritanceModel(RD);
345 Gen->HandleVTable(RD);
348void BackendConsumer::anchor() { }
353 BackendCon->DiagnosticHandlerImpl(DI);
364 const llvm::SourceMgr &LSM = *D.getSourceMgr();
368 const MemoryBuffer *LBuf =
369 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
373 std::unique_ptr<llvm::MemoryBuffer> CBuf =
374 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
375 LBuf->getBufferIdentifier());
380 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
386#define ComputeDiagID(Severity, GroupName, DiagID) \
388 switch (Severity) { \
389 case llvm::DS_Error: \
390 DiagID = diag::err_fe_##GroupName; \
392 case llvm::DS_Warning: \
393 DiagID = diag::warn_fe_##GroupName; \
395 case llvm::DS_Remark: \
396 llvm_unreachable("'remark' severity not expected"); \
398 case llvm::DS_Note: \
399 DiagID = diag::note_fe_##GroupName; \
404#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
406 switch (Severity) { \
407 case llvm::DS_Error: \
408 DiagID = diag::err_fe_##GroupName; \
410 case llvm::DS_Warning: \
411 DiagID = diag::warn_fe_##GroupName; \
413 case llvm::DS_Remark: \
414 DiagID = diag::remark_fe_##GroupName; \
416 case llvm::DS_Note: \
417 DiagID = diag::note_fe_##GroupName; \
423 const llvm::SMDiagnostic &D = DI.getSMDiag();
426 if (DI.isInlineAsmDiag())
434 D.print(
nullptr, llvm::errs());
435 Diags.Report(DiagID).AddString(
"cannot compile inline asm");
443 StringRef Message = D.getMessage();
444 (void)Message.consume_front(
"error: ");
448 if (D.getLoc() != SMLoc())
454 if (DI.isInlineAsmDiag()) {
458 Diags.Report(LocCookie, DiagID).AddString(Message);
460 if (D.getLoc().isValid()) {
464 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
465 unsigned Column = D.getColumnNo();
477 Diags.Report(Loc, DiagID).AddString(Message);
484 std::string Message = D.getMsgStr().str();
492 Diags.Report(LocCookie, DiagID).AddString(Message);
499 Diags.Report(Loc, DiagID).AddString(Message);
507 if (D.getSeverity() != llvm::DS_Warning)
516 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
517 << D.getStackSize() << D.getStackLimit()
518 << llvm::demangle(D.getFunction().getName());
523 const llvm::DiagnosticInfoResourceLimit &D) {
527 unsigned DiagID = diag::err_fe_backend_resource_limit;
528 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
530 Diags.Report(*Loc, DiagID)
531 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
532 << llvm::demangle(D.getFunction().getName());
537 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
538 StringRef &Filename,
unsigned &
Line,
unsigned &
Column)
const {
543 if (D.isLocationAvailable()) {
546 auto FE =
FileMgr.getOptionalFileRef(Filename);
548 FE =
FileMgr.getOptionalFileRef(D.getAbsolutePath());
567 if (DILoc.
isInvalid() && D.isLocationAvailable())
572 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
578std::optional<FullSourceLoc>
581 for (
const auto &Pair : ManglingFullSourceLocs) {
582 if (Pair.first == Hash)
589 const llvm::DiagnosticInfoUnsupported &D) {
591 assert(D.getSeverity() == llvm::DS_Error ||
592 D.getSeverity() == llvm::DS_Warning);
596 bool BadDebugInfo =
false;
599 raw_string_ostream MsgStream(Msg);
603 if (Context !=
nullptr) {
605 MsgStream << D.getMessage();
607 DiagnosticPrinterRawOStream DP(MsgStream);
611 auto DiagType = D.getSeverity() == llvm::DS_Error
612 ? diag::err_fe_backend_unsupported
613 : diag::warn_fe_backend_unsupported;
614 Diags.Report(Loc, DiagType) << Msg;
621 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
626 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
628 assert(D.getSeverity() == llvm::DS_Remark ||
629 D.getSeverity() == llvm::DS_Warning);
633 bool BadDebugInfo =
false;
636 raw_string_ostream MsgStream(Msg);
640 if (Context !=
nullptr) {
642 MsgStream << D.getMsg();
644 DiagnosticPrinterRawOStream DP(MsgStream);
649 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
651 Diags.Report(Loc, DiagID) <<
AddFlagValue(D.getPassName()) << Msg;
658 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
663 const llvm::DiagnosticInfoOptimizationBase &D) {
665 if (D.isVerbose() && !D.getHotness())
671 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
673 }
else if (D.isMissed()) {
677 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
679 D, diag::remark_fe_backend_optimization_remark_missed);
681 assert(D.isAnalysis() &&
"Unknown remark type");
683 bool ShouldAlwaysPrint =
false;
684 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
685 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
687 if (ShouldAlwaysPrint ||
688 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
690 D, diag::remark_fe_backend_optimization_remark_analysis);
695 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
700 if (D.shouldAlwaysPrint() ||
701 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
703 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
707 const llvm::OptimizationRemarkAnalysisAliasing &D) {
712 if (D.shouldAlwaysPrint() ||
713 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
715 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
719 const llvm::DiagnosticInfoOptimizationFailure &D) {
732 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
733 ? diag::err_fe_backend_error_attr
734 : diag::warn_fe_backend_warning_attr)
735 << llvm::demangle(D.getFunctionName()) << D.getNote();
737 if (!CodeGenOpts.ShowInliningChain)
744 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
745 Diags.Report(Loc, DiagID) << llvm::demangle(FuncName.str());
749 if (!D.getDebugInlineChain().empty()) {
752 for (
const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
756 Loc =
SM.translateFileLineCol(*FE, Info.Line,
757 Info.Column ? Info.Column : 1);
758 EmitNote(Loc, Info.FuncName, I == 0);
764 auto InliningDecisions = D.getInliningDecisions();
765 if (InliningDecisions.empty())
768 for (
const auto &[I, Entry] : llvm::enumerate(InliningDecisions)) {
771 EmitNote(Loc, Entry.first, I == 0);
776 Diags.Report(LocCookie, diag::note_fe_backend_inlining_debug_info);
780 const llvm::DiagnosticInfoMisExpect &D) {
783 bool BadDebugInfo =
false;
787 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
794 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
801 unsigned DiagID = diag::err_fe_inline_asm;
802 llvm::DiagnosticSeverity Severity = DI.getSeverity();
804 switch (DI.getKind()) {
805 case llvm::DK_InlineAsm:
810 case llvm::DK_SrcMgr:
813 case llvm::DK_StackSize:
818 case llvm::DK_ResourceLimit:
826 case llvm::DK_OptimizationRemark:
831 case llvm::DK_OptimizationRemarkMissed:
836 case llvm::DK_OptimizationRemarkAnalysis:
841 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
846 case llvm::DK_OptimizationRemarkAnalysisAliasing:
851 case llvm::DK_MachineOptimizationRemark:
856 case llvm::DK_MachineOptimizationRemarkMissed:
861 case llvm::DK_MachineOptimizationRemarkAnalysis:
866 case llvm::DK_OptimizationFailure:
871 case llvm::DK_Unsupported:
874 case llvm::DK_DontCall:
877 case llvm::DK_MisExpect:
885 std::string MsgStorage;
887 raw_string_ostream Stream(MsgStorage);
888 DiagnosticPrinterRawOStream DP(Stream);
892 if (DI.getKind() == DK_Linker) {
893 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
894 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
900 Diags.Report(Loc, DiagID).AddString(MsgStorage);
905 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
906 OwnsVMContext(!_VMContext) {}
915 if (!LinkModules.empty())
923 << F.Filename << BCBuf.getError().message();
929 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
931 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
932 CI.getDiagnostics().Report(diag::err_cannot_open_file)
933 << F.Filename << EIB.message();
938 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
939 F.Internalize, F.LinkFlags});
958 return std::move(TheModule);
962 OwnsVMContext =
false;
976static std::unique_ptr<raw_pwrite_stream>
993 llvm_unreachable(
"Invalid action!");
996std::unique_ptr<ASTConsumer>
1007 if (loadLinkModules(CI))
1018 InFile, std::move(OS), CoverageInfo));
1023 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1025 std::unique_ptr<PPCallbacks> Callbacks =
1026 std::make_unique<MacroPPCallbacks>(
BEConsumer->getCodeGenerator(),
1033 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1034 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1037 Consumers[1] = std::move(
Result);
1038 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1041 return std::move(
Result);
1044std::unique_ptr<llvm::Module>
1045CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1049 auto DiagErrors = [&](
Error E) -> std::unique_ptr<llvm::Module> {
1052 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1062 VMContext->enableDebugTypeODRUniquing();
1064 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1066 return DiagErrors(BMsOrErr.takeError());
1067 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1073 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1077 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1078 Bm->parseModule(*VMContext);
1080 return DiagErrors(MOrErr.takeError());
1081 return std::move(*MOrErr);
1085 if (loadLinkModules(CI))
1089 llvm::SMDiagnostic Err;
1090 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1093 std::string VerifierErr;
1094 raw_string_ostream VerifierErrStream(VerifierErr);
1095 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1105 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1106 if (BMsOrErr && BMsOrErr->size()) {
1107 std::unique_ptr<llvm::Module> FirstM;
1108 for (
auto &BM : *BMsOrErr) {
1109 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1110 BM.parseModule(*VMContext);
1112 return DiagErrors(MOrErr.takeError());
1114 LinkModules.push_back({std::move(*MOrErr),
false,
1117 FirstM = std::move(*MOrErr);
1124 consumeError(BMsOrErr.takeError());
1130 if (Err.getLineNo() > 0) {
1131 assert(Err.getColumnNo() >= 0);
1132 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1133 Err.getLineNo(), Err.getColumnNo() + 1);
1137 StringRef Msg = Err.getMessage();
1138 Msg.consume_front(
"error: ");
1158 std::unique_ptr<raw_pwrite_stream> OS =
1165 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1169 TheModule = loadModule(*MainFile);
1174 if (TheModule->getTargetTriple().str() != TargetOpts.
Triple) {
1175 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1177 TheModule->setTargetTriple(Triple(TargetOpts.
Triple));
1184 LLVMContext &Ctx = TheModule->getContext();
1190 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1191 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1197 std::move(LinkModules),
"",
nullptr,
nullptr,
1201 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1206 Ctx.setDiscardValueNames(
false);
1207 Ctx.setDiagnosticHandler(
1208 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1210 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1211 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1214 setupLLVMOptimizationRemarks(
1215 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1216 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1217 CodeGenOpts.DiagnosticsHotnessThreshold);
1219 if (
Error E = OptRecordFileOrErr.takeError()) {
1223 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1230 OptRecordFile->keep();
1235void EmitAssemblyAction::anchor() { }
1239void EmitBCAction::anchor() { }
1243void EmitLLVMAction::anchor() { }
1247void EmitLLVMOnlyAction::anchor() { }
1251void EmitCodeGenOnlyAction::anchor() { }
1255void EmitObjAction::anchor() { }
Defines the clang::ASTContext interface.
#define ComputeDiagID(Severity, GroupName, DiagID)
static std::unique_ptr< raw_pwrite_stream > GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action)
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D, SourceManager &CSM)
ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr buffer to be a valid FullS...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::FileManager interface and associated types.
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
llvm::Module * getModule() const
void CompleteExternalDeclaration(DeclaratorDecl *D) override
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
void OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D)
bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D)
Specialized handler for StackSize diagnostic.
void HandleVTable(CXXRecordDecl *RD) override
Callback involved at the end of a translation unit to notify the consumer that a vtable for the given...
void HandleTagDeclDefinition(TagDecl *D) override
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
bool HandleTopLevelDecl(DeclGroupRef D) override
HandleTopLevelDecl - Handle the specified top-level declaration.
void Initialize(ASTContext &Ctx) override
Initialize - This is called to initialize the consumer, providing the ASTContext.
void HandleInlineFunctionDefinition(FunctionDecl *D) override
This callback is invoked each time an inline (method or friend) function definition in a class is com...
void OptimizationFailureHandler(const llvm::DiagnosticInfoOptimizationFailure &D)
void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI)
This function is invoked when the backend needs to report something to the user.
void HandleTagDeclRequiredDefinition(const TagDecl *D) override
This callback is invoked the first time each TagDecl is required to be complete.
void HandleInterestingDecl(DeclGroupRef D) override
HandleInterestingDecl - Handle the specified interesting declaration.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
std::optional< FullSourceLoc > getFunctionSourceLocation(const llvm::Function &F) const
bool ResourceLimitDiagHandler(const llvm::DiagnosticInfoResourceLimit &D)
Specialized handler for ResourceLimit diagnostic.
std::unique_ptr< llvm::Module > takeModule()
void AssignInheritanceModel(CXXRecordDecl *RD) override
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)
Specialized handler for InlineAsm diagnostic.
bool LinkInModules(llvm::Module *M)
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
void DontCallDiagHandler(const llvm::DiagnosticInfoDontCall &D)
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
CodeGenerator * getCodeGenerator()
void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)
Specialized handler for diagnostics reported using SMDiagnostic.
BackendConsumer(CompilerInstance &CI, BackendAction Action, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, llvm::LLVMContext &C, SmallVector< LinkModule, 4 > LinkModules, StringRef InFile, std::unique_ptr< raw_pwrite_stream > OS, CoverageSourceInfo *CoverageInfo, llvm::Module *CurLinkModule=nullptr)
Represents a C++ struct/union/class.
bool isMissedOptRemarkEnabled(StringRef PassName) const override
bool handleDiagnostics(const DiagnosticInfo &DI) override
ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
bool isPassedOptRemarkEnabled(StringRef PassName) const override
bool isAnyRemarkEnabled() const override
bool isAnalysisRemarkEnabled(StringRef PassName) const override
std::unique_ptr< ASTConsumer > CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override
Create the AST consumer object for this action, if supported.
CodeGenerator * getCodeGenerator() const
friend class BackendConsumer
void EndSourceFileAction() override
Callback at the end of processing a single input.
bool BeginSourceFileAction(CompilerInstance &CI) override
Callback at the start of processing a single input.
~CodeGenAction() override
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext=nullptr)
Create a new code generation action.
llvm::LLVMContext * takeLLVMContext()
Take the LLVM context used by this action.
BackendConsumer * BEConsumer
bool hasIRSupport() const override
Does this action support use with IR files?
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
std::unique_ptr< llvm::Module > takeModule()
Take the generated LLVM module, for use after the action has been run.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string OptRecordFile
The name of the file to which the backend should save YAML optimization records.
std::vector< BitcodeFileToLink > LinkBitcodeFiles
The files specified here are linked in to the module before optimizations.
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
The primary public interface to the Clang code generator.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
FileManager & getFileManager() const
Return the current file manager to the caller.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Decl - This represents one declaration (or definition), e.g.
Represents a ValueDecl that came out of a declarator.
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
EmitAssemblyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitBCAction(llvm::LLVMContext *_VMContext=nullptr)
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMAction(llvm::LLVMContext *_VMContext=nullptr)
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext=nullptr)
EmitObjAction(llvm::LLVMContext *_VMContext=nullptr)
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements support for file system lookup, file system caching, and directory search management.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getBufferForFile(FileEntryRef Entry, bool isVolatile=false, bool RequiresNullTerminator=true, std::optional< int64_t > MaybeLimit=std::nullopt, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
InputKind getCurrentFileKind() const
virtual void EndSourceFileAction()
Callback at the end of processing a single input.
CompilerInstance & getCompilerInstance() const
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
StringRef getCurrentFileOrBufferName() const
unsigned GenReducedBMI
Whether to generate reduced BMI for C++20 named modules.
std::string ModuleOutputPath
Output Path for module output file.
A SourceLocation and its associated SourceManager.
Represents a function declaration or definition.
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
A trivial tuple used to represent a source range.
Represents the declaration of a struct/union/class/enum.
const char * getDataLayoutString() const
Options for controlling the target.
std::string Triple
The name of the target triple to compile for.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string CPU
If given, the name of the target CPU to generate code for.
Represents a variable declaration or definition.
Defines the clang::TargetInfo interface.
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
The JSON file list parser is used to communicate input to InstallAPI.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
@ Result
The result type of a method or function.
void emitBackendOutput(CompilerInstance &CI, CodeGenOptions &CGOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
@ Backend_EmitAssembly
Emit native assembly files.
@ Backend_EmitLL
Emit human-readable LLVM assembly.
@ Backend_EmitBC
Emit LLVM bitcode files.
@ Backend_EmitObj
Emit native object files.
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
std::unique_ptr< CodeGenerator > CreateLLVMCodeGen(const CompilerInstance &CI, llvm::StringRef ModuleName, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
U cast(CodeGen::Address addr)
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)