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