https://github.com/adrian-prantl updated 
https://github.com/llvm/llvm-project/pull/242548

>From 010f6ef32665a25227c73705f6babb9719212485 Mon Sep 17 00:00:00 2001
From: Adrian Prantl <[email protected]>
Date: Fri, 13 Nov 2026 16:49:11 -0800
Subject: [PATCH 1/2] [clang] Locate backend diagnostics under
 -fdebug-prefix-map

Backend diagnostics are mapped back to a clang SourceLocation by
looking up the file name recorded in the debug info. With
-fdebug-prefix-map that name is the remapped path, which usually does
not exist, so the lookup fails and the diagnostic is reported at the
enclosing function instead. If the function lies outside the
"#pragma clang diagnostic ignored" region covering the real location,
the suppression is lost, and a build that passes without the prefix
map fails with -Werror. The notes of -fdiagnostics-show-inlining-chain
have the same problem.

When the name from the debug info does not refer to a file in the
compilation, undo each prefix map entry. The map is not invertible in
general, so accept a candidate only if it maps forward to the same
name and is part of the compilation, and fall back to the previous
behavior if candidates lead to different files. Compare paths in
normalized form, because the debug info may reassemble the remapped
path with different separators on Windows; that part is untested on
Windows.

rdar://192737670
Assisted-by: Claude
---
 .../CodeGenUtils/BackendDiagnosticHandler.cpp | 56 +++++++++++++++++--
 .../optimization-remark-debug-prefix-map.c    | 53 ++++++++++++++++++
 2 files changed, 104 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/Frontend/optimization-remark-debug-prefix-map.c

diff --git a/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp 
b/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
index 667a7948fa18f8..492091c179485d 100644
--- a/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
+++ b/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
@@ -13,12 +13,15 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/Hashing.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallString.h"
 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
 #include "llvm/Demangle/Demangle.h"
 #include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/Module.h"
+#include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
@@ -87,6 +90,51 @@ FullSourceLoc ConvertBackendLocation(const 
llvm::SMDiagnostic &D,
   return FullSourceLoc(NewLoc, CSM);
 }
 
+/// File paths in debug info have -fdebug-prefix-map substitutions
+/// applied. If \p DebugPath does not name a file in this compilation as is,
+/// undo each substitution and return the resulting file, unless several
+/// distinct files qualify.
+OptionalFileEntryRef lookupDebugFile(const SourceManager &SM,
+                                     const CodeGenOptions &CGOpts,
+                                     StringRef DebugPath) {
+  // A file of the same name outside this compilation is not the one the debug
+  // info refers to.
+  auto LookupInCompilation = [&](StringRef Path) -> OptionalFileEntryRef {
+    auto FE = SM.getFileManager().getOptionalFileRef(Path);
+    if (FE && SM.translateFile(*FE).isValid())
+      return FE;
+    return std::nullopt;
+  };
+  if (auto FE = LookupInCompilation(DebugPath))
+    return FE;
+  auto NormalizeSeparators = [](StringRef P) {
+    SmallString<256> N(P);
+    llvm::sys::path::remove_dots(N);
+    return N;
+  };
+  SmallString<256> NormalizedDebugPath = NormalizeSeparators(DebugPath);
+  OptionalFileEntryRef Result;
+  for (const auto &[From, To] : llvm::reverse(CGOpts.DebugPrefixMap)) {
+    SmallString<256> Path(DebugPath);
+    if (!llvm::sys::path::replace_path_prefix(Path, To, From))
+      continue;
+    // A later entry with an overlapping prefix may take precedence over this
+    // one, so the candidate must map forward to DebugPath again.
+    if (NormalizeSeparators(CGOpts.remapDebugPathPrefix(Path)) !=
+        NormalizedDebugPath)
+      continue;
+    auto FE = LookupInCompilation(Path);
+    if (!FE)
+      continue;
+    // Several prefixes can map to the same replacement. If they lead to
+    // different files, the debug info does not say which one is meant.
+    if (Result && *Result != *FE)
+      return std::nullopt;
+    Result = FE;
+  }
+  return Result;
+}
+
 } // namespace
 
 #define ComputeDiagID(Severity, GroupName, DiagID)                             
