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
109 const CompilerInstance &CI, BackendAction Action,
111 SmallVector<LinkModule, 4> LinkModules, StringRef InFile,
112 std::unique_ptr<raw_pwrite_stream> OS, CoverageSourceInfo *CoverageInfo,
113 llvm::Module *CurLinkModule)
114 : Diags(CI.getDiagnostics()), HeaderSearchOpts(CI.getHeaderSearchOpts()),
115 CodeGenOpts(CI.getCodeGenOpts()), TargetOpts(CI.getTargetOpts()),
116 LangOpts(CI.getLangOpts()), AsmOutStream(std::move(OS)), FS(VFS),
117 LLVMIRGeneration("irgen", "LLVM IR Generation Time"), Action(Action),
118 Gen(CreateLLVMCodeGen(Diags, InFile, std::move(VFS),
119 CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(),
120 CI.getCodeGenOpts(), C, CoverageInfo)),
121 LinkModules(std::move(LinkModules)), CurLinkModule(CurLinkModule) {
122 TimerIsEnabled = CodeGenOpts.TimePasses;
123 llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
124 llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
125}
126
127llvm::Module* BackendConsumer::getModule() const {
128 return Gen->GetModule();
129}
130
131std::unique_ptr<llvm::Module> BackendConsumer::takeModule() {
132 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
133}
134
136 return Gen.get();
137}
138
140 Gen->HandleCXXStaticMemberVarInstantiation(VD);
141}
142
144 assert(!Context && "initialized multiple times");
145
146 Context = &Ctx;
147
148 if (TimerIsEnabled)
149 LLVMIRGeneration.startTimer();
150
151 Gen->Initialize(Ctx);
152
153 if (TimerIsEnabled)
154 LLVMIRGeneration.stopTimer();
155}
156
158 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
159 Context->getSourceManager(),
160 "LLVM IR generation of declaration");
161
162 // Recurse.
163 if (TimerIsEnabled) {
164 LLVMIRGenerationRefCount += 1;
165 if (LLVMIRGenerationRefCount == 1)
166 LLVMIRGeneration.startTimer();
167 }
168
169 Gen->HandleTopLevelDecl(D);
170
171 if (TimerIsEnabled) {
172 LLVMIRGenerationRefCount -= 1;
173 if (LLVMIRGenerationRefCount == 0)
174 LLVMIRGeneration.stopTimer();
175 }
176
177 return true;
178}
179
182 Context->getSourceManager(),
183 "LLVM IR generation of inline function");
184 if (TimerIsEnabled)
185 LLVMIRGeneration.startTimer();
186
187 Gen->HandleInlineFunctionDefinition(D);
188
189 if (TimerIsEnabled)
190 LLVMIRGeneration.stopTimer();
191}
192
194 // Ignore interesting decls from the AST reader after IRGen is finished.
195 if (!IRGenFinished)
197}
198
199// Links each entry in LinkModules into our module. Returns true on error.
200bool BackendConsumer::LinkInModules(llvm::Module *M) {
201 for (auto &LM : LinkModules) {
202 assert(LM.Module && "LinkModule does not actually have a module");
203
204 if (LM.PropagateAttrs)
205 for (Function &F : *LM.Module) {
206 // Skip intrinsics. Keep consistent with how intrinsics are created
207 // in LLVM IR.
208 if (F.isIntrinsic())
209 continue;
211 F, CodeGenOpts, LangOpts, TargetOpts, LM.Internalize);
212 }
213
214 CurLinkModule = LM.Module.get();
215 bool Err;
216
217 if (LM.Internalize) {
218 Err = Linker::linkModules(
219 *M, std::move(LM.Module), LM.LinkFlags,
220 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
221 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
222 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
223 });
224 });
225 } else
226 Err = Linker::linkModules(*M, std::move(LM.Module), LM.LinkFlags);
227
228 if (Err)
229 return true;
230 }
231
232 LinkModules.clear();
233 return false; // success
234}
235
237 {
238 llvm::TimeTraceScope TimeScope("Frontend");
239 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
240 if (TimerIsEnabled) {
241 LLVMIRGenerationRefCount += 1;
242 if (LLVMIRGenerationRefCount == 1)
243 LLVMIRGeneration.startTimer();
244 }
245
246 Gen->HandleTranslationUnit(C);
247
248 if (TimerIsEnabled) {
249 LLVMIRGenerationRefCount -= 1;
250 if (LLVMIRGenerationRefCount == 0)
251 LLVMIRGeneration.stopTimer();
252 }
253
254 IRGenFinished = true;
255 }
256
257 // Silently ignore if we weren't initialized for some reason.
258 if (!getModule())
259 return;
260
261 LLVMContext &Ctx = getModule()->getContext();
262 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
263 Ctx.getDiagnosticHandler();
264 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
265 CodeGenOpts, this));
266
267 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
268 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
269
271 setupLLVMOptimizationRemarks(
272 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
273 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
274 CodeGenOpts.DiagnosticsHotnessThreshold);
275
276 if (Error E = OptRecordFileOrErr.takeError()) {
277 reportOptRecordError(std::move(E), Diags, CodeGenOpts);
278 return;
279 }
280
281 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
282 std::move(*OptRecordFileOrErr);
283
284 if (OptRecordFile &&
285 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
286 Ctx.setDiagnosticsHotnessRequested(true);
287
288 if (CodeGenOpts.MisExpect) {
289 Ctx.setMisExpectWarningRequested(true);
290 }
291
292 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
293 Ctx.setDiagnosticsMisExpectTolerance(
295 }
296
297 // Link each LinkModule into our module.
298 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(getModule()))
299 return;
300
301 for (auto &F : getModule()->functions()) {
302 if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
303 auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
304 // TODO: use a fast content hash when available.
305 auto NameHash = llvm::hash_value(F.getName());
306 ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
307 }
308 }
309
310 if (CodeGenOpts.ClearASTBeforeBackend) {
311 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
312 // Access to the AST is no longer available after this.
313 // Other things that the ASTContext manages are still available, e.g.
314 // the SourceManager. It'd be nice if we could separate out all the
315 // things in ASTContext used after this point and null out the
316 // ASTContext, but too many various parts of the ASTContext are still
317 // used in various parts.
318 C.cleanup();
319 C.getAllocator().Reset();
320 }
321
322 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
323
324 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts, LangOpts,
325 C.getTargetInfo().getDataLayoutString(), getModule(),
326 Action, FS, std::move(AsmOutStream), this);
327
328 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
329
330 if (OptRecordFile)
331 OptRecordFile->keep();
332}
333
336 Context->getSourceManager(),
337 "LLVM IR generation of declaration");
338 Gen->HandleTagDeclDefinition(D);
339}
340
342 Gen->HandleTagDeclRequiredDefinition(D);
343}
344
346 Gen->CompleteTentativeDefinition(D);
347}
348
350 Gen->CompleteExternalDeclaration(D);
351}
352
354 Gen->AssignInheritanceModel(RD);
355}
356
358 Gen->HandleVTable(RD);
359}
360
361void BackendConsumer::anchor() { }
362
363} // namespace clang
364
365bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
366 BackendCon->DiagnosticHandlerImpl(DI);
367 return true;
368}
369
370/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
371/// buffer to be a valid FullSourceLoc.
372static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
373 SourceManager &CSM) {
374 // Get both the clang and llvm source managers. The location is relative to
375 // a memory buffer that the LLVM Source Manager is handling, we need to add
376 // a copy to the Clang source manager.
377 const llvm::SourceMgr &LSM = *D.getSourceMgr();
378
379 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
380 // already owns its one and clang::SourceManager wants to own its one.
381 const MemoryBuffer *LBuf =
382 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
383
384 // Create the copy and transfer ownership to clang::SourceManager.
385 // TODO: Avoid copying files into memory.
386 std::unique_ptr<llvm::MemoryBuffer> CBuf =
387 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
388 LBuf->getBufferIdentifier());
389 // FIXME: Keep a file ID map instead of creating new IDs for each location.
390 FileID FID = CSM.createFileID(std::move(CBuf));
391
392 // Translate the offset into the file.
393 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
394 SourceLocation NewLoc =
395 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
396 return FullSourceLoc(NewLoc, CSM);
397}
398
399#define ComputeDiagID(Severity, GroupName, DiagID) \
400 do { \
401 switch (Severity) { \
402 case llvm::DS_Error: \
403 DiagID = diag::err_fe_##GroupName; \
404 break; \
405 case llvm::DS_Warning: \
406 DiagID = diag::warn_fe_##GroupName; \
407 break; \
408 case llvm::DS_Remark: \
409 llvm_unreachable("'remark' severity not expected"); \
410 break; \
411 case llvm::DS_Note: \
412 DiagID = diag::note_fe_##GroupName; \
413 break; \
414 } \
415 } while (false)
416
417#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
418 do { \
419 switch (Severity) { \
420 case llvm::DS_Error: \
421 DiagID = diag::err_fe_##GroupName; \
422 break; \
423 case llvm::DS_Warning: \
424 DiagID = diag::warn_fe_##GroupName; \
425 break; \
426 case llvm::DS_Remark: \
427 DiagID = diag::remark_fe_##GroupName; \
428 break; \
429 case llvm::DS_Note: \
430 DiagID = diag::note_fe_##GroupName; \
431 break; \
432 } \
433 } while (false)
434
435void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
436 const llvm::SMDiagnostic &D = DI.getSMDiag();
437
438 unsigned DiagID;
439 if (DI.isInlineAsmDiag())
440 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
441 else
442 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
443
444 // This is for the empty BackendConsumer that uses the clang diagnostic
445 // handler for IR input files.
446 if (!Context) {
447 D.print(nullptr, llvm::errs());
448 Diags.Report(DiagID).AddString("cannot compile inline asm");
449 return;
450 }
451
452 // There are a couple of different kinds of errors we could get here.
453 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
454
455 // Strip "error: " off the start of the message string.
456 StringRef Message = D.getMessage();
457 (void)Message.consume_front("error: ");
458
459 // If the SMDiagnostic has an inline asm source location, translate it.
461 if (D.getLoc() != SMLoc())
463
464 // If this problem has clang-level source location information, report the
465 // issue in the source with a note showing the instantiated
466 // code.
467 if (DI.isInlineAsmDiag()) {
468 SourceLocation LocCookie =
469 SourceLocation::getFromRawEncoding(DI.getLocCookie());
470 if (LocCookie.isValid()) {
471 Diags.Report(LocCookie, DiagID).AddString(Message);
472
473 if (D.getLoc().isValid()) {
474 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
475 // Convert the SMDiagnostic ranges into SourceRange and attach them
476 // to the diagnostic.
477 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
478 unsigned Column = D.getColumnNo();
480 Loc.getLocWithOffset(Range.second - Column));
481 }
482 }
483 return;
484 }
485 }
486
487 // Otherwise, report the backend issue as occurring in the generated .s file.
488 // If Loc is invalid, we still need to report the issue, it just gets no
489 // location info.
490 Diags.Report(Loc, DiagID).AddString(Message);
491}
492
493bool
494BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
495 unsigned DiagID;
496 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
497 std::string Message = D.getMsgStr().str();
498
499 // If this problem has clang-level source location information, report the
500 // issue as being a problem in the source with a note showing the instantiated
501 // code.
502 SourceLocation LocCookie =
504 if (LocCookie.isValid())
505 Diags.Report(LocCookie, DiagID).AddString(Message);
506 else {
507 // Otherwise, report the backend diagnostic as occurring in the generated
508 // .s file.
509 // If Loc is invalid, we still need to report the diagnostic, it just gets
510 // no location info.
512 Diags.Report(Loc, DiagID).AddString(Message);
513 }
514 // We handled all the possible severities.
515 return true;
516}
517
518bool
519BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
520 if (D.getSeverity() != llvm::DS_Warning)
521 // For now, the only support we have for StackSize diagnostic is warning.
522 // We do not know how to format other severities.
523 return false;
524
525 auto Loc = getFunctionSourceLocation(D.getFunction());
526 if (!Loc)
527 return false;
528
529 Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
530 << D.getStackSize() << D.getStackLimit()
531 << llvm::demangle(D.getFunction().getName());
532 return true;
533}
534
536 const llvm::DiagnosticInfoResourceLimit &D) {
537 auto Loc = getFunctionSourceLocation(D.getFunction());
538 if (!Loc)
539 return false;
540 unsigned DiagID = diag::err_fe_backend_resource_limit;
541 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
542
543 Diags.Report(*Loc, DiagID)
544 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
545 << llvm::demangle(D.getFunction().getName());
546 return true;
547}
548
550 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
551 StringRef &Filename, unsigned &Line, unsigned &Column) const {
552 SourceManager &SourceMgr = Context->getSourceManager();
553 FileManager &FileMgr = SourceMgr.getFileManager();
554 SourceLocation DILoc;
555
556 if (D.isLocationAvailable()) {
558 if (Line > 0) {
559 auto FE = FileMgr.getOptionalFileRef(Filename);
560 if (!FE)
561 FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());
562 if (FE) {
563 // If -gcolumn-info was not used, Column will be 0. This upsets the
564 // source manager, so pass 1 if Column is not set.
565 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
566 }
567 }
568 BadDebugInfo = DILoc.isInvalid();
569 }
570
571 // If a location isn't available, try to approximate it using the associated
572 // function definition. We use the definition's right brace to differentiate
573 // from diagnostics that genuinely relate to the function itself.
574 FullSourceLoc Loc(DILoc, SourceMgr);
575 if (Loc.isInvalid()) {
576 if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
577 Loc = *MaybeLoc;
578 }
579
580 if (DILoc.isInvalid() && D.isLocationAvailable())
581 // If we were not able to translate the file:line:col information
582 // back to a SourceLocation, at least emit a note stating that
583 // we could not translate this location. This can happen in the
584 // case of #line directives.
585 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
586 << Filename << Line << Column;
587
588 return Loc;
589}
590
591std::optional<FullSourceLoc>
593 auto Hash = llvm::hash_value(F.getName());
594 for (const auto &Pair : ManglingFullSourceLocs) {
595 if (Pair.first == Hash)
596 return Pair.second;
597 }
598 return std::nullopt;
599}
600
602 const llvm::DiagnosticInfoUnsupported &D) {
603 // We only support warnings or errors.
604 assert(D.getSeverity() == llvm::DS_Error ||
605 D.getSeverity() == llvm::DS_Warning);
606
607 StringRef Filename;
608 unsigned Line, Column;
609 bool BadDebugInfo = false;
611 std::string Msg;
612 raw_string_ostream MsgStream(Msg);
613
614 // Context will be nullptr for IR input files, we will construct the diag
615 // message from llvm::DiagnosticInfoUnsupported.
616 if (Context != nullptr) {
618 MsgStream << D.getMessage();
619 } else {
620 DiagnosticPrinterRawOStream DP(MsgStream);
621 D.print(DP);
622 }
623
624 auto DiagType = D.getSeverity() == llvm::DS_Error
625 ? diag::err_fe_backend_unsupported
626 : diag::warn_fe_backend_unsupported;
627 Diags.Report(Loc, DiagType) << Msg;
628
629 if (BadDebugInfo)
630 // If we were not able to translate the file:line:col information
631 // back to a SourceLocation, at least emit a note stating that
632 // we could not translate this location. This can happen in the
633 // case of #line directives.
634 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
635 << Filename << Line << Column;
636}
637
639 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
640 // We only support warnings and remarks.
641 assert(D.getSeverity() == llvm::DS_Remark ||
642 D.getSeverity() == llvm::DS_Warning);
643
644 StringRef Filename;
645 unsigned Line, Column;
646 bool BadDebugInfo = false;
648 std::string Msg;
649 raw_string_ostream MsgStream(Msg);
650
651 // Context will be nullptr for IR input files, we will construct the remark
652 // message from llvm::DiagnosticInfoOptimizationBase.
653 if (Context != nullptr) {
655 MsgStream << D.getMsg();
656 } else {
657 DiagnosticPrinterRawOStream DP(MsgStream);
658 D.print(DP);
659 }
660
661 if (D.getHotness())
662 MsgStream << " (hotness: " << *D.getHotness() << ")";
663
664 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
665
666 if (BadDebugInfo)
667 // If we were not able to translate the file:line:col information
668 // back to a SourceLocation, at least emit a note stating that
669 // we could not translate this location. This can happen in the
670 // case of #line directives.
671 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
672 << Filename << Line << Column;
673}
674
676 const llvm::DiagnosticInfoOptimizationBase &D) {
677 // Without hotness information, don't show noisy remarks.
678 if (D.isVerbose() && !D.getHotness())
679 return;
680
681 if (D.isPassed()) {
682 // Optimization remarks are active only if the -Rpass flag has a regular
683 // expression that matches the name of the pass name in \p D.
684 if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
685 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
686 } else if (D.isMissed()) {
687 // Missed optimization remarks are active only if the -Rpass-missed
688 // flag has a regular expression that matches the name of the pass
689 // name in \p D.
690 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
692 D, diag::remark_fe_backend_optimization_remark_missed);
693 } else {
694 assert(D.isAnalysis() && "Unknown remark type");
695
696 bool ShouldAlwaysPrint = false;
697 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
698 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
699
700 if (ShouldAlwaysPrint ||
701 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
703 D, diag::remark_fe_backend_optimization_remark_analysis);
704 }
705}
706
708 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
709 // Optimization analysis remarks are active if the pass name is set to
710 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
711 // regular expression that matches the name of the pass name in \p D.
712
713 if (D.shouldAlwaysPrint() ||
714 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
716 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
717}
718
720 const llvm::OptimizationRemarkAnalysisAliasing &D) {
721 // Optimization analysis remarks are active if the pass name is set to
722 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
723 // regular expression that matches the name of the pass name in \p D.
724
725 if (D.shouldAlwaysPrint() ||
726 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
728 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
729}
730
732 const llvm::DiagnosticInfoOptimizationFailure &D) {
733 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
734}
735
736void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
737 SourceLocation LocCookie =
739
740 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
741 // should instead assert that LocCookie.isValid().
742 if (!LocCookie.isValid())
743 return;
744
745 Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
746 ? diag::err_fe_backend_error_attr
747 : diag::warn_fe_backend_warning_attr)
748 << llvm::demangle(D.getFunctionName()) << D.getNote();
749}
750
752 const llvm::DiagnosticInfoMisExpect &D) {
753 StringRef Filename;
754 unsigned Line, Column;
755 bool BadDebugInfo = false;
758
759 Diags.Report(Loc, diag::warn_profile_data_misexpect) << D.getMsg().str();
760
761 if (BadDebugInfo)
762 // If we were not able to translate the file:line:col information
763 // back to a SourceLocation, at least emit a note stating that
764 // we could not translate this location. This can happen in the
765 // case of #line directives.
766 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
767 << Filename << Line << Column;
768}
769
770/// This function is invoked when the backend needs
771/// to report something to the user.
772void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
773 unsigned DiagID = diag::err_fe_inline_asm;
774 llvm::DiagnosticSeverity Severity = DI.getSeverity();
775 // Get the diagnostic ID based.
776 switch (DI.getKind()) {
777 case llvm::DK_InlineAsm:
778 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
779 return;
780 ComputeDiagID(Severity, inline_asm, DiagID);
781 break;
782 case llvm::DK_SrcMgr:
783 SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
784 return;
785 case llvm::DK_StackSize:
786 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
787 return;
788 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
789 break;
790 case llvm::DK_ResourceLimit:
791 if (ResourceLimitDiagHandler(cast<DiagnosticInfoResourceLimit>(DI)))
792 return;
793 ComputeDiagID(Severity, backend_resource_limit, DiagID);
794 break;
795 case DK_Linker:
796 ComputeDiagID(Severity, linking_module, DiagID);
797 break;
798 case llvm::DK_OptimizationRemark:
799 // Optimization remarks are always handled completely by this
800 // handler. There is no generic way of emitting them.
801 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
802 return;
803 case llvm::DK_OptimizationRemarkMissed:
804 // Optimization remarks are always handled completely by this
805 // handler. There is no generic way of emitting them.
806 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
807 return;
808 case llvm::DK_OptimizationRemarkAnalysis:
809 // Optimization remarks are always handled completely by this
810 // handler. There is no generic way of emitting them.
811 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
812 return;
813 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
814 // Optimization remarks are always handled completely by this
815 // handler. There is no generic way of emitting them.
816 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
817 return;
818 case llvm::DK_OptimizationRemarkAnalysisAliasing:
819 // Optimization remarks are always handled completely by this
820 // handler. There is no generic way of emitting them.
821 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
822 return;
823 case llvm::DK_MachineOptimizationRemark:
824 // Optimization remarks are always handled completely by this
825 // handler. There is no generic way of emitting them.
826 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
827 return;
828 case llvm::DK_MachineOptimizationRemarkMissed:
829 // Optimization remarks are always handled completely by this
830 // handler. There is no generic way of emitting them.
831 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
832 return;
833 case llvm::DK_MachineOptimizationRemarkAnalysis:
834 // Optimization remarks are always handled completely by this
835 // handler. There is no generic way of emitting them.
836 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
837 return;
838 case llvm::DK_OptimizationFailure:
839 // Optimization failures are always handled completely by this
840 // handler.
841 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
842 return;
843 case llvm::DK_Unsupported:
844 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
845 return;
846 case llvm::DK_DontCall:
847 DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
848 return;
849 case llvm::DK_MisExpect:
850 MisExpectDiagHandler(cast<DiagnosticInfoMisExpect>(DI));
851 return;
852 default:
853 // Plugin IDs are not bound to any value as they are set dynamically.
854 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
855 break;
856 }
857 std::string MsgStorage;
858 {
859 raw_string_ostream Stream(MsgStorage);
860 DiagnosticPrinterRawOStream DP(Stream);
861 DI.print(DP);
862 }
863
864 if (DI.getKind() == DK_Linker) {
865 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
866 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
867 return;
868 }
869
870 // Report the backend message using the usual diagnostic mechanism.
872 Diags.Report(Loc, DiagID).AddString(MsgStorage);
873}
874#undef ComputeDiagID
875
876CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
877 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
878 OwnsVMContext(!_VMContext) {}
879
881 TheModule.reset();
882 if (OwnsVMContext)
883 delete VMContext;
884}
885
886bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {
887 if (!LinkModules.empty())
888 return false;
889
892 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
893 if (!BCBuf) {
894 CI.getDiagnostics().Report(diag::err_cannot_open_file)
895 << F.Filename << BCBuf.getError().message();
896 LinkModules.clear();
897 return true;
898 }
899
901 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
902 if (!ModuleOrErr) {
903 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
904 CI.getDiagnostics().Report(diag::err_cannot_open_file)
905 << F.Filename << EIB.message();
906 });
907 LinkModules.clear();
908 return true;
909 }
910 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
911 F.Internalize, F.LinkFlags});
912 }
913 return false;
914}
915
916bool CodeGenAction::hasIRSupport() const { return true; }
917
919 // If the consumer creation failed, do nothing.
920 if (!getCompilerInstance().hasASTConsumer())
921 return;
922
923 // Steal the module from the consumer.
924 TheModule = BEConsumer->takeModule();
925}
926
927std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
928 return std::move(TheModule);
929}
930
931llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
932 OwnsVMContext = false;
933 return VMContext;
934}
935
938}
939
942 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
943 return true;
944}
945
946static std::unique_ptr<raw_pwrite_stream>
947GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
948 switch (Action) {
950 return CI.createDefaultOutputFile(false, InFile, "s");
951 case Backend_EmitLL:
952 return CI.createDefaultOutputFile(false, InFile, "ll");
953 case Backend_EmitBC:
954 return CI.createDefaultOutputFile(true, InFile, "bc");
956 return nullptr;
958 return CI.createNullOutputFile();
959 case Backend_EmitObj:
960 return CI.createDefaultOutputFile(true, InFile, "o");
961 }
962
963 llvm_unreachable("Invalid action!");
964}
965
966std::unique_ptr<ASTConsumer>
968 BackendAction BA = static_cast<BackendAction>(Act);
969 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
970 if (!OS)
971 OS = GetOutputStream(CI, InFile, BA);
972
973 if (BA != Backend_EmitNothing && !OS)
974 return nullptr;
975
976 // Load bitcode modules to link with, if we need to.
977 if (loadLinkModules(CI))
978 return nullptr;
979
980 CoverageSourceInfo *CoverageInfo = nullptr;
981 // Add the preprocessor callback only when the coverage mapping is generated.
982 if (CI.getCodeGenOpts().CoverageMapping)
984 CI.getPreprocessor());
985
986 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
987 CI, BA, &CI.getVirtualFileSystem(), *VMContext, std::move(LinkModules),
988 InFile, std::move(OS), CoverageInfo));
989 BEConsumer = Result.get();
990
991 // Enable generating macro debug info only when debug info is not disabled and
992 // also macro debug info is enabled.
993 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
994 CI.getCodeGenOpts().MacroDebugInfo) {
995 std::unique_ptr<PPCallbacks> Callbacks =
996 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
997 CI.getPreprocessor());
998 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
999 }
1000
1001 if (CI.getFrontendOpts().GenReducedBMI &&
1002 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
1003 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1004 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1007 Consumers[1] = std::move(Result);
1008 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
1009 }
1010
1011 return std::move(Result);
1012}
1013
1014std::unique_ptr<llvm::Module>
1015CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1018
1019 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1020 unsigned DiagID =
1022 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1023 CI.getDiagnostics().Report(DiagID) << EIB.message();
1024 });
1025 return {};
1026 };
1027
1028 // For ThinLTO backend invocations, ensure that the context
1029 // merges types based on ODR identifiers. We also need to read
1030 // the correct module out of a multi-module bitcode file.
1031 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1032 VMContext->enableDebugTypeODRUniquing();
1033
1034 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1035 if (!BMsOrErr)
1036 return DiagErrors(BMsOrErr.takeError());
1037 BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1038 // We have nothing to do if the file contains no ThinLTO module. This is
1039 // possible if ThinLTO compilation was not able to split module. Content of
1040 // the file was already processed by indexing and will be passed to the
1041 // linker using merged object file.
1042 if (!Bm) {
1043 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1044 M->setTargetTriple(CI.getTargetOpts().Triple);
1045 return M;
1046 }
1048 Bm->parseModule(*VMContext);
1049 if (!MOrErr)
1050 return DiagErrors(MOrErr.takeError());
1051 return std::move(*MOrErr);
1052 }
1053
1054 // Load bitcode modules to link with, if we need to.
1055 if (loadLinkModules(CI))
1056 return nullptr;
1057
1058 // Handle textual IR and bitcode file with one single module.
1059 llvm::SMDiagnostic Err;
1060 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1061 return M;
1062
1063 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1064 // output), place the extra modules (actually only one, a regular LTO module)
1065 // into LinkModules as if we are using -mlink-bitcode-file.
1066 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1067 if (BMsOrErr && BMsOrErr->size()) {
1068 std::unique_ptr<llvm::Module> FirstM;
1069 for (auto &BM : *BMsOrErr) {
1071 BM.parseModule(*VMContext);
1072 if (!MOrErr)
1073 return DiagErrors(MOrErr.takeError());
1074 if (FirstM)
1075 LinkModules.push_back({std::move(*MOrErr), /*PropagateAttrs=*/false,
1076 /*Internalize=*/false, /*LinkFlags=*/{}});
1077 else
1078 FirstM = std::move(*MOrErr);
1079 }
1080 if (FirstM)
1081 return FirstM;
1082 }
1083 // If BMsOrErr fails, consume the error and use the error message from
1084 // parseIR.
1085 consumeError(BMsOrErr.takeError());
1086
1087 // Translate from the diagnostic info to the SourceManager location if
1088 // available.
1089 // TODO: Unify this with ConvertBackendLocation()
1091 if (Err.getLineNo() > 0) {
1092 assert(Err.getColumnNo() >= 0);
1093 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1094 Err.getLineNo(), Err.getColumnNo() + 1);
1095 }
1096
1097 // Strip off a leading diagnostic code if there is one.
1098 StringRef Msg = Err.getMessage();
1099 Msg.consume_front("error: ");
1100
1101 unsigned DiagID =
1103
1104 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1105 return {};
1106}
1107
1109 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1111 return;
1112 }
1113
1114 // If this is an IR file, we have to treat it specially.
1115 BackendAction BA = static_cast<BackendAction>(Act);
1117 auto &CodeGenOpts = CI.getCodeGenOpts();
1118 auto &Diagnostics = CI.getDiagnostics();
1119 std::unique_ptr<raw_pwrite_stream> OS =
1121 if (BA != Backend_EmitNothing && !OS)
1122 return;
1123
1125 FileID FID = SM.getMainFileID();
1126 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1127 if (!MainFile)
1128 return;
1129
1130 TheModule = loadModule(*MainFile);
1131 if (!TheModule)
1132 return;
1133
1134 const TargetOptions &TargetOpts = CI.getTargetOpts();
1135 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1136 Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1137 << TargetOpts.Triple;
1138 TheModule->setTargetTriple(TargetOpts.Triple);
1139 }
1140
1141 EmbedObject(TheModule.get(), CodeGenOpts, Diagnostics);
1142 EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1143
1144 LLVMContext &Ctx = TheModule->getContext();
1145
1146 // Restore any diagnostic handler previously set before returning from this
1147 // function.
1148 struct RAII {
1149 LLVMContext &Ctx;
1150 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1151 ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1152 } _{Ctx};
1153
1154 // Set clang diagnostic handler. To do this we need to create a fake
1155 // BackendConsumer.
1156 BackendConsumer Result(CI, BA, &CI.getVirtualFileSystem(), *VMContext,
1157 std::move(LinkModules), "", nullptr, nullptr,
1158 TheModule.get());
1159
1160 // Link in each pending link module.
1161 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(&*TheModule))
1162 return;
1163
1164 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1165 // true here because the valued names are needed for reading textual IR.
1166 Ctx.setDiscardValueNames(false);
1167 Ctx.setDiagnosticHandler(
1168 std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1169
1170 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1171 Ctx.setDefaultTargetFeatures(llvm::join(TargetOpts.Features, ","));
1172
1174 setupLLVMOptimizationRemarks(
1175 Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1176 CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1177 CodeGenOpts.DiagnosticsHotnessThreshold);
1178
1179 if (Error E = OptRecordFileOrErr.takeError()) {
1180 reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1181 return;
1182 }
1183 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1184 std::move(*OptRecordFileOrErr);
1185
1187 Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts, TargetOpts,
1188 CI.getLangOpts(), CI.getTarget().getDataLayoutString(), TheModule.get(),
1189 BA, CI.getFileManager().getVirtualFileSystemPtr(), std::move(OS));
1190 if (OptRecordFile)
1191 OptRecordFile->keep();
1192}
1193
1194//
1195
1196void EmitAssemblyAction::anchor() { }
1197EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1198 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1199
1200void EmitBCAction::anchor() { }
1201EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1202 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1203
1204void EmitLLVMAction::anchor() { }
1205EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1206 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1207
1208void EmitLLVMOnlyAction::anchor() { }
1209EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1210 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1211
1212void EmitCodeGenOnlyAction::anchor() { }
1214 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1215
1216void EmitObjAction::anchor() { }
1217EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1218 : 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.
BackendConsumer(const CompilerInstance &CI, BackendAction Action, IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, llvm::LLVMContext &C, SmallVector< LinkModule, 4 > LinkModules, StringRef InFile, std::unique_ptr< raw_pwrite_stream > OS, CoverageSourceInfo *CoverageInfo, llvm::Module *CurLinkModule=nullptr)
void HandleTranslationUnit(ASTContext &C) override
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
void CompleteTentativeDefinition(VarDecl *D) override
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D)
Specialized handler for unsupported backend feature diagnostic.
bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D)
Specialized handler for InlineAsm diagnostic.
bool LinkInModules(llvm::Module *M)
const FullSourceLoc getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo, StringRef &Filename, unsigned &Line, unsigned &Column) const
Get the best possible source location to represent a diagnostic that may have associated debug info.
void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID)
Specialized handlers for optimization remarks.
void DontCallDiagHandler(const llvm::DiagnosticInfoDontCall &D)
void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D)
Specialized handler for misexpect warnings.
CodeGenerator * getCodeGenerator()
void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D)
Specialized handler for diagnostics reported using SMDiagnostic.
Represents a C++ struct/union/class.
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.
std::unique_ptr< raw_pwrite_stream > createDefaultOutputFile(bool Binary=true, StringRef BaseInput="", StringRef Extension="", bool RemoveFileOnSignal=true, bool CreateMissingDirectories=false, bool ForceUseTemporary=false)
Create the default output file (from the invocation's options) and add it to the list of tracked outp...
FileManager & getFileManager() const
Return the current file manager to the caller.
InMemoryModuleCache & getModuleCache() const
Preprocessor & getPreprocessor() const
Return the current preprocessor.
TargetOptions & getTargetOpts()
std::unique_ptr< llvm::raw_pwrite_stream > takeOutputStream()
FrontendOptions & getFrontendOpts()
HeaderSearchOptions & getHeaderSearchOpts()
TargetInfo & getTarget() const
llvm::vfs::FileSystem & getVirtualFileSystem() const
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
SourceManager & getSourceManager() const
Return the current source manager.
std::unique_ptr< raw_pwrite_stream > createNullOutputFile()
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Decl - This represents one declaration (or definition), e.g.
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:3576
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:2076
The JSON file list parser is used to communicate input to InstallAPI.
void EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts, DiagnosticsEngine &Diags)
static void reportOptRecordError(Error E, DiagnosticsEngine &Diags, const CodeGenOptions &CodeGenOpts)
CodeGenerator * CreateLLVMCodeGen(DiagnosticsEngine &Diags, llvm::StringRef ModuleName, IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS, const HeaderSearchOptions &HeaderSearchOpts, const PreprocessorOptions &PreprocessorOpts, const CodeGenOptions &CGO, llvm::LLVMContext &C, CoverageSourceInfo *CoverageInfo=nullptr)
CreateLLVMCodeGen - Create a CodeGenerator instance.
void EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, std::unique_ptr< raw_pwrite_stream > OS, BackendConsumer *BC=nullptr)
@ Result
The result type of a method or function.
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
BackendAction
Definition: BackendUtil.h:35
@ Backend_EmitAssembly
Emit native assembly files.
Definition: BackendUtil.h:36
@ Backend_EmitLL
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:38
@ Backend_EmitBC
Emit LLVM bitcode files.
Definition: BackendUtil.h:37
@ Backend_EmitObj
Emit native object files.
Definition: BackendUtil.h:41
@ Backend_EmitMCNull
Run CodeGen, but don't emit anything.
Definition: BackendUtil.h:40
@ Backend_EmitNothing
Don't emit anything (benchmarking mode)
Definition: BackendUtil.h:39
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.