clang 20.0.0git
CodeGenAction.cpp
Go to the documentation of this file.
1//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "BackendConsumer.h"
11#include "CGCall.h"
12#include "CodeGenModule.h"
13#include "CoverageMappingGen.h"
14#include "MacroPPCallbacks.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclGroup.h"
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 <optional>
55using namespace clang;
56using namespace llvm;
57
58#define DEBUG_TYPE "codegenaction"
59
60namespace clang {
61class BackendConsumer;
63public:
65 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
66
67 bool handleDiagnostics(const DiagnosticInfo &DI) override;
68
69 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
70 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
71 }
72 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
73 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
74 }
75 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
76 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
77 }
78
79 bool isAnyRemarkEnabled() const override {
80 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
83 }
84
85private:
86 const CodeGenOptions &CodeGenOpts;
87 BackendConsumer *BackendCon;
88};
89
90static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
91 const CodeGenOptions &CodeGenOpts) {
92 handleAllErrors(
93 std::move(E),
94 [&](const LLVMRemarkSetupFileError &E) {
95 Diags.Report(diag::err_cannot_open_file)
96 << CodeGenOpts.OptRecordFile << E.message();
97 },
98 [&](const LLVMRemarkSetupPatternError &E) {
99 Diags.Report(diag::err_drv_optimization_remark_pattern)
100 << E.message() << CodeGenOpts.OptRecordPasses;
101 },
102 [&](const LLVMRemarkSetupFormatError &E) {
103 Diags.Report(diag::err_drv_optimization_remark_format)
104 << CodeGenOpts.OptRecordFormat;
105 });
106}
107
110 LLVMContext &C,
111 SmallVector<LinkModule, 4> LinkModules,
112 StringRef InFile,
113 std::unique_ptr<raw_pwrite_stream> OS,
114 CoverageSourceInfo *CoverageInfo,
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),
119 Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS),
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
130llvm::Module* BackendConsumer::getModule() const {
131 return Gen->GetModule();
132}
133
134std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
135 return std::unique_ptr<llvm::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
161 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
162 Context->getSourceManager(),
163 "LLVM IR generation of declaration");
164
165 // Recurse.
166 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
167 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
168
169 Gen->HandleTopLevelDecl(D);
170
171 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
172 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
173
174 return true;
175}
176
179 Context->getSourceManager(),
180 "LLVM IR generation of inline function");
181 if (TimerIsEnabled)
182 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
183
184 Gen->HandleInlineFunctionDefinition(D);
185
186 if (TimerIsEnabled)
187 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
188}
189
191 // Ignore interesting decls from the AST reader after IRGen is finished.
192 if (!IRGenFinished)
194}
195
196// Links each entry in LinkModules into our module. Returns true on error.
197bool BackendConsumer::LinkInModules(llvm::Module *M) {
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 // Skip intrinsics. Keep consistent with how intrinsics are created
204 // in LLVM IR.
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; // success
231}
232
234 {
235 llvm::TimeTraceScope TimeScope("Frontend");
236 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
237 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
238 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
239
240 Gen->HandleTranslationUnit(C);
241
242 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
243 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
244
245 IRGenFinished = true;
246 }
247
248 // Silently ignore if we weren't initialized for some reason.
249 if (!getModule())
250 return;
251
252 LLVMContext &Ctx = getModule()->getContext();
253 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
254 Ctx.getDiagnosticHandler();
255 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
256 CodeGenOpts, this));
257
258 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
259 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
260
262 setupLLVMOptimizationRemarks(
263 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
264 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
265 CodeGenOpts.DiagnosticsHotnessThreshold);
266
267 if (Error E = OptRecordFileOrErr.takeError()) {
268 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
269 return;
270 }
271
272 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
273 std::move(*OptRecordFileOrErr);
274
275 if (OptRecordFile &&
276 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
277 Ctx.setDiagnosticsHotnessRequested(true);
278
279 if (CodeGenOpts.MisExpect) {
280 Ctx.setMisExpectWarningRequested(true);
281 }
282
283 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
284 Ctx.setDiagnosticsMisExpectTolerance(
286 }
287
288 // Link each LinkModule into our module.
289 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
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 // TODO: use a fast content hash when available.
296 auto NameHash = llvm::hash_value(F.getName());
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 // Access to the AST is no longer available after this.
304 // Other things that the ASTContext manages are still available, e.g.
305 // the SourceManager. It'd be nice if we could separate out all the
306 // things in ASTContext used after this point and null out the
307 // ASTContext, but too many various parts of the ASTContext are still
308 // used in various parts.
309 C.cleanup();
310 C.getAllocator().Reset();
311 }
312
313 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
314
315 emitBackendOutput(CI, C.getTargetInfo().getDataLayoutString(), getModule(),
316 Action, FS, std::move(AsmOutStream), this);
317
318 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
319
320 if (OptRecordFile)
321 OptRecordFile->keep();
322}
323
326 Context->getSourceManager(),
327 "LLVM IR generation of declaration");
328 Gen->HandleTagDeclDefinition(D);
329}
330
332 Gen->HandleTagDeclRequiredDefinition(D);
333}
334
336 Gen->CompleteTentativeDefinition(D);
337}
338
340 Gen->CompleteExternalDeclaration(D);
341}
342
344 Gen->AssignInheritanceModel(RD);
345}
346
348 Gen->HandleVTable(RD);
349}
350
351void BackendConsumer::anchor() { }
352
353} // namespace clang
354
355bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
356 BackendCon->DiagnosticHandlerImpl(DI);
357 return true;
358}
359
360/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
361/// buffer to be a valid FullSourceLoc.
362static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
363 SourceManager &CSM) {
364 // Get both the clang and llvm source managers. The location is relative to
365 // a memory buffer that the LLVM Source Manager is handling, we need to add
366 // a copy to the Clang source manager.
367 const llvm::SourceMgr &LSM = *D.getSourceMgr();
368
369 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
370 // already owns its one and clang::SourceManager wants to own its one.
371 const MemoryBuffer *LBuf =
372 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
373
374 // Create the copy and transfer ownership to clang::SourceManager.
375 // TODO: Avoid copying files into memory.
376 std::unique_ptr<llvm::MemoryBuffer> CBuf =
377 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
378 LBuf->getBufferIdentifier());
379 // FIXME: Keep a file ID map instead of creating new IDs for each location.
380 FileID FID = CSM.createFileID(std::move(CBuf));
381
382 // Translate the offset into the file.
383 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
384 SourceLocation NewLoc =
385 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
386 return FullSourceLoc(NewLoc, CSM);
387}
388
389#define ComputeDiagID(Severity, GroupName, DiagID) \
390 do { \
391 switch (Severity) { \
392 case llvm::DS_Error: \
393 DiagID = diag::err_fe_##GroupName; \
394 break; \
395 case llvm::DS_Warning: \
396 DiagID = diag::warn_fe_##GroupName; \
397 break; \
398 case llvm::DS_Remark: \
399 llvm_unreachable("'remark' severity not expected"); \
400 break; \
401 case llvm::DS_Note: \
402 DiagID = diag::note_fe_##GroupName; \
403 break; \
404 } \
405 } while (false)
406
407#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
408 do { \
409 switch (Severity) { \
410 case llvm::DS_Error: \
411 DiagID = diag::err_fe_##GroupName; \
412 break; \
413 case llvm::DS_Warning: \
414 DiagID = diag::warn_fe_##GroupName; \
415 break; \
416 case llvm::DS_Remark: \
417 DiagID = diag::remark_fe_##GroupName; \
418 break; \
419 case llvm::DS_Note: \
420 DiagID = diag::note_fe_##GroupName; \
421 break; \
422 } \
423 } while (false)
424
425void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
426 const llvm::SMDiagnostic &D = DI.getSMDiag();
427
428 unsigned DiagID;
429 if (DI.isInlineAsmDiag())
430 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
431 else
432 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
433
434 // This is for the empty BackendConsumer that uses the clang diagnostic
435 // handler for IR input files.
436 if (!Context) {
437 D.print(nullptr, llvm::errs());
438 Diags.Report(DiagID).AddString("cannot compile inline asm");
439 return;
440 }
441
442 // There are a couple of different kinds of errors we could get here.
443 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
444
445 // Strip "error: " off the start of the message string.
446 StringRef Message = D.getMessage();
447 (void)Message.consume_front("error: ");
448
449 // If the SMDiagnostic has an inline asm source location, translate it.
451 if (D.getLoc() != SMLoc())
453
454 // If this problem has clang-level source location information, report the
455 // issue in the source with a note showing the instantiated
456 // code.
457 if (DI.isInlineAsmDiag()) {
458 SourceLocation LocCookie =
459 SourceLocation::getFromRawEncoding(DI.getLocCookie());
460 if (LocCookie.isValid()) {
461 Diags.Report(LocCookie, DiagID).AddString(Message);
462
463 if (D.getLoc().isValid()) {
464 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
465 // Convert the SMDiagnostic ranges into SourceRange and attach them
466 // to the diagnostic.
467 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
468 unsigned Column = D.getColumnNo();
470 Loc.getLocWithOffset(Range.second - Column));
471 }
472 }
473 return;
474 }
475 }
476
477 // Otherwise, report the backend issue as occurring in the generated .s file.
478 // If Loc is invalid, we still need to report the issue, it just gets no
479 // location info.
480 Diags.Report(Loc, DiagID).AddString(Message);
481}
482
483bool
484BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
485 unsigned DiagID;
486 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
487 std::string Message = D.getMsgStr().str();
488
489 // If this problem has clang-level source location information, report the
490 // issue as being a problem in the source with a note showing the instantiated
491 // code.
492 SourceLocation LocCookie =
494 if (LocCookie.isValid())
495 Diags.Report(LocCookie, DiagID).AddString(Message);
496 else {
497 // Otherwise, report the backend diagnostic as occurring in the generated
498 // .s file.
499 // If Loc is invalid, we still need to report the diagnostic, it just gets
500 // no location info.
502 Diags.Report(Loc, DiagID).AddString(Message);
503 }
504 // We handled all the possible severities.
505 return true;
506}
507
508bool
509BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
510 if (D.getSeverity() != llvm::DS_Warning)
511 // For now, the only support we have for StackSize diagnostic is warning.
512 // We do not know how to format other severities.
513 return false;
514
515 auto Loc = getFunctionSourceLocation(D.getFunction());
516 if (!Loc)
517 return false;
518
519 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
520 << D.getStackSize() << D.getStackLimit()
521 << llvm::demangle(D.getFunction().getName());
522 return true;
523}
524
526 const llvm::DiagnosticInfoResourceLimit &D) {
527 auto Loc = getFunctionSourceLocation(D.getFunction());
528 if (!Loc)
529 return false;
530 unsigned DiagID = diag::err_fe_backend_resource_limit;
531 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
532
533 Diags.Report(*Loc, DiagID)
534 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
535 << llvm::demangle(D.getFunction().getName());
536 return true;
537}
538
540 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
541 StringRef &Filename, unsigned &Line, unsigned &Column) const {
542 SourceManager &SourceMgr = Context->getSourceManager();
543 FileManager &FileMgr = SourceMgr.getFileManager();
544 SourceLocation DILoc;
545
546 if (D.isLocationAvailable()) {
548 if (Line > 0) {
549 auto FE = FileMgr.getOptionalFileRef(Filename);
550 if (!FE)
551 FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());
552 if (FE) {
553 // If -gcolumn-info was not used, Column will be 0. This upsets the
554 // source manager, so pass 1 if Column is not set.
555 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
556 }
557 }
558 BadDebugInfo = DILoc.isInvalid();
559 }
560
561 // If a location isn't available, try to approximate it using the associated
562 // function definition. We use the definition's right brace to differentiate
563 // from diagnostics that genuinely relate to the function itself.
564 FullSourceLoc Loc(DILoc, SourceMgr);
565 if (Loc.isInvalid()) {
566 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
567 Loc = *MaybeLoc;
568 }
569
570 if (DILoc.isInvalid() && D.isLocationAvailable())
571 // If we were not able to translate the file:line:col information
572 // back to a SourceLocation, at least emit a note stating that
573 // we could not translate this location. This can happen in the
574 // case of #line directives.
575 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
576 << Filename << Line << Column;
577
578 return Loc;
579}
580
581std::optional<FullSourceLoc>
583 auto Hash = llvm::hash_value(F.getName());
584 for (const auto &Pair : ManglingFullSourceLocs) {
585 if (Pair.first == Hash)
586 return Pair.second;
587 }
588 return std::nullopt;
589}
590
592 const llvm::DiagnosticInfoUnsupported &D) {
593 // We only support warnings or errors.
594 assert(D.getSeverity() == llvm::DS_Error ||
595 D.getSeverity() == llvm::DS_Warning);
596
597 StringRef Filename;
598 unsigned Line, Column;
599 bool BadDebugInfo = false;
601 std::string Msg;
602 raw_string_ostream MsgStream(Msg);
603
604 // Context will be nullptr for IR input files, we will construct the diag
605 // message from llvm::DiagnosticInfoUnsupported.
606 if (Context != nullptr) {
608 MsgStream << D.getMessage();
609 } else {
610 DiagnosticPrinterRawOStream DP(MsgStream);
611 D.print(DP);
612 }
613
614 auto DiagType = D.getSeverity() == llvm::DS_Error
615 ? diag::err_fe_backend_unsupported
616 : diag::warn_fe_backend_unsupported;
617 Diags.Report(Loc, DiagType) << Msg;
618
619 if (BadDebugInfo)
620 // If we were not able to translate the file:line:col information
621 // back to a SourceLocation, at least emit a note stating that
622 // we could not translate this location. This can happen in the
623 // case of #line directives.
624 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
625 << Filename << Line << Column;
626}
627
629 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
630 // We only support warnings and remarks.
631 assert(D.getSeverity() == llvm::DS_Remark ||
632 D.getSeverity() == llvm::DS_Warning);
633
634 StringRef Filename;
635 unsigned Line, Column;
636 bool BadDebugInfo = false;
638 std::string Msg;
639 raw_string_ostream MsgStream(Msg);
640
641 // Context will be nullptr for IR input files, we will construct the remark
642 // message from llvm::DiagnosticInfoOptimizationBase.
643 if (Context != nullptr) {
645 MsgStream << D.getMsg();
646 } else {
647 DiagnosticPrinterRawOStream DP(MsgStream);
648 D.print(DP);
649 }
650
651 if (D.getHotness())
652 MsgStream << " (hotness: " << *D.getHotness() << ")";
653
654 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
655
656 if (BadDebugInfo)
657 // If we were not able to translate the file:line:col information
658 // back to a SourceLocation, at least emit a note stating that
659 // we could not translate this location. This can happen in the
660 // case of #line directives.
661 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
662 << Filename << Line << Column;
663}
664
666 const llvm::DiagnosticInfoOptimizationBase &D) {
667 // Without hotness information, don't show noisy remarks.
668 if (D.isVerbose() && !D.getHotness())
669 return;
670
671 if (D.isPassed()) {
672 // Optimization remarks are active only if the -Rpass flag has a regular
673 // expression that matches the name of the pass name in \p D.
674 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
675 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
676 } else if (D.isMissed()) {
677 // Missed optimization remarks are active only if the -Rpass-missed
678 // flag has a regular expression that matches the name of the pass
679 // name in \p D.
680 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
682 D, diag::remark_fe_backend_optimization_remark_missed);
683 } else {
684 assert(D.isAnalysis() && "Unknown remark type");
685
686 bool ShouldAlwaysPrint = false;
687 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
688 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
689
690 if (ShouldAlwaysPrint ||
691 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
693 D, diag::remark_fe_backend_optimization_remark_analysis);
694 }
695}
696
698 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
699 // Optimization analysis remarks are active if the pass name is set to
700 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
701 // regular expression that matches the name of the pass name in \p D.
702
703 if (D.shouldAlwaysPrint() ||
704 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
706 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
707}
708
710 const llvm::OptimizationRemarkAnalysisAliasing &D) {
711 // Optimization analysis remarks are active if the pass name is set to
712 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
713 // regular expression that matches the name of the pass name in \p D.
714
715 if (D.shouldAlwaysPrint() ||
716 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
718 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
719}
720
722 const llvm::DiagnosticInfoOptimizationFailure &D) {
723 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
724}
725
726void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
727 SourceLocation LocCookie =
729
730 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
731 // should instead assert that LocCookie.isValid().
732 if (!LocCookie.isValid())
733 return;
734
735 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
736 ? diag::err_fe_backend_error_attr
737 : diag::warn_fe_backend_warning_attr)
738 << llvm::demangle(D.getFunctionName()) << D.getNote();
739}
740
742 const llvm::DiagnosticInfoMisExpect &D) {
743 StringRef Filename;
744 unsigned Line, Column;
745 bool BadDebugInfo = false;
748
749 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
750
751 if (BadDebugInfo)
752 // If we were not able to translate the file:line:col information
753 // back to a SourceLocation, at least emit a note stating that
754 // we could not translate this location. This can happen in the
755 // case of #line directives.
756 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
757 << Filename << Line << Column;
758}
759
760/// This function is invoked when the backend needs
761/// to report something to the user.
762void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
763 unsigned DiagID = diag::err_fe_inline_asm;
764 llvm::DiagnosticSeverity Severity = DI.getSeverity();
765 // Get the diagnostic ID based.
766 switch (DI.getKind()) {
767 case llvm::DK_InlineAsm:
768 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
769 return;
770 ComputeDiagID(Severity, inline_asm, DiagID);
771 break;
772 case llvm::DK_SrcMgr:
773 SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
774 return;
775 case llvm::DK_StackSize:
776 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
777 return;
778 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
779 break;
780 case llvm::DK_ResourceLimit:
781 if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))
782 return;
783 ComputeDiagID(Severity, backend_resource_limit, DiagID);
784 break;
785 case DK_Linker:
786 ComputeDiagID(Severity, linking_module, DiagID);
787 break;
788 case llvm::DK_OptimizationRemark:
789 // Optimization remarks are always handled completely by this
790 // handler. There is no generic way of emitting them.
791 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
792 return;
793 case llvm::DK_OptimizationRemarkMissed:
794 // Optimization remarks are always handled completely by this
795 // handler. There is no generic way of emitting them.
796 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
797 return;
798 case llvm::DK_OptimizationRemarkAnalysis:
799 // Optimization remarks are always handled completely by this
800 // handler. There is no generic way of emitting them.
801 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
802 return;
803 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
804 // Optimization remarks are always handled completely by this
805 // handler. There is no generic way of emitting them.
806 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
807 return;
808 case llvm::DK_OptimizationRemarkAnalysisAliasing:
809 // Optimization remarks are always handled completely by this
810 // handler. There is no generic way of emitting them.
811 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
812 return;
813 case llvm::DK_MachineOptimizationRemark:
814 // Optimization remarks are always handled completely by this
815 // handler. There is no generic way of emitting them.
816 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
817 return;
818 case llvm::DK_MachineOptimizationRemarkMissed:
819 // Optimization remarks are always handled completely by this
820 // handler. There is no generic way of emitting them.
821 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
822 return;
823 case llvm::DK_MachineOptimizationRemarkAnalysis:
824 // Optimization remarks are always handled completely by this
825 // handler. There is no generic way of emitting them.
826 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
827 return;
828 case llvm::DK_OptimizationFailure:
829 // Optimization failures are always handled completely by this
830 // handler.
831 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
832 return;
833 case llvm::DK_Unsupported:
834 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
835 return;
836 case llvm::DK_DontCall:
837 DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
838 return;
839 case llvm::DK_MisExpect:
840 MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
841 return;
842 default:
843 // Plugin IDs are not bound to any value as they are set dynamically.
844 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
845 break;
846 }
847 std::string MsgStorage;
848 {
849 raw_string_ostream Stream(MsgStorage);
850 DiagnosticPrinterRawOStream DP(Stream);
851 DI.print(DP);
852 }
853
854 if (DI.getKind() == DK_Linker) {
855 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
856 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
857 return;
858 }
859
860 // Report the backend message using the usual diagnostic mechanism.
862 Diags.Report(Loc, DiagID).AddString(MsgStorage);
863}
864#undef ComputeDiagID
865
866CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
867 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
868 OwnsVMContext(!_VMContext) {}
869
871 TheModule.reset();
872 if (OwnsVMContext)
873 delete VMContext;
874}
875
876bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {
877 if (!LinkModules.empty())
878 return false;
879
882 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
883 if (!BCBuf) {
884 CI.getDiagnostics().Report(diag::err_cannot_open_file)
885 << F.Filename << BCBuf.getError().message();
886 LinkModules.clear();
887 return true;
888 }
889
891 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
892 if (!ModuleOrErr) {
893 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
894 CI.getDiagnostics().Report(diag::err_cannot_open_file)
895 << F.Filename << EIB.message();
896 });
897 LinkModules.clear();
898 return true;
899 }
900 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
901 F.Internalize, F.LinkFlags});
902 }
903 return false;
904}
905
906bool CodeGenAction::hasIRSupport() const { return true; }
907
909 // If the consumer creation failed, do nothing.
910 if (!getCompilerInstance().hasASTConsumer())
911 return;
912
913 // Steal the module from the consumer.
914 TheModule = BEConsumer->takeModule();
915}
916
917std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
918 return std::move(TheModule);
919}
920
921llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
922 OwnsVMContext = false;
923 return VMContext;
924}
925
928}
929
932 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
933 return true;
934}
935
936static std::unique_ptr<raw_pwrite_stream>
937GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
938 switch (Action) {
940 return CI.createDefaultOutputFile(false, InFile, "s");
941 case Backend_EmitLL:
942 return CI.createDefaultOutputFile(false, InFile, "ll");
943 case Backend_EmitBC:
944 return CI.createDefaultOutputFile(true, InFile, "bc");
946 return nullptr;
948 return CI.createNullOutputFile();
949 case Backend_EmitObj:
950 return CI.createDefaultOutputFile(true, InFile, "o");
951 }
952
953 llvm_unreachable("Invalid action!");
954}
955
956std::unique_ptr<ASTConsumer>
958 BackendAction BA = static_cast<BackendAction>(Act);
959 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
960 if (!OS)
961 OS = GetOutputStream(CI, InFile, BA);
962
963 if (BA != Backend_EmitNothing && !OS)
964 return nullptr;
965
966 // Load bitcode modules to link with, if we need to.
967 if (loadLinkModules(CI))
968 return nullptr;
969
970 CoverageSourceInfo *CoverageInfo = nullptr;
971 // Add the preprocessor callback only when the coverage mapping is generated.
972 if (CI.getCodeGenOpts().CoverageMapping)
974 CI.getPreprocessor());
975
976 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
977 CI, BA, &CI.getVirtualFileSystem(), *VMContext, std::move(LinkModules),
978 InFile, std::move(OS), CoverageInfo));
979 BEConsumer = Result.get();
980
981 // Enable generating macro debug info only when debug info is not disabled and
982 // also macro debug info is enabled.
983 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
984 CI.getCodeGenOpts().MacroDebugInfo) {
985 std::unique_ptr<PPCallbacks> Callbacks =
986 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
987 CI.getPreprocessor());
988 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
989 }
990
992 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
993 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
994 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
997 Consumers[1] = std::move(Result);
998 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
999 }
1000
1001 return std::move(Result);
1002}
1003
1004std::unique_ptr<llvm::Module>
1005CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1008
1009 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1010 unsigned DiagID =
1012 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1013 CI.getDiagnostics().Report(DiagID) << EIB.message();
1014 });
1015 return {};
1016 };
1017
1018 // For ThinLTO backend invocations, ensure that the context
1019 // merges types based on ODR identifiers. We also need to read
1020 // the correct module out of a multi-module bitcode file.
1021 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1022 VMContext->enableDebugTypeODRUniquing();
1023
1024 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1025 if (!BMsOrErr)
1026 return DiagErrors(BMsOrErr.takeError());
1027 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1028 // We have nothing to do if the file contains no ThinLTO module. This is
1029 // possible if ThinLTO compilation was not able to split module. Content of
1030 // the file was already processed by indexing and will be passed to the
1031 // linker using merged object file.
1032 if (!Bm) {
1033 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1034 M->setTargetTriple(CI.getTargetOpts().Triple);
1035 return M;
1036 }
1038 Bm->parseModule(*VMContext);
1039 if (!MOrErr)
1040 return DiagErrors(MOrErr.takeError());
1041 return std::move(*MOrErr);
1042 }
1043
1044 // Load bitcode modules to link with, if we need to.
1045 if (loadLinkModules(CI))
1046 return nullptr;
1047
1048 // Handle textual IR and bitcode file with one single module.
1049 llvm::SMDiagnostic Err;
1050 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1051 return M;
1052
1053 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1054 // output), place the extra modules (actually only one, a regular LTO module)
1055 // into LinkModules as if we are using -mlink-bitcode-file.
1056 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1057 if (BMsOrErr && BMsOrErr->size()) {
1058 std::unique_ptr<llvm::Module> FirstM;
1059 for (auto &BM : *BMsOrErr) {
1061 BM.parseModule(*VMContext);
1062 if (!MOrErr)
1063 return DiagErrors(MOrErr.takeError());
1064 if (FirstM)
1065 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
1066 /*Internalize=*/false, /*LinkFlags=*/{}});
1067 else
1068 FirstM = std::move(*MOrErr);
1069 }
1070 if (FirstM)
1071 return FirstM;
1072 }
1073 // If BMsOrErr fails, consume the error and use the error message from
1074 // parseIR.
1075 consumeError(BMsOrErr.takeError());
1076
1077 // Translate from the diagnostic info to the SourceManager location if
1078 // available.
1079 // TODO: Unify this with ConvertBackendLocation()
1081 if (Err.getLineNo() > 0) {
1082 assert(Err.getColumnNo() >= 0);
1083 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1084 Err.getLineNo(), Err.getColumnNo() + 1);
1085 }
1086
1087 // Strip off a leading diagnostic code if there is one.
1088 StringRef Msg = Err.getMessage();
1089 Msg.consume_front("error: ");
1090
1091 unsigned DiagID =
1093
1094 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1095 return {};
1096}
1097
1099 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1101 return;
1102 }
1103
1104 // If this is an IR file, we have to treat it specially.
1105 BackendAction BA = static_cast<BackendAction>(Act);
1107 auto &CodeGenOpts = CI.getCodeGenOpts();
1108 auto &Diagnostics = CI.getDiagnostics();
1109 std::unique_ptr<raw_pwrite_stream> OS =
1111 if (BA != Backend_EmitNothing && !OS)
1112 return;
1113
1115 FileID FID = SM.getMainFileID();
1116 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1117 if (!MainFile)
1118 return;
1119
1120 TheModule = loadModule(*MainFile);
1121 if (!TheModule)
1122 return;
1123
1124 const TargetOptions &TargetOpts = CI.getTargetOpts();
1125 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1126 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1127 << TargetOpts.Triple;
1128 TheModule->setTargetTriple(TargetOpts.Triple);
1129 }
1130
1131 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1132 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1133
1134 LLVMContext &Ctx = TheModule->getContext();
1135
1136 // Restore any diagnostic handler previously set before returning from this
1137 // function.
1138 struct RAII {
1139 LLVMContext &Ctx;
1140 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1141 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1142 } _{Ctx};
1143
1144 // Set clang diagnostic handler. To do this we need to create a fake
1145 // BackendConsumer.
1146 BackendConsumer Result(CI, BA, &CI.getVirtualFileSystem(), *VMContext,
1147 std::move(LinkModules), "", nullptr, nullptr,
1148 TheModule.get());
1149
1150 // Link in each pending link module.
1151 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
1152 return;
1153
1154 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1155 // true here because the valued names are needed for reading textual IR.
1156 Ctx.setDiscardValueNames(false);
1157 Ctx.setDiagnosticHandler(
1158 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1159
1160 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1161 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1162
1164 setupLLVMOptimizationRemarks(
1165 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1166 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1167 CodeGenOpts.DiagnosticsHotnessThreshold);
1168
1169 if (Error E = OptRecordFileOrErr.takeError()) {
1170 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1171 return;
1172 }
1173 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1174 std::move(*OptRecordFileOrErr);
1175
1176 emitBackendOutput(CI, CI.getTarget().getDataLayoutString(), TheModule.get(),
1178 std::move(OS));
1179 if (OptRecordFile)
1180 OptRecordFile->keep();
1181}
1182
1183//
1184
1185void EmitAssemblyAction::anchor() { }
1186EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1187 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1188
1189void EmitBCAction::anchor() { }
1190EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1191 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1192
1193void EmitLLVMAction::anchor() { }
1194EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1195 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1196
1197void EmitLLVMOnlyAction::anchor() { }
1198EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1199 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1200
1201void EmitCodeGenOnlyAction::anchor() { }
1203 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1204
1205void EmitObjAction::anchor() { }
1206EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1207 : CodeGenAction(Backend_EmitObj, _VMContext) {}
Defines the clang::ASTContext interface.
#define SM(sm)
Definition: Cuda.cpp:84
const Decl * D
Expr * E
#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.
StringRef Filename
Definition: Format.cpp:3051
Defines the clang::Preprocessor interface.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:741
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.
Definition: DeclCXX.h:258
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
Definition: CodeGenAction.h:27
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(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
Definition: CodeGenAction.h:88
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.
Definition: ModuleBuilder.h:52
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.
Definition: DeclBase.h:86
SourceLocation getLocation() const
Definition: DeclBase.h:442
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:735
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1220
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:231
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:896
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.
Definition: FileManager.h:53
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.
Definition: FileManager.h:245
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
Definition: FileManager.h:258
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.
Definition: Decl.h:1935
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
Definition: LangOptions.h:110
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
PrettyStackTraceDecl - If a crash occurs, indicate that it happened when doing something to a specifi...
Definition: DeclBase.h:1286
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
Definition: Diagnostic.h:1153
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
const char * getDataLayoutString() const
Definition: TargetInfo.h:1271
Options for controlling the target.
Definition: TargetOptions.h:26
std::string Triple
The name of the target triple to compile for.
Definition: TargetOptions.h:29
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
Definition: TargetOptions.h:58
std::string CPU
If given, the name of the target CPU to generate code for.
Definition: TargetOptions.h:36
Represents a variable declaration or definition.
Definition: Decl.h:882
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...
Definition: CGCall.cpp:2078
The JSON file list parser is used to communicate input to InstallAPI.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
void emitBackendOutput(CompilerInstance &CI, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
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 EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
BackendAction
Definition: BackendUtil.h:33
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:34
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:36
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:35
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:39
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:38
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:37
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
bool patternMatches(StringRef String) const
Matches the given string against the regex, if there is some.
bool hasValidPattern() const
Returns true iff the optimization remark holds a valid regular expression.