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/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
52#include "llvm/Support/SourceMgr.h"
53#include "llvm/Support/TimeProfiler.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/ToolOutputFile.h"
56#include "llvm/Transforms/IPO/Internalize.h"
57#include "llvm/Transforms/Utils/Cloning.h"
63#define DEBUG_TYPE "codegenaction"
66llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex;
74 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
79 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
82 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
85 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
89 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
90 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
91 CodeGenOpts.OptimizationRemark.hasValidPattern();
103 [&](
const LLVMRemarkSetupFileError &E) {
104 Diags.
Report(diag::err_cannot_open_file)
107 [&](
const LLVMRemarkSetupPatternError &E) {
108 Diags.
Report(diag::err_drv_optimization_remark_pattern)
111 [&](
const LLVMRemarkSetupFormatError &E) {
112 Diags.
Report(diag::err_drv_optimization_remark_format)
122 std::unique_ptr<raw_pwrite_stream> OS,
124 llvm::Module *CurLinkModule)
125 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
126 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
127 AsmOutStream(
std::move(OS)), FS(VFS), Action(Action),
129 LinkModules(
std::move(LinkModules)), CurLinkModule(CurLinkModule) {
130 TimerIsEnabled = CodeGenOpts.TimePasses;
132 llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex);
133 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
136 if (CodeGenOpts.TimePasses)
137 LLVMIRGeneration.init(
"irgen",
"LLVM IR generation", CI.getTimerGroup());
141 return Gen->GetModule();
145 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
157 assert(!Context &&
"initialized multiple times");
162 LLVMIRGeneration.startTimer();
164 Gen->Initialize(Ctx);
167 LLVMIRGeneration.stopTimer();
172 Context->getSourceManager(),
173 "LLVM IR generation of declaration");
176 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
177 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
179 Gen->HandleTopLevelDecl(D);
181 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
182 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
189 Context->getSourceManager(),
190 "LLVM IR generation of inline function");
192 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
194 Gen->HandleInlineFunctionDefinition(D);
197 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
206 for (
auto &LM : LinkModules) {
207 assert(LM.Module &&
"LinkModule does not actually have a module");
209 if (LM.PropagateAttrs)
216 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
219 CurLinkModule = LM.Module.get();
222 if (LM.Internalize) {
223 Err = Linker::linkModules(
224 *M, std::move(LM.Module), LM.LinkFlags,
225 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
226 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
227 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
231 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
243 llvm::TimeTraceScope TimeScope(
"Frontend");
244 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
245 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
246 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
248 Gen->HandleTranslationUnit(
C);
250 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
251 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
258 LLVMContext &Ctx =
getModule()->getContext();
259 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
260 Ctx.getDiagnosticHandler();
261 llvm::scope_exit RestoreDiagnosticHandler(
262 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
263 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
266 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
267 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features,
","));
270 setupLLVMOptimizationRemarks(
271 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
272 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
273 CodeGenOpts.DiagnosticsHotnessThreshold);
275 if (
Error E = OptRecordFileOrErr.takeError()) {
280 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
282 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
283 llvm::driver::ProfileInstrKind::ProfileNone)
284 Ctx.setDiagnosticsHotnessRequested(
true);
286 if (CodeGenOpts.MisExpect) {
287 Ctx.setMisExpectWarningRequested(
true);
290 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
291 Ctx.setDiagnosticsMisExpectTolerance(
292 CodeGenOpts.DiagnosticsMisExpectTolerance);
299 for (
auto &F :
getModule()->functions()) {
300 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
301 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
304 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
308 if (CodeGenOpts.ClearASTBeforeBackend) {
309 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
317 C.getAllocator().Reset();
323 C.getTargetInfo().getDataLayoutString(),
getModule(),
324 Action, FS, std::move(AsmOutStream),
this);
327 OptRecordFile->keep();
332 Context->getSourceManager(),
333 "LLVM IR generation of declaration");
334 Gen->HandleTagDeclDefinition(D);
338 Gen->HandleTagDeclRequiredDefinition(D);
342 Gen->CompleteTentativeDefinition(D);
346 Gen->CompleteExternalDeclaration(D);
350 Gen->AssignInheritanceModel(RD);
354 Gen->HandleVTable(RD);
357void BackendConsumer::anchor() { }
362 BackendCon->DiagnosticHandlerImpl(DI);
373 const llvm::SourceMgr &LSM = *D.getSourceMgr();
377 const MemoryBuffer *LBuf =
378 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
382 std::unique_ptr<llvm::MemoryBuffer> CBuf =
383 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
384 LBuf->getBufferIdentifier());
389 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
395#define ComputeDiagID(Severity, GroupName, DiagID) \
397 switch (Severity) { \
398 case llvm::DS_Error: \
399 DiagID = diag::err_fe_##GroupName; \
401 case llvm::DS_Warning: \
402 DiagID = diag::warn_fe_##GroupName; \
404 case llvm::DS_Remark: \
405 llvm_unreachable("'remark' severity not expected"); \
407 case llvm::DS_Note: \
408 DiagID = diag::note_fe_##GroupName; \
413#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
415 switch (Severity) { \
416 case llvm::DS_Error: \
417 DiagID = diag::err_fe_##GroupName; \
419 case llvm::DS_Warning: \
420 DiagID = diag::warn_fe_##GroupName; \
422 case llvm::DS_Remark: \
423 DiagID = diag::remark_fe_##GroupName; \
425 case llvm::DS_Note: \
426 DiagID = diag::note_fe_##GroupName; \
432 const llvm::SMDiagnostic &D = DI.getSMDiag();
435 if (DI.isInlineAsmDiag())
443 D.print(
nullptr, llvm::errs());
444 Diags.Report(DiagID).AddString(
"cannot compile inline asm");
452 StringRef Message = D.getMessage();
453 (void)Message.consume_front(
"error: ");
457 if (D.getLoc() != SMLoc())
463 if (DI.isInlineAsmDiag()) {
467 Diags.Report(LocCookie, DiagID).AddString(Message);
469 if (D.getLoc().isValid()) {
473 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
474 unsigned Column = D.getColumnNo();
486 Diags.Report(Loc, DiagID).AddString(Message);
493 std::string Message = D.getMsgStr().str();
501 Diags.Report(LocCookie, DiagID).AddString(Message);
508 Diags.Report(Loc, DiagID).AddString(Message);
516 if (D.getSeverity() != llvm::DS_Warning)
525 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
526 << D.getStackSize() << D.getStackLimit()
527 << llvm::demangle(D.getFunction().getName());
532 const llvm::DiagnosticInfoResourceLimit &D) {
536 unsigned DiagID = diag::err_fe_backend_resource_limit;
537 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
539 Diags.Report(*Loc, DiagID)
540 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
541 << llvm::demangle(D.getFunction().getName());
546 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
547 StringRef &Filename,
unsigned &
Line,
unsigned &
Column)
const {
552 if (D.isLocationAvailable()) {
555 auto FE =
FileMgr.getOptionalFileRef(Filename);
557 FE =
FileMgr.getOptionalFileRef(D.getAbsolutePath());
576 if (DILoc.
isInvalid() && D.isLocationAvailable())
581 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
587std::optional<FullSourceLoc>
590 for (
const auto &Pair : ManglingFullSourceLocs) {
591 if (Pair.first == Hash)
598 const llvm::DiagnosticInfoUnsupported &D) {
600 assert(D.getSeverity() == llvm::DS_Error ||
601 D.getSeverity() == llvm::DS_Warning);
605 bool BadDebugInfo =
false;
608 raw_string_ostream MsgStream(Msg);
612 if (Context !=
nullptr) {
614 MsgStream << D.getMessage();
616 DiagnosticPrinterRawOStream DP(MsgStream);
620 auto DiagType = D.getSeverity() == llvm::DS_Error
621 ? diag::err_fe_backend_unsupported
622 : diag::warn_fe_backend_unsupported;
623 Diags.Report(Loc, DiagType) << Msg;
630 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
635 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
637 assert(D.getSeverity() == llvm::DS_Remark ||
638 D.getSeverity() == llvm::DS_Warning);
642 bool BadDebugInfo =
false;
645 raw_string_ostream MsgStream(Msg);
649 if (Context !=
nullptr) {
651 MsgStream << D.getMsg();
653 DiagnosticPrinterRawOStream DP(MsgStream);
658 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
660 Diags.Report(Loc, DiagID) <<
AddFlagValue(D.getPassName()) << Msg;
667 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
672 const llvm::DiagnosticInfoOptimizationBase &D) {
674 if (D.isVerbose() && !D.getHotness())
680 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
682 }
else if (D.isMissed()) {
686 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
688 D, diag::remark_fe_backend_optimization_remark_missed);
690 assert(D.isAnalysis() &&
"Unknown remark type");
692 bool ShouldAlwaysPrint =
false;
693 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
694 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
696 if (ShouldAlwaysPrint ||
697 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
699 D, diag::remark_fe_backend_optimization_remark_analysis);
704 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
709 if (D.shouldAlwaysPrint() ||
710 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
712 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
716 const llvm::OptimizationRemarkAnalysisAliasing &D) {
721 if (D.shouldAlwaysPrint() ||
722 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
724 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
728 const llvm::DiagnosticInfoOptimizationFailure &D) {
741 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
742 ? diag::err_fe_backend_error_attr
743 : diag::warn_fe_backend_warning_attr)
744 << llvm::demangle(D.getFunctionName()) << D.getNote();
746 if (!CodeGenOpts.ShowInliningChain)
753 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
754 Diags.Report(Loc, DiagID) << llvm::demangle(FuncName.str());
758 if (!D.getDebugInlineChain().empty()) {
761 for (
const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
765 Loc =
SM.translateFileLineCol(*FE, Info.Line,
766 Info.Column ? Info.Column : 1);
767 EmitNote(Loc, Info.FuncName, I == 0);
773 auto InliningDecisions = D.getInliningDecisions();
774 if (InliningDecisions.empty())
777 for (
const auto &[I, Entry] : llvm::enumerate(InliningDecisions)) {
780 EmitNote(Loc, Entry.first, I == 0);
785 Diags.Report(LocCookie, diag::note_fe_backend_inlining_debug_info);
789 const llvm::DiagnosticInfoMisExpect &D) {
792 bool BadDebugInfo =
false;
796 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
803 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
810 unsigned DiagID = diag::err_fe_inline_asm;
811 llvm::DiagnosticSeverity Severity = DI.getSeverity();
813 switch (DI.getKind()) {
814 case llvm::DK_InlineAsm:
819 case llvm::DK_SrcMgr:
822 case llvm::DK_StackSize:
827 case llvm::DK_ResourceLimit:
835 case llvm::DK_OptimizationRemark:
840 case llvm::DK_OptimizationRemarkMissed:
845 case llvm::DK_OptimizationRemarkAnalysis:
850 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
855 case llvm::DK_OptimizationRemarkAnalysisAliasing:
860 case llvm::DK_MachineOptimizationRemark:
865 case llvm::DK_MachineOptimizationRemarkMissed:
870 case llvm::DK_MachineOptimizationRemarkAnalysis:
875 case llvm::DK_OptimizationFailure:
880 case llvm::DK_Unsupported:
883 case llvm::DK_DontCall:
886 case llvm::DK_MisExpect:
894 std::string MsgStorage;
896 raw_string_ostream Stream(MsgStorage);
897 DiagnosticPrinterRawOStream DP(Stream);
901 if (DI.getKind() == DK_Linker) {
902 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
903 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
909 Diags.Report(Loc, DiagID).AddString(MsgStorage);
914 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
915 OwnsVMContext(!_VMContext) {}
937 return std::move(TheModule);
941 OwnsVMContext =
false;
955static std::unique_ptr<raw_pwrite_stream>
972 llvm_unreachable(
"Invalid action!");
975std::unique_ptr<ASTConsumer>
997 InFile, std::move(OS), CoverageInfo));
1002 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1004 std::unique_ptr<PPCallbacks> Callbacks =
1005 std::make_unique<MacroPPCallbacks>(
BEConsumer->getCodeGenerator(),
1012 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1013 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1016 Consumers[1] = std::move(
Result);
1017 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1020 return std::move(
Result);
1023std::unique_ptr<llvm::Module>
1024CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1028 auto DiagErrors = [&](
Error E) -> std::unique_ptr<llvm::Module> {
1031 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1041 VMContext->enableDebugTypeODRUniquing();
1043 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1045 return DiagErrors(BMsOrErr.takeError());
1046 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1052 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1056 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1057 Bm->parseModule(*VMContext);
1059 return DiagErrors(MOrErr.takeError());
1060 return std::move(*MOrErr);
1068 llvm::SMDiagnostic Err;
1069 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1072 std::string VerifierErr;
1073 raw_string_ostream VerifierErrStream(VerifierErr);
1074 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1084 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1085 if (BMsOrErr && BMsOrErr->size()) {
1086 std::unique_ptr<llvm::Module> FirstM;
1087 for (
auto &BM : *BMsOrErr) {
1088 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1089 BM.parseModule(*VMContext);
1091 return DiagErrors(MOrErr.takeError());
1093 LinkModules.push_back({std::move(*MOrErr),
false,
1096 FirstM = std::move(*MOrErr);
1103 consumeError(BMsOrErr.takeError());
1109 if (Err.getLineNo() > 0) {
1110 assert(Err.getColumnNo() >= 0);
1111 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1112 Err.getLineNo(), Err.getColumnNo() + 1);
1116 StringRef Msg = Err.getMessage();
1117 Msg.consume_front(
"error: ");
1137 std::unique_ptr<raw_pwrite_stream> OS =
1144 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1148 TheModule = loadModule(*MainFile);
1153 if (TheModule->getTargetTriple().str() != TargetOpts.
Triple) {
1154 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1156 TheModule->setTargetTriple(Triple(TargetOpts.
Triple));
1163 LLVMContext &Ctx = TheModule->getContext();
1169 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1170 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1176 std::move(LinkModules),
"",
nullptr,
nullptr,
1180 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1185 Ctx.setDiscardValueNames(
false);
1186 Ctx.setDiagnosticHandler(
1187 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1189 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1190 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1193 setupLLVMOptimizationRemarks(
1194 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1195 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1196 CodeGenOpts.DiagnosticsHotnessThreshold);
1198 if (
Error E = OptRecordFileOrErr.takeError()) {
1202 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1209 OptRecordFile->keep();
1214void EmitAssemblyAction::anchor() { }
1218void EmitBCAction::anchor() { }
1222void EmitLLVMAction::anchor() { }
1226void EmitLLVMOnlyAction::anchor() { }
1230void EmitCodeGenOnlyAction::anchor() { }
1234void 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
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::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.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
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::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)
bool loadLinkModules(CompilerInstance &CI, llvm::LLVMContext &Ctx, llvm::SmallVectorImpl< LinkModule > &LinkModules)
Load every bitcode file listed in CodeGenOpts.LinkBitcodeFiles into LinkModules.
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::dependencies::ModuleID &ID)