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/IRReader/IRReader.h"
43#include "llvm/LTO/LTOBackend.h"
44#include "llvm/Linker/Linker.h"
46#include "llvm/Support/MemoryBuffer.h"
47#include "llvm/Support/SourceMgr.h"
48#include "llvm/Support/TimeProfiler.h"
49#include "llvm/Support/Timer.h"
50#include "llvm/Support/ToolOutputFile.h"
51#include "llvm/Transforms/IPO/Internalize.h"
52#include "llvm/Transforms/Utils/Cloning.h"
58#define DEBUG_TYPE "codegenaction"
65 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
94 [&](
const LLVMRemarkSetupFileError &
E) {
95 Diags.
Report(diag::err_cannot_open_file)
98 [&](
const LLVMRemarkSetupPatternError &
E) {
99 Diags.
Report(diag::err_drv_optimization_remark_pattern)
102 [&](
const LLVMRemarkSetupFormatError &
E) {
103 Diags.
Report(diag::err_drv_optimization_remark_format)
113 llvm::Module *CurLinkModule)
114 : Diags(CI.getDiagnostics()), HeaderSearchOpts(CI.getHeaderSearchOpts()),
115 CodeGenOpts(CI.getCodeGenOpts()), TargetOpts(CI.getTargetOpts()),
116 LangOpts(CI.getLangOpts()), AsmOutStream(
std::move(OS)), FS(VFS),
117 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"), Action(Action),
119 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
120 CI.getCodeGenOpts(),
C, CoverageInfo)),
121 LinkModules(
std::move(LinkModules)), CurLinkModule(CurLinkModule) {
122 TimerIsEnabled = CodeGenOpts.TimePasses;
123 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
124 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
128 return Gen->GetModule();
132 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
140 Gen->HandleCXXStaticMemberVarInstantiation(VD);
144 assert(!Context &&
"initialized multiple times");
149 LLVMIRGeneration.startTimer();
151 Gen->Initialize(Ctx);
154 LLVMIRGeneration.stopTimer();
160 "LLVM IR generation of declaration");
163 if (TimerIsEnabled) {
164 LLVMIRGenerationRefCount += 1;
165 if (LLVMIRGenerationRefCount == 1)
166 LLVMIRGeneration.startTimer();
169 Gen->HandleTopLevelDecl(
D);
171 if (TimerIsEnabled) {
172 LLVMIRGenerationRefCount -= 1;
173 if (LLVMIRGenerationRefCount == 0)
174 LLVMIRGeneration.stopTimer();
183 "LLVM IR generation of inline function");
185 LLVMIRGeneration.startTimer();
187 Gen->HandleInlineFunctionDefinition(
D);
190 LLVMIRGeneration.stopTimer();
201 for (
auto &LM : LinkModules) {
202 assert(LM.Module &&
"LinkModule does not actually have a module");
204 if (LM.PropagateAttrs)
211 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
214 CurLinkModule = LM.Module.get();
217 if (LM.Internalize) {
218 Err = Linker::linkModules(
219 *M, std::move(LM.Module), LM.LinkFlags,
220 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
221 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
222 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
226 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
238 llvm::TimeTraceScope TimeScope(
"Frontend");
239 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
240 if (TimerIsEnabled) {
241 LLVMIRGenerationRefCount += 1;
242 if (LLVMIRGenerationRefCount == 1)
243 LLVMIRGeneration.startTimer();
246 Gen->HandleTranslationUnit(
C);
248 if (TimerIsEnabled) {
249 LLVMIRGenerationRefCount -= 1;
250 if (LLVMIRGenerationRefCount == 0)
251 LLVMIRGeneration.stopTimer();
254 IRGenFinished =
true;
261 LLVMContext &Ctx =
getModule()->getContext();
262 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
263 Ctx.getDiagnosticHandler();
264 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
267 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
268 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
271 setupLLVMOptimizationRemarks(
276 if (Error
E = OptRecordFileOrErr.takeError()) {
281 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
282 std::move(*OptRecordFileOrErr);
286 Ctx.setDiagnosticsHotnessRequested(
true);
288 if (CodeGenOpts.MisExpect) {
289 Ctx.setMisExpectWarningRequested(
true);
293 Ctx.setDiagnosticsMisExpectTolerance(
301 for (
auto &F :
getModule()->functions()) {
302 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
303 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
306 ManglingFullSourceLocs.push_back(std::make_pair(NameHash,
Loc));
310 if (CodeGenOpts.ClearASTBeforeBackend) {
311 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
319 C.getAllocator().Reset();
325 C.getTargetInfo().getDataLayoutString(),
getModule(),
326 Action, FS, std::move(AsmOutStream),
this);
328 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
331 OptRecordFile->keep();
337 "LLVM IR generation of declaration");
338 Gen->HandleTagDeclDefinition(
D);
342 Gen->HandleTagDeclRequiredDefinition(
D);
346 Gen->CompleteTentativeDefinition(
D);
350 Gen->CompleteExternalDeclaration(
D);
354 Gen->AssignInheritanceModel(RD);
358 Gen->HandleVTable(RD);
361void BackendConsumer::anchor() { }
377 const llvm::SourceMgr &LSM = *
D.getSourceMgr();
381 const MemoryBuffer *LBuf =
382 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(
D.getLoc()));
386 std::unique_ptr<llvm::MemoryBuffer> CBuf =
387 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
388 LBuf->getBufferIdentifier());
393 unsigned Offset =
D.getLoc().getPointer() - LBuf->getBufferStart();
399#define ComputeDiagID(Severity, GroupName, DiagID) \
401 switch (Severity) { \
402 case llvm::DS_Error: \
403 DiagID = diag::err_fe_##GroupName; \
405 case llvm::DS_Warning: \
406 DiagID = diag::warn_fe_##GroupName; \
408 case llvm::DS_Remark: \
409 llvm_unreachable("'remark' severity not expected"); \
411 case llvm::DS_Note: \
412 DiagID = diag::note_fe_##GroupName; \
417#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
419 switch (Severity) { \
420 case llvm::DS_Error: \
421 DiagID = diag::err_fe_##GroupName; \
423 case llvm::DS_Warning: \
424 DiagID = diag::warn_fe_##GroupName; \
426 case llvm::DS_Remark: \
427 DiagID = diag::remark_fe_##GroupName; \
429 case llvm::DS_Note: \
430 DiagID = diag::note_fe_##GroupName; \
436 const llvm::SMDiagnostic &
D = DI.getSMDiag();
439 if (DI.isInlineAsmDiag())
447 D.
print(
nullptr, llvm::errs());
456 StringRef Message =
D.getMessage();
457 (void)Message.consume_front(
"error: ");
461 if (
D.getLoc() != SMLoc())
467 if (DI.isInlineAsmDiag()) {
473 if (
D.getLoc().isValid()) {
477 for (
const std::pair<unsigned, unsigned> &
Range :
D.getRanges()) {
478 unsigned Column =
D.getColumnNo();
497 std::string Message =
D.getMsgStr().str();
520 if (
D.getSeverity() != llvm::DS_Warning)
529 Diags.
Report(*
Loc, diag::warn_fe_frame_larger_than)
530 <<
D.getStackSize() <<
D.getStackLimit()
531 << llvm::demangle(
D.getFunction().getName());
536 const llvm::DiagnosticInfoResourceLimit &
D) {
540 unsigned DiagID = diag::err_fe_backend_resource_limit;
544 <<
D.getResourceName() <<
D.getResourceSize() <<
D.getResourceLimit()
545 << llvm::demangle(
D.getFunction().getName());
550 const llvm::DiagnosticInfoWithLocationBase &
D,
bool &BadDebugInfo,
556 if (
D.isLocationAvailable()) {
580 if (DILoc.
isInvalid() &&
D.isLocationAvailable())
585 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
591std::optional<FullSourceLoc>
594 for (
const auto &Pair : ManglingFullSourceLocs) {
595 if (Pair.first == Hash)
602 const llvm::DiagnosticInfoUnsupported &
D) {
604 assert(
D.getSeverity() == llvm::DS_Error ||
605 D.getSeverity() == llvm::DS_Warning);
609 bool BadDebugInfo =
false;
612 raw_string_ostream MsgStream(Msg);
616 if (Context !=
nullptr) {
618 MsgStream <<
D.getMessage();
620 DiagnosticPrinterRawOStream DP(MsgStream);
624 auto DiagType =
D.getSeverity() == llvm::DS_Error
625 ? diag::err_fe_backend_unsupported
626 : diag::warn_fe_backend_unsupported;
634 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
639 const llvm::DiagnosticInfoOptimizationBase &
D,
unsigned DiagID) {
641 assert(
D.getSeverity() == llvm::DS_Remark ||
642 D.getSeverity() == llvm::DS_Warning);
646 bool BadDebugInfo =
false;
649 raw_string_ostream MsgStream(Msg);
653 if (Context !=
nullptr) {
655 MsgStream <<
D.getMsg();
657 DiagnosticPrinterRawOStream DP(MsgStream);
662 MsgStream <<
" (hotness: " << *
D.getHotness() <<
")";
671 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
676 const llvm::DiagnosticInfoOptimizationBase &
D) {
678 if (
D.isVerbose() && !
D.getHotness())
686 }
else if (
D.isMissed()) {
692 D, diag::remark_fe_backend_optimization_remark_missed);
694 assert(
D.isAnalysis() &&
"Unknown remark type");
696 bool ShouldAlwaysPrint =
false;
697 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&
D))
698 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
700 if (ShouldAlwaysPrint ||
703 D, diag::remark_fe_backend_optimization_remark_analysis);
708 const llvm::OptimizationRemarkAnalysisFPCommute &
D) {
713 if (
D.shouldAlwaysPrint() ||
716 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
720 const llvm::OptimizationRemarkAnalysisAliasing &
D) {
725 if (
D.shouldAlwaysPrint() ||
728 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
732 const llvm::DiagnosticInfoOptimizationFailure &
D) {
745 Diags.
Report(LocCookie,
D.getSeverity() == DiagnosticSeverity::DS_Error
746 ? diag::err_fe_backend_error_attr
747 : diag::warn_fe_backend_warning_attr)
748 << llvm::demangle(
D.getFunctionName()) <<
D.getNote();
752 const llvm::DiagnosticInfoMisExpect &
D) {
755 bool BadDebugInfo =
false;
759 Diags.
Report(
Loc, diag::warn_profile_data_misexpect) <<
D.getMsg().str();
766 Diags.
Report(
Loc, diag::note_fe_backend_invalid_loc)
773 unsigned DiagID = diag::err_fe_inline_asm;
774 llvm::DiagnosticSeverity Severity = DI.getSeverity();
776 switch (DI.getKind()) {
777 case llvm::DK_InlineAsm:
782 case llvm::DK_SrcMgr:
785 case llvm::DK_StackSize:
790 case llvm::DK_ResourceLimit:
798 case llvm::DK_OptimizationRemark:
803 case llvm::DK_OptimizationRemarkMissed:
808 case llvm::DK_OptimizationRemarkAnalysis:
813 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
818 case llvm::DK_OptimizationRemarkAnalysisAliasing:
823 case llvm::DK_MachineOptimizationRemark:
828 case llvm::DK_MachineOptimizationRemarkMissed:
833 case llvm::DK_MachineOptimizationRemarkAnalysis:
838 case llvm::DK_OptimizationFailure:
843 case llvm::DK_Unsupported:
846 case llvm::DK_DontCall:
849 case llvm::DK_MisExpect:
857 std::string MsgStorage;
859 raw_string_ostream Stream(MsgStorage);
860 DiagnosticPrinterRawOStream DP(Stream);
864 if (DI.getKind() == DK_Linker) {
865 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
866 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
877 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
878 OwnsVMContext(!_VMContext) {}
887 if (!LinkModules.empty())
895 << F.Filename << BCBuf.getError().message();
901 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
903 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
904 CI.getDiagnostics().Report(diag::err_cannot_open_file)
905 << F.Filename << EIB.message();
910 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
911 F.Internalize, F.LinkFlags});
928 return std::move(TheModule);
932 OwnsVMContext =
false;
946static std::unique_ptr<raw_pwrite_stream>
963 llvm_unreachable(
"Invalid action!");
966std::unique_ptr<ASTConsumer>
977 if (loadLinkModules(CI))
988 InFile, std::move(OS), CoverageInfo));
993 if (CI.
getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
995 std::unique_ptr<PPCallbacks> Callbacks =
1003 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1004 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1007 Consumers[1] = std::move(
Result);
1008 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1011 return std::move(
Result);
1014std::unique_ptr<llvm::Module>
1015CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1019 auto DiagErrors = [&](Error
E) -> std::unique_ptr<llvm::Module> {
1022 handleAllErrors(std::move(
E), [&](ErrorInfoBase &EIB) {
1032 VMContext->enableDebugTypeODRUniquing();
1036 return DiagErrors(BMsOrErr.takeError());
1037 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1043 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1048 Bm->parseModule(*VMContext);
1050 return DiagErrors(MOrErr.takeError());
1051 return std::move(*MOrErr);
1055 if (loadLinkModules(CI))
1059 llvm::SMDiagnostic Err;
1060 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1067 if (BMsOrErr && BMsOrErr->size()) {
1068 std::unique_ptr<llvm::Module> FirstM;
1069 for (
auto &BM : *BMsOrErr) {
1071 BM.parseModule(*VMContext);
1073 return DiagErrors(MOrErr.takeError());
1075 LinkModules.push_back({std::move(*MOrErr),
false,
1078 FirstM = std::move(*MOrErr);
1085 consumeError(BMsOrErr.takeError());
1091 if (Err.getLineNo() > 0) {
1092 assert(Err.getColumnNo() >= 0);
1093 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1094 Err.getLineNo(), Err.getColumnNo() + 1);
1098 StringRef Msg = Err.getMessage();
1099 Msg.consume_front(
"error: ");
1119 std::unique_ptr<raw_pwrite_stream> OS =
1126 std::optional<MemoryBufferRef> MainFile =
SM.getBufferOrNone(FID);
1130 TheModule = loadModule(*MainFile);
1135 if (TheModule->getTargetTriple() != TargetOpts.
Triple) {
1136 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1138 TheModule->setTargetTriple(TargetOpts.
Triple);
1141 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1144 LLVMContext &Ctx = TheModule->getContext();
1150 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1151 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1157 std::move(LinkModules),
"",
nullptr,
nullptr,
1161 if (!CodeGenOpts.LinkBitcodePostopt &&
Result.LinkInModules(&*TheModule))
1166 Ctx.setDiscardValueNames(
false);
1167 Ctx.setDiagnosticHandler(
1168 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &
Result));
1170 Ctx.setDefaultTargetCPU(TargetOpts.
CPU);
1171 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.
Features,
","));
1174 setupLLVMOptimizationRemarks(
1175 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1176 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1177 CodeGenOpts.DiagnosticsHotnessThreshold);
1179 if (Error
E = OptRecordFileOrErr.takeError()) {
1183 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1184 std::move(*OptRecordFileOrErr);
1191 OptRecordFile->keep();
1196void EmitAssemblyAction::anchor() { }
1200void EmitBCAction::anchor() { }
1204void EmitLLVMAction::anchor() { }
1208void EmitLLVMOnlyAction::anchor() { }
1212void EmitCodeGenOnlyAction::anchor() { }
1216void 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.
BackendConsumer(const 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)
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.
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()
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, 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
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.
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)