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(), M: getModule(), Action, VFS: FS,
323 OS: std::move(AsmOutStream), BC: this);
324
325 if (OptRecordFile)
326 OptRecordFile->keep();
327}
328
329void BackendConsumer::HandleTagDeclDefinition(TagDecl *D) {
330 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
331 Context->getSourceManager(),
332 "LLVM IR generation of declaration");
333 Gen->HandleTagDeclDefinition(D);
334}
335
336void BackendConsumer::HandleTagDeclRequiredDefinition(const TagDecl *D) {
337 Gen->HandleTagDeclRequiredDefinition(D);
338}
339
340void BackendConsumer::CompleteTentativeDefinition(VarDecl *D) {
341 Gen->CompleteTentativeDefinition(D);
342}
343
344void BackendConsumer::CompleteExternalDeclaration(DeclaratorDecl *D) {
345 Gen->CompleteExternalDeclaration(D);
346}
347
348void BackendConsumer::AssignInheritanceModel(CXXRecordDecl *RD) {
349 Gen->AssignInheritanceModel(RD);
350}
351
352void BackendConsumer::HandleVTable(CXXRecordDecl *RD) {
353 Gen->HandleVTable(RD);
354}
355
356void BackendConsumer::anchor() { }
357
358} // namespace clang
359
360bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
361 BackendCon->DiagnosticHandlerImpl(DI);
362 return true;
363}
364
365/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
366/// buffer to be a valid FullSourceLoc.
367static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
368 SourceManager &CSM) {
369 // Get both the clang and llvm source managers. The location is relative to
370 // a memory buffer that the LLVM Source Manager is handling, we need to add
371 // a copy to the Clang source manager.
372 const llvm::SourceMgr &LSM = *D.getSourceMgr();
373
374 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
375 // already owns its one and clang::SourceManager wants to own its one.
376 const MemoryBuffer *LBuf =
377 LSM.getMemoryBuffer(i: LSM.FindBufferContainingLoc(Loc: D.getLoc()));
378
379 // Create the copy and transfer ownership to clang::SourceManager.
380 // TODO: Avoid copying files into memory.
381 std::unique_ptr<llvm::MemoryBuffer> CBuf =
382 llvm::MemoryBuffer::getMemBufferCopy(InputData: LBuf->getBuffer(),
383 BufferName: LBuf->getBufferIdentifier());
384 // FIXME: Keep a file ID map instead of creating new IDs for each location.
385 FileID FID = CSM.createFileID(Buffer: std::move(CBuf));
386
387 // Translate the offset into the file.
388 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
389 SourceLocation NewLoc =
390 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
391 return FullSourceLoc(NewLoc, CSM);
392}
393
394#define ComputeDiagID(Severity, GroupName, DiagID) \
395 do { \
396 switch (Severity) { \
397 case llvm::DS_Error: \
398 DiagID = diag::err_fe_##GroupName; \
399 break; \
400 case llvm::DS_Warning: \
401 DiagID = diag::warn_fe_##GroupName; \
402 break; \
403 case llvm::DS_Remark: \
404 llvm_unreachable("'remark' severity not expected"); \
405 break; \
406 case llvm::DS_Note: \
407 DiagID = diag::note_fe_##GroupName; \
408 break; \
409 } \
410 } while (false)
411
412#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
413 do { \
414 switch (Severity) { \
415 case llvm::DS_Error: \
416 DiagID = diag::err_fe_##GroupName; \
417 break; \
418 case llvm::DS_Warning: \
419 DiagID = diag::warn_fe_##GroupName; \
420 break; \
421 case llvm::DS_Remark: \
422 DiagID = diag::remark_fe_##GroupName; \
423 break; \
424 case llvm::DS_Note: \
425 DiagID = diag::note_fe_##GroupName; \
426 break; \
427 } \
428 } while (false)
429
430void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
431 const llvm::SMDiagnostic &D = DI.getSMDiag();
432
433 unsigned DiagID;
434 if (DI.isInlineAsmDiag())
435 ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
436 else
437 ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
438
439 // This is for the empty BackendConsumer that uses the clang diagnostic
440 // handler for IR input files.
441 if (!Context) {
442 D.print(ProgName: nullptr, S&: llvm::errs());
443 Diags.Report(DiagID).AddString(V: "cannot compile inline asm");
444 return;
445 }
446
447 // There are a couple of different kinds of errors we could get here.
448 // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
449
450 // Strip "error: " off the start of the message string.
451 StringRef Message = D.getMessage();
452 (void)Message.consume_front(Prefix: "error: ");
453
454 // If the SMDiagnostic has an inline asm source location, translate it.
455 FullSourceLoc Loc;
456 if (D.getLoc() != SMLoc())
457 Loc = ConvertBackendLocation(D, CSM&: Context->getSourceManager());
458
459 // If this problem has clang-level source location information, report the
460 // issue in the source with a note showing the instantiated
461 // code.
462 if (DI.isInlineAsmDiag()) {
463 SourceLocation LocCookie =
464 SourceLocation::getFromRawEncoding(Encoding: DI.getLocCookie());
465 if (LocCookie.isValid()) {
466 Diags.Report(Loc: LocCookie, DiagID).AddString(V: Message);
467
468 if (D.getLoc().isValid()) {
469 DiagnosticBuilder B = Diags.Report(Loc, DiagID: diag::note_fe_inline_asm_here);
470 // Convert the SMDiagnostic ranges into SourceRange and attach them
471 // to the diagnostic.
472 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
473 unsigned Column = D.getColumnNo();
474 B << SourceRange(Loc.getLocWithOffset(Offset: Range.first - Column),
475 Loc.getLocWithOffset(Offset: Range.second - Column));
476 }
477 }
478 return;
479 }
480 }
481
482 // Otherwise, report the backend issue as occurring in the generated .s file.
483 // If Loc is invalid, we still need to report the issue, it just gets no
484 // location info.
485 Diags.Report(Loc, DiagID).AddString(V: Message);
486}
487
488bool
489BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
490 unsigned DiagID;
491 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
492 std::string Message = D.getMsgStr().str();
493
494 // If this problem has clang-level source location information, report the
495 // issue as being a problem in the source with a note showing the instantiated
496 // code.
497 SourceLocation LocCookie =
498 SourceLocation::getFromRawEncoding(Encoding: D.getLocCookie());
499 if (LocCookie.isValid())
500 Diags.Report(Loc: LocCookie, DiagID).AddString(V: Message);
501 else {
502 // Otherwise, report the backend diagnostic as occurring in the generated
503 // .s file.
504 // If Loc is invalid, we still need to report the diagnostic, it just gets
505 // no location info.
506 FullSourceLoc Loc;
507 Diags.Report(Loc, DiagID).AddString(V: Message);
508 }
509 // We handled all the possible severities.
510 return true;
511}
512
513bool
514BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
515 if (D.getSeverity() != llvm::DS_Warning)
516 // For now, the only support we have for StackSize diagnostic is warning.
517 // We do not know how to format other severities.
518 return false;
519
520 auto Loc = getFunctionSourceLocation(F: D.getFunction());
521 if (!Loc)
522 return false;
523
524 Diags.Report(Loc: *Loc, DiagID: diag::warn_fe_frame_larger_than)
525 << D.getStackSize() << D.getStackLimit()
526 << llvm::demangle(MangledName: D.getFunction().getName());
527 return true;
528}
529
530bool BackendConsumer::ResourceLimitDiagHandler(
531 const llvm::DiagnosticInfoResourceLimit &D) {
532 auto Loc = getFunctionSourceLocation(F: D.getFunction());
533 if (!Loc)
534 return false;
535 unsigned DiagID = diag::err_fe_backend_resource_limit;
536 ComputeDiagID(D.getSeverity(), backend_resource_limit, DiagID);
537
538 Diags.Report(Loc: *Loc, DiagID)
539 << D.getResourceName() << D.getResourceSize() << D.getResourceLimit()
540 << llvm::demangle(MangledName: D.getFunction().getName());
541 return true;
542}
543
544const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
545 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
546 StringRef &Filename, unsigned &Line, unsigned &Column) const {
547 SourceManager &SourceMgr = Context->getSourceManager();
548 FileManager &FileMgr = SourceMgr.getFileManager();
549 SourceLocation DILoc;
550
551 if (D.isLocationAvailable()) {
552 D.getLocation(RelativePath&: Filename, Line, Column);
553 if (Line > 0) {
554 auto FE = FileMgr.getOptionalFileRef(Filename);
555 if (!FE)
556 FE = FileMgr.getOptionalFileRef(Filename: D.getAbsolutePath());
557 if (FE) {
558 // If -gcolumn-info was not used, Column will be 0. This upsets the
559 // source manager, so pass 1 if Column is not set.
560 DILoc = SourceMgr.translateFileLineCol(SourceFile: *FE, Line, Col: Column ? Column : 1);
561 }
562 }
563 BadDebugInfo = DILoc.isInvalid();
564 }
565
566 // If a location isn't available, try to approximate it using the associated
567 // function definition. We use the definition's right brace to differentiate
568 // from diagnostics that genuinely relate to the function itself.
569 FullSourceLoc Loc(DILoc, SourceMgr);
570 if (Loc.isInvalid()) {
571 if (auto MaybeLoc = getFunctionSourceLocation(F: D.getFunction()))
572 Loc = *MaybeLoc;
573 }
574
575 if (DILoc.isInvalid() && D.isLocationAvailable())
576 // If we were not able to translate the file:line:col information
577 // back to a SourceLocation, at least emit a note stating that
578 // we could not translate this location. This can happen in the
579 // case of #line directives.
580 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
581 << Filename << Line << Column;
582
583 return Loc;
584}
585
586std::optional<FullSourceLoc>
587BackendConsumer::getFunctionSourceLocation(const Function &F) const {
588 auto Hash = llvm::hash_value(S: F.getName());
589 for (const auto &Pair : ManglingFullSourceLocs) {
590 if (Pair.first == Hash)
591 return Pair.second;
592 }
593 return std::nullopt;
594}
595
596void BackendConsumer::UnsupportedDiagHandler(
597 const llvm::DiagnosticInfoUnsupported &D) {
598 // We only support warnings or errors.
599 assert(D.getSeverity() == llvm::DS_Error ||
600 D.getSeverity() == llvm::DS_Warning);
601
602 StringRef Filename;
603 unsigned Line, Column;
604 bool BadDebugInfo = false;
605 FullSourceLoc Loc;
606 std::string Msg;
607 raw_string_ostream MsgStream(Msg);
608
609 // Context will be nullptr for IR input files, we will construct the diag
610 // message from llvm::DiagnosticInfoUnsupported.
611 if (Context != nullptr) {
612 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
613 MsgStream << D.getMessage();
614 } else {
615 DiagnosticPrinterRawOStream DP(MsgStream);
616 D.print(DP);
617 }
618
619 auto DiagType = D.getSeverity() == llvm::DS_Error
620 ? diag::err_fe_backend_unsupported
621 : diag::warn_fe_backend_unsupported;
622 Diags.Report(Loc, DiagID: DiagType) << Msg;
623
624 if (BadDebugInfo)
625 // If we were not able to translate the file:line:col information
626 // back to a SourceLocation, at least emit a note stating that
627 // we could not translate this location. This can happen in the
628 // case of #line directives.
629 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
630 << Filename << Line << Column;
631}
632
633void BackendConsumer::UnsupportedTargetIntrinsicDiagHandler(
634 const llvm::DiagnosticInfoUnsupportedTargetIntrinsic &D) {
635 assert(D.getSeverity() == llvm::DS_Error &&
636 "unsupported target intrinsic diagnostic should be an error");
637
638 StringRef Filename;
639 unsigned Line, Column;
640 bool BadDebugInfo = false;
641 FullSourceLoc Loc;
642 std::string Msg;
643 raw_string_ostream MsgStream(Msg);
644
645 // Context will be nullptr for IR input files, so construct the diagnostic
646 // message from llvm::DiagnosticInfoUnsupportedTargetIntrinsic.
647 if (Context != nullptr) {
648 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
649 MsgStream << D.getMessage();
650 } else {
651 DiagnosticPrinterRawOStream DP(MsgStream);
652 D.print(DP);
653 }
654
655 Diags.Report(Loc, DiagID: diag::err_fe_backend_unsupported) << Msg;
656
657 if (BadDebugInfo) {
658 // If we were not able to translate the file:line:col information
659 // back to a SourceLocation, at least emit a note stating that
660 // we could not translate this location. This can happen in the
661 // case of #line directives.
662 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
663 << Filename << Line << Column;
664 }
665}
666
667void BackendConsumer::EmitOptimizationMessage(
668 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
669 // We only support warnings and remarks.
670 assert(D.getSeverity() == llvm::DS_Remark ||
671 D.getSeverity() == llvm::DS_Warning);
672
673 StringRef Filename;
674 unsigned Line, Column;
675 bool BadDebugInfo = false;
676 FullSourceLoc Loc;
677 std::string Msg;
678 raw_string_ostream MsgStream(Msg);
679
680 // Context will be nullptr for IR input files, we will construct the remark
681 // message from llvm::DiagnosticInfoOptimizationBase.
682 if (Context != nullptr) {
683 Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
684 MsgStream << D.getMsg();
685 } else {
686 DiagnosticPrinterRawOStream DP(MsgStream);
687 D.print(DP);
688 }
689
690 if (D.getHotness())
691 MsgStream << " (hotness: " << *D.getHotness() << ")";
692
693 Diags.Report(Loc, DiagID) << AddFlagValue(D.getPassName()) << Msg;
694
695 if (BadDebugInfo)
696 // If we were not able to translate the file:line:col information
697 // back to a SourceLocation, at least emit a note stating that
698 // we could not translate this location. This can happen in the
699 // case of #line directives.
700 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
701 << Filename << Line << Column;
702}
703
704void BackendConsumer::OptimizationRemarkHandler(
705 const llvm::DiagnosticInfoOptimizationBase &D) {
706 // Without hotness information, don't show noisy remarks.
707 if (D.isVerbose() && !D.getHotness())
708 return;
709
710 if (D.isPassed()) {
711 // Optimization remarks are active only if the -Rpass flag has a regular
712 // expression that matches the name of the pass name in \p D.
713 if (CodeGenOpts.OptimizationRemark.patternMatches(String: D.getPassName()))
714 EmitOptimizationMessage(D, DiagID: diag::remark_fe_backend_optimization_remark);
715 } else if (D.isMissed()) {
716 // Missed optimization remarks are active only if the -Rpass-missed
717 // flag has a regular expression that matches the name of the pass
718 // name in \p D.
719 if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(String: D.getPassName()))
720 EmitOptimizationMessage(
721 D, DiagID: diag::remark_fe_backend_optimization_remark_missed);
722 } else {
723 assert(D.isAnalysis() && "Unknown remark type");
724
725 bool ShouldAlwaysPrint = false;
726 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(Val: &D))
727 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
728
729 if (ShouldAlwaysPrint ||
730 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: D.getPassName()))
731 EmitOptimizationMessage(
732 D, DiagID: diag::remark_fe_backend_optimization_remark_analysis);
733 }
734}
735
736void BackendConsumer::OptimizationRemarkHandler(
737 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
738 // Optimization analysis remarks are active if the pass name is set to
739 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
740 // regular expression that matches the name of the pass name in \p D.
741
742 if (D.shouldAlwaysPrint() ||
743 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: D.getPassName()))
744 EmitOptimizationMessage(
745 D, DiagID: diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
746}
747
748void BackendConsumer::OptimizationRemarkHandler(
749 const llvm::OptimizationRemarkAnalysisAliasing &D) {
750 // Optimization analysis remarks are active if the pass name is set to
751 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
752 // regular expression that matches the name of the pass name in \p D.
753
754 if (D.shouldAlwaysPrint() ||
755 CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(String: D.getPassName()))
756 EmitOptimizationMessage(
757 D, DiagID: diag::remark_fe_backend_optimization_remark_analysis_aliasing);
758}
759
760void BackendConsumer::OptimizationFailureHandler(
761 const llvm::DiagnosticInfoOptimizationFailure &D) {
762 EmitOptimizationMessage(D, DiagID: diag::warn_fe_backend_optimization_failure);
763}
764
765void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
766 SourceLocation LocCookie =
767 SourceLocation::getFromRawEncoding(Encoding: D.getLocCookie());
768
769 // FIXME: we can't yet diagnose indirect calls. When/if we can, we
770 // should instead assert that LocCookie.isValid().
771 if (!LocCookie.isValid())
772 return;
773
774 Diags.Report(Loc: LocCookie, DiagID: D.getSeverity() == DiagnosticSeverity::DS_Error
775 ? diag::err_fe_backend_error_attr
776 : diag::warn_fe_backend_warning_attr)
777 << llvm::demangle(MangledName: D.getFunctionName()) << D.getNote();
778
779 if (!CodeGenOpts.ShowInliningChain)
780 return;
781
782 auto EmitNote = [&](SourceLocation Loc, StringRef FuncName, bool IsFirst) {
783 if (!Loc.isValid())
784 Loc = LocCookie;
785 unsigned DiagID =
786 IsFirst ? diag::note_fe_backend_in : diag::note_fe_backend_inlined;
787 Diags.Report(Loc, DiagID) << llvm::demangle(MangledName: FuncName.str());
788 };
789
790 // Try debug info first for accurate source locations.
791 if (!D.getDebugInlineChain().empty()) {
792 SourceManager &SM = Context->getSourceManager();
793 FileManager &FM = SM.getFileManager();
794 for (const auto &[I, Info] : llvm::enumerate(First: D.getDebugInlineChain())) {
795 SourceLocation Loc;
796 if (Info.Line > 0)
797 if (auto FE = FM.getOptionalFileRef(Filename: Info.Filename))
798 Loc = SM.translateFileLineCol(SourceFile: *FE, Line: Info.Line,
799 Col: Info.Column ? Info.Column : 1);
800 EmitNote(Loc, Info.FuncName, I == 0);
801 }
802 return;
803 }
804
805 // Fall back to heuristic (srcloc metadata) when debug info is unavailable.
806 auto InliningDecisions = D.getInliningDecisions();
807 if (InliningDecisions.empty())
808 return;
809
810 for (const auto &[I, Entry] : llvm::enumerate(First&: InliningDecisions)) {
811 SourceLocation Loc =
812 I == 0 ? LocCookie : SourceLocation::getFromRawEncoding(Encoding: Entry.second);
813 EmitNote(Loc, Entry.first, I == 0);
814 }
815
816 // Suggest enabling debug info (at least -gline-directives-only) for more
817 // accurate locations.
818 Diags.Report(Loc: LocCookie, DiagID: diag::note_fe_backend_inlining_debug_info);
819}
820
821void BackendConsumer::MisExpectDiagHandler(
822 const llvm::DiagnosticInfoMisExpect &D) {
823 StringRef Filename;
824 unsigned Line, Column;
825 bool BadDebugInfo = false;
826 FullSourceLoc Loc =
827 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
828
829 Diags.Report(Loc, DiagID: diag::warn_profile_data_misexpect) << D.getMsg().str();
830
831 if (BadDebugInfo)
832 // If we were not able to translate the file:line:col information
833 // back to a SourceLocation, at least emit a note stating that
834 // we could not translate this location. This can happen in the
835 // case of #line directives.
836 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
837 << Filename << Line << Column;
838}
839
840/// This function is invoked when the backend needs
841/// to report something to the user.
842void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
843 unsigned DiagID = diag::err_fe_inline_asm;
844 llvm::DiagnosticSeverity Severity = DI.getSeverity();
845 // Get the diagnostic ID based.
846 switch (DI.getKind()) {
847 case llvm::DK_InlineAsm:
848 if (InlineAsmDiagHandler(D: cast<DiagnosticInfoInlineAsm>(Val: DI)))
849 return;
850 ComputeDiagID(Severity, inline_asm, DiagID);
851 break;
852 case llvm::DK_SrcMgr:
853 SrcMgrDiagHandler(DI: cast<DiagnosticInfoSrcMgr>(Val: DI));
854 return;
855 case llvm::DK_StackSize:
856 if (StackSizeDiagHandler(D: cast<DiagnosticInfoStackSize>(Val: DI)))
857 return;
858 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
859 break;
860 case llvm::DK_ResourceLimit:
861 if (ResourceLimitDiagHandler(D: cast<DiagnosticInfoResourceLimit>(Val: DI)))
862 return;
863 ComputeDiagID(Severity, backend_resource_limit, DiagID);
864 break;
865 case DK_Linker:
866 ComputeDiagID(Severity, linking_module, DiagID);
867 break;
868 case llvm::DK_OptimizationRemark:
869 // Optimization remarks are always handled completely by this
870 // handler. There is no generic way of emitting them.
871 OptimizationRemarkHandler(D: cast<OptimizationRemark>(Val: DI));
872 return;
873 case llvm::DK_OptimizationRemarkMissed:
874 // Optimization remarks are always handled completely by this
875 // handler. There is no generic way of emitting them.
876 OptimizationRemarkHandler(D: cast<OptimizationRemarkMissed>(Val: DI));
877 return;
878 case llvm::DK_OptimizationRemarkAnalysis:
879 // Optimization remarks are always handled completely by this
880 // handler. There is no generic way of emitting them.
881 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysis>(Val: DI));
882 return;
883 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
884 // Optimization remarks are always handled completely by this
885 // handler. There is no generic way of emitting them.
886 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysisFPCommute>(Val: DI));
887 return;
888 case llvm::DK_OptimizationRemarkAnalysisAliasing:
889 // Optimization remarks are always handled completely by this
890 // handler. There is no generic way of emitting them.
891 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysisAliasing>(Val: DI));
892 return;
893 case llvm::DK_MachineOptimizationRemark:
894 // Optimization remarks are always handled completely by this
895 // handler. There is no generic way of emitting them.
896 OptimizationRemarkHandler(D: cast<MachineOptimizationRemark>(Val: DI));
897 return;
898 case llvm::DK_MachineOptimizationRemarkMissed:
899 // Optimization remarks are always handled completely by this
900 // handler. There is no generic way of emitting them.
901 OptimizationRemarkHandler(D: cast<MachineOptimizationRemarkMissed>(Val: DI));
902 return;
903 case llvm::DK_MachineOptimizationRemarkAnalysis:
904 // Optimization remarks are always handled completely by this
905 // handler. There is no generic way of emitting them.
906 OptimizationRemarkHandler(D: cast<MachineOptimizationRemarkAnalysis>(Val: DI));
907 return;
908 case llvm::DK_OptimizationFailure:
909 // Optimization failures are always handled completely by this
910 // handler.
911 OptimizationFailureHandler(D: cast<DiagnosticInfoOptimizationFailure>(Val: DI));
912 return;
913 case llvm::DK_Unsupported:
914 UnsupportedDiagHandler(D: cast<DiagnosticInfoUnsupported>(Val: DI));
915 return;
916 case llvm::DK_UnsupportedTargetIntrinsic:
917 UnsupportedTargetIntrinsicDiagHandler(
918 D: cast<DiagnosticInfoUnsupportedTargetIntrinsic>(Val: DI));
919 return;
920 case llvm::DK_DontCall:
921 DontCallDiagHandler(D: cast<DiagnosticInfoDontCall>(Val: DI));
922 return;
923 case llvm::DK_MisExpect:
924 MisExpectDiagHandler(D: cast<DiagnosticInfoMisExpect>(Val: DI));
925 return;
926 default:
927 // Plugin IDs are not bound to any value as they are set dynamically.
928 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
929 break;
930 }
931 std::string MsgStorage;
932 {
933 raw_string_ostream Stream(MsgStorage);
934 DiagnosticPrinterRawOStream DP(Stream);
935 DI.print(DP);
936 }
937
938 if (DI.getKind() == DK_Linker) {
939 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
940 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
941 return;
942 }
943
944 // Report the backend message using the usual diagnostic mechanism.
945 FullSourceLoc Loc;
946 Diags.Report(Loc, DiagID).AddString(V: MsgStorage);
947}
948#undef ComputeDiagID
949
950CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
951 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
952 OwnsVMContext(!_VMContext) {}
953
954CodeGenAction::~CodeGenAction() {
955 TheModule.reset();
956 if (OwnsVMContext)
957 delete VMContext;
958}
959
960bool CodeGenAction::hasIRSupport() const { return true; }
961
962void CodeGenAction::EndSourceFileAction() {
963 ASTFrontendAction::EndSourceFileAction();
964
965 // If the consumer creation failed, do nothing.
966 if (!getCompilerInstance().hasASTConsumer())
967 return;
968
969 // Steal the module from the consumer.
970 TheModule = BEConsumer->takeModule();
971}
972
973std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
974 return std::move(TheModule);
975}
976
977llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
978 OwnsVMContext = false;
979 return VMContext;
980}
981
982CodeGenerator *CodeGenAction::getCodeGenerator() const {
983 return BEConsumer->getCodeGenerator();
984}
985
986bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) {
987 if (CI.getFrontendOpts().GenReducedBMI)
988 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
989 return ASTFrontendAction::BeginSourceFileAction(CI);
990}
991
992static std::unique_ptr<raw_pwrite_stream>
993GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
994 switch (Action) {
995 case Backend_EmitAssembly:
996 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "s");
997 case Backend_EmitLL:
998 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "ll");
999 case Backend_EmitBC:
1000 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "bc");
1001 case Backend_EmitNothing:
1002 return nullptr;
1003 case Backend_EmitMCNull:
1004 return CI.createNullOutputFile();
1005 case Backend_EmitObj:
1006 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "o");
1007 }
1008
1009 llvm_unreachable("Invalid action!");
1010}
1011
1012std::unique_ptr<ASTConsumer>
1013CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
1014 BackendAction BA = static_cast<BackendAction>(Act);
1015 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
1016 if (!OS)
1017 OS = GetOutputStream(CI, InFile, Action: BA);
1018
1019 if (BA != Backend_EmitNothing && !OS)
1020 return nullptr;
1021
1022 // Load bitcode modules to link with, if we need to.
1023 if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules))
1024 return nullptr;
1025
1026 CoverageSourceInfo *CoverageInfo = nullptr;
1027 // Add the preprocessor callback only when the coverage mapping is generated.
1028 if (CI.getCodeGenOpts().CoverageMapping)
1029 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
1030 CI.getPreprocessor());
1031
1032 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1033 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
1034 InFile, std::move(OS), CoverageInfo));
1035 BEConsumer = Result.get();
1036
1037 // Enable generating macro debug info only when debug info is not disabled and
1038 // also macro debug info is enabled.
1039 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1040 CI.getCodeGenOpts().MacroDebugInfo) {
1041 std::unique_ptr<PPCallbacks> Callbacks =
1042 std::make_unique<MacroPPCallbacks>(args: BEConsumer->getCodeGenerator(),
1043 args&: CI.getPreprocessor());
1044 CI.getPreprocessor().addPPCallbacks(C: std::move(Callbacks));
1045 }
1046
1047 if (CI.getFrontendOpts().GenReducedBMI &&
1048 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
1049 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
1050 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
1051 args&: CI.getPreprocessor(), args&: CI.getModuleCache(),
1052 args&: CI.getFrontendOpts().ModuleOutputPath, args&: CI.getCodeGenOpts());
1053 Consumers[1] = std::move(Result);
1054 return std::make_unique<MultiplexConsumer>(args: std::move(Consumers));
1055 }
1056
1057 return std::move(Result);
1058}
1059
1060std::unique_ptr<llvm::Module>
1061CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1062 CompilerInstance &CI = getCompilerInstance();
1063 SourceManager &SM = CI.getSourceManager();
1064
1065 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1066 unsigned DiagID =
1067 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
1068 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
1069 CI.getDiagnostics().Report(DiagID) << EIB.message();
1070 });
1071 return {};
1072 };
1073
1074 // For ThinLTO backend invocations, ensure that the context
1075 // merges types based on ODR identifiers. We also need to read
1076 // the correct module out of a multi-module bitcode file.
1077 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1078 VMContext->enableDebugTypeODRUniquing();
1079
1080 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
1081 if (!BMsOrErr)
1082 return DiagErrors(BMsOrErr.takeError());
1083 BitcodeModule *Bm = llvm::lto::findThinLTOModule(BMs: *BMsOrErr);
1084 // We have nothing to do if the file contains no ThinLTO module. This is
1085 // possible if ThinLTO compilation was not able to split module. Content of
1086 // the file was already processed by indexing and will be passed to the
1087 // linker using merged object file.
1088 if (!Bm) {
1089 auto M = std::make_unique<llvm::Module>(args: "empty", args&: *VMContext);
1090 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
1091 return M;
1092 }
1093 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1094 Bm->parseModule(Context&: *VMContext);
1095 if (!MOrErr)
1096 return DiagErrors(MOrErr.takeError());
1097 return std::move(*MOrErr);
1098 }
1099
1100 // Load bitcode modules to link with, if we need to.
1101 if (clang::loadLinkModules(CI, Ctx&: *VMContext, LinkModules))
1102 return nullptr;
1103
1104 // Handle textual IR and bitcode file with one single module.
1105 llvm::SMDiagnostic Err;
1106 if (std::unique_ptr<llvm::Module> M = parseIR(Buffer: MBRef, Err, Context&: *VMContext)) {
1107 // For LLVM IR files, always verify the input and report the error in a way
1108 // that does not ask people to report an issue for it.
1109 std::string VerifierErr;
1110 raw_string_ostream VerifierErrStream(VerifierErr);
1111 if (llvm::verifyModule(M: *M, OS: &VerifierErrStream)) {
1112 CI.getDiagnostics().Report(DiagID: diag::err_invalid_llvm_ir) << VerifierErr;
1113 return {};
1114 }
1115 return M;
1116 }
1117
1118 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1119 // output), place the extra modules (actually only one, a regular LTO module)
1120 // into LinkModules as if we are using -mlink-bitcode-file.
1121 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
1122 if (BMsOrErr && BMsOrErr->size()) {
1123 std::unique_ptr<llvm::Module> FirstM;
1124 for (auto &BM : *BMsOrErr) {
1125 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1126 BM.parseModule(Context&: *VMContext);
1127 if (!MOrErr)
1128 return DiagErrors(MOrErr.takeError());
1129 if (FirstM)
1130 LinkModules.push_back(Elt: {.Module: std::move(*MOrErr), /*PropagateAttrs=*/false,
1131 /*Internalize=*/false, /*LinkFlags=*/{}});
1132 else
1133 FirstM = std::move(*MOrErr);
1134 }
1135 if (FirstM)
1136 return FirstM;
1137 }
1138 // If BMsOrErr fails, consume the error and use the error message from
1139 // parseIR.
1140 consumeError(Err: BMsOrErr.takeError());
1141
1142 // Translate from the diagnostic info to the SourceManager location if
1143 // available.
1144 // TODO: Unify this with ConvertBackendLocation()
1145 SourceLocation Loc;
1146 if (Err.getLineNo() > 0) {
1147 assert(Err.getColumnNo() >= 0);
1148 Loc = SM.translateFileLineCol(SourceFile: SM.getFileEntryForID(FID: SM.getMainFileID()),
1149 Line: Err.getLineNo(), Col: Err.getColumnNo() + 1);
1150 }
1151
1152 // Strip off a leading diagnostic code if there is one.
1153 StringRef Msg = Err.getMessage();
1154 Msg.consume_front(Prefix: "error: ");
1155
1156 unsigned DiagID =
1157 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
1158
1159 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1160 return {};
1161}
1162
1163void CodeGenAction::ExecuteAction() {
1164 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1165 this->ASTFrontendAction::ExecuteAction();
1166 return;
1167 }
1168
1169 // If this is an IR file, we have to treat it specially.
1170 BackendAction BA = static_cast<BackendAction>(Act);
1171 CompilerInstance &CI = getCompilerInstance();
1172 auto &CodeGenOpts = CI.getCodeGenOpts();
1173 auto &Diagnostics = CI.getDiagnostics();
1174 std::unique_ptr<raw_pwrite_stream> OS =
1175 GetOutputStream(CI, InFile: getCurrentFileOrBufferName(), Action: BA);
1176 if (BA != Backend_EmitNothing && !OS)
1177 return;
1178
1179 SourceManager &SM = CI.getSourceManager();
1180 FileID FID = SM.getMainFileID();
1181 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1182 if (!MainFile)
1183 return;
1184
1185 TheModule = loadModule(MBRef: *MainFile);
1186 if (!TheModule)
1187 return;
1188
1189 const TargetOptions &TargetOpts = CI.getTargetOpts();
1190 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
1191 Diagnostics.Report(Loc: SourceLocation(), DiagID: diag::warn_fe_override_module)
1192 << TargetOpts.Triple;
1193 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
1194 }
1195
1196 EmbedObject(M: TheModule.get(), CGOpts: CodeGenOpts, VFS&: CI.getVirtualFileSystem(),
1197 Diags&: Diagnostics);
1198 EmbedBitcode(M: TheModule.get(), CGOpts: CodeGenOpts, Buf: *MainFile);
1199
1200 LLVMContext &Ctx = TheModule->getContext();
1201
1202 // Restore any diagnostic handler previously set before returning from this
1203 // function.
1204 struct RAII {
1205 LLVMContext &Ctx;
1206 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1207 ~RAII() { Ctx.setDiagnosticHandler(DH: std::move(PrevHandler)); }
1208 } _{.Ctx: Ctx};
1209
1210 // Set clang diagnostic handler. To do this we need to create a fake
1211 // BackendConsumer.
1212 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
1213 std::move(LinkModules), "", nullptr, nullptr,
1214 TheModule.get());
1215
1216 // Link in each pending link module.
1217 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(M: &*TheModule))
1218 return;
1219
1220 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1221 // true here because the valued names are needed for reading textual IR.
1222 Ctx.setDiscardValueNames(false);
1223 Ctx.setDiagnosticHandler(
1224 DH: std::make_unique<ClangDiagnosticHandler>(args&: CodeGenOpts, args: &Result));
1225
1226 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1227 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
1228
1229 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
1230 setupLLVMOptimizationRemarks(
1231 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
1232 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
1233 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
1234
1235 if (Error E = OptRecordFileOrErr.takeError()) {
1236 reportOptRecordError(E: std::move(E), Diags&: Diagnostics, CodeGenOpts);
1237 return;
1238 }
1239 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1240
1241 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(), M: TheModule.get(), Action: BA,
1242 VFS: CI.getFileManager().getVirtualFileSystemPtr(),
1243 OS: std::move(OS));
1244 if (OptRecordFile)
1245 OptRecordFile->keep();
1246}
1247
1248//
1249
1250void EmitAssemblyAction::anchor() { }
1251EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1252 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1253
1254void EmitBCAction::anchor() { }
1255EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1256 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1257
1258void EmitLLVMAction::anchor() { }
1259EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1260 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1261
1262void EmitLLVMOnlyAction::anchor() { }
1263EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1264 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1265
1266void EmitCodeGenOnlyAction::anchor() { }
1267EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1268 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1269
1270void EmitObjAction::anchor() { }
1271EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1272 : CodeGenAction(Backend_EmitObj, _VMContext) {}
1273