clang: lib/CodeGen/CodeGenAction.cpp Source File (original) (raw)
1
2
3
4
5
6
7
8
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"
45#include "llvm/Pass.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"
53
54#include
55using namespace clang;
56using namespace llvm;
57
58#define DEBUG_TYPE "codegenaction"
59
63public:
65 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
66
68
71 }
74 }
77 }
78
83 }
84
85private:
88};
89
92 handleAllErrors(
93 std::move(E),
94 [&](const LLVMRemarkSetupFileError &E) {
95 Diags.Report(diag::err_cannot_open_file)
97 },
98 [&](const LLVMRemarkSetupPatternError &E) {
99 Diags.Report(diag::err_drv_optimization_remark_pattern)
101 },
102 [&](const LLVMRemarkSetupFormatError &E) {
103 Diags.Report(diag::err_drv_optimization_remark_format)
105 });
106}
107
110 LLVMContext &C,
112 StringRef InFile,
113 std::unique_ptr<raw_pwrite_stream> OS,
115 llvm::Module *CurLinkModule)
116 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
117 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
118 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),
120 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
121 CI.getCodeGenOpts(), C, CoverageInfo)),
122 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {
123 TimerIsEnabled = CodeGenOpts.TimePasses;
124 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
125 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
126 if (CodeGenOpts.TimePasses)
127 LLVMIRGeneration.init("irgen", "LLVM IR generation", CI.getTimerGroup());
128}
129
131 return Gen->GetModule();
132}
133
135 return std::unique_ptrllvm::Module(Gen->ReleaseModule());
136}
137
139 return Gen.get();
140}
141
143 Gen->HandleCXXStaticMemberVarInstantiation(VD);
144}
145
147 assert(!Context && "initialized multiple times");
148
149 Context = &Ctx;
150
151 if (TimerIsEnabled)
152 LLVMIRGeneration.startTimer();
153
154 Gen->Initialize(Ctx);
155
156 if (TimerIsEnabled)
157 LLVMIRGeneration.stopTimer();
158}
159
163 "LLVM IR generation of declaration");
164
165
166 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
168
169 Gen->HandleTopLevelDecl(D);
170
171 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
173
174 return true;
175}
176
180 "LLVM IR generation of inline function");
181 if (TimerIsEnabled)
183
184 Gen->HandleInlineFunctionDefinition(D);
185
186 if (TimerIsEnabled)
188}
189
191
192 if (!IRGenFinished)
194}
195
196
198 for (auto &LM : LinkModules) {
199 assert(LM.Module && "LinkModule does not actually have a module");
200
201 if (LM.PropagateAttrs)
202 for (Function &F : *LM.Module) {
203
204
205 if (F.isIntrinsic())
206 continue;
208 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
209 }
210
211 CurLinkModule = LM.Module.get();
212 bool Err;
213
214 if (LM.Internalize) {
215 Err = Linker::linkModules(
216 *M, std::move(LM.Module), LM.LinkFlags,
217 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
218 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
219 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
220 });
221 });
222 } else
223 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
224
225 if (Err)
226 return true;
227 }
228
229 LinkModules.clear();
230 return false;
231}
232
234 {
235 llvm::TimeTraceScope TimeScope("Frontend");
236 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
237 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
239
240 Gen->HandleTranslationUnit(C);
241
242 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
244
245 IRGenFinished = true;
246 }
247
248
250 return;
251
252 LLVMContext &Ctx = getModule()->getContext();
253 std::unique_ptr OldDiagnosticHandler =
254 Ctx.getDiagnosticHandler();
255 Ctx.setDiagnosticHandler(std::make_unique(
256 CodeGenOpts, this));
257
258 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
259 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
260
262 setupLLVMOptimizationRemarks(
264 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
266
267 if (Error E = OptRecordFileOrErr.takeError()) {
269 return;
270 }
271
272 std::unique_ptrllvm::ToolOutputFile OptRecordFile =
273 std::move(*OptRecordFileOrErr);
274
275 if (OptRecordFile &&
277 Ctx.setDiagnosticsHotnessRequested(true);
278
279 if (CodeGenOpts.MisExpect) {
280 Ctx.setMisExpectWarningRequested(true);
281 }
282
284 Ctx.setDiagnosticsMisExpectTolerance(
286 }
287
288
290 return;
291
292 for (auto &F : getModule()->functions()) {
293 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
294 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
295
297 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
298 }
299 }
300
301 if (CodeGenOpts.ClearASTBeforeBackend) {
302 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
303
304
305
306
307
308
309 C.cleanup();
310 C.getAllocator().Reset();
311 }
312
314
316 C.getTargetInfo().getDataLayoutString(), getModule(),
317 Action, FS, std::move(AsmOutStream), this);
318
319 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
320
321 if (OptRecordFile)
322 OptRecordFile->keep();
323}
324
328 "LLVM IR generation of declaration");
329 Gen->HandleTagDeclDefinition(D);
330}
331
333 Gen->HandleTagDeclRequiredDefinition(D);
334}
335
337 Gen->CompleteTentativeDefinition(D);
338}
339
341 Gen->CompleteExternalDeclaration(D);
342}
343
345 Gen->AssignInheritanceModel(RD);
346}
347
349 Gen->HandleVTable(RD);
350}
351
352void BackendConsumer::anchor() { }
353
354}
355
358 return true;
359}
360
361
362
365
366
367
368 const llvm::SourceMgr &LSM = *D.getSourceMgr();
369
370
371
372 const MemoryBuffer *LBuf =
373 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
374
375
376
377 std::unique_ptrllvm::MemoryBuffer CBuf =
378 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
379 LBuf->getBufferIdentifier());
380
382
383
384 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
388}
389
390#define ComputeDiagID(Severity, GroupName, DiagID) \
391 do { \
392 switch (Severity) { \
393 case llvm::DS_Error: \
394 DiagID = diag::err_fe_##GroupName; \
395 break; \
396 case llvm::DS_Warning: \
397 DiagID = diag::warn_fe_##GroupName; \
398 break; \
399 case llvm::DS_Remark: \
400 llvm_unreachable("'remark' severity not expected"); \
401 break; \
402 case llvm::DS_Note: \
403 DiagID = diag::note_fe_##GroupName; \
404 break; \
405 } \
406 } while (false)
407
408#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
409 do { \
410 switch (Severity) { \
411 case llvm::DS_Error: \
412 DiagID = diag::err_fe_##GroupName; \
413 break; \
414 case llvm::DS_Warning: \
415 DiagID = diag::warn_fe_##GroupName; \
416 break; \
417 case llvm::DS_Remark: \
418 DiagID = diag::remark_fe_##GroupName; \
419 break; \
420 case llvm::DS_Note: \
421 DiagID = diag::note_fe_##GroupName; \
422 break; \
423 } \
424 } while (false)
425
427 const llvm::SMDiagnostic &D = DI.getSMDiag();
428
429 unsigned DiagID;
430 if (DI.isInlineAsmDiag())
431 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
432 else
433 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
434
435
436
437 if (!Context) {
438 D.print(nullptr, llvm::errs());
439 Diags.Report(DiagID).AddString("cannot compile inline asm");
440 return;
441 }
442
443
444
445
446
447 StringRef Message = D.getMessage();
448 (void)Message.consume_front("error: ");
449
450
452 if (D.getLoc() != SMLoc())
454
455
456
457
458 if (DI.isInlineAsmDiag()) {
461 if (LocCookie.isValid()) {
463
464 if (D.getLoc().isValid()) {
466
467
468 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
469 unsigned Column = D.getColumnNo();
472 }
473 }
474 return;
475 }
476 }
477
478
479
480
482}
483
484bool
486 unsigned DiagID;
488 std::string Message = D.getMsgStr().str();
489
490
491
492
497 else {
498
499
500
501
504 }
505
506 return true;
507}
508
509bool
511 if (D.getSeverity() != llvm::DS_Warning)
512
513
514 return false;
515
517 if ()
518 return false;
519
520 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
521 << D.getStackSize() << D.getStackLimit()
522 << llvm::demangle(D.getFunction().getName());
523 return true;
524}
525
527 const llvm::DiagnosticInfoResourceLimit &D) {
529 if ()
530 return false;
531 unsigned DiagID = diag::err_fe_backend_resource_limit;
532 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
533
535 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
536 << llvm::demangle(D.getFunction().getName());
537 return true;
538}
539
541 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
546
547 if (D.isLocationAvailable()) {
549 if (Line > 0) {
551 if (!FE)
553 if (FE) {
554
555
557 }
558 }
559 BadDebugInfo = DILoc.isInvalid();
560 }
561
562
563
564
568 Loc = *MaybeLoc;
569 }
570
571 if (DILoc.isInvalid() && D.isLocationAvailable())
572
573
574
575
576 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
578
579 return Loc;
580}
581
582std::optional
585 for (const auto &Pair : ManglingFullSourceLocs) {
586 if (Pair.first == Hash)
587 return Pair.second;
588 }
589 return std::nullopt;
590}
591
593 const llvm::DiagnosticInfoUnsupported &D) {
594
595 assert(D.getSeverity() == llvm::DS_Error ||
596 D.getSeverity() == llvm::DS_Warning);
597
600 bool BadDebugInfo = false;
602 std::string Msg;
603 raw_string_ostream MsgStream(Msg);
604
605
606
607 if (Context != nullptr) {
609 MsgStream << D.getMessage();
610 } else {
611 DiagnosticPrinterRawOStream DP(MsgStream);
613 }
614
615 auto DiagType = D.getSeverity() == llvm::DS_Error
616 ? diag::err_fe_backend_unsupported
617 : diag::warn_fe_backend_unsupported;
618 Diags.Report(Loc, DiagType) << Msg;
619
620 if (BadDebugInfo)
621
622
623
624
625 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
627}
628
630 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
631
632 assert(D.getSeverity() == llvm::DS_Remark ||
633 D.getSeverity() == llvm::DS_Warning);
634
637 bool BadDebugInfo = false;
639 std::string Msg;
640 raw_string_ostream MsgStream(Msg);
641
642
643
644 if (Context != nullptr) {
646 MsgStream << D.getMsg();
647 } else {
648 DiagnosticPrinterRawOStream DP(MsgStream);
650 }
651
652 if (D.getHotness())
653 MsgStream << " (hotness: " << *D.getHotness() << ")";
654
656
657 if (BadDebugInfo)
658
659
660
661
662 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
664}
665
667 const llvm::DiagnosticInfoOptimizationBase &D) {
668
669 if (D.isVerbose() && .getHotness())
670 return;
671
672 if (D.isPassed()) {
673
674
677 } else if (D.isMissed()) {
678
679
680
683 D, diag::remark_fe_backend_optimization_remark_missed);
684 } else {
685 assert(D.isAnalysis() && "Unknown remark type");
686
687 bool ShouldAlwaysPrint = false;
688 if (auto *ORA = dyn_castllvm::OptimizationRemarkAnalysis(&D))
689 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
690
691 if (ShouldAlwaysPrint ||
694 D, diag::remark_fe_backend_optimization_remark_analysis);
695 }
696}
697
699 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
700
701
702
703
704 if (D.shouldAlwaysPrint() ||
707 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
708}
709
711 const llvm::OptimizationRemarkAnalysisAliasing &D) {
712
713
714
715
716 if (D.shouldAlwaysPrint() ||
719 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
720}
721
723 const llvm::DiagnosticInfoOptimizationFailure &D) {
725}
726
730
731
732
733 if (!LocCookie.isValid())
734 return;
735
736 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
737 ? diag::err_fe_backend_error_attr
738 : diag::warn_fe_backend_warning_attr)
739 << llvm::demangle(D.getFunctionName()) << D.getNote();
740}
741
743 const llvm::DiagnosticInfoMisExpect &D) {
746 bool BadDebugInfo = false;
749
750 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
751
752 if (BadDebugInfo)
753
754
755
756
757 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
759}
760
761
762
764 unsigned DiagID = diag::err_fe_inline_asm;
765 llvm::DiagnosticSeverity Severity = DI.getSeverity();
766
767 switch (DI.getKind()) {
768 case llvm::DK_InlineAsm:
770 return;
772 break;
773 case llvm::DK_SrcMgr:
775 return;
776 case llvm::DK_StackSize:
778 return;
779 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
780 break;
781 case llvm::DK_ResourceLimit:
783 return;
784 ComputeDiagID(Severity, backend_resource_limit, DiagID);
785 break;
786 case DK_Linker:
788 break;
789 case llvm::DK_OptimizationRemark:
790
791
793 return;
794 case llvm::DK_OptimizationRemarkMissed:
795
796
798 return;
799 case llvm::DK_OptimizationRemarkAnalysis:
800
801
803 return;
804 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
805
806
808 return;
809 case llvm::DK_OptimizationRemarkAnalysisAliasing:
810
811
813 return;
814 case llvm::DK_MachineOptimizationRemark:
815
816
818 return;
819 case llvm::DK_MachineOptimizationRemarkMissed:
820
821
823 return;
824 case llvm::DK_MachineOptimizationRemarkAnalysis:
825
826
828 return;
829 case llvm::DK_OptimizationFailure:
830
831
833 return;
834 case llvm::DK_Unsupported:
836 return;
837 case llvm::DK_DontCall:
839 return;
840 case llvm::DK_MisExpect:
842 return;
843 default:
844
846 break;
847 }
848 std::string MsgStorage;
849 {
850 raw_string_ostream Stream(MsgStorage);
851 DiagnosticPrinterRawOStream DP(Stream);
852 DI.print(DP);
853 }
854
855 if (DI.getKind() == DK_Linker) {
856 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
857 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
858 return;
859 }
860
861
864}
865#undef ComputeDiagID
866
868 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
869 OwnsVMContext(!_VMContext) {}
870
872 TheModule.reset();
873 if (OwnsVMContext)
874 delete VMContext;
875}
876
878 if (!LinkModules.empty())
879 return false;
880
884 if (!BCBuf) {
886 << F.Filename << BCBuf.getError().message();
887 LinkModules.clear();
888 return true;
889 }
890
892 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
893 if (!ModuleOrErr) {
894 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
895 CI.getDiagnostics().Report(diag::err_cannot_open_file)
896 << F.Filename << EIB.message();
897 });
898 LinkModules.clear();
899 return true;
900 }
901 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
902 F.Internalize, F.LinkFlags});
903 }
904 return false;
905}
906
908
910
912 return;
913
914
916}
917
919 return std::move(TheModule);
920}
921
923 OwnsVMContext = false;
924 return VMContext;
925}
926
929}
930
934 return true;
935}
936
937static std::unique_ptr<raw_pwrite_stream>
939 switch (Action) {
947 return nullptr;
952 }
953
954 llvm_unreachable("Invalid action!");
955}
956
957std::unique_ptr
960 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
961 if (!OS)
963
965 return nullptr;
966
967
968 if (loadLinkModules(CI))
969 return nullptr;
970
972
976
979 InFile, std::move(OS), CoverageInfo));
981
982
983
984 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
986 std::unique_ptr Callbacks =
990 }
991
994 std::vector<std::unique_ptr> Consumers(2);
995 Consumers[0] = std::make_unique(
998 Consumers[1] = std::move(Result);
999 return std::make_unique(std::move(Consumers));
1000 }
1001
1002 return std::move(Result);
1003}
1004
1005std::unique_ptrllvm::Module
1006CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1009
1010 auto DiagErrors = [&](Error E) -> std::unique_ptrllvm::Module {
1011 unsigned DiagID =
1013 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1015 });
1016 return {};
1017 };
1018
1019
1020
1021
1023 VMContext->enableDebugTypeODRUniquing();
1024
1026 if (!BMsOrErr)
1027 return DiagErrors(BMsOrErr.takeError());
1028 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1029
1030
1031
1032
1033 if (!Bm) {
1034 auto M = std::make_uniquellvm::Module("empty", *VMContext);
1036 return M;
1037 }
1039 Bm->parseModule(*VMContext);
1040 if (!MOrErr)
1041 return DiagErrors(MOrErr.takeError());
1042 return std::move(*MOrErr);
1043 }
1044
1045
1046 if (loadLinkModules(CI))
1047 return nullptr;
1048
1049
1050 llvm::SMDiagnostic Err;
1051 if (std::unique_ptrllvm::Module M = parseIR(MBRef, Err, *VMContext))
1052 return M;
1053
1054
1055
1056
1058 if (BMsOrErr && BMsOrErr->size()) {
1059 std::unique_ptrllvm::Module FirstM;
1060 for (auto &BM : *BMsOrErr) {
1062 BM.parseModule(*VMContext);
1063 if (!MOrErr)
1064 return DiagErrors(MOrErr.takeError());
1065 if (FirstM)
1066 LinkModules.push_back({std::move(*MOrErr), false,
1067 false, {}});
1068 else
1069 FirstM = std::move(*MOrErr);
1070 }
1071 if (FirstM)
1072 return FirstM;
1073 }
1074
1075
1076 consumeError(BMsOrErr.takeError());
1077
1078
1079
1080
1082 if (Err.getLineNo() > 0) {
1083 assert(Err.getColumnNo() >= 0);
1084 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1085 Err.getLineNo(), Err.getColumnNo() + 1);
1086 }
1087
1088
1089 StringRef Msg = Err.getMessage();
1090 Msg.consume_front("error: ");
1091
1092 unsigned DiagID =
1094
1096 return {};
1097}
1098
1102 return;
1103 }
1104
1105
1110 std::unique_ptr<raw_pwrite_stream> OS =
1113 return;
1114
1116 FileID FID = SM.getMainFileID();
1117 std::optional MainFile = SM.getBufferOrNone(FID);
1118 if (!MainFile)
1119 return;
1120
1121 TheModule = loadModule(*MainFile);
1122 if (!TheModule)
1123 return;
1124
1126 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1127 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1128 << TargetOpts.Triple;
1129 TheModule->setTargetTriple(TargetOpts.Triple);
1130 }
1131
1132 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1133 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1134
1135 LLVMContext &Ctx = TheModule->getContext();
1136
1137
1138
1139 struct RAII {
1140 LLVMContext &Ctx;
1141 std::unique_ptr PrevHandler = Ctx.getDiagnosticHandler();
1142 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1143 } _{Ctx};
1144
1145
1146
1148 std::move(LinkModules), "", nullptr, nullptr,
1149 TheModule.get());
1150
1151
1152 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
1153 return;
1154
1155
1156
1157 Ctx.setDiscardValueNames(false);
1158 Ctx.setDiagnosticHandler(
1159 std::make_unique(CodeGenOpts, &Result));
1160
1161 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1162 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1163
1165 setupLLVMOptimizationRemarks(
1166 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1167 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1168 CodeGenOpts.DiagnosticsHotnessThreshold);
1169
1170 if (Error E = OptRecordFileOrErr.takeError()) {
1172 return;
1173 }
1174 std::unique_ptrllvm::ToolOutputFile OptRecordFile =
1175 std::move(*OptRecordFileOrErr);
1176
1180 std::move(OS));
1181 if (OptRecordFile)
1182 OptRecordFile->keep();
1183}
1184
1185
1186
1187void EmitAssemblyAction::anchor() { }
1190
1191void EmitBCAction::anchor() { }
1194
1195void EmitLLVMAction::anchor() { }
1198
1199void EmitLLVMOnlyAction::anchor() { }
1202
1203void EmitCodeGenOnlyAction::anchor() { }
1206
1207void 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.
InMemoryModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Decl - This represents one declaration (or definition), e.g.
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.
@ 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)