33#include "llvm/ADT/Hashing.h"
34#include "llvm/Bitcode/BitcodeReader.h"
35#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
36#include "llvm/Demangle/Demangle.h"
37#include "llvm/IR/DebugInfo.h"
38#include "llvm/IR/DiagnosticInfo.h"
39#include "llvm/IR/DiagnosticPrinter.h"
40#include "llvm/IR/GlobalValue.h"
41#include "llvm/IR/LLVMContext.h"
42#include "llvm/IR/LLVMRemarkStreamer.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IRReader/IRReader.h"
45#include "llvm/LTO/LTOBackend.h"
46#include "llvm/Linker/Linker.h"
48#include "llvm/Support/MemoryBuffer.h"
49#include "llvm/Support/SourceMgr.h"
50#include "llvm/Support/TimeProfiler.h"
51#include "llvm/Support/Timer.h"
52#include "llvm/Support/ToolOutputFile.h"
53#include "llvm/Support/YAMLTraits.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) {}
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)
118 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &
C,
120 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
121 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
122 AsmOutStream(
std::move(OS)), Context(nullptr), FS(VFS),
123 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
124 LLVMIRGenerationRefCount(0),
126 PPOpts, CodeGenOpts,
C, CoverageInfo)),
127 LinkModules(
std::move(LinkModules)) {
128 TimerIsEnabled = CodeGenOpts.TimePasses;
129 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
130 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
144 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
145 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
146 Context(nullptr), FS(
VFS),
147 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
148 LLVMIRGenerationRefCount(0),
150 CodeGenOpts,
C, CoverageInfo)),
151 LinkModules(
std::move(LinkModules)), CurLinkModule(
Module) {
152 TimerIsEnabled = CodeGenOpts.TimePasses;
153 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
154 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
158 return Gen->GetModule();
162 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
170 Gen->HandleCXXStaticMemberVarInstantiation(VD);
174 assert(!Context &&
"initialized multiple times");
179 LLVMIRGeneration.startTimer();
181 Gen->Initialize(Ctx);
184 LLVMIRGeneration.stopTimer();
190 "LLVM IR generation of declaration");
193 if (TimerIsEnabled) {
194 LLVMIRGenerationRefCount += 1;
195 if (LLVMIRGenerationRefCount == 1)
196 LLVMIRGeneration.startTimer();
199 Gen->HandleTopLevelDecl(
D);
201 if (TimerIsEnabled) {
202 LLVMIRGenerationRefCount -= 1;
203 if (LLVMIRGenerationRefCount == 0)
204 LLVMIRGeneration.stopTimer();
213 "LLVM IR generation of inline function");
215 LLVMIRGeneration.startTimer();
217 Gen->HandleInlineFunctionDefinition(
D);
220 LLVMIRGeneration.stopTimer();
231 for (
auto &LM : LinkModules) {
232 assert(LM.Module &&
"LinkModule does not actually have a module");
234 if (LM.PropagateAttrs)
241 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
244 CurLinkModule = LM.Module.get();
247 if (LM.Internalize) {
248 Err = Linker::linkModules(
249 *M, std::move(LM.Module), LM.LinkFlags,
250 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
251 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
252 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
256 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
268 llvm::TimeTraceScope TimeScope(
"Frontend");
269 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
270 if (TimerIsEnabled) {
271 LLVMIRGenerationRefCount += 1;
272 if (LLVMIRGenerationRefCount == 1)
273 LLVMIRGeneration.startTimer();
276 Gen->HandleTranslationUnit(
C);
278 if (TimerIsEnabled) {
279 LLVMIRGenerationRefCount -= 1;
280 if (LLVMIRGenerationRefCount == 0)
281 LLVMIRGeneration.stopTimer();
284 IRGenFinished =
true;
291 LLVMContext &Ctx =
getModule()->getContext();
292 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
293 Ctx.getDiagnosticHandler();
294 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
297 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
298 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
301 setupLLVMOptimizationRemarks(
306 if (Error
E = OptRecordFileOrErr.takeError()) {
311 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
312 std::move(*OptRecordFileOrErr);
316 Ctx.setDiagnosticsHotnessRequested(
true);
318 if (CodeGenOpts.MisExpect) {
319 Ctx.setMisExpectWarningRequested(
true);
323 Ctx.setDiagnosticsMisExpectTolerance(
331 for (
auto &F :
getModule()->functions()) {
332 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
333 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
336 ManglingFullSourceLocs.push_back(std::make_pair(NameHash,
Loc));
340 if (CodeGenOpts.ClearASTBeforeBackend) {
341 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
349 C.getAllocator().Reset();
355 C.getTargetInfo().getDataLayoutString(),
getModule(),
356 Action, FS, std::move(AsmOutStream),
this);
358 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
361 OptRecordFile->keep();
367 "LLVM IR generation of declaration");
368 Gen->HandleTagDeclDefinition(
D);
372 Gen->HandleTagDeclRequiredDefinition(
D);
376 Gen->CompleteTentativeDefinition(
D);
380 Gen->CompleteExternalDeclaration(
D);
384 Gen->AssignInheritanceModel(RD);
388 Gen->HandleVTable(RD);
391void BackendConsumer::anchor() { }
407 const llvm::SourceMgr &LSM = *
D.getSourceMgr();
411 const MemoryBuffer *LBuf =
412 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(
D.getLoc()));
416 std::unique_ptr<llvm::MemoryBuffer> CBuf =
417 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
418 LBuf->getBufferIdentifier());
423 unsigned Offset =
D.getLoc().getPointer() - LBuf->getBufferStart();
429#define ComputeDiagID(Severity, GroupName, DiagID) \
431 switch (Severity) { \
432 case llvm::DS_Error: \
433 DiagID = diag::err_fe_##GroupName; \
435 case llvm::DS_Warning: \
436 DiagID = diag::warn_fe_##GroupName; \
438 case llvm::DS_Remark: \
439 llvm_unreachable("'remark' severity not expected"); \
441 case llvm::DS_Note: \
442 DiagID = diag::note_fe_##GroupName; \
447#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
449 switch (Severity) { \
450 case llvm::DS_Error: \
451 DiagID = diag::err_fe_##GroupName; \
453 case llvm::DS_Warning: \
454 DiagID = diag::warn_fe_##GroupName; \
456 case llvm::DS_Remark: \
457 DiagID = diag::remark_fe_##GroupName; \
459 case llvm::DS_Note: \
460 DiagID = diag::note_fe_##GroupName; \
466 const llvm::SMDiagnostic &
D = DI.getSMDiag();
469 if (DI.isInlineAsmDiag())
477 D.
print(
nullptr, llvm::errs());
486 StringRef Message =
D.getMessage();
487 (void)Message.consume_front(
"error: ");
491 if (
D.getLoc() != SMLoc())
497 if (DI.isInlineAsmDiag()) {
503 if (
D.getLoc().isValid()) {
507 for (
const std::pair<unsigned, unsigned> &
Range :
D.getRanges()) {
508 unsigned Column =
D.getColumnNo();
527 std::string Message =
D.getMsgStr().str();
550 if (
D.getSeverity() != llvm::DS_Warning)
559 Diags.
Report(*
Loc, diag::warn_fe_frame_larger_than)
560 <<
D.getStackSize() <<
D.getStackLimit()
561 << llvm::demangle(
D.getFunction().getName());
566 const llvm::DiagnosticInfoResourceLimit &
D) {
570 unsigned DiagID = diag::err_fe_backend_resource_limit;
574 <<
D.getResourceName() <<
D.getResourceSize() <<
D.getResourceLimit()
575 << llvm::demangle(
D.getFunction().getName());
580 const llvm::DiagnosticInfoWithLocationBase &
D,
bool &BadDebugInfo,
586 if (
D.isLocationAvailable()) {
591 FE = FileMgr.
getFile(
D.getAbsolutePath());
610 if (DILoc.
isInvalid() &&
D.isLocationAvailable())
615 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
621std::optional<FullSourceLoc>
624 for (
const auto &Pair : ManglingFullSourceLocs) {
625 if (Pair.first == Hash)
632 const llvm::DiagnosticInfoUnsupported &
D) {
634 assert(
D.getSeverity() == llvm::DS_Error ||
635 D.getSeverity() == llvm::DS_Warning);
639 bool BadDebugInfo =
false;
642 raw_string_ostream MsgStream(Msg);
646 if (Context !=
nullptr) {
648 MsgStream <<
D.getMessage();
650 DiagnosticPrinterRawOStream DP(MsgStream);
654 auto DiagType =
D.getSeverity() == llvm::DS_Error
655 ? diag::err_fe_backend_unsupported
656 : diag::warn_fe_backend_unsupported;
657 Diags.
Report(
Loc, DiagType) << MsgStream.str();
664 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
669 const llvm::DiagnosticInfoOptimizationBase &
D,
unsigned DiagID) {
671 assert(
D.getSeverity() == llvm::DS_Remark ||
672 D.getSeverity() == llvm::DS_Warning);
676 bool BadDebugInfo =
false;
679 raw_string_ostream MsgStream(Msg);
683 if (Context !=
nullptr) {
685 MsgStream <<
D.getMsg();
687 DiagnosticPrinterRawOStream DP(MsgStream);
692 MsgStream <<
" (hotness: " << *
D.getHotness() <<
")";
703 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
708 const llvm::DiagnosticInfoOptimizationBase &
D) {
710 if (
D.isVerbose() && !
D.getHotness())
718 }
else if (
D.isMissed()) {
724 D, diag::remark_fe_backend_optimization_remark_missed);
726 assert(
D.isAnalysis() &&
"Unknown remark type");
728 bool ShouldAlwaysPrint =
false;
729 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&
D))
730 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
732 if (ShouldAlwaysPrint ||
735 D, diag::remark_fe_backend_optimization_remark_analysis);
740 const llvm::OptimizationRemarkAnalysisFPCommute &
D) {
745 if (
D.shouldAlwaysPrint() ||
748 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
752 const llvm::OptimizationRemarkAnalysisAliasing &
D) {
757 if (
D.shouldAlwaysPrint() ||
760 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
764 const llvm::DiagnosticInfoOptimizationFailure &
D) {
777 Diags.
Report(LocCookie,
D.getSeverity() == DiagnosticSeverity::DS_Error
778 ? diag::err_fe_backend_error_attr
779 : diag::warn_fe_backend_warning_attr)
780 << llvm::demangle(
D.getFunctionName()) <<
D.getNote();
784 const llvm::DiagnosticInfoMisExpect &
D) {
787 bool BadDebugInfo =
false;
791 Diags.
Report(
Loc, diag::warn_profile_data_misexpect) <<
D.getMsg().str();
798 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
805 unsigned DiagID = diag::err_fe_inline_asm;
806 llvm::DiagnosticSeverity Severity = DI.getSeverity();
808 switch (DI.getKind()) {
809 case llvm::DK_InlineAsm:
814 case llvm::DK_SrcMgr:
817 case llvm::DK_StackSize:
822 case llvm::DK_ResourceLimit:
830 case llvm::DK_OptimizationRemark:
835 case llvm::DK_OptimizationRemarkMissed:
840 case llvm::DK_OptimizationRemarkAnalysis:
845 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
850 case llvm::DK_OptimizationRemarkAnalysisAliasing:
855 case llvm::DK_MachineOptimizationRemark:
860 case llvm::DK_MachineOptimizationRemarkMissed:
865 case llvm::DK_MachineOptimizationRemarkAnalysis:
870 case llvm::DK_OptimizationFailure:
875 case llvm::DK_Unsupported:
878 case llvm::DK_DontCall:
881 case llvm::DK_MisExpect:
889 std::string MsgStorage;
891 raw_string_ostream Stream(MsgStorage);
892 DiagnosticPrinterRawOStream DP(Stream);
896 if (DI.getKind() == DK_Linker) {
897 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
898 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
909 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
910 OwnsVMContext(!_VMContext) {}
919 if (!LinkModules.empty())
927 << F.Filename << BCBuf.getError().message();
933 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
935 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
936 CI.getDiagnostics().Report(diag::err_cannot_open_file)
937 << F.Filename << EIB.message();
942 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
943 F.Internalize, F.LinkFlags});
960 return std::move(TheModule);
964 OwnsVMContext =
false;
978static std::unique_ptr<raw_pwrite_stream>
995 llvm_unreachable(
"Invalid action!");
998std::unique_ptr<ASTConsumer>
1009 if (loadLinkModules(CI))
1022 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
1027 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1029 std::unique_ptr<PPCallbacks> Callbacks =
1037 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1038 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1041 Consumers[1] = std::move(
Result);
1042 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1045 return std::move(
Result);
1048std::unique_ptr<llvm::Module>
1049CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1053 auto DiagErrors = [&](Error
E) -> std::unique_ptr<llvm::Module> {
1056 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1066 VMContext->enableDebugTypeODRUniquing();
1070 return DiagErrors(BMsOrErr.takeError());
1071 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1077 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1082 Bm->parseModule(*VMContext);
1084 return DiagErrors(MOrErr.takeError());
1085 return std::move(*MOrErr);
1089 if (loadLinkModules(CI))
1093 llvm::SMDiagnostic Err;
1094 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1101 if (BMsOrErr && BMsOrErr->size()) {
1102 std::unique_ptr<llvm::Module> FirstM;
1103 for (
auto &BM : *BMsOrErr) {
1105 BM.parseModule(*VMContext);
1107 return DiagErrors(MOrErr.takeError());
1109 LinkModules.push_back({std::move(*MOrErr),
false,
1112 FirstM = std::move(*MOrErr);
1119 consumeError(BMsOrErr.takeError());
1125 if (Err.getLineNo() > 0) {
1126 assert(Err.getColumnNo() >= 0);
1127 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1128 Err.getLineNo(), Err.getColumnNo() + 1);
1132 StringRef Msg = Err.getMessage();
1133 Msg.consume_front(
"error: ");
1153 std::unique_ptr<raw_pwrite_stream> OS =
1160 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1164 TheModule = loadModule(*MainFile);
1169 if (TheModule->getTargetTriple() != TargetOpts.
Triple) {
1170 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1172 TheModule->setTargetTriple(TargetOpts.
Triple);
1175 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1178 LLVMContext &Ctx = TheModule->getContext();
1184 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1185 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1194 std::move(LinkModules), *VMContext,
nullptr);
1197 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1202 Ctx.setDiscardValueNames(
false);
1203 Ctx.setDiagnosticHandler(
1204 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1206 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1207 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1210 setupLLVMOptimizationRemarks(
1211 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1212 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1213 CodeGenOpts.DiagnosticsHotnessThreshold);
1215 if (Error
E = OptRecordFileOrErr.takeError()) {
1219 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1220 std::move(*OptRecordFileOrErr);
1227 OptRecordFile->keep();
1232void EmitAssemblyAction::anchor() { }
1236void EmitBCAction::anchor() { }
1240void EmitLLVMAction::anchor() { }
1244void EmitLLVMOnlyAction::anchor() { }
1248void EmitCodeGenOnlyAction::anchor() { }
1252void 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.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
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.
BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts, const TargetOptions &TargetOpts, const LangOptions &LangOpts, const std::string &InFile, SmallVector< LinkModule, 4 > LinkModules, std::unique_ptr< raw_pwrite_stream > OS, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
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.
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
Callback to run the program action, using the initialized compiler instance.
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::optional< uint64_t > DiagnosticsHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
std::optional< uint32_t > DiagnosticsMisExpectTolerance
The maximum percentage profiling weights can deviate from the expected values in order to be included...
std::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
OptRemark OptimizationRemark
Selected optimizations for which we should enable optimization remarks.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
OptRemark OptimizationRemarkAnalysis
Selected optimizations for which we should enable optimization analyses.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
OptRemark OptimizationRemarkMissed
Selected optimizations for which we should enable missed optimization remarks.
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.
InMemoryModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
PreprocessorOptions & getPreprocessorOpts()
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.
SourceLocation getLocation() const
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
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)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
llvm::ErrorOr< const FileEntry * > getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
InputKind getCurrentFileKind() const
CompilerInstance & getCompilerInstance() const
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.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Describes a module or submodule.
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
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...
FileManager & getFileManager() const
SourceLocation translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const
Get the source location for the given file:line:col triplet.
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.
void AddString(StringRef V) const
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.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
@ Result
The result type of a method or function.
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)
Diagnostic wrappers for TextAPI types for error reporting.
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)