[llvm] Implement a custom stream for LDBG macro to handle newlines (PR #150750)

Mehdi Amini via llvm-commits llvm-commits at lists.llvm.org
Sat Jul 26 03:55:14 PDT 2025


================
@@ -30,37 +30,71 @@ namespace llvm {
 #define DEBUGLOG_WITH_STREAM_AND_TYPE(STREAM, TYPE)                            \
   for (bool _c = (::llvm::DebugFlag && ::llvm::isCurrentDebugType(TYPE)); _c;  \
        _c = false)                                                             \
-  ::llvm::impl::LogWithNewline(TYPE, __SHORT_FILE__, __LINE__, (STREAM))
+  ::llvm::impl::LogWithNewline(TYPE, __SHORT_FILE__, __LINE__, (STREAM))       \
+      .stream()
 #else
 #define DEBUGLOG_WITH_STREAM_AND_TYPE(STREAM, TYPE)                            \
   for (bool _c = (::llvm::DebugFlag && ::llvm::isCurrentDebugType(TYPE)); _c;  \
        _c = false)                                                             \
-  ::llvm::impl::LogWithNewline(TYPE, __FILE__, __LINE__, (STREAM))
+  ::llvm::impl::LogWithNewline(TYPE, __FILE__, __LINE__, (STREAM)).stream()
 #endif
 
 namespace impl {
-class LogWithNewline {
+
+/// A raw_ostream that tracks `\n` and print the prefix.
+class LLVM_ABI raw_ldbg_ostream : public raw_ostream {
+  std::string Prefix;
+  raw_ostream &Os;
+
+  /// Split the line on newlines and insert the prefix before each newline.
+  /// Forward everything to the underlying stream.
+  void write_impl(const char *Ptr, size_t Size) final {
+    auto Str = StringRef(Ptr, Size);
+    auto Eol = Str.find('\n');
+    while (Eol != StringRef::npos) {
+      StringRef Line = Str.take_front(Eol + 1);
+      Os.write(Line.data(), Line.size());
+      Os.write(Prefix.c_str(), Prefix.size());
+
+      Str = Str.drop_front(Eol + 1);
+      Eol = Str.find('\n');
+    }
+    Os.write(Str.data(), Str.size());
+  }
+
 public:
-  LogWithNewline(const char *debug_type, const char *file, int line,
-                 raw_ostream &os)
-      : os(os) {
-#if !defined(__SHORT_FILE__)
-    file = ::llvm::impl::LogWithNewline::getShortFileName(file);
-#endif
-    if (debug_type)
-      os << "[" << debug_type << "] ";
-    os << file << ":" << line << " ";
+  explicit raw_ldbg_ostream(std::string Prefix, raw_ostream &Os)
+      : Prefix(std::move(Prefix)), Os(Os) {
+    SetUnbuffered();
   }
-  ~LogWithNewline() { os << '\n'; }
-  template <typename T> raw_ostream &operator<<(const T &t) && {
-    return os << t;
+
+  void emitPrefix() { Os.write(Prefix.c_str(), Prefix.size()); }
+
+  raw_ostream &getOs() { return Os; }
+
+  /// Forward the current_pos method to the underlying stream.
+  uint64_t current_pos() const final { return Os.tell(); }
----------------
joker-eph wrote:

I don't believe this is correct: the prefix is written to the underlying stream, which tracks the position

https://github.com/llvm/llvm-project/pull/150750


More information about the llvm-commits mailing list