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