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