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