31#include "llvm/ADT/Hashing.h"
32#include "llvm/Bitcode/BitcodeReader.h"
33#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
34#include "llvm/Demangle/Demangle.h"
35#include "llvm/IR/DebugInfo.h"
36#include "llvm/IR/DiagnosticInfo.h"
37#include "llvm/IR/DiagnosticPrinter.h"
38#include "llvm/IR/GlobalValue.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/LLVMRemarkStreamer.h"
41#include "llvm/IR/Module.h"
42#include "llvm/IR/Verifier.h"
43#include "llvm/IRReader/IRReader.h"
44#include "llvm/LTO/LTOBackend.h"
45#include "llvm/Linker/Linker.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/SourceMgr.h"
49#include "llvm/Support/TimeProfiler.h"
50#include "llvm/Support/Timer.h"
51#include "llvm/Support/ToolOutputFile.h"
52#include "llvm/Transforms/IPO/Internalize.h"
53#include "llvm/Transforms/Utils/Cloning.h"
59#define DEBUG_TYPE "codegenaction"
66 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
95 [&](
const LLVMRemarkSetupFileError &
E) {
96 Diags.
Report(diag::err_cannot_open_file)
99 [&](
const LLVMRemarkSetupPatternError &
E) {
100 Diags.
Report(diag::err_drv_optimization_remark_pattern)
103 [&](
const LLVMRemarkSetupFormatError &
E) {
104 Diags.
Report(diag::err_drv_optimization_remark_format)
114 std::unique_ptr<raw_pwrite_stream> OS,
116 llvm::Module *CurLinkModule)
117 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
118 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
119 AsmOutStream(
std::move(OS)), FS(VFS), Action(Action),
121 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
122 CI.getCodeGenOpts(),
C, CoverageInfo)),
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());
144 Gen->HandleCXXStaticMemberVarInstantiation(VD);
148 assert(!Context &&
"initialized multiple times");
153 LLVMIRGeneration.startTimer();
155 Gen->Initialize(Ctx);
158 LLVMIRGeneration.stopTimer();
164 "LLVM IR generation of declaration");
167 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
170 Gen->HandleTopLevelDecl(
D);
172 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
181 "LLVM IR generation of inline function");
185 Gen->HandleInlineFunctionDefinition(
D);
199 for (
auto &LM : LinkModules) {
200 assert(LM.Module &&
"LinkModule does not actually have a module");
202 if (LM.PropagateAttrs)
209 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
212 CurLinkModule = LM.Module.get();
215 if (LM.Internalize) {
216 Err = Linker::linkModules(
217 *M, std::move(LM.Module), LM.LinkFlags,
218 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
219 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
220 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
224 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
236 llvm::TimeTraceScope TimeScope(
"Frontend");
237 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
238 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
241 Gen->HandleTranslationUnit(
C);
243 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
246 IRGenFinished =
true;
253 LLVMContext &Ctx =
getModule()->getContext();
254 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
255 Ctx.getDiagnosticHandler();
256 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
259 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
260 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
263 setupLLVMOptimizationRemarks(
268 if (Error
E = OptRecordFileOrErr.takeError()) {
273 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
274 std::move(*OptRecordFileOrErr);
276 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
277 llvm::driver::ProfileInstrKind::ProfileNone)
278 Ctx.setDiagnosticsHotnessRequested(
true);
280 if (CodeGenOpts.MisExpect) {
281 Ctx.setMisExpectWarningRequested(
true);
285 Ctx.setDiagnosticsMisExpectTolerance(
293 for (
auto &F :
getModule()->functions()) {
294 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
295 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
298 ManglingFullSourceLocs.push_back(std::make_pair(NameHash,
Loc));
302 if (CodeGenOpts.ClearASTBeforeBackend) {
303 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
311 C.getAllocator().Reset();
317 C.getTargetInfo().getDataLayoutString(),
getModule(),
318 Action, FS, std::move(AsmOutStream),
this);
320 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
323 OptRecordFile->keep();
329 "LLVM IR generation of declaration");
330 Gen->HandleTagDeclDefinition(
D);
334 Gen->HandleTagDeclRequiredDefinition(
D);
338 Gen->CompleteTentativeDefinition(
D);
342 Gen->CompleteExternalDeclaration(
D);
346 Gen->AssignInheritanceModel(RD);
350 Gen->HandleVTable(RD);
353void BackendConsumer::anchor() { }
369 const llvm::SourceMgr &LSM = *
D.getSourceMgr();
373 const MemoryBuffer *LBuf =
374 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(
D.getLoc()));
378 std::unique_ptr<llvm::MemoryBuffer> CBuf =
379 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
380 LBuf->getBufferIdentifier());
385 unsigned Offset =
D.getLoc().getPointer() - LBuf->getBufferStart();
391#define ComputeDiagID(Severity, GroupName, DiagID) \
393 switch (Severity) { \
394 case llvm::DS_Error: \
395 DiagID = diag::err_fe_##GroupName; \
397 case llvm::DS_Warning: \
398 DiagID = diag::warn_fe_##GroupName; \
400 case llvm::DS_Remark: \
401 llvm_unreachable("'remark' severity not expected"); \
403 case llvm::DS_Note: \
404 DiagID = diag::note_fe_##GroupName; \
409#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
411 switch (Severity) { \
412 case llvm::DS_Error: \
413 DiagID = diag::err_fe_##GroupName; \
415 case llvm::DS_Warning: \
416 DiagID = diag::warn_fe_##GroupName; \
418 case llvm::DS_Remark: \
419 DiagID = diag::remark_fe_##GroupName; \
421 case llvm::DS_Note: \
422 DiagID = diag::note_fe_##GroupName; \
428 const llvm::SMDiagnostic &
D = DI.getSMDiag();
431 if (DI.isInlineAsmDiag())
439 D.
print(
nullptr, llvm::errs());
448 StringRef Message =
D.getMessage();
449 (void)Message.consume_front(
"error: ");
453 if (
D.getLoc() != SMLoc())
459 if (DI.isInlineAsmDiag()) {
465 if (
D.getLoc().isValid()) {
469 for (
const std::pair<unsigned, unsigned> &
Range :
D.getRanges()) {
470 unsigned Column =
D.getColumnNo();
489 std::string Message =
D.getMsgStr().str();
512 if (
D.getSeverity() != llvm::DS_Warning)
521 Diags.
Report(*
Loc, diag::warn_fe_frame_larger_than)
522 <<
D.getStackSize() <<
D.getStackLimit()
523 << llvm::demangle(
D.getFunction().getName());
528 const llvm::DiagnosticInfoResourceLimit &
D) {
532 unsigned DiagID = diag::err_fe_backend_resource_limit;
536 <<
D.getResourceName() <<
D.getResourceSize() <<
D.getResourceLimit()
537 << llvm::demangle(
D.getFunction().getName());
542 const llvm::DiagnosticInfoWithLocationBase &
D,
bool &BadDebugInfo,
548 if (
D.isLocationAvailable()) {
572 if (DILoc.
isInvalid() &&
D.isLocationAvailable())
577 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
583std::optional<FullSourceLoc>
586 for (
const auto &Pair : ManglingFullSourceLocs) {
587 if (Pair.first == Hash)
594 const llvm::DiagnosticInfoUnsupported &
D) {
596 assert(
D.getSeverity() == llvm::DS_Error ||
597 D.getSeverity() == llvm::DS_Warning);
601 bool BadDebugInfo =
false;
604 raw_string_ostream MsgStream(Msg);
608 if (Context !=
nullptr) {
610 MsgStream <<
D.getMessage();
612 DiagnosticPrinterRawOStream DP(MsgStream);
616 auto DiagType =
D.getSeverity() == llvm::DS_Error
617 ? diag::err_fe_backend_unsupported
618 : diag::warn_fe_backend_unsupported;
626 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
631 const llvm::DiagnosticInfoOptimizationBase &
D,
unsigned DiagID) {
633 assert(
D.getSeverity() == llvm::DS_Remark ||
634 D.getSeverity() == llvm::DS_Warning);
638 bool BadDebugInfo =
false;
641 raw_string_ostream MsgStream(Msg);
645 if (Context !=
nullptr) {
647 MsgStream <<
D.getMsg();
649 DiagnosticPrinterRawOStream DP(MsgStream);
654 MsgStream <<
" (hotness: " << *
D.getHotness() <<
")";
663 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
668 const llvm::DiagnosticInfoOptimizationBase &
D) {
670 if (
D.isVerbose() && !
D.getHotness())
678 }
else if (
D.isMissed()) {
684 D, diag::remark_fe_backend_optimization_remark_missed);
686 assert(
D.isAnalysis() &&
"Unknown remark type");
688 bool ShouldAlwaysPrint =
false;
689 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&
D))
690 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
692 if (ShouldAlwaysPrint ||
695 D, diag::remark_fe_backend_optimization_remark_analysis);
700 const llvm::OptimizationRemarkAnalysisFPCommute &
D) {
705 if (
D.shouldAlwaysPrint() ||
708 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
712 const llvm::OptimizationRemarkAnalysisAliasing &
D) {
717 if (
D.shouldAlwaysPrint() ||
720 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
724 const llvm::DiagnosticInfoOptimizationFailure &
D) {
737 Diags.
Report(LocCookie,
D.getSeverity() == DiagnosticSeverity::DS_Error
738 ? diag::err_fe_backend_error_attr
739 : diag::warn_fe_backend_warning_attr)
740 << llvm::demangle(
D.getFunctionName()) <<
D.getNote();
744 const llvm::DiagnosticInfoMisExpect &
D) {
747 bool BadDebugInfo =
false;
751 Diags.
Report(
Loc, diag::warn_profile_data_misexpect) <<
D.getMsg().str();
758 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
765 unsigned DiagID = diag::err_fe_inline_asm;
766 llvm::DiagnosticSeverity Severity = DI.getSeverity();
768 switch (DI.getKind()) {
769 case llvm::DK_InlineAsm:
774 case llvm::DK_SrcMgr:
777 case llvm::DK_StackSize:
782 case llvm::DK_ResourceLimit:
790 case llvm::DK_OptimizationRemark:
795 case llvm::DK_OptimizationRemarkMissed:
800 case llvm::DK_OptimizationRemarkAnalysis:
805 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
810 case llvm::DK_OptimizationRemarkAnalysisAliasing:
815 case llvm::DK_MachineOptimizationRemark:
820 case llvm::DK_MachineOptimizationRemarkMissed:
825 case llvm::DK_MachineOptimizationRemarkAnalysis:
830 case llvm::DK_OptimizationFailure:
835 case llvm::DK_Unsupported:
838 case llvm::DK_DontCall:
841 case llvm::DK_MisExpect:
849 std::string MsgStorage;
851 raw_string_ostream Stream(MsgStorage);
852 DiagnosticPrinterRawOStream DP(Stream);
856 if (DI.getKind() == DK_Linker) {
857 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
858 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
869 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
870 OwnsVMContext(!_VMContext) {}
879 if (!LinkModules.empty())
887 << F.Filename << BCBuf.getError().message();
893 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
895 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
896 CI.getDiagnostics().Report(diag::err_cannot_open_file)
897 << F.Filename << EIB.message();
902 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
903 F.Internalize, F.LinkFlags});
922 return std::move(TheModule);
926 OwnsVMContext =
false;
940static std::unique_ptr<raw_pwrite_stream>
957 llvm_unreachable(
"Invalid action!");
960std::unique_ptr<ASTConsumer>
971 if (loadLinkModules(CI))
982 InFile, std::move(OS), CoverageInfo));
987 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
989 std::unique_ptr<PPCallbacks> Callbacks =
997 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
998 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1001 Consumers[1] = std::move(
Result);
1002 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1005 return std::move(
Result);
1008std::unique_ptr<llvm::Module>
1009CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1013 auto DiagErrors = [&](Error
E) -> std::unique_ptr<llvm::Module> {
1016 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1026 VMContext->enableDebugTypeODRUniquing();
1030 return DiagErrors(BMsOrErr.takeError());
1031 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1037 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1042 Bm->parseModule(*VMContext);
1044 return DiagErrors(MOrErr.takeError());
1045 return std::move(*MOrErr);
1049 if (loadLinkModules(CI))
1053 llvm::SMDiagnostic Err;
1054 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1057 std::string VerifierErr;
1058 raw_string_ostream VerifierErrStream(VerifierErr);
1059 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1070 if (BMsOrErr && BMsOrErr->size()) {
1071 std::unique_ptr<llvm::Module> FirstM;
1072 for (
auto &BM : *BMsOrErr) {
1074 BM.parseModule(*VMContext);
1076 return DiagErrors(MOrErr.takeError());
1078 LinkModules.push_back({std::move(*MOrErr),
false,
1081 FirstM = std::move(*MOrErr);
1088 consumeError(BMsOrErr.takeError());
1094 if (Err.getLineNo() > 0) {
1095 assert(Err.getColumnNo() >= 0);
1096 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1097 Err.getLineNo(), Err.getColumnNo() + 1);
1101 StringRef Msg = Err.getMessage();
1102 Msg.consume_front(
"error: ");
1122 std::unique_ptr<raw_pwrite_stream> OS =
1129 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1133 TheModule = loadModule(*MainFile);
1138 if (TheModule->getTargetTriple().str() != TargetOpts.
Triple) {
1139 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1141 TheModule->setTargetTriple(Triple(TargetOpts.
Triple));
1144 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1147 LLVMContext &Ctx = TheModule->getContext();
1153 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1154 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1160 std::move(LinkModules),
"",
nullptr,
nullptr,
1164 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1169 Ctx.setDiscardValueNames(
false);
1170 Ctx.setDiagnosticHandler(
1171 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1173 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1174 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1177 setupLLVMOptimizationRemarks(
1178 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1179 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1180 CodeGenOpts.DiagnosticsHotnessThreshold);
1182 if (Error
E = OptRecordFileOrErr.takeError()) {
1186 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1187 std::move(*OptRecordFileOrErr);
1194 OptRecordFile->keep();
1199void EmitAssemblyAction::anchor() { }
1203void EmitBCAction::anchor() { }
1207void EmitLLVMAction::anchor() { }
1211void EmitLLVMOnlyAction::anchor() { }
1215void EmitCodeGenOnlyAction::anchor() { }
1219void 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.
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
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.
llvm::TimerGroup & getTimerGroup() const
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...
llvm::Timer & getFrontendTimer() const
FileManager & getFileManager() const
Return the current file manager to the caller.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetInfo & getTarget() 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, bool IsText=true)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
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...
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.
@ 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 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)