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 Ctx.setDiagnosticHandler(DH: std::make_unique<ClangDiagnosticHandler>(
252 args: CodeGenOpts, args: this));
253
254 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
255 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
256
257 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
258 setupLLVMOptimizationRemarks(
259 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
260 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
261 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
262
263 if (Error E = OptRecordFileOrErr.takeError()) {
264 reportOptRecordError(E: std::move(E), Diags, CodeGenOpts);
265 return;
266 }
267
268 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
269
270 if (OptRecordFile && CodeGenOpts.getProfileUse() !=
271 llvm::driver::ProfileInstrKind::ProfileNone)
272 Ctx.setDiagnosticsHotnessRequested(true);
273
274 if (CodeGenOpts.MisExpect) {
275 Ctx.setMisExpectWarningRequested(true);
276 }
277
278 if (CodeGenOpts.DiagnosticsMisExpectTolerance) {
279 Ctx.setDiagnosticsMisExpectTolerance(
280 CodeGenOpts.DiagnosticsMisExpectTolerance);
281 }
282
283 // Link each LinkModule into our module.
284 if (!CodeGenOpts.LinkBitcodePostopt && LinkInModules(M: getModule()))
285 return;
286
287 for (auto &F : getModule()->functions()) {
288 if (const Decl *FD = Gen->GetDeclForMangledName(MangledName: F.getName())) {
289 auto Loc = FD->getASTContext().getFullLoc(Loc: FD->getLocation());
290 // TODO: use a fast content hash when available.
291 auto NameHash = llvm::hash_value(S: F.getName());
292 ManglingFullSourceLocs.push_back(x: std::make_pair(x&: NameHash, y&: Loc));
293 }
294 }
295
296 if (CodeGenOpts.ClearASTBeforeBackend) {
297 LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
298 // Access to the AST is no longer available after this.
299 // Other things that the ASTContext manages are still available, e.g.
300 // the SourceManager. It'd be nice if we could separate out all the
301 // things in ASTContext used after this point and null out the
302 // ASTContext, but too many various parts of the ASTContext are still
303 // used in various parts.
304 C.cleanup();
305 C.getAllocator().Reset();
306 }
307
308 EmbedBitcode(M: getModule(), CGOpts: CodeGenOpts, Buf: llvm::MemoryBufferRef());
309
310 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(),
311 TDesc: C.getTargetInfo().getDataLayoutString(), M: getModule(),
312 Action, VFS: FS, OS: std::move(AsmOutStream), BC: this);
313
314 Ctx.setDiagnosticHandler(DH: std::move(OldDiagnosticHandler));
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
737void BackendConsumer::MisExpectDiagHandler(
738 const llvm::DiagnosticInfoMisExpect &D) {
739 StringRef Filename;
740 unsigned Line, Column;
741 bool BadDebugInfo = false;
742 FullSourceLoc Loc =
743 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
744
745 Diags.Report(Loc, DiagID: diag::warn_profile_data_misexpect) << D.getMsg().str();
746
747 if (BadDebugInfo)
748 // If we were not able to translate the file:line:col information
749 // back to a SourceLocation, at least emit a note stating that
750 // we could not translate this location. This can happen in the
751 // case of #line directives.
752 Diags.Report(Loc, DiagID: diag::note_fe_backend_invalid_loc)
753 << Filename << Line << Column;
754}
755
756/// This function is invoked when the backend needs
757/// to report something to the user.
758void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
759 unsigned DiagID = diag::err_fe_inline_asm;
760 llvm::DiagnosticSeverity Severity = DI.getSeverity();
761 // Get the diagnostic ID based.
762 switch (DI.getKind()) {
763 case llvm::DK_InlineAsm:
764 if (InlineAsmDiagHandler(D: cast<DiagnosticInfoInlineAsm>(Val: DI)))
765 return;
766 ComputeDiagID(Severity, inline_asm, DiagID);
767 break;
768 case llvm::DK_SrcMgr:
769 SrcMgrDiagHandler(DI: cast<DiagnosticInfoSrcMgr>(Val: DI));
770 return;
771 case llvm::DK_StackSize:
772 if (StackSizeDiagHandler(D: cast<DiagnosticInfoStackSize>(Val: DI)))
773 return;
774 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
775 break;
776 case llvm::DK_ResourceLimit:
777 if (ResourceLimitDiagHandler(D: cast<DiagnosticInfoResourceLimit>(Val: DI)))
778 return;
779 ComputeDiagID(Severity, backend_resource_limit, DiagID);
780 break;
781 case DK_Linker:
782 ComputeDiagID(Severity, linking_module, DiagID);
783 break;
784 case llvm::DK_OptimizationRemark:
785 // Optimization remarks are always handled completely by this
786 // handler. There is no generic way of emitting them.
787 OptimizationRemarkHandler(D: cast<OptimizationRemark>(Val: DI));
788 return;
789 case llvm::DK_OptimizationRemarkMissed:
790 // Optimization remarks are always handled completely by this
791 // handler. There is no generic way of emitting them.
792 OptimizationRemarkHandler(D: cast<OptimizationRemarkMissed>(Val: DI));
793 return;
794 case llvm::DK_OptimizationRemarkAnalysis:
795 // Optimization remarks are always handled completely by this
796 // handler. There is no generic way of emitting them.
797 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysis>(Val: DI));
798 return;
799 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
800 // Optimization remarks are always handled completely by this
801 // handler. There is no generic way of emitting them.
802 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysisFPCommute>(Val: DI));
803 return;
804 case llvm::DK_OptimizationRemarkAnalysisAliasing:
805 // Optimization remarks are always handled completely by this
806 // handler. There is no generic way of emitting them.
807 OptimizationRemarkHandler(D: cast<OptimizationRemarkAnalysisAliasing>(Val: DI));
808 return;
809 case llvm::DK_MachineOptimizationRemark:
810 // Optimization remarks are always handled completely by this
811 // handler. There is no generic way of emitting them.
812 OptimizationRemarkHandler(D: cast<MachineOptimizationRemark>(Val: DI));
813 return;
814 case llvm::DK_MachineOptimizationRemarkMissed:
815 // Optimization remarks are always handled completely by this
816 // handler. There is no generic way of emitting them.
817 OptimizationRemarkHandler(D: cast<MachineOptimizationRemarkMissed>(Val: DI));
818 return;
819 case llvm::DK_MachineOptimizationRemarkAnalysis:
820 // Optimization remarks are always handled completely by this
821 // handler. There is no generic way of emitting them.
822 OptimizationRemarkHandler(D: cast<MachineOptimizationRemarkAnalysis>(Val: DI));
823 return;
824 case llvm::DK_OptimizationFailure:
825 // Optimization failures are always handled completely by this
826 // handler.
827 OptimizationFailureHandler(D: cast<DiagnosticInfoOptimizationFailure>(Val: DI));
828 return;
829 case llvm::DK_Unsupported:
830 UnsupportedDiagHandler(D: cast<DiagnosticInfoUnsupported>(Val: DI));
831 return;
832 case llvm::DK_DontCall:
833 DontCallDiagHandler(D: cast<DiagnosticInfoDontCall>(Val: DI));
834 return;
835 case llvm::DK_MisExpect:
836 MisExpectDiagHandler(D: cast<DiagnosticInfoMisExpect>(Val: DI));
837 return;
838 default:
839 // Plugin IDs are not bound to any value as they are set dynamically.
840 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
841 break;
842 }
843 std::string MsgStorage;
844 {
845 raw_string_ostream Stream(MsgStorage);
846 DiagnosticPrinterRawOStream DP(Stream);
847 DI.print(DP);
848 }
849
850 if (DI.getKind() == DK_Linker) {
851 assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
852 Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
853 return;
854 }
855
856 // Report the backend message using the usual diagnostic mechanism.
857 FullSourceLoc Loc;
858 Diags.Report(Loc, DiagID).AddString(V: MsgStorage);
859}
860#undef ComputeDiagID
861
862CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
863 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
864 OwnsVMContext(!_VMContext) {}
865
866CodeGenAction::~CodeGenAction() {
867 TheModule.reset();
868 if (OwnsVMContext)
869 delete VMContext;
870}
871
872bool CodeGenAction::loadLinkModules(CompilerInstance &CI) {
873 if (!LinkModules.empty())
874 return false;
875
876 for (const CodeGenOptions::BitcodeFileToLink &F :
877 CI.getCodeGenOpts().LinkBitcodeFiles) {
878 auto BCBuf = CI.getFileManager().getBufferForFile(Filename: F.Filename);
879 if (!BCBuf) {
880 CI.getDiagnostics().Report(DiagID: diag::err_cannot_open_file)
881 << F.Filename << BCBuf.getError().message();
882 LinkModules.clear();
883 return true;
884 }
885
886 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
887 getOwningLazyBitcodeModule(Buffer: std::move(*BCBuf), Context&: *VMContext);
888 if (!ModuleOrErr) {
889 handleAllErrors(E: ModuleOrErr.takeError(), Handlers: [&](ErrorInfoBase &EIB) {
890 CI.getDiagnostics().Report(DiagID: diag::err_cannot_open_file)
891 << F.Filename << EIB.message();
892 });
893 LinkModules.clear();
894 return true;
895 }
896 LinkModules.push_back(Elt: {.Module: std::move(ModuleOrErr.get()), .PropagateAttrs: F.PropagateAttrs,
897 .Internalize: F.Internalize, .LinkFlags: F.LinkFlags});
898 }
899 return false;
900}
901
902bool CodeGenAction::hasIRSupport() const { return true; }
903
904void CodeGenAction::EndSourceFileAction() {
905 ASTFrontendAction::EndSourceFileAction();
906
907 // If the consumer creation failed, do nothing.
908 if (!getCompilerInstance().hasASTConsumer())
909 return;
910
911 // Steal the module from the consumer.
912 TheModule = BEConsumer->takeModule();
913}
914
915std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
916 return std::move(TheModule);
917}
918
919llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
920 OwnsVMContext = false;
921 return VMContext;
922}
923
924CodeGenerator *CodeGenAction::getCodeGenerator() const {
925 return BEConsumer->getCodeGenerator();
926}
927
928bool CodeGenAction::BeginSourceFileAction(CompilerInstance &CI) {
929 if (CI.getFrontendOpts().GenReducedBMI)
930 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
931 return ASTFrontendAction::BeginSourceFileAction(CI);
932}
933
934static std::unique_ptr<raw_pwrite_stream>
935GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
936 switch (Action) {
937 case Backend_EmitAssembly:
938 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "s");
939 case Backend_EmitLL:
940 return CI.createDefaultOutputFile(Binary: false, BaseInput: InFile, Extension: "ll");
941 case Backend_EmitBC:
942 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "bc");
943 case Backend_EmitNothing:
944 return nullptr;
945 case Backend_EmitMCNull:
946 return CI.createNullOutputFile();
947 case Backend_EmitObj:
948 return CI.createDefaultOutputFile(Binary: true, BaseInput: InFile, Extension: "o");
949 }
950
951 llvm_unreachable("Invalid action!");
952}
953
954std::unique_ptr<ASTConsumer>
955CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
956 BackendAction BA = static_cast<BackendAction>(Act);
957 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
958 if (!OS)
959 OS = GetOutputStream(CI, InFile, Action: BA);
960
961 if (BA != Backend_EmitNothing && !OS)
962 return nullptr;
963
964 // Load bitcode modules to link with, if we need to.
965 if (loadLinkModules(CI))
966 return nullptr;
967
968 CoverageSourceInfo *CoverageInfo = nullptr;
969 // Add the preprocessor callback only when the coverage mapping is generated.
970 if (CI.getCodeGenOpts().CoverageMapping)
971 CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
972 CI.getPreprocessor());
973
974 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
975 CI, BA, CI.getVirtualFileSystemPtr(), *VMContext, std::move(LinkModules),
976 InFile, std::move(OS), CoverageInfo));
977 BEConsumer = Result.get();
978
979 // Enable generating macro debug info only when debug info is not disabled and
980 // also macro debug info is enabled.
981 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
982 CI.getCodeGenOpts().MacroDebugInfo) {
983 std::unique_ptr<PPCallbacks> Callbacks =
984 std::make_unique<MacroPPCallbacks>(args: BEConsumer->getCodeGenerator(),
985 args&: CI.getPreprocessor());
986 CI.getPreprocessor().addPPCallbacks(C: std::move(Callbacks));
987 }
988
989 if (CI.getFrontendOpts().GenReducedBMI &&
990 !CI.getFrontendOpts().ModuleOutputPath.empty()) {
991 std::vector<std::unique_ptr<ASTConsumer>> Consumers(2);
992 Consumers[0] = std::make_unique<ReducedBMIGenerator>(
993 args&: CI.getPreprocessor(), args&: CI.getModuleCache(),
994 args&: CI.getFrontendOpts().ModuleOutputPath, args&: CI.getCodeGenOpts());
995 Consumers[1] = std::move(Result);
996 return std::make_unique<MultiplexConsumer>(args: std::move(Consumers));
997 }
998
999 return std::move(Result);
1000}
1001
1002std::unique_ptr<llvm::Module>
1003CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1004 CompilerInstance &CI = getCompilerInstance();
1005 SourceManager &SM = CI.getSourceManager();
1006
1007 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1008 unsigned DiagID =
1009 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
1010 handleAllErrors(E: std::move(E), Handlers: [&](ErrorInfoBase &EIB) {
1011 CI.getDiagnostics().Report(DiagID) << EIB.message();
1012 });
1013 return {};
1014 };
1015
1016 // For ThinLTO backend invocations, ensure that the context
1017 // merges types based on ODR identifiers. We also need to read
1018 // the correct module out of a multi-module bitcode file.
1019 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1020 VMContext->enableDebugTypeODRUniquing();
1021
1022 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
1023 if (!BMsOrErr)
1024 return DiagErrors(BMsOrErr.takeError());
1025 BitcodeModule *Bm = llvm::lto::findThinLTOModule(BMs: *BMsOrErr);
1026 // We have nothing to do if the file contains no ThinLTO module. This is
1027 // possible if ThinLTO compilation was not able to split module. Content of
1028 // the file was already processed by indexing and will be passed to the
1029 // linker using merged object file.
1030 if (!Bm) {
1031 auto M = std::make_unique<llvm::Module>(args: "empty", args&: *VMContext);
1032 M->setTargetTriple(Triple(CI.getTargetOpts().Triple));
1033 return M;
1034 }
1035 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1036 Bm->parseModule(Context&: *VMContext);
1037 if (!MOrErr)
1038 return DiagErrors(MOrErr.takeError());
1039 return std::move(*MOrErr);
1040 }
1041
1042 // Load bitcode modules to link with, if we need to.
1043 if (loadLinkModules(CI))
1044 return nullptr;
1045
1046 // Handle textual IR and bitcode file with one single module.
1047 llvm::SMDiagnostic Err;
1048 if (std::unique_ptr<llvm::Module> M = parseIR(Buffer: MBRef, Err, Context&: *VMContext)) {
1049 // For LLVM IR files, always verify the input and report the error in a way
1050 // that does not ask people to report an issue for it.
1051 std::string VerifierErr;
1052 raw_string_ostream VerifierErrStream(VerifierErr);
1053 if (llvm::verifyModule(M: *M, OS: &VerifierErrStream)) {
1054 CI.getDiagnostics().Report(DiagID: diag::err_invalid_llvm_ir) << VerifierErr;
1055 return {};
1056 }
1057 return M;
1058 }
1059
1060 // If MBRef is a bitcode with multiple modules (e.g., -fsplit-lto-unit
1061 // output), place the extra modules (actually only one, a regular LTO module)
1062 // into LinkModules as if we are using -mlink-bitcode-file.
1063 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(Buffer: MBRef);
1064 if (BMsOrErr && BMsOrErr->size()) {
1065 std::unique_ptr<llvm::Module> FirstM;
1066 for (auto &BM : *BMsOrErr) {
1067 Expected<std::unique_ptr<llvm::Module>> MOrErr =
1068 BM.parseModule(Context&: *VMContext);
1069 if (!MOrErr)
1070 return DiagErrors(MOrErr.takeError());
1071 if (FirstM)
1072 LinkModules.push_back(Elt: {.Module: std::move(*MOrErr), /*PropagateAttrs=*/false,
1073 /*Internalize=*/false, /*LinkFlags=*/{}});
1074 else
1075 FirstM = std::move(*MOrErr);
1076 }
1077 if (FirstM)
1078 return FirstM;
1079 }
1080 // If BMsOrErr fails, consume the error and use the error message from
1081 // parseIR.
1082 consumeError(Err: BMsOrErr.takeError());
1083
1084 // Translate from the diagnostic info to the SourceManager location if
1085 // available.
1086 // TODO: Unify this with ConvertBackendLocation()
1087 SourceLocation Loc;
1088 if (Err.getLineNo() > 0) {
1089 assert(Err.getColumnNo() >= 0);
1090 Loc = SM.translateFileLineCol(SourceFile: SM.getFileEntryForID(FID: SM.getMainFileID()),
1091 Line: Err.getLineNo(), Col: Err.getColumnNo() + 1);
1092 }
1093
1094 // Strip off a leading diagnostic code if there is one.
1095 StringRef Msg = Err.getMessage();
1096 Msg.consume_front(Prefix: "error: ");
1097
1098 unsigned DiagID =
1099 CI.getDiagnostics().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0");
1100
1101 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1102 return {};
1103}
1104
1105void CodeGenAction::ExecuteAction() {
1106 if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1107 this->ASTFrontendAction::ExecuteAction();
1108 return;
1109 }
1110
1111 // If this is an IR file, we have to treat it specially.
1112 BackendAction BA = static_cast<BackendAction>(Act);
1113 CompilerInstance &CI = getCompilerInstance();
1114 auto &CodeGenOpts = CI.getCodeGenOpts();
1115 auto &Diagnostics = CI.getDiagnostics();
1116 std::unique_ptr<raw_pwrite_stream> OS =
1117 GetOutputStream(CI, InFile: getCurrentFileOrBufferName(), Action: BA);
1118 if (BA != Backend_EmitNothing && !OS)
1119 return;
1120
1121 SourceManager &SM = CI.getSourceManager();
1122 FileID FID = SM.getMainFileID();
1123 std::optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1124 if (!MainFile)
1125 return;
1126
1127 TheModule = loadModule(MBRef: *MainFile);
1128 if (!TheModule)
1129 return;
1130
1131 const TargetOptions &TargetOpts = CI.getTargetOpts();
1132 if (TheModule->getTargetTriple().str() != TargetOpts.Triple) {
1133 Diagnostics.Report(Loc: SourceLocation(), DiagID: diag::warn_fe_override_module)
1134 << TargetOpts.Triple;
1135 TheModule->setTargetTriple(Triple(TargetOpts.Triple));
1136 }
1137
1138 EmbedObject(M: TheModule.get(), CGOpts: CodeGenOpts, VFS&: CI.getVirtualFileSystem(),
1139 Diags&: Diagnostics);
1140 EmbedBitcode(M: TheModule.get(), CGOpts: CodeGenOpts, Buf: *MainFile);
1141
1142 LLVMContext &Ctx = TheModule->getContext();
1143
1144 // Restore any diagnostic handler previously set before returning from this
1145 // function.
1146 struct RAII {
1147 LLVMContext &Ctx;
1148 std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1149 ~RAII() { Ctx.setDiagnosticHandler(DH: std::move(PrevHandler)); }
1150 } _{.Ctx: Ctx};
1151
1152 // Set clang diagnostic handler. To do this we need to create a fake
1153 // BackendConsumer.
1154 BackendConsumer Result(CI, BA, CI.getVirtualFileSystemPtr(), *VMContext,
1155 std::move(LinkModules), "", nullptr, nullptr,
1156 TheModule.get());
1157
1158 // Link in each pending link module.
1159 if (!CodeGenOpts.LinkBitcodePostopt && Result.LinkInModules(M: &*TheModule))
1160 return;
1161
1162 // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1163 // true here because the valued names are needed for reading textual IR.
1164 Ctx.setDiscardValueNames(false);
1165 Ctx.setDiagnosticHandler(
1166 DH: std::make_unique<ClangDiagnosticHandler>(args&: CodeGenOpts, args: &Result));
1167
1168 Ctx.setDefaultTargetCPU(TargetOpts.CPU);
1169 Ctx.setDefaultTargetFeatures(llvm::join(R: TargetOpts.Features, Separator: ","));
1170
1171 Expected<LLVMRemarkFileHandle> OptRecordFileOrErr =
1172 setupLLVMOptimizationRemarks(
1173 Context&: Ctx, RemarksFilename: CodeGenOpts.OptRecordFile, RemarksPasses: CodeGenOpts.OptRecordPasses,
1174 RemarksFormat: CodeGenOpts.OptRecordFormat, RemarksWithHotness: CodeGenOpts.DiagnosticsWithHotness,
1175 RemarksHotnessThreshold: CodeGenOpts.DiagnosticsHotnessThreshold);
1176
1177 if (Error E = OptRecordFileOrErr.takeError()) {
1178 reportOptRecordError(E: std::move(E), Diags&: Diagnostics, CodeGenOpts);
1179 return;
1180 }
1181 LLVMRemarkFileHandle OptRecordFile = std::move(*OptRecordFileOrErr);
1182
1183 emitBackendOutput(CI, CGOpts&: CI.getCodeGenOpts(),
1184 TDesc: CI.getTarget().getDataLayoutString(), M: TheModule.get(), Action: BA,
1185 VFS: CI.getFileManager().getVirtualFileSystemPtr(),
1186 OS: std::move(OS));
1187 if (OptRecordFile)
1188 OptRecordFile->keep();
1189}
1190
1191//
1192
1193void EmitAssemblyAction::anchor() { }
1194EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1195 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1196
1197void EmitBCAction::anchor() { }
1198EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1199 : CodeGenAction(Backend_EmitBC, _VMContext) {}
1200
1201void EmitLLVMAction::anchor() { }
1202EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1203 : CodeGenAction(Backend_EmitLL, _VMContext) {}
1204
1205void EmitLLVMOnlyAction::anchor() { }
1206EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1207 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1208
1209void EmitCodeGenOnlyAction::anchor() { }
1210EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1211 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1212
1213void EmitObjAction::anchor() { }
1214EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1215 : CodeGenAction(Backend_EmitObj, _VMContext) {}
1216