28 #include "llvm/ADT/Hashing.h"
29 #include "llvm/Bitcode/BitcodeReader.h"
30 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31 #include "llvm/Demangle/Demangle.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/DiagnosticPrinter.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/LLVMRemarkStreamer.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IRReader/IRReader.h"
40 #include "llvm/LTO/LTOBackend.h"
41 #include "llvm/Linker/Linker.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include "llvm/Support/TimeProfiler.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/YAMLTraits.h"
49 #include "llvm/Transforms/IPO/Internalize.h"
52 using namespace clang;
55 #define DEBUG_TYPE "codegenaction"
62 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
64 bool handleDiagnostics(
const DiagnosticInfo &DI)
override;
67 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
70 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
73 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
77 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
78 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
79 CodeGenOpts.OptimizationRemark.hasValidPattern();
91 [&](
const LLVMRemarkSetupFileError &E) {
92 Diags.
Report(diag::err_cannot_open_file)
95 [&](
const LLVMRemarkSetupPatternError &E) {
96 Diags.
Report(diag::err_drv_optimization_remark_pattern)
99 [&](
const LLVMRemarkSetupFormatError &E) {
100 Diags.
Report(diag::err_drv_optimization_remark_format)
106 using LinkModule = CodeGenAction::LinkModule;
108 virtual void anchor();
115 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
118 Timer LLVMIRGeneration;
119 unsigned LLVMIRGenerationRefCount;
124 bool IRGenFinished =
false;
126 bool TimerIsEnabled =
false;
128 std::unique_ptr<CodeGenerator> Gen;
140 std::vector<std::pair<llvm::hash_code, FullSourceLoc>>
141 ManglingFullSourceLocs;
145 llvm::Module *CurLinkModule =
nullptr;
155 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
157 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
158 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
159 AsmOutStream(
std::move(OS)), Context(nullptr),
160 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
161 LLVMIRGenerationRefCount(0),
163 CodeGenOpts, C, CoverageInfo)),
164 LinkModules(
std::move(LinkModules)) {
165 TimerIsEnabled = CodeGenOpts.TimePasses;
166 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
167 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
181 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
182 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
184 LLVMIRGeneration(
"irgen",
"LLVM IR Generation Time"),
185 LLVMIRGenerationRefCount(0),
187 CodeGenOpts, C, CoverageInfo)),
188 LinkModules(
std::move(LinkModules)), CurLinkModule(
Module) {
189 TimerIsEnabled = CodeGenOpts.TimePasses;
190 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
191 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
193 llvm::Module *
getModule()
const {
return Gen->GetModule(); }
195 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
201 Gen->HandleCXXStaticMemberVarInstantiation(VD);
205 assert(!Context &&
"initialized multiple times");
210 LLVMIRGeneration.startTimer();
212 Gen->Initialize(Ctx);
215 LLVMIRGeneration.stopTimer();
221 "LLVM IR generation of declaration");
224 if (TimerIsEnabled) {
225 LLVMIRGenerationRefCount += 1;
226 if (LLVMIRGenerationRefCount == 1)
227 LLVMIRGeneration.startTimer();
230 Gen->HandleTopLevelDecl(D);
232 if (TimerIsEnabled) {
233 LLVMIRGenerationRefCount -= 1;
234 if (LLVMIRGenerationRefCount == 0)
235 LLVMIRGeneration.stopTimer();
244 "LLVM IR generation of inline function");
246 LLVMIRGeneration.startTimer();
248 Gen->HandleInlineFunctionDefinition(D);
251 LLVMIRGeneration.stopTimer();
257 HandleTopLevelDecl(D);
262 for (
auto &LM : LinkModules) {
263 if (LM.PropagateAttrs)
264 for (Function &F : *LM.Module) {
269 Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
272 CurLinkModule = LM.Module.get();
275 if (LM.Internalize) {
276 Err = Linker::linkModules(
277 *getModule(), std::move(LM.Module), LM.LinkFlags,
278 [](llvm::Module &M,
const llvm::StringSet<> &GVS) {
279 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
280 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
284 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
296 llvm::TimeTraceScope TimeScope(
"Frontend");
297 PrettyStackTraceString CrashInfo(
"Per-file LLVM IR generation");
298 if (TimerIsEnabled) {
299 LLVMIRGenerationRefCount += 1;
300 if (LLVMIRGenerationRefCount == 1)
301 LLVMIRGeneration.startTimer();
304 Gen->HandleTranslationUnit(C);
306 if (TimerIsEnabled) {
307 LLVMIRGenerationRefCount -= 1;
308 if (LLVMIRGenerationRefCount == 0)
309 LLVMIRGeneration.stopTimer();
312 IRGenFinished =
true;
319 LLVMContext &Ctx = getModule()->getContext();
320 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
321 Ctx.getDiagnosticHandler();
322 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
326 setupLLVMOptimizationRemarks(
327 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
328 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
329 CodeGenOpts.DiagnosticsHotnessThreshold);
331 if (
Error E = OptRecordFileOrErr.takeError()) {
336 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
337 std::move(*OptRecordFileOrErr);
341 Ctx.setDiagnosticsHotnessRequested(
true);
343 if (CodeGenOpts.MisExpect) {
344 Ctx.setMisExpectWarningRequested(
true);
347 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
348 Ctx.setDiagnosticsMisExpectTolerance(
349 CodeGenOpts.DiagnosticsMisExpectTolerance);
356 for (
auto &F : getModule()->functions()) {
357 if (
const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
358 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
361 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
365 if (CodeGenOpts.ClearASTBeforeBackend) {
366 LLVM_DEBUG(llvm::dbgs() <<
"Clearing AST...\n");
374 C.getAllocator().Reset();
377 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
380 LangOpts, C.getTargetInfo().getDataLayoutString(),
381 getModule(), Action, std::move(AsmOutStream));
383 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
386 OptRecordFile->keep();
392 "LLVM IR generation of declaration");
393 Gen->HandleTagDeclDefinition(D);
397 Gen->HandleTagDeclRequiredDefinition(D);
401 Gen->CompleteTentativeDefinition(D);
405 Gen->CompleteExternalDeclaration(D);
409 Gen->AssignInheritanceModel(RD);
413 Gen->HandleVTable(RD);
419 getBestLocationFromDebugLoc(
const llvm::DiagnosticInfoWithLocationBase &D,
420 bool &BadDebugInfo, StringRef &
Filename,
421 unsigned &
Line,
unsigned &Column)
const;
425 void DiagnosticHandlerImpl(
const llvm::DiagnosticInfo &DI);
429 bool InlineAsmDiagHandler(
const llvm::DiagnosticInfoInlineAsm &D);
431 void SrcMgrDiagHandler(
const llvm::DiagnosticInfoSrcMgr &D);
435 bool StackSizeDiagHandler(
const llvm::DiagnosticInfoStackSize &D);
437 void UnsupportedDiagHandler(
const llvm::DiagnosticInfoUnsupported &D);
441 void EmitOptimizationMessage(
const llvm::DiagnosticInfoOptimizationBase &D,
444 OptimizationRemarkHandler(
const llvm::DiagnosticInfoOptimizationBase &D);
445 void OptimizationRemarkHandler(
446 const llvm::OptimizationRemarkAnalysisFPCommute &D);
447 void OptimizationRemarkHandler(
448 const llvm::OptimizationRemarkAnalysisAliasing &D);
449 void OptimizationFailureHandler(
450 const llvm::DiagnosticInfoOptimizationFailure &D);
451 void DontCallDiagHandler(
const DiagnosticInfoDontCall &D);
454 void MisExpectDiagHandler(
const llvm::DiagnosticInfoMisExpect &D);
457 void BackendConsumer::anchor() {}
472 const llvm::SourceMgr &LSM = *D.getSourceMgr();
476 const MemoryBuffer *LBuf =
477 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
481 std::unique_ptr<llvm::MemoryBuffer> CBuf =
482 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
483 LBuf->getBufferIdentifier());
488 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
494 #define ComputeDiagID(Severity, GroupName, DiagID) \
496 switch (Severity) { \
497 case llvm::DS_Error: \
498 DiagID = diag::err_fe_##GroupName; \
500 case llvm::DS_Warning: \
501 DiagID = diag::warn_fe_##GroupName; \
503 case llvm::DS_Remark: \
504 llvm_unreachable("'remark' severity not expected"); \
506 case llvm::DS_Note: \
507 DiagID = diag::note_fe_##GroupName; \
512 #define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
514 switch (Severity) { \
515 case llvm::DS_Error: \
516 DiagID = diag::err_fe_##GroupName; \
518 case llvm::DS_Warning: \
519 DiagID = diag::warn_fe_##GroupName; \
521 case llvm::DS_Remark: \
522 DiagID = diag::remark_fe_##GroupName; \
524 case llvm::DS_Note: \
525 DiagID = diag::note_fe_##GroupName; \
531 const llvm::SMDiagnostic &D = DI.getSMDiag();
534 if (DI.isInlineAsmDiag())
542 D.print(
nullptr, llvm::errs());
551 StringRef Message = D.getMessage();
552 (void)Message.consume_front(
"error: ");
556 if (D.getLoc() != SMLoc())
562 if (DI.isInlineAsmDiag()) {
568 if (D.getLoc().isValid()) {
572 for (
const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
573 unsigned Column = D.getColumnNo();
615 if (D.getSeverity() != llvm::DS_Warning)
625 Diags.
Report(*Loc, diag::warn_fe_frame_larger_than)
626 <<
static_cast<uint32_t
>(D.getStackSize())
627 <<
static_cast<uint32_t
>(D.getStackLimit())
628 << llvm::demangle(D.getFunction().getName().str());
633 const llvm::DiagnosticInfoWithLocationBase &D,
bool &BadDebugInfo,
634 StringRef &
Filename,
unsigned &
Line,
unsigned &Column)
const {
639 if (D.isLocationAvailable()) {
644 FE = FileMgr.
getFile(D.getAbsolutePath());
663 if (DILoc.
isInvalid() && D.isLocationAvailable())
668 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
677 for (
const auto &Pair : ManglingFullSourceLocs) {
678 if (Pair.first == Hash)
685 const llvm::DiagnosticInfoUnsupported &D) {
687 assert(D.getSeverity() == llvm::DS_Error ||
688 D.getSeverity() == llvm::DS_Warning);
691 unsigned Line, Column;
692 bool BadDebugInfo =
false;
695 raw_string_ostream MsgStream(Msg);
699 if (Context !=
nullptr) {
701 MsgStream << D.getMessage();
703 DiagnosticPrinterRawOStream DP(MsgStream);
707 auto DiagType = D.getSeverity() == llvm::DS_Error
708 ? diag::err_fe_backend_unsupported
709 : diag::warn_fe_backend_unsupported;
710 Diags.
Report(Loc, DiagType) << MsgStream.str();
717 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
722 const llvm::DiagnosticInfoOptimizationBase &D,
unsigned DiagID) {
724 assert(D.getSeverity() == llvm::DS_Remark ||
725 D.getSeverity() == llvm::DS_Warning);
728 unsigned Line, Column;
729 bool BadDebugInfo =
false;
732 raw_string_ostream MsgStream(Msg);
736 if (Context !=
nullptr) {
738 MsgStream << D.getMsg();
740 DiagnosticPrinterRawOStream DP(MsgStream);
745 MsgStream <<
" (hotness: " << *D.getHotness() <<
")";
756 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
761 const llvm::DiagnosticInfoOptimizationBase &D) {
763 if (D.isVerbose() && !D.getHotness())
771 }
else if (D.isMissed()) {
777 D, diag::remark_fe_backend_optimization_remark_missed);
779 assert(D.isAnalysis() &&
"Unknown remark type");
781 bool ShouldAlwaysPrint =
false;
782 if (
auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
783 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
785 if (ShouldAlwaysPrint ||
788 D, diag::remark_fe_backend_optimization_remark_analysis);
793 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
798 if (D.shouldAlwaysPrint() ||
801 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
805 const llvm::OptimizationRemarkAnalysisAliasing &D) {
810 if (D.shouldAlwaysPrint() ||
813 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
817 const llvm::DiagnosticInfoOptimizationFailure &D) {
830 Diags.
Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
831 ? diag::err_fe_backend_error_attr
832 : diag::warn_fe_backend_warning_attr)
833 << llvm::demangle(D.getFunctionName().str()) << D.getNote();
837 const llvm::DiagnosticInfoMisExpect &D) {
839 unsigned Line, Column;
840 bool BadDebugInfo =
false;
844 Diags.
Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
851 Diags.
Report(Loc, diag::note_fe_backend_invalid_loc)
858 unsigned DiagID = diag::err_fe_inline_asm;
859 llvm::DiagnosticSeverity
Severity = DI.getSeverity();
861 switch (DI.getKind()) {
862 case llvm::DK_InlineAsm:
867 case llvm::DK_SrcMgr:
870 case llvm::DK_StackSize:
878 case llvm::DK_OptimizationRemark:
883 case llvm::DK_OptimizationRemarkMissed:
888 case llvm::DK_OptimizationRemarkAnalysis:
893 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
898 case llvm::DK_OptimizationRemarkAnalysisAliasing:
903 case llvm::DK_MachineOptimizationRemark:
908 case llvm::DK_MachineOptimizationRemarkMissed:
913 case llvm::DK_MachineOptimizationRemarkAnalysis:
918 case llvm::DK_OptimizationFailure:
923 case llvm::DK_Unsupported:
926 case llvm::DK_DontCall:
929 case llvm::DK_MisExpect:
939 raw_string_ostream Stream(MsgStorage);
940 DiagnosticPrinterRawOStream DP(Stream);
944 if (DI.getKind() == DK_Linker) {
945 assert(CurLinkModule &&
"CurLinkModule must be set for linker diagnostics");
946 Diags.
Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
957 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
958 OwnsVMContext(!_VMContext) {}
978 return std::move(TheModule);
982 OwnsVMContext =
false;
990 static std::unique_ptr<raw_pwrite_stream>
1007 llvm_unreachable(
"Invalid action!");
1010 std::unique_ptr<ASTConsumer>
1021 VMContext->setOpaquePointers(
true);
1024 if (LinkModules.empty())
1030 << F.Filename << BCBuf.getError().message();
1031 LinkModules.clear();
1036 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
1038 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1039 CI.getDiagnostics().Report(diag::err_cannot_open_file)
1040 << F.Filename << EIB.message();
1042 LinkModules.clear();
1045 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
1046 F.Internalize, F.LinkFlags});
1059 std::move(OS), *VMContext, CoverageInfo));
1066 std::unique_ptr<PPCallbacks> Callbacks =
1072 return std::move(Result);
1075 std::unique_ptr<llvm::Module>
1076 CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1084 VMContext->enableDebugTypeODRUniquing();
1086 auto DiagErrors = [&](
Error E) -> std::unique_ptr<llvm::Module> {
1089 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1097 return DiagErrors(BMsOrErr.takeError());
1098 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1104 auto M = std::make_unique<llvm::Module>(
"empty", *VMContext);
1109 Bm->parseModule(*VMContext);
1111 return DiagErrors(MOrErr.takeError());
1112 return std::move(*MOrErr);
1115 llvm::SMDiagnostic Err;
1116 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1123 if (Err.getLineNo() > 0) {
1124 assert(Err.getColumnNo() >= 0);
1125 Loc =
SM.translateFileLineCol(
SM.getFileEntryForID(
SM.getMainFileID()),
1126 Err.getLineNo(), Err.getColumnNo() + 1);
1130 StringRef Msg = Err.getMessage();
1131 if (Msg.startswith(
"error: "))
1132 Msg = Msg.substr(7);
1152 std::unique_ptr<raw_pwrite_stream> OS =
1163 TheModule = loadModule(*MainFile);
1168 if (TheModule->getTargetTriple() != TargetOpts.
Triple) {
1169 Diagnostics.Report(
SourceLocation(), diag::warn_fe_override_module)
1171 TheModule->setTargetTriple(TargetOpts.
Triple);
1174 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1177 LLVMContext &Ctx = TheModule->getContext();
1183 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1184 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1192 std::move(LinkModules), *VMContext,
nullptr);
1195 Ctx.setDiscardValueNames(
false);
1196 Ctx.setDiagnosticHandler(
1197 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1200 setupLLVMOptimizationRemarks(
1201 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1202 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1203 CodeGenOpts.DiagnosticsHotnessThreshold);
1205 if (
Error E = OptRecordFileOrErr.takeError()) {
1209 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1210 std::move(*OptRecordFileOrErr);
1217 OptRecordFile->keep();
1222 void EmitAssemblyAction::anchor() { }
1226 void EmitBCAction::anchor() { }
1230 void EmitLLVMAction::anchor() { }
1234 void EmitLLVMOnlyAction::anchor() { }
1238 void EmitCodeGenOnlyAction::anchor() { }
1242 void EmitObjAction::anchor() { }