clang 23.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/ADT/ScopeExit.h"
33#include "llvm/Bitcode/BitcodeReader.h"
34#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
35#include "llvm/Demangle/Demangle.h"
36#include "llvm/IR/DebugInfo.h"
37#include "llvm/IR/DiagnosticInfo.h"
38#include "llvm/IR/DiagnosticPrinter.h"
39#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/LLVMContext.h"
41#include "llvm/IR/LLVMRemarkStreamer.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/PassTimingInfo.h"
44#include "llvm/IR/Verifier.h"
45#include "llvm/IRReader/IRReader.h"
46#include "llvm/LTO/LTOBackend.h"
47#include "llvm/Linker/Linker.h"
48#include "llvm/Pass.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
51#include "llvm/Support/Mutex.h"
52#include "llvm/Support/SourceMgr.h"
53#include "llvm/Support/TimeProfiler.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/ToolOutputFile.h"
56#include "llvm/Transforms/IPO/Internalize.h"
57#include "llvm/Transforms/Utils/Cloning.h"
58
59#include <optional>
60using namespace clang;
61using namespace llvm;
62
63#define DEBUG_TYPE "codegenaction"
64
65namespace {
66llvm::ManagedStatic<llvm::sys::SmartMutex<true>> TimePassesMutex;
67}
68
69namespace clang {
70class BackendConsumer;
72public:
74 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
75
76 bool handleDiagnostics(const DiagnosticInfo &DI) override;
77
78 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
79 return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
80 }
81 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
82 return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
83 }
84 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
85 return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
86 }
87
88 bool isAnyRemarkEnabled() const override {
89 return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
90 CodeGenOpts.OptimizationRemarkMissed.hasValidPattern() ||
91 CodeGenOpts.OptimizationRemark.hasValidPattern();
92 }
93
94private:
95 const CodeGenOptions &CodeGenOpts;
96 BackendConsumer *BackendCon;
97};
98
100 const CodeGenOptions &CodeGenOpts) {
101 handleAllErrors(
102 std::move(E),
103 [&](const LLVMRemarkSetupFileError &E) {
104 Diags.Report(diag::err_cannot_open_file)
105 << CodeGenOpts.OptRecordFile << E.message();
106 },
107 [&](const LLVMRemarkSetupPatternError &E) {
108 Diags.Report(diag::err_drv_optimization_remark_pattern)
109 << E.message() << CodeGenOpts.OptRecordPasses;
110 },
111 [&](const LLVMRemarkSetupFormatError &E) {
112 Diags.Report(diag::err_drv_optimization_remark_format)
113 << CodeGenOpts.OptRecordFormat;
114 });
115}
116
119 LLVMContext &C,
120 SmallVector<LinkModule, 4> LinkModules,
121 StringRef InFile,
122 std::unique_ptr<raw_pwrite_stream> OS,
123 CoverageSourceInfo *CoverageInfo,
124 llvm::Module *CurLinkModule)
125 : CI(CI), Diags(CI.getDiagnostics()), CodeGenOpts(CI.getCodeGenOpts()),
126 TargetOpts(CI.getTargetOpts()), LangOpts(CI.getLangOpts()),
127 AsmOutStream(std::move(OS)), FS(VFS), Action(Action),
128 Gen(CreateLLVMCodeGen(CI, InFile, C, CoverageInfo)),
129 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {
130 TimerIsEnabled = CodeGenOpts.TimePasses;
131 {
132 llvm::sys::SmartScopedLock<true> Lock(*TimePassesMutex);
133 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
134 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
135 }
136 if (CodeGenOpts.TimePasses)
137 LLVMIRGeneration.init("irgen", "LLVM IR generation", CI.getTimerGroup());
138}
139
140llvm::Module* BackendConsumer::getModule() const {
141 return Gen->GetModule();
142}
143
144std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
145 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
146}
147
149 return Gen.get();
150}
151
155
157 assert(!Context && "initialized multiple times");
158
159 Context = &Ctx;
160
161 if (TimerIsEnabled)
162 LLVMIRGeneration.startTimer();
163
164 Gen->Initialize(Ctx);
165
166 if (TimerIsEnabled)
167 LLVMIRGeneration.stopTimer();
168}
169
171 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
172 Context->getSourceManager(),
173 "LLVM IR generation of declaration");
174
175 // Recurse.
176 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
177 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
178
179 Gen->HandleTopLevelDecl(D);
180
181 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
182 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
183
184 return true;
185}
186
189 Context->getSourceManager(),
190 "LLVM IR generation of inline function");
191 if (TimerIsEnabled)
192 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
193
194 Gen->HandleInlineFunctionDefinition(D);
195
196 if (TimerIsEnabled)
197 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
198}
199
203
204// Links each entry in LinkModules into our module. Returns true on error.
205bool BackendConsumer::LinkInModules(llvm::Module *M) {
206 for (auto &LM : LinkModules) {
207 assert(LM.Module && "LinkModule does not actually have a module");
208
209 if (LM.PropagateAttrs)
210 for (Function &F : *LM.Module) {
211 // Skip intrinsics. Keep consistent with how intrinsics are created
212 // in LLVM IR.
213 if (F.isIntrinsic())
214 continue;
216 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
217 }
218
219 CurLinkModule = LM.Module.get();
220 bool Err;
221
222 if (LM.Internalize) {
223 Err = Linker::linkModules(
224 *M, std::move(LM.Module), LM.LinkFlags,
225 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
226 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
227 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
228 });
229 });
230 } else
231 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
232
233 if (Err)
234 return true;
235 }
236
237 LinkModules.clear();
238 return false; // success
239}
240
242 {
243 llvm::TimeTraceScope TimeScope("Frontend");
244 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
245 if (TimerIsEnabled && !LLVMIRGenerationRefCount++)
246 CI.getFrontendTimer().yieldTo(LLVMIRGeneration);
247
248 Gen->HandleTranslationUnit(C);
249
250 if (TimerIsEnabled && !--LLVMIRGenerationRefCount)
251 LLVMIRGeneration.yieldTo(CI.getFrontendTimer());
252 }
253
254 // Silently ignore if we weren't initialized for some reason.
255 if (!getModule())
256 return;
257
258 LLVMContext &Ctx = getModule()->getContext();
259 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
260 Ctx.getDiagnosticHandler();
261 llvm::scope_exit RestoreDiagnosticHandler(
262 [&]() { Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler)); });
263 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
264 CodeGenOpts, this));
265
266 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
267 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
268
269 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
270 setupLLVMOptimizationRemarks(
271 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
272 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
273 CodeGenOpts.DiagnosticsHotnessThreshold);
274
275 if (Error E = OptRecordFileOrErr.takeError()) {
276 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
277 return;
278 }
279
280 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
281
282 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
283 llvm::driver::ProfileInstrKind::ProfileNone)
284 Ctx.setDiagnosticsHotnessRequested(true);
285
286 if (CodeGenOpts.MisExpect) {
287 Ctx.setMisExpectWarningRequested(true);
288 }
289
290 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
291 Ctx.setDiagnosticsMisExpectTolerance(
292 CodeGenOpts.DiagnosticsMisExpectTolerance);
293 }
294
295 // Link each LinkModule into our module.
296 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
297 return;
298
299 for (auto &F : getModule()->functions()) {
300 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
301 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
302 // TODO: use a fast content hash when available.
303 auto NameHash = llvm::hash_value(F.getName());
304 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
305 }
306 }
307
308 if (CodeGenOpts.ClearASTBeforeBackend) {
309 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
310 // Access to the AST is no longer available after this.
311 // Other things that the ASTContext manages are still available, e.g.
312 // the SourceManager. It'd be nice if we could separate out all the
313 // things in ASTContext used after this point and null out the
314 // ASTContext, but too many various parts of the ASTContext are still
315 // used in various parts.
316 C.cleanup();
317 C.getAllocator().Reset();
318 }
319
320 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
321
322 emitBackendOutput(CI, CI.getCodeGenOpts(),
323 C.getTargetInfo().getDataLayoutString(), getModule(),
324 Action, FS, std::move(AsmOutStream), this);
325
326 if (OptRecordFile)
327 OptRecordFile->keep();
328}
329
332 Context->getSourceManager(),
333 "LLVM IR generation of declaration");
334 Gen->HandleTagDeclDefinition(D);
335}
336
338 Gen->HandleTagDeclRequiredDefinition(D);
339}
340
342 Gen->CompleteTentativeDefinition(D);
343}
344
346 Gen->CompleteExternalDeclaration(D);
347}
348
350 Gen->AssignInheritanceModel(RD);
351}
352
354 Gen->HandleVTable(RD);
355}
356
357void BackendConsumer::anchor() { }
358
359} // namespace clang
360
361bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
362 BackendCon->DiagnosticHandlerImpl(DI);
363 return true;
364}
365
366/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
367/// buffer to be a valid FullSourceLoc.
368static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
369 SourceManager &CSM) {
370 // Get both the clang and llvm source managers. The location is relative to
371 // a memory buffer that the LLVM Source Manager is handling, we need to add
372 // a copy to the Clang source manager.
373 const llvm::SourceMgr &LSM = *D.getSourceMgr();
374
375 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
376 // already owns its one and clang::SourceManager wants to own its one.
377 const MemoryBuffer *LBuf =
378 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
379
380 // Create the copy and transfer ownership to clang::SourceManager.
381 // TODO: Avoid copying files into memory.
382 std::unique_ptr<llvm::MemoryBuffer> CBuf =
383 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
384 LBuf->getBufferIdentifier());
385 // FIXME: Keep a file ID map instead of creating new IDs for each location.
386 FileID FID = CSM.createFileID(std::move(CBuf));
387
388 // Translate the offset into the file.
389 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
390 SourceLocation NewLoc =
391 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
392 return FullSourceLoc(NewLoc, CSM);
393}
394
395#define ComputeDiagID(Severity, GroupName, DiagID) \
396 do { \
397 switch (Severity) { \
398 case llvm::DS_Error: \
399 DiagID = diag::err_fe_##GroupName; \
400 break; \
401 case llvm::DS_Warning: \
402 DiagID = diag::warn_fe_##GroupName; \
403 break; \
404 case llvm::DS_Remark: \
405 llvm_unreachable("'remark' severity not expected"); \
406 break; \
407 case llvm::DS_Note: \
408 DiagID = diag::note_fe_##GroupName; \
409 break; \
410 } \
411 } while (false)
412
413#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
414 do { \
415 switch (Severity) { \
416 case llvm::DS_Error: \
417 DiagID = diag::err_fe_##GroupName; \
418 break; \
419 case llvm::DS_Warning: \
420 DiagID = diag::warn_fe_##GroupName; \
421 break; \
422 case llvm::DS_Remark: \
423 DiagID = diag::remark_fe_##GroupName; \
424 break; \
425 case llvm::DS_Note: \
426 DiagID = diag::note_fe_##GroupName; \
427 break; \
428 } \
429 } while (false)
430
431void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
432 const llvm::SMDiagnostic &D = DI.getSMDiag();
433
434 unsigned DiagID;
435 if (DI.isInlineAsmDiag())
436 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
437 else
438 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
439
440 // This is for the empty BackendConsumer that uses the clang diagnostic
441 // handler for IR input files.
442 if (!Context) {
443 D.print(nullptr, llvm::errs());
444 Diags.Report(DiagID).AddString("cannot compile inline asm");
445 return;
446 }
447
448 // There are a couple of different kinds of errors we could get here.
449 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
450
451 // Strip "error: " off the start of the message string.
452 StringRef Message = D.getMessage();
453 (void)Message.consume_front("error: ");
454
455 // If the SMDiagnostic has an inline asm source location, translate it.
456 FullSourceLoc Loc;
457 if (D.getLoc() != SMLoc())
458 Loc = ConvertBackendLocation(D, Context->getSourceManager());
459
460 // If this problem has clang-level source location information, report the
461 // issue in the source with a note showing the instantiated
462 // code.
463 if (DI.isInlineAsmDiag()) {
464 SourceLocation LocCookie =
465 SourceLocation::getFromRawEncoding(DI.getLocCookie());
466 if (LocCookie.isValid()) {
467 Diags.Report(LocCookie, DiagID).AddString(Message);
468
469 if (D.getLoc().isValid()) {
470 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
471 // Convert the SMDiagnostic ranges into SourceRange and attach them
472 // to the diagnostic.
473 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
474 unsigned Column = D.getColumnNo();
475 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
476 Loc.getLocWithOffset(Range.second - Column));
477 }
478 }
479 return;
480 }
481 }
482
483 // Otherwise, report the backend issue as occurring in the generated .s file.
484 // If Loc is invalid, we still need to report the issue, it just gets no
485 // location info.
486 Diags.Report(Loc, DiagID).AddString(Message);
487}
488
489bool
490BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
491 unsigned DiagID;
492 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
493 std::string Message = D.getMsgStr().str();
494
495 // If this problem has clang-level source location information, report the
496 // issue as being a problem in the source with a note showing the instantiated
497 // code.
498 SourceLocation LocCookie =
499 SourceLocation::getFromRawEncoding(D.getLocCookie());
500 if (LocCookie.isValid())
501 Diags.Report(LocCookie, DiagID).AddString(Message);
502 else {
503 // Otherwise, report the backend diagnostic as occurring in the generated
504 // .s file.
505 // If Loc is invalid, we still need to report the diagnostic, it just gets
506 // no location info.
507 FullSourceLoc Loc;
508 Diags.Report(Loc, DiagID).AddString(Message);
509 }
510 // We handled all the possible severities.
511 return true;
512}
513
514bool
515BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
516 if (D.getSeverity() != llvm::DS_Warning)
517 // For now, the only support we have for StackSize diagnostic is warning.
518 // We do not know how to format other severities.
519 return false;
520
521 auto Loc = getFunctionSourceLocation(D.getFunction());
522 if (!Loc)
523 return false;
524
525 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
526 << D.getStackSize() << D.getStackLimit()
527 << llvm::demangle(D.getFunction().getName());
528 return true;
529}
530
532 const llvm::DiagnosticInfoResourceLimit &D) {
533 auto Loc = getFunctionSourceLocation(D.getFunction());
534 if (!Loc)
535 return false;
536 unsigned DiagID = diag::err_fe_backend_resource_limit;
537 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
538
539 Diags.Report(*Loc, DiagID)
540 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
541 << llvm::demangle(D.getFunction().getName());
542 return true;
543}
544
546 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
547 StringRef &Filename, unsigned &Line, unsigned &Column) const {
548 SourceManager &SourceMgr = Context->getSourceManager();
549 FileManager &FileMgr = SourceMgr.getFileManager();
550 SourceLocation DILoc;
551
552 if (D.isLocationAvailable()) {
553 D.getLocation(Filename, Line, Column);
554 if (Line > 0) {
555 auto FE = FileMgr.getOptionalFileRef(Filename);
556 if (!FE)
557 FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());
558 if (FE) {
559 // If -gcolumn-info was not used, Column will be 0. This upsets the
560 // source manager, so pass 1 if Column is not set.
561 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
562 }
563 }
564 BadDebugInfo = DILoc.isInvalid();
565 }
566
567 // If a location isn't available, try to approximate it using the associated
568 // function definition. We use the definition's right brace to differentiate
569 // from diagnostics that genuinely relate to the function itself.
570 FullSourceLoc Loc(DILoc, SourceMgr);
571 if (Loc.isInvalid()) {
572 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
573 Loc = *MaybeLoc;
574 }
575
576 if (DILoc.isInvalid() && D.isLocationAvailable())
577 // If we were not able to translate the file:line:col information
578 // back to a SourceLocation, at least emit a note stating that
579 // we could not translate this location. This can happen in the
580 // case of #line directives.
581 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
582 << Filename << Line << Column;
583
584 return Loc;
585}
586
587std::optional<FullSourceLoc>
589 auto Hash = llvm::hash_value(F.getName());
590 for (const auto &Pair : ManglingFullSourceLocs) {
591 if (Pair.first == Hash)
592 return Pair.second;
593 }
594 return std::nullopt;
595}
596
598 const llvm::DiagnosticInfoUnsupported &D) {
599 // We only support warnings or errors.
600 assert(D.getSeverity() == llvm::DS_Error ||
601 D.getSeverity() == llvm::DS_Warning);
602
603 StringRef Filename;
604 unsigned Line, Column;
605 bool BadDebugInfo = false;
606 FullSourceLoc Loc;
607 std::string Msg;
608 raw_string_ostream MsgStream(Msg);
609
610 // Context will be nullptr for IR input files, we will construct the diag
611 // message from llvm::DiagnosticInfoUnsupported.
612 if (Context != nullptr) {
613 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
614 MsgStream << D.getMessage();
615 } else {
616 DiagnosticPrinterRawOStream DP(MsgStream);
617 D.print(DP);
618 }
619
620 auto DiagType = D.getSeverity() == llvm::DS_Error
621 ? diag::err_fe_backend_unsupported
622 : diag::warn_fe_backend_unsupported;
623 Diags.Report(Loc, DiagType) << Msg;
624
625 if (BadDebugInfo)
626 // If we were not able to translate the file:line:col information
627 // back to a SourceLocation, at least emit a note stating that
628 // we could not translate this location. This can happen in the
629 // case of #line directives.
630 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
631 << Filename << Line << Column;
632}
633
635 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
636 // We only support warnings and remarks.
637 assert(D.getSeverity() == llvm::DS_Remark ||
638 D.getSeverity() == llvm::DS_Warning);
639
640 StringRef Filename;
641 unsigned Line, Column;
642 bool BadDebugInfo = false;
643 FullSourceLoc Loc;
644 std::string Msg;
645 raw_string_ostream MsgStream(Msg);
646
647 // Context will be nullptr for IR input files, we will construct the remark
648 // message from llvm::DiagnosticInfoOptimizationBase.
649 if (Context != nullptr) {
650 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
651 MsgStream << D.getMsg();
652 } else {
653 DiagnosticPrinterRawOStream DP(MsgStream);
654 D.print(DP);
655 }
656
657 if (D.getHotness())
658 MsgStream << " (hotness: " << *D.getHotness() << ")";
659
660 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
661
662 if (BadDebugInfo)
663 // If we were not able to translate the file:line:col information
664 // back to a SourceLocation, at least emit a note stating that
665 // we could not translate this location. This can happen in the
666 // case of #line directives.
667 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
668 << Filename << Line << Column;
669}
670
672 const llvm::DiagnosticInfoOptimizationBase &D) {
673 // Without hotness information, don't show noisy remarks.
674 if (D.isVerbose() && !D.getHotness())
675 return;
676
677 if (D.isPassed()) {
678 // Optimization remarks are active only if the -Rpass flag has a regular
679 // expression that matches the name of the pass name in \p D.
680 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
681 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
682 } else if (D.isMissed()) {
683 // Missed optimization remarks are active only if the -Rpass-missed
684 // flag has a regular expression that matches the name of the pass
685 // name in \p D.
686 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
688 D, diag::remark_fe_backend_optimization_remark_missed);
689 } else {
690 assert(D.isAnalysis() && "Unknown remark type");
691
692 bool ShouldAlwaysPrint = false;
693 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
694 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
695
696 if (ShouldAlwaysPrint ||
697 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
699 D, diag::remark_fe_backend_optimization_remark_analysis);
700 }
701}
702
704 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
705 // Optimization analysis remarks are active if the pass name is set to
706 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
707 // regular expression that matches the name of the pass name in \p D.
708
709 if (D.shouldAlwaysPrint() ||
710 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
712 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
713}
714
716 const llvm::OptimizationRemarkAnalysisAliasing &D) {
717 // Optimization analysis remarks are active if the pass name is set to
718 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
719 // regular expression that matches the name of the pass name in \p D.
720
721 if (D.shouldAlwaysPrint() ||
722 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
724 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
725}
726
728 const llvm::DiagnosticInfoOptimizationFailure &D) {
729 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
730}
731
732void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
733 SourceLocation LocCookie =
734 SourceLocation::getFromRawEncoding(D.getLocCookie());
735
736 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
737 // should instead assert that LocCookie.isValid().
738 if (!LocCookie.isValid())
739 return;
740
741 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
742 ? diag::err_fe_backend_error_attr
743 : diag::warn_fe_backend_warning_attr)
744 << llvm::demangle(D.getFunctionName()) << D.getNote();
745
746 if (!CodeGenOpts.ShowInliningChain)
747 return;
748
749 auto EmitNote = [&](SourceLocation Loc, StringRef FuncName, bool IsFirst) {
750 if (!Loc.isValid())
751 Loc = LocCookie;
752 unsigned DiagID =
753 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
754 Diags.Report(Loc, DiagID) << llvm::demangle(FuncName.str());
755 };
756
757 // Try debug info first for accurate source locations.
758 if (!D.getDebugInlineChain().empty()) {
759 SourceManager &SM = Context->getSourceManager();
760 FileManager &FM = SM.getFileManager();
761 for (const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
762 SourceLocation Loc;
763 if (Info.Line > 0)
764 if (auto FE = FM.getOptionalFileRef(Info.Filename))
765 Loc = SM.translateFileLineCol(*FE, Info.Line,
766 Info.Column ? Info.Column : 1);
767 EmitNote(Loc, Info.FuncName, I == 0);
768 }
769 return;
770 }
771
772 // Fall back to heuristic (srcloc metadata) when debug info is unavailable.
773 auto InliningDecisions = D.getInliningDecisions();
774 if (InliningDecisions.empty())
775 return;
776
777 for (const auto &[I, Entry] : llvm::enumerate(InliningDecisions)) {
778 SourceLocation Loc =
779 I == 0 ? LocCookie : SourceLocation::getFromRawEncoding(Entry.second);
780 EmitNote(Loc, Entry.first, I == 0);
781 }
782
783 // Suggest enabling debug info (at least -gline-directives-only) for more
784 // accurate locations.
785 Diags.Report(LocCookie, diag::note_fe_backend_inlining_debug_info);
786}
787
789 const llvm::DiagnosticInfoMisExpect &D) {
790 StringRef Filename;
791 unsigned Line, Column;
792 bool BadDebugInfo = false;
793 FullSourceLoc Loc =
794 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
795
796 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
797
798 if (BadDebugInfo)
799 // If we were not able to translate the file:line:col information
800 // back to a SourceLocation, at least emit a note stating that
801 // we could not translate this location. This can happen in the
802 // case of #line directives.
803 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
804 << Filename << Line << Column;
805}
806
807/// This function is invoked when the backend needs
808/// to report something to the user.
809void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
810 unsigned DiagID = diag::err_fe_inline_asm;
811 llvm::DiagnosticSeverity Severity = DI.getSeverity();
812 // Get the diagnostic ID based.
813 switch (DI.getKind()) {
814 case llvm::DK_InlineAsm:
816 return;
817 ComputeDiagID(Severity, inline_asm, DiagID);
818 break;
819 case llvm::DK_SrcMgr:
821 return;
822 case llvm::DK_StackSize:
824 return;
825 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
826 break;
827 case llvm::DK_ResourceLimit:
829 return;
830 ComputeDiagID(Severity, backend_resource_limit, DiagID);
831 break;
832 case DK_Linker:
833 ComputeDiagID(Severity, linking_module, DiagID);
834 break;
835 case llvm::DK_OptimizationRemark:
836 // Optimization remarks are always handled completely by this
837 // handler. There is no generic way of emitting them.
839 return;
840 case llvm::DK_OptimizationRemarkMissed:
841 // Optimization remarks are always handled completely by this
842 // handler. There is no generic way of emitting them.
844 return;
845 case llvm::DK_OptimizationRemarkAnalysis:
846 // Optimization remarks are always handled completely by this
847 // handler. There is no generic way of emitting them.
849 return;
850 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
851 // Optimization remarks are always handled completely by this
852 // handler. There is no generic way of emitting them.
854 return;
855 case llvm::DK_OptimizationRemarkAnalysisAliasing:
856 // Optimization remarks are always handled completely by this
857 // handler. There is no generic way of emitting them.
859 return;
860 case llvm::DK_MachineOptimizationRemark:
861 // Optimization remarks are always handled completely by this
862 // handler. There is no generic way of emitting them.
864 return;
865 case llvm::DK_MachineOptimizationRemarkMissed:
866 // Optimization remarks are always handled completely by this
867 // handler. There is no generic way of emitting them.
869 return;
870 case llvm::DK_MachineOptimizationRemarkAnalysis:
871 // Optimization remarks are always handled completely by this
872 // handler. There is no generic way of emitting them.
874 return;
875 case llvm::DK_OptimizationFailure:
876 // Optimization failures are always handled completely by this
877 // handler.
879 return;
880 case llvm::DK_Unsupported:
882 return;
883 case llvm::DK_DontCall:
885 return;
886 case llvm::DK_MisExpect:
888 return;
889 default:
890 // Plugin IDs are not bound to any value as they are set dynamically.
891 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
892 break;
893 }
894 std::string MsgStorage;
895 {
896 raw_string_ostream Stream(MsgStorage);
897 DiagnosticPrinterRawOStream DP(Stream);
898 DI.print(DP);
899 }
900
901 if (DI.getKind() == DK_Linker) {
902 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
903 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
904 return;
905 }
906
907 // Report the backend message using the usual diagnostic mechanism.
908 FullSourceLoc Loc;
909 Diags.Report(Loc, DiagID).AddString(MsgStorage);
910}
911#undef ComputeDiagID
912
913CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
914 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
915 OwnsVMContext(!_VMContext) {}
916
918 TheModule.reset();
919 if (OwnsVMContext)
920 delete VMContext;
921}
922
923bool CodeGenAction::hasIRSupport() const { return true; }
924
927
928 // If the consumer creation failed, do nothing.
929 if (!getCompilerInstance().hasASTConsumer())
930 return;
931
932 // Steal the module from the consumer.
933 TheModule = BEConsumer->takeModule();
934}
935
936std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
937 return std::move(TheModule);
938}
939
940llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
941 OwnsVMContext = false;
942 return VMContext;
943}
944
946 return BEConsumer->getCodeGenerator();
947}
948
954
955static std::unique_ptr<raw_pwrite_stream>
956GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
957 switch (Action) {
959 return CI.createDefaultOutputFile(false, InFile, "s");
960 case Backend_EmitLL:
961 return CI.createDefaultOutputFile(false, InFile, "ll");
962 case Backend_EmitBC:
963 return CI.createDefaultOutputFile(true, InFile, "bc");
965 return nullptr;
967 return CI.createNullOutputFile();
968 case Backend_EmitObj:
969 return CI.createDefaultOutputFile(true, InFile, "o");
970 }
971
972 llvm_unreachable("Invalid action!");
973}
974
975std::unique_ptr<ASTConsumer>
977 BackendAction BA = static_cast<BackendAction>(Act);
978 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
979 if (!OS)
980 OS = GetOutputStream(CI, InFile, BA);
981
982 if (BA != Backend_EmitNothing && !OS)
983 return nullptr;
984
985 // Load bitcode modules to link with, if we need to.
986 if (clang::loadLinkModules(CI, *VMContext, LinkModules))
987 return nullptr;
988
989 CoverageSourceInfo *CoverageInfo = nullptr;
990 // Add the preprocessor callback only when the coverage mapping is generated.
991 if (CI.getCodeGenOpts().CoverageMapping)
993 CI.getPreprocessor());
994
995 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
996 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
997 InFile, std::move(OS), CoverageInfo));
998 BEConsumer = Result.get();
999
1000 // Enable generating macro debug info only when debug info is not disabled and
1001 // also macro debug info is enabled.
1002 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1003 CI.getCodeGenOpts().MacroDebugInfo) {
1004 std::unique_ptr<PPCallbacks> Callbacks =
1005 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1006 CI.getPreprocessor());
1007 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1008 }
1009
1010 if (CI.getFrontendOpts().GenReducedBMI &&
1011 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
1012 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1013 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1016 Consumers[1] = std::move(Result);
1017 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1018 }
1019
1020 return std::move(Result);
1021}
1022
1023std::unique_ptr<llvm::Module>
1024CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1027
1028 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1029 unsigned DiagID =
1031 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1032 CI.getDiagnostics().Report(DiagID) << EIB.message();
1033 });
1034 return {};
1035 };
1036
1037 // For ThinLTO backend invocations, ensure that the context
1038 // merges types based on ODR identifiers. We also need to read
1039 // the correct module out of a multi-module bitcode file.
1040 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1041 VMContext->enableDebugTypeODRUniquing();
1042
1043 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1044 if (!BMsOrErr)
1045 return DiagErrors(BMsOrErr.takeError());
1046 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1047 // We have nothing to do if the file contains no ThinLTO module. This is
1048 // possible if ThinLTO compilation was not able to split module. Content of
1049 // the file was already processed by indexing and will be passed to the
1050 // linker using merged object file.
1051 if (!Bm) {
1052 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1053 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
1054 return M;
1055 }
1056 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1057 Bm->parseModule(*VMContext);
1058 if (!MOrErr)
1059 return DiagErrors(MOrErr.takeError());
1060 return std::move(*MOrErr);
1061 }
1062
1063 // Load bitcode modules to link with, if we need to.
1064 if (clang::loadLinkModules(CI, *VMContext, LinkModules))
1065 return nullptr;
1066
1067 // Handle textual IR and bitcode file with one single module.
1068 llvm::SMDiagnostic Err;
1069 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext)) {
1070 // For LLVM IR files, always verify the input and report the error in a way
1071 // that does not ask people to report an issue for it.
1072 std::string VerifierErr;
1073 raw_string_ostream VerifierErrStream(VerifierErr);
1074 if (llvm::verifyModule(*M, &VerifierErrStream)) {
1075 CI.getDiagnostics().Report(diag::err_invalid_llvm_ir) << VerifierErr;
1076 return {};
1077 }
1078 return M;
1079 }
1080
1081 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1082 // output), place the extra modules (actually only one, a regular LTO module)
1083 // into LinkModules as if we are using -mlink-bitcode-file.
1084 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1085 if (BMsOrErr && BMsOrErr->size()) {
1086 std::unique_ptr<llvm::Module> FirstM;
1087 for (auto &BM : *BMsOrErr) {
1088 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1089 BM.parseModule(*VMContext);
1090 if (!MOrErr)
1091 return DiagErrors(MOrErr.takeError());
1092 if (FirstM)
1093 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
1094 /*Internalize=*/false, /*LinkFlags=*/{}});
1095 else
1096 FirstM = std::move(*MOrErr);
1097 }
1098 if (FirstM)
1099 return FirstM;
1100 }
1101 // If BMsOrErr fails, consume the error and use the error message from
1102 // parseIR.
1103 consumeError(BMsOrErr.takeError());
1104
1105 // Translate from the diagnostic info to the SourceManager location if
1106 // available.
1107 // TODO: Unify this with ConvertBackendLocation()
1108 SourceLocation Loc;
1109 if (Err.getLineNo() > 0) {
1110 assert(Err.getColumnNo() >= 0);
1111 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1112 Err.getLineNo(), Err.getColumnNo() + 1);
1113 }
1114
1115 // Strip off a leading diagnostic code if there is one.
1116 StringRef Msg = Err.getMessage();
1117 Msg.consume_front("error: ");
1118
1119 unsigned DiagID =
1121
1122 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1123 return {};
1124}
1125
1127 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1129 return;
1130 }
1131
1132 // If this is an IR file, we have to treat it specially.
1133 BackendAction BA = static_cast<BackendAction>(Act);
1135 auto &CodeGenOpts = CI.getCodeGenOpts();
1136 auto &Diagnostics = CI.getDiagnostics();
1137 std::unique_ptr<raw_pwrite_stream> OS =
1139 if (BA != Backend_EmitNothing && !OS)
1140 return;
1141
1143 FileID FID = SM.getMainFileID();
1144 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1145 if (!MainFile)
1146 return;
1147
1148 TheModule = loadModule(*MainFile);
1149 if (!TheModule)
1150 return;
1151
1152 const TargetOptions &TargetOpts = CI.getTargetOpts();
1153 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
1154 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1155 << TargetOpts.Triple;
1156 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
1157 }
1158
1159 EmbedObject(TheModule.get(), CodeGenOpts, CI.getVirtualFileSystem(),
1160 Diagnostics);
1161 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1162
1163 LLVMContext &Ctx = TheModule->getContext();
1164
1165 // Restore any diagnostic handler previously set before returning from this
1166 // function.
1167 struct RAII {
1168 LLVMContext &Ctx;
1169 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1170 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1171 } _{Ctx};
1172
1173 // Set clang diagnostic handler. To do this we need to create a fake
1174 // BackendConsumer.
1175 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
1176 std::move(LinkModules), "", nullptr, nullptr,
1177 TheModule.get());
1178
1179 // Link in each pending link module.
1180 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
1181 return;
1182
1183 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1184 // true here because the valued names are needed for reading textual IR.
1185 Ctx.setDiscardValueNames(false);
1186 Ctx.setDiagnosticHandler(
1187 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1188
1189 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1190 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1191
1192 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
1193 setupLLVMOptimizationRemarks(
1194 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1195 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1196 CodeGenOpts.DiagnosticsHotnessThreshold);
1197
1198 if (Error E = OptRecordFileOrErr.takeError()) {
1199 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1200 return;
1201 }
1202 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1203
1205 CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1207 std::move(OS));
1208 if (OptRecordFile)
1209 OptRecordFile->keep();
1210}
1211
1212//
1213
1214void EmitAssemblyAction::anchor() { }
1215EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1216 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1217
1218void EmitBCAction::anchor() { }
1219EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1220 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1221
1222void EmitLLVMAction::anchor() { }
1223EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1224 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1225
1226void EmitLLVMOnlyAction::anchor() { }
1227EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1228 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1229
1230void EmitCodeGenOnlyAction::anchor() { }
1232 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1233
1234void EmitObjAction::anchor() { }
1235EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1236 : CodeGenAction(Backend_EmitObj, _VMContext) {}
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.
unsigned IsFirst
Indicates that this is the first token of the file.
#define SM(sm)
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *D)
HandleCXXStaticMemberVarInstantiation - Tell the consumer that this.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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
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
bool hasIRSupport() const override
Does this action support use with IR files?
void ExecuteAction() override
Implement the ExecuteAction interface by running Sema on the already-initialized AST consumer.
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::string OptRecordPasses
The regex that filters the passes that should be saved to the optimization records.
std::string ThinLTOIndexFile
Name of the function summary index file to use for ThinLTO function importing.
std::string OptRecordFormat
The format used for serializing remarks (default: YAML)
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.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false, bool SetOnlyIfDifferent=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
FileManager & getFileManager() const
Return the current file manager to the caller.
ModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
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...
iterator begin()
Definition DeclGroup.h:95
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Represents a ValueDecl that came out of a declarator.
Definition Decl.h:780
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:233
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.
Definition Diagnostic.h:914
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:52
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true, bool IsText=true)
Get a FileEntryRef if it exists, without doing anything on error.
InputKind getCurrentFileKind() const
virtual void EndSourceFileAction()
Callback at the end of processing a single input.
CompilerInstance & getCompilerInstance() const
virtual bool BeginSourceFileAction(CompilerInstance &CI)
Callback at the start of processing a single input.
StringRef getCurrentFileOrBufferName() const
unsigned GenReducedBMI
Whether to generate reduced BMI for C++20 named modules.
std::string ModuleOutputPath
Output Path for module output file.
A SourceLocation and its associated SourceManager.
Represents a function declaration or definition.
Definition Decl.h:2018
@ 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...
Definition DeclBase.h:1313
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...
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.
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3739
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.
Definition Decl.h:924
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:2307
The JSON file list parser is used to communicate input to InstallAPI.
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
@ Result
The result type of a method or function.
Definition TypeBase.h:905
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 EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::vfs::FileSystem &VFS, DiagnosticsEngine &Diags)
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
std::unique_ptr< CodeGenerator > CreateLLVMCodeGen(const CompilerInstance &CI, llvm::StringRef ModuleName, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
U cast(CodeGen::Address addr)
Definition Address.h:327
bool loadLinkModules(CompilerInstance &CI, llvm::LLVMContext &Ctx, llvm::SmallVectorImpl< LinkModule > &LinkModules)
Load every bitcode file listed in CodeGenOpts.LinkBitcodeFiles into LinkModules.
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
hash_code hash_value(const clang::dependencies::ModuleID &ID)