\
@@ -151,15 +199,14 @@ const FullSourceLoc 
BackendDiagnosticConsumer::getBestLocationFromDebugLoc(
     const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
     StringRef &Filename, unsigned &Line, unsigned &Column) const {
   SourceManager &SourceMgr = *SM;
-  FileManager &FileMgr = SourceMgr.getFileManager();
   SourceLocation DILoc;
 
   if (D.isLocationAvailable()) {
     D.getLocation(Filename, Line, Column);
     if (Line > 0) {
-      auto FE = FileMgr.getOptionalFileRef(Filename);
+      auto FE = lookupDebugFile(SourceMgr, CodeGenOpts, Filename);
       if (!FE)
-        FE = FileMgr.getOptionalFileRef(D.getAbsolutePath());
+        FE = lookupDebugFile(SourceMgr, CodeGenOpts, D.getAbsolutePath());
       if (FE) {
         // If -gcolumn-info was not used, Column will be 0. This upsets the
         // source manager, so pass 1 if Column is not set.
@@ -502,11 +549,10 @@ void BackendDiagnosticConsumer::DontCallDiagHandler(
   // Try debug info first for accurate source locations.
   if (!D.getDebugInlineChain().empty()) {
     SourceManager &SrcMgr = *SM;
-    FileManager &FM = SrcMgr.getFileManager();
     for (const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
       SourceLocation Loc;
       if (Info.Line > 0)
-        if (auto FE = FM.getOptionalFileRef(Info.Filename))
+        if (auto FE = lookupDebugFile(SrcMgr, CodeGenOpts, Info.Filename))
           Loc = SrcMgr.translateFileLineCol(*FE, Info.Line,
                                             Info.Column ? Info.Column : 1);
       EmitNote(Loc, Info.FuncName, I == 0);
diff --git a/clang/test/Frontend/optimization-remark-debug-prefix-map.c 
b/clang/test/Frontend/optimization-remark-debug-prefix-map.c
new file mode 100644
index 00000000000000..af19a6f543dc45
--- /dev/null
+++ b/clang/test/Frontend/optimization-remark-debug-prefix-map.c
@@ -0,0 +1,53 @@
+/// Backend diagnostics are mapped back to the source through the file names in
+/// the debug info, which have -fdebug-prefix-map applied.
+
+// RUN: rm -rf %t && split-file --no-leading-lines %s %t
+// RUN: mkdir %t/decoy && cp %t/src/t.c %t/decoy/t.c
+
+// RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
+// RUN:   -fdebug-prefix-map=%t/src=%{fs-src-root}elsewhere
+// RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
+// RUN:   -fdebug-prefix-map=%t/src=.
+
+/// The inverse mapping is ambiguous; only the file being compiled is a match.
+// RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
+// RUN:   -fdebug-prefix-map=%t/src=. -fdebug-prefix-map=%t/decoy=.
+
+/// A file outside the compilation exists under the remapped name.
+// RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
+// RUN:   -fdebug-compilation-dir=%t -fdebug-prefix-map=%t/src=%t/decoy
+
+/// Two files in the compilation map to the same name, so the debug info does 
not
+/// identify the file; fall back to the location of the function.
+// RUN: %clang_cc1 %t/src/both.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify -I%t \
+// RUN:   -fdebug-prefix-map=%t/a=%{fs-src-root}M 
-fdebug-prefix-map=%t/b=%{fs-src-root}M
+
+//--- src/t.c
+int foo(int x, int y) __attribute__((always_inline));
+int foo(int x, int y) { return x + y; }
+
+int bar(int j) {
+  // expected-remark@+1 {{'foo' inlined into 'bar'}}
+  return foo(j, j - 2);
+}
+
+//--- src/both.c
+static inline __attribute__((always_inline)) int foo(int x, int y) {
+  return x + y;
+}
+#include "a/h.h"
+#include "b/h.h"
+
+//--- a/h.h
+// expected-remark@+2 {{'foo' inlined into 'callA'}}
+// expected-note@+1 {{could not determine the original source location}}
+int callA(int j) {
+  return foo(j, j - 2);
+}
+
+//--- b/h.h
+// Maps to the same name in the debug info as a/h.h.
+
+int callB(int j) {
+  return j + (j - 2);
+}

>From fa7e2174a79ef0aa7d19f07c75377b1c94820711 Mon Sep 17 00:00:00 2001
From: Adrian Prantl <[email protected]>
Date: Mon, 16 Nov 2026 12:19:23 -0800
Subject: [PATCH 2/2] amend! [clang] Locate backend diagnostics under
 -fdebug-prefix-map

[clang] Locate backend diagnostics under -fdebug-prefix-map

Backend diagnostics are mapped back to a clang SourceLocation by
looking up the file name recorded in the debug info. With
-fdebug-prefix-map that name is the remapped path, which usually does
not exist, so the lookup fails and the diagnostic is reported at the
enclosing function instead. If the function lies outside the
"#pragma clang diagnostic ignored" region covering the real location,
the suppression is lost, and a build that passes without the prefix
map fails with -Werror. The notes of -fdiagnostics-show-inlining-chain
have the same problem.

Record which source file each DIFile was created for when CGDebugInfo
creates it, and resolve debug locations through their DIFile instead
of its file name. DiagnosticLocation and DebugInlineInfo now provide
the DIFile for this. Debug info that clang did not generate, e.g. from
LLVM IR input, still falls back to the file name. Files with line
directives are left out, because their debug locations use presumed
lines. Without checksums, distinct files whose remapped names are
equal share a DIFile; locations in such a DIFile fall back to the
enclosing function.

rdar://192737670
Assisted-by: Claude
---
 .../CodeGenUtils/BackendDiagnosticHandler.h   | 21 ++++++
 clang/lib/CodeGen/CGDebugInfo.cpp             | 39 ++++++++++-
 clang/lib/CodeGen/CGDebugInfo.h               | 21 ++++++
 clang/lib/CodeGen/CodeGenAction.cpp           |  3 +
 .../CodeGenUtils/BackendDiagnosticHandler.cpp | 70 +++++--------------
 .../optimization-remark-debug-prefix-map.c    | 50 +++++++++++--
 llvm/include/llvm/IR/DiagnosticInfo.h         |  2 +
 llvm/lib/IR/DiagnosticInfo.cpp                |  3 +-
 8 files changed, 149 insertions(+), 60 deletions(-)

diff --git a/clang/include/clang/CodeGenUtils/BackendDiagnosticHandler.h 
b/clang/include/clang/CodeGenUtils/BackendDiagnosticHandler.h
index 484b5c68594951..0a6d10ae00a946 100644
--- a/clang/include/clang/CodeGenUtils/BackendDiagnosticHandler.h
+++ b/clang/include/clang/CodeGenUtils/BackendDiagnosticHandler.h
@@ -19,15 +19,20 @@
 #ifndef LLVM_CLANG_CODEGENUTILS_BACKENDDIAGNOSTICHANDLER_H
 #define LLVM_CLANG_CODEGENUTILS_BACKENDDIAGNOSTICHANDLER_H
 
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/Hashing.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/IR/DiagnosticHandler.h"
 #include <memory>
 #include <optional>
+#include <utility>
 #include <vector>
 
 namespace llvm {
+class DIFile;
 class DiagnosticInfo;
 class DiagnosticInfoDontCall;
 class DiagnosticInfoInlineAsm;
@@ -83,6 +88,15 @@ class BackendDiagnosticConsumer {
   std::optional<FullSourceLoc>
   getFunctionSourceLocation(const llvm::Function &F) const;
 
+  /// Set the source file of each DIFile that clang created, or std::nullopt
+  /// for a DIFile shared by several files, which identifies none of them.
+  /// Debug locations in other DIFiles, e.g. from LLVM IR input, are matched to
+  /// source files by name.
+  void setDIFileSources(
+      llvm::DenseMap<const llvm::DIFile *, OptionalFileEntryRef> Sources) {
+    DIFileSources = std::move(Sources);
+  }
+
   /// Get the best possible source location to represent a diagnostic that
   /// may have associated debug info.
   const FullSourceLoc
@@ -135,6 +149,11 @@ class BackendDiagnosticConsumer {
   /// Note that misexpect remarks are emitted through ORE
   void MisExpectDiagHandler(const llvm::DiagnosticInfoMisExpect &D);
 
+  /// Find the source file for a debug location in \p File, falling back to
+  /// looking up \p Names in order if \p File is not in DIFileSources.
+  OptionalFileEntryRef getSourceFile(const llvm::DIFile *File,
+                                     ArrayRef<StringRef> Names) const;
+
   DiagnosticsEngine &Diags;
   const CodeGenOptions &CodeGenOpts;
   SourceManager *SM = nullptr;
@@ -149,6 +168,8 @@ class BackendDiagnosticConsumer {
   // because we optimize for time building this map rather than time
   // retrieving an entry, as backend diagnostics are uncommon.
   std::vector<std::pair<llvm::hash_code, FullSourceLoc>> 
ManglingFullSourceLocs;
+
+  llvm::DenseMap<const llvm::DIFile *, OptionalFileEntryRef> DIFileSources;
 };
 
 } // namespace clang
diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index bc516406269c2c..933d66a0faa855 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -635,8 +635,43 @@ llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation 
Loc) {
     if (CSKind)
       CSInfo.emplace(*CSKind, Checksum);
   }
-  return createFile(FileName, CSInfo,
-                    getSource(SM, SM.getFileID(getMacroDebugLoc(CGM, Loc))));
+  llvm::DIFile *F =
+      createFile(FileName, CSInfo,
+                 getSource(SM, SM.getFileID(getMacroDebugLoc(CGM, Loc))));
+  if (Loc.isValid())
+    recordDIFileSource(F, FID);
+  return F;
+}
+
+void CGDebugInfo::recordDIFileSource(const llvm::DIFile *F, FileID FID) {
+  SourceManager &SM = CGM.getContext().getSourceManager();
+  if (!SM.getFileEntryRefForID(FID))
+    FID = FileID();
+  auto [It, Inserted] = DIFileSources.try_emplace(F, DIFileSource{FID});
+  DIFileSource &Source = It->second;
+  if (Inserted || !Source.FID.isValid() || Source.FID == FID)
+    return;
+  // A DIFile also created for a location outside any file does not describe a
+  // file. Without checksums, distinct files whose remapped names are equal
+  // share a DIFile.
+  if (!FID.isValid())
+    Source.FID = FileID();
+  else if (SM.getFileEntryRefForID(Source.FID) != SM.getFileEntryRefForID(FID))
+    Source.Shared = true;
+}
+
+llvm::DenseMap<const llvm::DIFile *, OptionalFileEntryRef>
+CGDebugInfo::getDIFileSources() const {
+  SourceManager &SM = CGM.getContext().getSourceManager();
+  llvm::DenseMap<const llvm::DIFile *, OptionalFileEntryRef> Sources;
+  for (const auto &[F, Source] : DIFileSources) {
+    if (!Source.FID.isValid() ||
+        SM.getSLocEntry(Source.FID).getFile().hasLineDirectives())
+      continue;
+    Sources[F] = Source.Shared ? OptionalFileEntryRef()
+                               : SM.getFileEntryRefForID(Source.FID);
+  }
+  return Sources;
 }
 
 llvm::DIFile *CGDebugInfo::createFile(
diff --git a/clang/lib/CodeGen/CGDebugInfo.h b/clang/lib/CodeGen/CGDebugInfo.h
index 3f11cea5bcb7ff..eec34e056e82af 100644
--- a/clang/lib/CodeGen/CGDebugInfo.h
+++ b/clang/lib/CodeGen/CGDebugInfo.h
@@ -23,6 +23,7 @@
 #include "clang/AST/TypeOrdering.h"
 #include "clang/Basic/ASTSourceDescriptor.h"
 #include "clang/Basic/CodeGenOptions.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/DenseSet.h"
@@ -166,6 +167,16 @@ class CGDebugInfo {
   llvm::BumpPtrAllocator DebugInfoNames;
 
   llvm::DenseMap<const char *, llvm::TrackingMDRef> DIFileCache;
+  /// Where a DIFile came from, for mapping debug locations back to files.
+  struct DIFileSource {
+    /// The file the DIFile was first created for. Invalid if the DIFile was
+    /// also created for a location that is not in a file, such as one renamed
+    /// by a line directive.
+    FileID FID;
+    /// Whether the DIFile was also created for a different file.
+    bool Shared = false;
+  };
+  llvm::DenseMap<const llvm::DIFile *, DIFileSource> DIFileSources;
   llvm::DenseMap<const FunctionDecl *, llvm::TrackingMDRef> SPCache;
   /// Cache declarations relevant to DW_TAG_imported_declarations (C++
   /// using declarations and global alias variables) that aren't covered
@@ -592,6 +603,13 @@ class CGDebugInfo {
   /// Emit information about global variable alias.
   void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl);
 
+  /// Return the source file each DIFile was created for, or std::nullopt for a
+  /// DIFile shared by several files. DIFiles of files with line directives are
+  /// omitted, because debug locations in them use presumed lines. Line
+  /// directives are only all known once the translation unit is parsed.
+  llvm::DenseMap<const llvm::DIFile *, OptionalFileEntryRef>
+  getDIFileSources() const;
+
   /// Emit C++ using directive.
   void EmitUsingDirective(const UsingDirectiveDecl &UD);
 
@@ -778,6 +796,9 @@ class CGDebugInfo {
   /// location.
   llvm::DIFile *getOrCreateFile(SourceLocation Loc);
 
+  /// Note that \p F was created for a location in \p FID.
+  void recordDIFileSource(const llvm::DIFile *F, FileID FID);
+
   /// Create a file debug info descriptor for a source file.
   llvm::DIFile *
   createFile(StringRef FileName,
diff --git a/clang/lib/CodeGen/CodeGenAction.cpp 
b/clang/lib/CodeGen/CodeGenAction.cpp
index c54cc093218c91..dd7ba0b741c857 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -9,6 +9,7 @@
 #include "clang/CodeGen/CodeGenAction.h"
 #include "BackendConsumer.h"
 #include "CGCall.h"
+#include "CGDebugInfo.h"
 #include "CodeGenModule.h"
 #include "CoverageMappingGen.h"
 #include "MacroPPCallbacks.h"
@@ -248,6 +249,8 @@ void BackendConsumer::HandleTranslationUnit(ASTContext &C) {
       DiagConsumer.addFunctionSourceLocation(F.getName(), Loc);
     }
   }
+  if (CodeGen::CGDebugInfo *DI = Gen->CGM().getModuleDebugInfo())
+    DiagConsumer.setDIFileSources(DI->getDIFileSources());
 
   if (CodeGenOpts.ClearASTBeforeBackend) {
     LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
diff --git a/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp 
b/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
index 492091c179485d..b8e391a760b89c 100644
--- a/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
+++ b/clang/lib/CodeGenUtils/BackendDiagnosticHandler.cpp
@@ -13,15 +13,12 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/Hashing.h"
-#include "llvm/ADT/STLExtras.h"
-#include "llvm/ADT/SmallString.h"
 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
 #include "llvm/Demangle/Demangle.h"
 #include "llvm/IR/DiagnosticInfo.h"
 #include "llvm/IR/DiagnosticPrinter.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/Module.h"
-#include "llvm/Support/Path.h"
 #include "llvm/Support/raw_ostream.h"
 
 using namespace clang;
@@ -90,51 +87,6 @@ FullSourceLoc ConvertBackendLocation(const 
llvm::SMDiagnostic &D,
   return FullSourceLoc(NewLoc, CSM);
 }
 
-/// File paths in debug info have -fdebug-prefix-map substitutions
-/// applied. If \p DebugPath does not name a file in this compilation as is,
-/// undo each substitution and return the resulting file, unless several
-/// distinct files qualify.
-OptionalFileEntryRef lookupDebugFile(const SourceManager &SM,
-                                     const CodeGenOptions &CGOpts,
-                                     StringRef DebugPath) {
-  // A file of the same name outside this compilation is not the one the debug
-  // info refers to.
-  auto LookupInCompilation = [&](StringRef Path) -> OptionalFileEntryRef {
-    auto FE = SM.getFileManager().getOptionalFileRef(Path);
-    if (FE && SM.translateFile(*FE).isValid())
-      return FE;
-    return std::nullopt;
-  };
-  if (auto FE = LookupInCompilation(DebugPath))
-    return FE;
-  auto NormalizeSeparators = [](StringRef P) {
-    SmallString<256> N(P);
-    llvm::sys::path::remove_dots(N);
-    return N;
-  };
-  SmallString<256> NormalizedDebugPath = NormalizeSeparators(DebugPath);
-  OptionalFileEntryRef Result;
-  for (const auto &[From, To] : llvm::reverse(CGOpts.DebugPrefixMap)) {
-    SmallString<256> Path(DebugPath);
-    if (!llvm::sys::path::replace_path_prefix(Path, To, From))
-      continue;
-    // A later entry with an overlapping prefix may take precedence over this
-    // one, so the candidate must map forward to DebugPath again.
-    if (NormalizeSeparators(CGOpts.remapDebugPathPrefix(Path)) !=
-        NormalizedDebugPath)
-      continue;
-    auto FE = LookupInCompilation(Path);
-    if (!FE)
-      continue;
-    // Several prefixes can map to the same replacement. If they lead to
-    // different files, the debug info does not say which one is meant.
-    if (Result && *Result != *FE)
-      return std::nullopt;
-    Result = FE;
-  }
-  return Result;
-}
-
 } // namespace
 
 #define ComputeDiagID(Severity, GroupName, DiagID)                             
\
@@ -195,6 +147,21 @@ BackendDiagnosticConsumer::getFunctionSourceLocation(const 
Function &F) const {
   return std::nullopt;
 }
 
+OptionalFileEntryRef
+BackendDiagnosticConsumer::getSourceFile(const llvm::DIFile *File,
+                                         ArrayRef<StringRef> Names) const {
+  auto It = DIFileSources.find(File);
+  // A DIFile shared by several files identifies none of them, and looking up
+  // its name could find the wrong one.
+  if (It != DIFileSources.end())
+    return It->second;
+  FileManager &FileMgr = SM->getFileManager();
+  for (StringRef Name : Names)
+    if (auto FE = FileMgr.getOptionalFileRef(Name))
+      return FE;
+  return std::nullopt;
+}
+
 const FullSourceLoc BackendDiagnosticConsumer::getBestLocationFromDebugLoc(
     const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
     StringRef &Filename, unsigned &Line, unsigned &Column) const {
@@ -204,9 +171,8 @@ const FullSourceLoc 
BackendDiagnosticConsumer::getBestLocationFromDebugLoc(
   if (D.isLocationAvailable()) {
     D.getLocation(Filename, Line, Column);
     if (Line > 0) {
-      auto FE = lookupDebugFile(SourceMgr, CodeGenOpts, Filename);
-      if (!FE)
-        FE = lookupDebugFile(SourceMgr, CodeGenOpts, D.getAbsolutePath());
+      auto FE = getSourceFile(D.getLocation().getFile(),
+                              {Filename, D.getAbsolutePath()});
       if (FE) {
         // If -gcolumn-info was not used, Column will be 0. This upsets the
         // source manager, so pass 1 if Column is not set.
@@ -552,7 +518,7 @@ void BackendDiagnosticConsumer::DontCallDiagHandler(
     for (const auto &[I, Info] : llvm::enumerate(D.getDebugInlineChain())) {
       SourceLocation Loc;
       if (Info.Line > 0)
-        if (auto FE = lookupDebugFile(SrcMgr, CodeGenOpts, Info.Filename))
+        if (auto FE = getSourceFile(Info.File, Info.Filename))
           Loc = SrcMgr.translateFileLineCol(*FE, Info.Line,
                                             Info.Column ? Info.Column : 1);
       EmitNote(Loc, Info.FuncName, I == 0);
diff --git a/clang/test/Frontend/optimization-remark-debug-prefix-map.c 
b/clang/test/Frontend/optimization-remark-debug-prefix-map.c
index af19a6f543dc45..385e97d746ce8a 100644
--- a/clang/test/Frontend/optimization-remark-debug-prefix-map.c
+++ b/clang/test/Frontend/optimization-remark-debug-prefix-map.c
@@ -1,5 +1,5 @@
-/// Backend diagnostics are mapped back to the source through the file names in
-/// the debug info, which have -fdebug-prefix-map applied.
+/// Backend diagnostics are mapped back to the source through the debug info,
+/// whose file names have -fdebug-prefix-map applied.
 
 // RUN: rm -rf %t && split-file --no-leading-lines %s %t
 // RUN: mkdir %t/decoy && cp %t/src/t.c %t/decoy/t.c
@@ -9,7 +9,7 @@
 // RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
 // RUN:   -fdebug-prefix-map=%t/src=.
 
-/// The inverse mapping is ambiguous; only the file being compiled is a match.
+/// A file outside the compilation maps to the same name.
 // RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
 // RUN:   -fdebug-prefix-map=%t/src=. -fdebug-prefix-map=%t/decoy=.
 
@@ -17,11 +17,25 @@
 // RUN: %clang_cc1 %t/src/t.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
 // RUN:   -fdebug-compilation-dir=%t -fdebug-prefix-map=%t/src=%t/decoy
 
-/// Two files in the compilation map to the same name, so the debug info does 
not
-/// identify the file; fall back to the location of the function.
+/// Without checksums, two files in the compilation that map to the same name
+/// share a DIFile, which then does not identify the file; fall back to the
+/// location of the function.
 // RUN: %clang_cc1 %t/src/both.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify -I%t \
+// RUN:   -dwarf-version=4 \
 // RUN:   -fdebug-prefix-map=%t/a=%{fs-src-root}M 
-fdebug-prefix-map=%t/b=%{fs-src-root}M
 
+/// Line directives make debug locations use presumed lines, which do not map
+/// back to the file, even if a DIFile for the file was created before the
+/// directive was seen.
+// RUN: %clang_cc1 %t/src/line.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify \
+// RUN:   -fdebug-prefix-map=%t/src=%{fs-src-root}elsewhere
+
+/// The same holds if the file with line directives shares a DIFile with
+/// another file.
+// RUN: %clang_cc1 %t/src/line-shared.c -Rpass=inline -O1 
-debug-info-kind=line-tables-only -emit-llvm-only -verify -I%t \
+// RUN:   -dwarf-version=4 \
+// RUN:   -fdebug-prefix-map=%t/c=%{fs-src-root}M 
-fdebug-prefix-map=%t/b=%{fs-src-root}M
+
 //--- src/t.c
 int foo(int x, int y) __attribute__((always_inline));
 int foo(int x, int y) { return x + y; }
@@ -51,3 +65,29 @@ int callA(int j) {
 int callB(int j) {
   return j + (j - 2);
 }
+
+//--- src/line.c
+int foo(int x, int y) __attribute__((always_inline));
+int foo(int x, int y) { return x + y; }
+int before_line_directive;
+#line 100
+// expected-remark@+2 {{'foo' inlined into 'bar'}}
+// expected-note@+1 {{could not determine the original source location}}
+int bar(int j) {
+  return foo(j, j - 2);
+}
+
+//--- src/line-shared.c
+static inline __attribute__((always_inline)) int foo(int x, int y) {
+  return x + y;
+}
+#include "c/h.h"
+#include "b/h.h"
+
+//--- c/h.h
+#line 1
+// expected-remark@+2 {{'foo' inlined into 'callC'}}
+// expected-note@+1 {{could not determine the original source location}}
+int callC(int j) {
+  return foo(j, j - 2);
+}
diff --git a/llvm/include/llvm/IR/DiagnosticInfo.h 
b/llvm/include/llvm/IR/DiagnosticInfo.h
index da62b62bd8c74a..b5639dac9ff9df 100644
--- a/llvm/include/llvm/IR/DiagnosticInfo.h
+++ b/llvm/include/llvm/IR/DiagnosticInfo.h
@@ -337,6 +337,7 @@ class DiagnosticLocation {
   LLVM_ABI DiagnosticLocation(const DISubprogram *SP);
 
   bool isValid() const { return File; }
+  const DIFile *getFile() const { return File; }
   /// Return the full path to the file.
   LLVM_ABI std::string getAbsolutePath() const;
   /// Return the file name relative to the compilation directory.
@@ -1224,6 +1225,7 @@ struct DebugInlineInfo {
   StringRef Filename;
   unsigned Line;
   unsigned Column;
+  const DIFile *File = nullptr;
 };
 
 class LLVM_ABI DiagnosticInfoDontCall : public DiagnosticInfo {
diff --git a/llvm/lib/IR/DiagnosticInfo.cpp b/llvm/lib/IR/DiagnosticInfo.cpp
index a24b6d09350080..f6a5de1f9eefa8 100644
--- a/llvm/lib/IR/DiagnosticInfo.cpp
+++ b/llvm/lib/IR/DiagnosticInfo.cpp
@@ -525,7 +525,8 @@ void llvm::diagnoseDontCall(const CallInst &CI) {
           if (auto *Scope = Loc->getScope())
             if (auto *SP = Scope->getSubprogram())
               DebugChain.push_back({SP->getName(), Loc->getFilename(),
-                                    Loc->getLine(), Loc->getColumn()});
+                                    Loc->getLine(), Loc->getColumn(),
+                                    Loc->getFile()});
         };
         if (const DILocation *Loc = DL.get()) {
           AddLocation(Loc);

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to