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