From a3cb0ae9268338f5920043b566396bd43e763f41 Mon Sep 17 00:00:00 2001 From: Martijn Courteaux Date: Sun, 22 Nov 2026 19:46:36 +0100 Subject: [PATCH] Link GPU device code to the conceptual stmt in the html output The conceptual_stmt_html output links the device code of GPU kernels to the conceptual stmt it was made from, for CUDA and for the APIs with C-like source (OpenCL, Metal, D3D12, WebGPU), in the same way as the assembly: by line of IR, and within a line by IR node. Lowering prints the conceptual stmt with its source map before the GPU loops are offloaded, and each device code generator says where in it each line of its output came from. The Module keeps that per device code buffer, for the html. - The C-like code generators note where print_stmt() and print_expr() print each Stmt and Expr. The line that assigns the value of an Expr is left to that Expr, after the lines of its operands. - PTX is compiled with line tables that point into the conceptual stmt. The .loc directives are read, for their line and column, and taken out of the device code again. - A Stmt that was rewritten since the conceptual stmt was printed is found by the first node within it that was printed (StmtSourceMap::find_within). The device code itself is unchanged. CodeGen_LLVM::init_debug_info() takes the source to point into; compile() prints one itself if it has to. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011FRemhS639vq75urwV44oe --- doc/DebugSymbols.md | 7 + src/CodeGen_C.cpp | 36 +++- src/CodeGen_C.h | 15 ++ src/CodeGen_D3D12Compute_Dev.cpp | 11 +- src/CodeGen_GPU_Dev.cpp | 26 +++ src/CodeGen_GPU_Dev.h | 15 ++ src/CodeGen_LLVM.cpp | 100 +++++----- src/CodeGen_LLVM.h | 11 +- src/CodeGen_Metal_Dev.cpp | 13 +- src/CodeGen_OpenCL_Dev.cpp | 11 +- src/CodeGen_PTX_Dev.cpp | 88 ++++++++- src/CodeGen_WebGPU_Dev.cpp | 13 +- src/IRPrinter.cpp | 28 +++ src/IRPrinter.h | 6 + src/Lower.cpp | 9 +- src/Module.cpp | 12 ++ src/Module.h | 17 ++ src/OffloadGPULoops.cpp | 18 +- src/OffloadGPULoops.h | 13 +- src/StmtToHTML.cpp | 71 +++++--- src/irvisualizer/html_template_StmtToHTML.css | 40 +++- src/irvisualizer/html_template_StmtToHTML.js | 172 ++++++++++++++++-- test/correctness/debug_symbols.cpp | 98 ++++++++++ 23 files changed, 702 insertions(+), 128 deletions(-) diff --git a/doc/DebugSymbols.md b/doc/DebugSymbols.md index 6edaccfb8b5f..3b6f05ea4b2a 100644 --- a/doc/DebugSymbols.md +++ b/doc/DebugSymbols.md @@ -87,6 +87,13 @@ numbers of the assembly file, without the lines that hold the debug info. This needs every IR node to be printed in one place only, so lowering copies the IR nodes that the stmt uses in more than one place. +The `conceptual_stmt_html` output also links the device code of GPU kernels to +the conceptual stmt it was made from, for CUDA (PTX) and for the APIs whose +device code is C-like source (OpenCL, Metal, D3D12, WebGPU), in the same way as +the assembly: by line of IR, and within a line by IR node. The device code +itself is not changed for this, and has no line information in it. Device code +that isn't text to read, like SPIR-V, is not linked. + ## Caveats - The code is still fully optimized, so many variables are ``, diff --git a/src/CodeGen_C.cpp b/src/CodeGen_C.cpp index ba79bb68c2b3..455cec014b22 100644 --- a/src/CodeGen_C.cpp +++ b/src/CodeGen_C.cpp @@ -1313,7 +1313,18 @@ void CodeGen_C::compile(const Buffer<> &buffer) { string CodeGen_C::print_expr(const Expr &e) { id = "$$ BAD ID $$"; + // An Expr that was rewritten since line_source was printed is not noted: + // what is printed for it goes to what it is printed within. + const StmtSourceMap::Location *l = line_source ? line_source->find(e.get(), 0) : nullptr; + if (!l) { + e.accept(this); + return id; + } + const size_t i = printed_nodes.size(); + const uint32_t start = (uint32_t)stream.tellp(); + printed_nodes.push_back({start, start, IRPosition{l->line, l->order}}); e.accept(this); + printed_nodes[i].end = (uint32_t)stream.tellp(); return id; } @@ -1334,7 +1345,16 @@ string CodeGen_C::print_cast_expr(const Type &t, const Expr &e) { } void CodeGen_C::print_stmt(const Stmt &s) { + if (!line_source) { + s.accept(this); + return; + } + const StmtSourceMap::Location *l = line_source->find_within(s.get()); + const size_t i = printed_nodes.size(); + const uint32_t start = (uint32_t)stream.tellp(); + printed_nodes.push_back({start, start, l ? IRPosition{l->line, l->order} : IRPosition()}); s.accept(this); + printed_nodes[i].end = (uint32_t)stream.tellp(); } string CodeGen_C::print_assignment(Type t, const std::string &rhs) { @@ -2240,7 +2260,7 @@ void CodeGen_C::visit(const LetStmt *op) { id_value = op->name; } ScopedBinding bind(bound_ids, op->name, id_value); - op->body.accept(this); + print_stmt(op->body); } // Halide asserts have different semantics to C asserts. They're @@ -2308,7 +2328,7 @@ void CodeGen_C::visit(const Acquire *op) { open_scope(); stream << get_indent() << "#pragma omp taskyield\n"; close_scope(""); - op->body.accept(this); + print_stmt(op->body); close_scope(""); } @@ -2317,11 +2337,11 @@ void CodeGen_C::visit(const Atomic *op) { internal_assert(!inside_atomic_mutex_node) << "Nested atomic mutex locks detected. This might causes a deadlock.\n"; ScopedValue old_inside_atomic_mutex_node(inside_atomic_mutex_node, true); - op->body.accept(this); + print_stmt(op->body); } else { // Issue atomic stores. ScopedValue old_emit_atomic_stores(emit_atomic_stores, true); - op->body.accept(this); + print_stmt(op->body); } } @@ -2349,7 +2369,7 @@ void CodeGen_C::visit(const For *op) { open_scope(); { ScopedBinding bind(bound_ids, op->name, op->name); - op->body.accept(this); + print_stmt(op->body); } close_scope("for " + print_name(op->name)); } @@ -2517,7 +2537,7 @@ void CodeGen_C::visit(const Allocate *op) { emit_halide_free_helper(op_name, free_function); } - op->body.accept(this); + print_stmt(op->body); // Free the memory if it was allocated on the heap and there is no matching // Free node. @@ -2554,13 +2574,13 @@ void CodeGen_C::visit(const IfThenElse *op) { stream << get_indent() << "if (" << cond_id << ")\n"; open_scope(); - op->then_case.accept(this); + print_stmt(op->then_case); close_scope("if " + cond_id); if (op->else_case.defined()) { stream << get_indent() << "else\n"; open_scope(); - op->else_case.accept(this); + print_stmt(op->else_case); close_scope("if " + cond_id + " else"); } } diff --git a/src/CodeGen_C.h b/src/CodeGen_C.h index 3d84588045d6..51e2b058db4c 100644 --- a/src/CodeGen_C.h +++ b/src/CodeGen_C.h @@ -38,6 +38,21 @@ class CodeGen_C : public IRPrinter { CPlusPlusFunctionInfoHeader, }; + /** If set, print_stmt() and print_expr() note in printed_nodes where + * they print each Stmt and Expr, and where that is in this printing of + * the IR, or of IR that it was lowered from. The stream must support + * tellp(). */ + const StmtSourceMap *line_source = nullptr; + + /** Where a Stmt or an Expr was printed, as byte offsets into the stream, + * and where it is in line_source. They are in the order they began + * printing. */ + struct PrintedNode { + uint32_t start, end; + IRPosition position; + }; + std::vector printed_nodes; + /** Initialize a C code generator pointing at a particular output * stream (e.g. a file, or std::cout) */ CodeGen_C(std::ostream &dest, diff --git a/src/CodeGen_D3D12Compute_Dev.cpp b/src/CodeGen_D3D12Compute_Dev.cpp index 8070a1276ac4..ed86c4d263cf 100644 --- a/src/CodeGen_D3D12Compute_Dev.cpp +++ b/src/CodeGen_D3D12Compute_Dev.cpp @@ -447,7 +447,7 @@ void CodeGen_D3D12Compute_Dev::CodeGen_D3D12Compute_C::visit(const For *loop) { stream << get_indent() << print_type(Int(32)) << " " << print_name(loop->name) << " = " << simt_intrinsic(loop->name) << ";\n"; - loop->body.accept(this); + print_stmt(loop->body); } void CodeGen_D3D12Compute_Dev::CodeGen_D3D12Compute_C::visit(const Ramp *op) { @@ -1437,7 +1437,7 @@ void CodeGen_D3D12Compute_Dev::CodeGen_D3D12Compute_C::visit(const Allocate *op) // Already handled internal_assert(!groupshared_allocations.contains(op->name)); groupshared_allocations.push(op->name); - op->body.accept(this); + print_stmt(op->body); } else { open_scope(); @@ -1467,7 +1467,7 @@ void CodeGen_D3D12Compute_Dev::CodeGen_D3D12Compute_C::visit(const Allocate *op) alloc.type = op->type; allocations.push(op->name, alloc); - op->body.accept(this); + print_stmt(op->body); // Should have been freed internally internal_assert(!allocations.contains(op->name)); @@ -2141,7 +2141,7 @@ void CodeGen_D3D12Compute_Dev::CodeGen_D3D12Compute_C::add_kernel(Stmt s, // Emit the kernel code: open_scope(); - print(s); + print_stmt(s); close_scope("kernel " + name); for (const auto &arg : args) { @@ -2161,6 +2161,8 @@ void CodeGen_D3D12Compute_Dev::init_module() { // wipe the internal kernel source src_stream.str(""); src_stream.clear(); + d3d12compute_c.line_source = line_source; + d3d12compute_c.printed_nodes.clear(); // Emit SM version marker for runtime to select FXC (SM 5.1) vs DXC (SM 6.x). // Emitted as a real #define (not a comment) so generated shader code can @@ -2270,6 +2272,7 @@ void CodeGen_D3D12Compute_Dev::init_module() { vector CodeGen_D3D12Compute_Dev::compile_to_src() { string str = src_stream.str(); + source_lines = line_source ? lines_of_printed_nodes(str, d3d12compute_c.printed_nodes) : std::vector(); debug(1) << "D3D12Compute kernel:\n" << str << "\n"; vector buffer(str.begin(), str.end()); diff --git a/src/CodeGen_GPU_Dev.cpp b/src/CodeGen_GPU_Dev.cpp index eaac4b61cb95..33c17b13de73 100644 --- a/src/CodeGen_GPU_Dev.cpp +++ b/src/CodeGen_GPU_Dev.cpp @@ -6,6 +6,7 @@ #include "IRMutator.h" #include "IROperator.h" #include "IRVisitor.h" +#include namespace Halide { namespace Internal { @@ -278,5 +279,30 @@ std::string CodeGen_GPU_C::print_extern_call(const Call *op) { return rhs.str(); } +std::vector lines_of_printed_nodes(const std::string &text, const std::vector &nodes) { + std::vector line_starts{0}; + for (uint32_t i = 0; i < (uint32_t)text.size(); i++) { + if (text[i] == '\n') { + line_starts.push_back(i + 1); + } + } + // The nodes are in the order they began printing, so those within a node + // come after it, and overwrite its lines. What is left to a node is what + // was printed for it alone, like the line that assigns the value of an + // Expr after the lines of its operands. + std::vector result(line_starts.size()); + for (const CodeGen_C::PrintedNode &n : nodes) { + if (n.position.line == 0 || n.end <= n.start) { + continue; + } + const size_t first = std::upper_bound(line_starts.begin(), line_starts.end(), n.start) - line_starts.begin() - 1; + const size_t last = std::upper_bound(line_starts.begin(), line_starts.end(), n.end - 1) - line_starts.begin() - 1; + for (size_t i = first; i <= last; i++) { + result[i] = n.position; + } + } + return result; +} + } // namespace Internal } // namespace Halide diff --git a/src/CodeGen_GPU_Dev.h b/src/CodeGen_GPU_Dev.h index cd23419f6ad9..4397a344fde0 100644 --- a/src/CodeGen_GPU_Dev.h +++ b/src/CodeGen_GPU_Dev.h @@ -14,10 +14,25 @@ namespace Halide { namespace Internal { +struct StmtSourceMap; + +/** For each line of text, C-like source that a CodeGen_C printed: where the + * innermost Stmt or Expr that it was printed for is (see + * CodeGen_C::line_source), of those that it is known of. */ +std::vector lines_of_printed_nodes(const std::string &text, const std::vector &nodes); + /** A code generator that emits GPU code from a given Halide stmt. */ struct CodeGen_GPU_Dev { virtual ~CodeGen_GPU_Dev(); + /** If set before init_module(): a printing of IR that holds the Stmts of + * the kernels, or that they were lowered from. compile_to_src() then says + * in source_lines where in it each line of the source it returns came + * from. That stays empty for code generators that don't keep track, or + * whose output isn't text. */ + const StmtSourceMap *line_source = nullptr; + std::vector source_lines; + /** Compile a GPU kernel into the module. This may be called many times * with different kernels, which will all be accumulated into a single * source module shared by a given Halide pipeline. */ diff --git a/src/CodeGen_LLVM.cpp b/src/CodeGen_LLVM.cpp index c3b79310acad..508ccff1b884 100644 --- a/src/CodeGen_LLVM.cpp +++ b/src/CodeGen_LLVM.cpp @@ -173,11 +173,12 @@ llvm::GlobalValue::LinkageTypes llvm_linkage(LinkageType t) { } // namespace struct CodeGen_LLVM::DebugInfo { - // What the debug info points into, which is own_source if compile() had - // to print it itself. - StmtSourceMap own_source; + // What the debug info points into. const StmtSourceMap *source = nullptr; + // Only describe which code came from where, not the values in it. + bool line_tables_only = false; + std::unique_ptr builder; DICompileUnit *unit = nullptr; DIFile *file = nullptr; @@ -196,32 +197,11 @@ struct CodeGen_LLVM::DebugInfo { // The source is the conceptual Stmt, which the functions themselves // are not in. Each starts where the first of its code that is in it // does. - class FirstPrinted : public IRGraphVisitor { - using IRGraphVisitor::include; - void include(const Expr &e) override { - if (!found && !(found = source.find(e.get(), 0))) { - IRGraphVisitor::include(e); - } - } - void include(const Stmt &s) override { - if (!found && !(found = source.find(s.get(), 0))) { - IRGraphVisitor::include(s); - } - } - - public: - const StmtSourceMap &source; - const StmtSourceMap::Location *found = nullptr; - explicit FirstPrinted(const StmtSourceMap &source) - : source(source) { - } - } first(*source); - first(f.body); function = StmtSourceMap::Function{f.name, 0, 1, 1}; - if (first.found) { - function->start = first.found->start; - function->line = first.found->line; - function->column = first.found->column; + if (const StmtSourceMap::Location *first = source->find_within(f.body.get())) { + function->start = first->start; + function->line = first->line; + function->column = first->column; } } @@ -255,7 +235,13 @@ struct CodeGen_LLVM::DebugInfo { saved_location = d->location; saved_start = d->location_start; if (d->scope) { - if (const StmtSourceMap::Location *l = d->source->find(node, d->location_start)) { + const StmtSourceMap::Location *l = d->source->find(node, d->location_start); + if (!l && node->node_type > StrongestExprNodeType) { + // A Stmt that was rewritten since it was printed is where + // what is left of it is. + l = d->source->find_within(node); + } + if (l) { d->location = DILocation::get(d->scope->getContext(), l->line, l->column, d->scope); d->location_start = l->start; } @@ -307,27 +293,12 @@ struct CodeGen_LLVM::DebugInfo { return result; } - // The debug info points into source, a printing of input or of its - // conceptual Stmt. If source is null, input is printed, or its conceptual - // Stmt if conceptual is set. - static std::unique_ptr make(llvm::Module &m, const Module &input, const Target &target, - const StmtSourceMap *source, bool conceptual, + static std::unique_ptr make(llvm::Module &m, const Target &target, + const StmtSourceMap &source, bool line_tables_only, StructType *buffer_t, StructType *type_t, StructType *dimension_t) { auto d = std::make_unique(); - if (source) { - d->source = source; - } else { - if (conceptual) { - d->own_source = print_with_source_map(input.get_conceptual_stmt()); - d->own_source.path = input.name() + ".conceptual.stmt"; - } else { - d->own_source = print_with_source_map(input); - d->own_source.path = input.name() + ".stmt"; - } - d->source = &d->own_source; - } - internal_assert(d->source->functions.empty() || d->source->functions.size() == input.functions().size()) - << "The debug source of a Module must be a printing of that Module or of its conceptual Stmt\n"; + d->source = &source; + d->line_tables_only = line_tables_only; const bool codeview = target.os == Target::Windows; if (!m.getModuleFlag("Debug Info Version")) { @@ -340,8 +311,9 @@ struct CodeGen_LLVM::DebugInfo { } else if (!m.getModuleFlag("Dwarf Version")) { // Version 5 could carry the text of the .stmt in the object, but // LLVM then describes many optimized variables with typed DWARF - // expressions that gdb can't evaluate. - m.addModuleFlag(llvm::Module::Max, "Dwarf Version", 4); + // expressions that gdb can't evaluate. Line tables need no more + // than version 2. + m.addModuleFlag(llvm::Module::Max, "Dwarf Version", line_tables_only ? 2 : 4); } SmallString<256> path(d->source->path); @@ -358,7 +330,8 @@ struct CodeGen_LLVM::DebugInfo { d->file = d->builder->createFile(sys::path::filename(path), sys::path::parent_path(path), DIFile::ChecksumInfo(DIFile::CSK_MD5, checksum)); d->unit = d->builder->createCompileUnit(dwarf::DW_LANG_C99, d->file, "Halide", - /* isOptimized */ true, "", 0, ""); + /* isOptimized */ true, "", 0, "", + line_tables_only ? DICompileUnit::DebugDirectivesOnly : DICompileUnit::FullDebug); d->pointer_bits = target.bits; // Describe halide_buffer_t, so that the debugger can show buffers. @@ -960,9 +933,20 @@ std::unique_ptr CodeGen_LLVM::compile(const Module &input) { user_assert(!(target.has_feature(Target::DebugSymbols) && target.has_feature(Target::DebugSymbolsConceptual))) << "The debug info of " << input.name() << " can point into the stmt (debug_symbols) " << "or into the conceptual stmt (debug_symbols_conceptual), but not both.\n"; - if (debug_source || target.has_feature(Target::DebugSymbols) || target.has_feature(Target::DebugSymbolsConceptual)) { - init_debug_info(debug_source, input, target.has_feature(Target::DebugSymbolsConceptual)); - } + if (debug_source) { + init_debug_info(*debug_source); + } else if (target.has_feature(Target::DebugSymbols)) { + own_debug_source = std::make_unique(print_with_source_map(input)); + own_debug_source->path = input.name() + ".stmt"; + init_debug_info(*own_debug_source); + } else if (target.has_feature(Target::DebugSymbolsConceptual)) { + own_debug_source = std::make_unique(print_with_source_map(input.get_conceptual_stmt())); + own_debug_source->path = input.name() + ".conceptual.stmt"; + init_debug_info(*own_debug_source); + } + internal_assert(!debug_info || debug_info->source->functions.empty() || + debug_info->source->functions.size() == input.functions().size()) + << "The debug source of a Module must be a printing of that Module or of its conceptual Stmt\n"; // Generate the code for this module. debug(1) << "Generating llvm bitcode...\n"; @@ -1213,8 +1197,8 @@ void CodeGen_LLVM::end_func(const std::vector &args) { current_function_args.clear(); } -void CodeGen_LLVM::init_debug_info(const StmtSourceMap *source, const Module &input, bool conceptual) { - debug_info = DebugInfo::make(*module, input, target, source, conceptual, +void CodeGen_LLVM::init_debug_info(const StmtSourceMap &source, bool line_tables_only) { + debug_info = DebugInfo::make(*module, target, source, line_tables_only, halide_buffer_t_type, type_t_type, dimension_t_type); } @@ -1227,7 +1211,7 @@ void CodeGen_LLVM::begin_debug_function(const std::string &name, const std::stri DebugInfo &d = *debug_info; uint32_t line = 0, column = 1, start = 0; if (node) { - const StmtSourceMap::Location *l = d.source->find(node, 0); + const StmtSourceMap::Location *l = d.source->find_within(node); if (!l) { return; } @@ -1861,7 +1845,7 @@ void CodeGen_LLVM::sym_pop(const string &name) { } void CodeGen_LLVM::add_debug_variable(const string &name, const Type &type, llvm::Value *value, unsigned arg_no) { - if (!debug_info || !debug_info->scope || !value || !builder->GetInsertBlock()) { + if (!debug_info || debug_info->line_tables_only || !debug_info->scope || !value || !builder->GetInsertBlock()) { return; } DebugInfo &d = *debug_info; diff --git a/src/CodeGen_LLVM.h b/src/CodeGen_LLVM.h index 566201d3185d..fa01feb9fd84 100644 --- a/src/CodeGen_LLVM.h +++ b/src/CodeGen_LLVM.h @@ -213,9 +213,14 @@ class CodeGen_LLVM : public IRVisitor { void add_debug_variable(const std::string &name, const Type &type, llvm::Value *value, unsigned arg_no = 0); /** Set up debug_info for the module being generated, pointing into - * source, a printing of input or of its conceptual Stmt. If source is - * null, input is printed, or its conceptual Stmt if conceptual is set. */ - void init_debug_info(const StmtSourceMap *source, const Module &input, bool conceptual); + * source, a printing of the IR that is compiled or of IR it was lowered + * from. If line_tables_only, the debug info only says which code came + * from where, and not what the values in it are. */ + void init_debug_info(const StmtSourceMap &source, bool line_tables_only = false); + + /** The printing compile() made itself for the debug info to point + * into, if any. */ + std::unique_ptr own_debug_source; /** If there is debug info, give the function being generated a * subprogram, starting at where node was printed. If node is null, it is diff --git a/src/CodeGen_Metal_Dev.cpp b/src/CodeGen_Metal_Dev.cpp index 73909d53a8f7..5f8101ec6245 100644 --- a/src/CodeGen_Metal_Dev.cpp +++ b/src/CodeGen_Metal_Dev.cpp @@ -308,7 +308,7 @@ void CodeGen_Metal_Dev::CodeGen_Metal_C::visit(const For *loop) { stream << get_indent() << print_type(Int(32)) << " " << print_name(loop->name) << " = " << simt_intrinsic(loop->name) << ";\n"; - loop->body.accept(this); + print_stmt(loop->body); } else { user_assert(loop->for_type != ForType::Parallel) << "Cannot use parallel loops inside Metal kernel\n"; @@ -569,7 +569,7 @@ void CodeGen_Metal_Dev::CodeGen_Metal_C::visit(const Allocate *op) { if (is_gpu_shared(op->memory_type)) { // Already handled - op->body.accept(this); + print_stmt(op->body); } else { open_scope(); @@ -600,7 +600,7 @@ void CodeGen_Metal_Dev::CodeGen_Metal_C::visit(const Allocate *op) { alloc.type = op->type; allocations.push(op->name, alloc); - op->body.accept(this); + print_stmt(op->body); // Should have been freed internally internal_assert(!allocations.contains(op->name)); @@ -857,7 +857,7 @@ void CodeGen_Metal_Dev::CodeGen_Metal_C::add_kernel(const Stmt &s, } } - print(s); + print_stmt(s); close_scope("kernel " + name); for (const auto &arg : args) { @@ -881,6 +881,8 @@ void CodeGen_Metal_Dev::init_module() { // wipe the internal kernel source src_stream.str(""); src_stream.clear(); + metal_c.line_source = line_source; + metal_c.printed_nodes.clear(); // Write out the Halide math functions. src_stream << "#pragma clang diagnostic ignored \"-Wunused-function\"\n" @@ -917,6 +919,7 @@ void CodeGen_Metal_Dev::init_module() { vector CodeGen_Metal_Dev::compile_to_src() { string str = src_stream.str(); + source_lines = line_source ? lines_of_printed_nodes(str, metal_c.printed_nodes) : std::vector(); debug(1) << "Metal kernel:\n" << str << "\n"; @@ -960,6 +963,8 @@ vector CodeGen_Metal_Dev::compile_to_src() { // Read the metallib into a buffer. buffer = read_entire_file(metallib); + // A metallib has no lines. + source_lines.clear(); debug(2) << "Metallib size: " << buffer.size() << "\n"; } else { buffer.push_back(0); diff --git a/src/CodeGen_OpenCL_Dev.cpp b/src/CodeGen_OpenCL_Dev.cpp index c4d312a88ec0..27470bb8c39c 100644 --- a/src/CodeGen_OpenCL_Dev.cpp +++ b/src/CodeGen_OpenCL_Dev.cpp @@ -248,7 +248,7 @@ void CodeGen_OpenCL_Dev::CodeGen_OpenCL_C::visit(const For *loop) { stream << get_indent() << print_type(Int(32)) << " " << print_name(loop->name) << " = " << simt_intrinsic(loop->name) << ";\n"; - loop->body.accept(this); + print_stmt(loop->body); } else { user_assert(loop->for_type != ForType::Parallel) << "Cannot use parallel loops inside OpenCL kernel\n"; @@ -794,7 +794,7 @@ void CodeGen_OpenCL_Dev::CodeGen_OpenCL_C::visit(const Allocate *op) { if (is_gpu_shared(op->memory_type)) { // Already handled - op->body.accept(this); + print_stmt(op->body); } else { open_scope(); @@ -825,7 +825,7 @@ void CodeGen_OpenCL_Dev::CodeGen_OpenCL_C::visit(const Allocate *op) { alloc.type = op->type; allocations.push(op->name, alloc); - op->body.accept(this); + print_stmt(op->body); // Should have been freed internally internal_assert(!allocations.contains(op->name)); @@ -1112,7 +1112,7 @@ void CodeGen_OpenCL_Dev::CodeGen_OpenCL_C::add_kernel(Stmt s, } } - print(s); + print_stmt(s); close_scope("kernel " + name); for (const auto &arg : args) { @@ -1136,6 +1136,8 @@ void CodeGen_OpenCL_Dev::init_module() { // wipe the internal kernel source src_stream.str(""); src_stream.clear(); + clc.line_source = line_source; + clc.printed_nodes.clear(); const Target &target = clc.get_target(); @@ -1186,6 +1188,7 @@ void CodeGen_OpenCL_Dev::init_module() { vector CodeGen_OpenCL_Dev::compile_to_src() { string str = src_stream.str(); + source_lines = line_source ? lines_of_printed_nodes(str, clc.printed_nodes) : std::vector(); debug(1) << "OpenCL kernel:\n" << str << "\n"; vector buffer(str.begin(), str.end()); diff --git a/src/CodeGen_PTX_Dev.cpp b/src/CodeGen_PTX_Dev.cpp index cc2100b04654..281bbbaace09 100644 --- a/src/CodeGen_PTX_Dev.cpp +++ b/src/CodeGen_PTX_Dev.cpp @@ -21,6 +21,8 @@ #include "Solve.h" #include "Substitute.h" #include "Target.h" +#include +#include #include #include @@ -232,6 +234,65 @@ void CodeGen_PTX_Dev::set_kernel_max_registers(int n) { kernel_max_registers = n; } +namespace { + +// Takes the line information out of PTX: the .loc and .file directives, and +// the labels and sections that only they use. Returns for each line that is +// left where in source the .loc directives say its code came from. +std::vector strip_line_info(std::string &ptx, const StmtSourceMap &source) { + std::vector lines; + std::string stripped; + IRPosition current; + for (size_t start = 0; start < ptx.size();) { + const size_t end = std::min(ptx.find('\n', start), ptx.size()); + const std::string_view whole = std::string_view(ptx).substr(start, end - start); + start = end + 1; + const size_t first = whole.find_first_not_of(" \t"); + const std::string_view line = first == std::string_view::npos ? std::string_view() : whole.substr(first); + auto begins = [&](std::string_view prefix) { + return line.substr(0, prefix.size()) == prefix; + }; + if (begins(".loc\t") || begins(".loc ")) { + // .loc + std::istringstream in{std::string(line.substr(4))}; + uint32_t file = 0, l = 0, column = 0; + in >> file >> l >> column; + const StmtSourceMap::Location *at = source.at(l, column); + current = IRPosition{l, at ? at->order : 0}; + continue; + } + if (begins(".file\t") || begins(".file ") || begins(".section\t.debug") || begins(".section .debug")) { + continue; + } + bool is_label = false; + for (std::string_view label : {"$L__tmp", "$L__func_begin", "$L__func_end"}) { + if (begins(label)) { + const std::string_view rest = line.substr(label.size()); + is_label = !rest.empty() && rest.back() == ':' && + rest.substr(0, rest.size() - 1).find_first_not_of("0123456789") == std::string_view::npos; + } + } + if (is_label) { + continue; + } + if (begins("}")) { + // The end of a function. + current = IRPosition(); + } + // Only instructions are code; labels, directives and declarations + // are not. + const bool is_instruction = first != 0 && first != std::string_view::npos && + line[0] != '.' && line[0] != '/' && line.back() != ':'; + stripped.append(whole); + stripped.push_back('\n'); + lines.push_back(is_instruction ? current : IRPosition()); + } + ptx = std::move(stripped); + return lines; +} + +} // namespace + void CodeGen_PTX_Dev::add_kernel(Stmt stmt, const std::string &name, const std::vector &args) { @@ -263,6 +324,13 @@ void CodeGen_PTX_Dev::add_kernel(Stmt stmt, function->setCallingConv(llvm::CallingConv::PTX_Kernel); + std::vector> debug_args; + debug_args.reserve(args.size()); + for (const auto &arg : args) { + debug_args.emplace_back(arg.is_buffer, arg.type); + } + begin_debug_function(name, name, stmt.get(), nullptr, debug_args); + // Make the initial basic block entry_block = BasicBlock::Create(*context, "entry", function); builder->SetInsertPoint(entry_block); @@ -291,7 +359,7 @@ void CodeGen_PTX_Dev::add_kernel(Stmt stmt, debug(1) << "Generating llvm bitcode for kernel...\n"; // Ok, we have a module, function, context, and a builder // pointing at a brand new basic block. We're good to go. - stmt.accept(this); + codegen(stmt); // Now we need to end the function builder->CreateRetVoid(); @@ -333,6 +401,8 @@ void CodeGen_PTX_Dev::add_kernel(Stmt stmt, << kernel_max_registers << " registers per thread\n"; } + end_debug_function(); + // Now verify the function is ok verifyFunction(*function); @@ -359,6 +429,12 @@ void CodeGen_PTX_Dev::init_module() { module = get_initial_module_for_ptx_device(target, context); init_builder(); + if (line_source) { + // Just the .loc directives is all it takes to know where the lines of + // PTX came from. + init_debug_info(*line_source, /* line_tables_only */ true); + } + struct Intrinsic { const char *name; Type ret_type; @@ -1382,6 +1458,8 @@ bool CodeGen_PTX_Dev::use_soft_float_abi() const { vector CodeGen_PTX_Dev::compile_to_src() { debug(2) << "In CodeGen_PTX_Dev::compile_to_src"; + finalize_debug_info(); + // DISABLED - hooked in here to force PrintBeforeAll option - seems to be the only way? /*char* argv[] = { "llc", "-print-before-all" };*/ /*int argc = sizeof(argv)/sizeof(char*);*/ @@ -1528,6 +1606,14 @@ vector CodeGen_PTX_Dev::compile_to_src() { << outstr.c_str() << "\n"; vector buffer(outstr.begin(), outstr.end()); + source_lines.clear(); + if (line_source) { + // The line information says where the PTX came from, and is not part + // of the device code. + std::string ptx(outstr.begin(), outstr.end()); + source_lines = strip_line_info(ptx, *line_source); + buffer.assign(ptx.begin(), ptx.end()); + } // Dump the SASS too if the cuda SDK is in the path debug(2) << "Compiling PTX to SASS. Will fail if CUDA SDK is not installed (and in the path).\n"; diff --git a/src/CodeGen_WebGPU_Dev.cpp b/src/CodeGen_WebGPU_Dev.cpp index 089cf36d7e8a..6c47bd1059c9 100644 --- a/src/CodeGen_WebGPU_Dev.cpp +++ b/src/CodeGen_WebGPU_Dev.cpp @@ -163,6 +163,8 @@ void CodeGen_WebGPU_Dev::init_module() { // Wipe the internal shader source. src_stream.str(""); src_stream.clear(); + wgsl.line_source = line_source; + wgsl.printed_nodes.clear(); // Write out the Halide math functions. src_stream @@ -192,6 +194,7 @@ void CodeGen_WebGPU_Dev::init_module() { vector CodeGen_WebGPU_Dev::compile_to_src() { string str = src_stream.str(); + source_lines = line_source ? lines_of_printed_nodes(str, wgsl.printed_nodes) : std::vector(); debug(1) << "WGSL shader:\n" << str << "\n"; vector buffer(str.begin(), str.end()); @@ -383,7 +386,7 @@ void CodeGen_WebGPU_Dev::CodeGen_WGSL::add_kernel( } // Generate function body. - print(s); + print_stmt(s); close_scope("shader " + name); @@ -413,7 +416,7 @@ void CodeGen_WebGPU_Dev::CodeGen_WGSL::visit(const Allocate *op) { if (is_gpu_shared(op->memory_type)) { internal_assert(!workgroup_allocations.count(op->name)); workgroup_allocations.insert({op->name, op}); - op->body.accept(this); + print_stmt(op->body); } else { open_scope(); @@ -441,7 +444,7 @@ void CodeGen_WebGPU_Dev::CodeGen_WGSL::visit(const Allocate *op) { alloc.type = op->type; allocations.push(op->name, alloc); - op->body.accept(this); + print_stmt(op->body); // Should have been freed internally internal_assert(!allocations.contains(op->name)); @@ -662,7 +665,7 @@ void CodeGen_WebGPU_Dev::CodeGen_WGSL::visit(const For *loop) { << "let " << print_name(loop->name) << " = i32(" << simt_intrinsic(loop->name) << ");\n"; - loop->body.accept(this); + print_stmt(loop->body); } else { user_assert(loop->for_type == ForType::Serial) @@ -677,7 +680,7 @@ void CodeGen_WebGPU_Dev::CodeGen_WGSL::visit(const For *loop) { // TODO: Use increment statement when supported by Chromium. << id_counter << " = " << id_counter << " + 1)\n"; open_scope(); - loop->body.accept(this); + print_stmt(loop->body); close_scope("for " + print_name(loop->name)); } } diff --git a/src/IRPrinter.cpp b/src/IRPrinter.cpp index d19f56e08db4..559929dbe25c 100644 --- a/src/IRPrinter.cpp +++ b/src/IRPrinter.cpp @@ -870,6 +870,34 @@ const StmtSourceMap::Location *StmtSourceMap::find(const IRNode *node, uint32_t return nullptr; } +const StmtSourceMap::Location *StmtSourceMap::find_within(const IRNode *node) const { + if (const Location *l = find(node, 0)) { + return l; + } + class FirstPrinted : public IRGraphVisitor { + using IRGraphVisitor::include; + void include(const Expr &e) override { + if (!found && !(found = source.find(e.get(), 0))) { + IRGraphVisitor::include(e); + } + } + void include(const Stmt &s) override { + if (!found && !(found = source.find(s.get(), 0))) { + IRGraphVisitor::include(s); + } + } + + public: + const StmtSourceMap &source; + const Location *found = nullptr; + explicit FirstPrinted(const StmtSourceMap &source) + : source(source) { + } + } first(*this); + node->accept(&first); + return first.found; +} + const StmtSourceMap::Location *StmtSourceMap::at(uint32_t line, uint32_t column) const { auto it = std::lower_bound(by_anchor.begin(), by_anchor.end(), std::make_pair(line, column), [&](uint32_t i, const std::pair &lc) { diff --git a/src/IRPrinter.h b/src/IRPrinter.h index cfcd1c8eb6f7..113cfa1e161f 100644 --- a/src/IRPrinter.h +++ b/src/IRPrinter.h @@ -224,6 +224,12 @@ struct StmtSourceMap { * was never printed. */ const Location *find(const IRNode *node, uint32_t parent_start) const; + /** The first printed copy of node, or else that of the first node within + * it that was printed, in the order IR is visited. IR that was rewritten + * after it was printed is found by what is left of it this way. Returns + * nullptr if there is none. */ + const Location *find_within(const IRNode *node) const; + /** The location with the given anchor. Of nested nodes that share one, * the innermost. Returns nullptr if there is none. */ const Location *at(uint32_t line, uint32_t column) const; diff --git a/src/Lower.cpp b/src/Lower.cpp index 8f160d7443df..8bd040a62241 100644 --- a/src/Lower.cpp +++ b/src/Lower.cpp @@ -559,7 +559,14 @@ void lower_impl(const vector &output_funcs, if (t.has_gpu_feature()) { debug(1) << "Offloading GPU loops...\n"; - s = inject_gpu_offload(s, t, any_strict_float, env); + // The html outputs show which line of the conceptual stmt, which + // still has the code of the kernels, each line of device code came + // from. + StmtSourceMap conceptual_source = print_with_source_map(result_module.get_conceptual_stmt()); + conceptual_source.path = pipeline_name + ".conceptual.stmt"; + std::map> device_code_lines; + s = inject_gpu_offload(s, t, any_strict_float, env, &conceptual_source, &device_code_lines); + result_module.set_device_code_lines(std::move(device_code_lines)); debug(2) << "Lowering after splitting off GPU loops:\n" << s << "\n\n"; } else { diff --git a/src/Module.cpp b/src/Module.cpp index 9c4bfd0dc434..656211434d37 100644 --- a/src/Module.cpp +++ b/src/Module.cpp @@ -340,6 +340,10 @@ struct ModuleContents { * etc...). In other words, we'd like to keep this * conceptually relevant and human-readable. */ Stmt conceptual_code; + + /** Where the lines of the device code came from in conceptual_code, by + * the name of the Buffer that holds it. */ + std::map> device_code_lines; }; template<> @@ -582,6 +586,14 @@ const Internal::Stmt &Module::get_conceptual_stmt() const { return contents->conceptual_code; } +void Module::set_device_code_lines(std::map> lines) { + contents->device_code_lines = std::move(lines); +} + +const std::map> &Module::get_device_code_lines() const { + return contents->device_code_lines; +} + void Module::compile(const std::map &output_files) const { validate_outputs(output_files); diff --git a/src/Module.h b/src/Module.h index fbe0f4c9a9a1..45c5ed1978f5 100644 --- a/src/Module.h +++ b/src/Module.h @@ -161,6 +161,15 @@ struct AutoSchedulerResults; using MetadataNameMap = std::map; using RuntimeNamespaceMap = std::map; +namespace Internal { +/** Where code came from in a printing of IR (see StmtSourceMap): the 1-based + * line, and the IR node as its StmtSourceMap::Location::order. Either is 0 + * if unknown. */ +struct IRPosition { + uint32_t line = 0, node = 0; +}; +} // namespace Internal + /** A halide module. This represents IR containing lowered function * definitions and buffers. */ class Module { @@ -252,6 +261,14 @@ class Module { /** Get the remembered conceptual Stmt, remembered before device-specific offloading. */ const Internal::Stmt &get_conceptual_stmt() const; + + /** Remember, for the device code in the Buffer of each name: where in + * the conceptual Stmt, as it is printed, each of its lines came from. + * The html outputs link the two with this. */ + void set_device_code_lines(std::map> lines); + + /** Get the remembered lines of the device code. */ + const std::map> &get_device_code_lines() const; }; /** Link a set of modules together into one module. */ diff --git a/src/OffloadGPULoops.cpp b/src/OffloadGPULoops.cpp index feb0cb1dc57e..e724b91bcdc6 100644 --- a/src/OffloadGPULoops.cpp +++ b/src/OffloadGPULoops.cpp @@ -98,6 +98,8 @@ class InjectGpuOffload : public IRMutator { const Target ⌖ const std::map &env; + std::map> *device_code_lines; + Expr get_state_var(const string &name) { // Expr v = Variable::make(type_of(), name); state_needed[name] = true; @@ -272,8 +274,10 @@ class InjectGpuOffload : public IRMutator { public: InjectGpuOffload(const Target &target, bool any_strict_float, - const std::map &env) - : target(target), env(env) { + const std::map &env, + const StmtSourceMap *line_source, + std::map> *device_code_lines) + : target(target), env(env), device_code_lines(device_code_lines) { Target device_target = target; // For the GPU target we just want to pass the flags, to avoid the // generated kernel code unintentionally having any dependence on the @@ -301,6 +305,7 @@ class InjectGpuOffload : public IRMutator { for (auto &i : cgdev) { i.second->set_any_strict_float(any_strict_float); + i.second->line_source = line_source; } internal_assert(!cgdev.empty()) << "Requested unknown GPU target: " << target.to_string() << "\n"; @@ -328,6 +333,9 @@ class InjectGpuOffload : public IRMutator { debug(2) << "Generating init_kernels for " << api_unique_name << "\n"; vector kernel_src = i.second->compile_to_src(); Expr kernel_src_buf = make_buffer_ptr(kernel_src, api_unique_name + "_gpu_source_kernels"); + if (device_code_lines && !i.second->source_lines.empty()) { + (*device_code_lines)[api_unique_name + "_gpu_source_kernels"] = i.second->source_lines; + } string init_kernels_name = "halide_" + api_unique_name + "_initialize_kernels"; vector init_args = {state_ptr_var, kernel_src_buf, Expr((int)kernel_src.size())}; @@ -420,9 +428,11 @@ class FlattenAliasedAllocations : public IRMutator { } // namespace Stmt inject_gpu_offload(const Stmt &s, const Target &host_target, bool any_strict_float, - const std::map &env) { + const std::map &env, + const StmtSourceMap *line_source, + std::map> *device_code_lines) { Stmt flattened = FlattenAliasedAllocations()(s); - return InjectGpuOffload(host_target, any_strict_float, env).inject(flattened); + return InjectGpuOffload(host_target, any_strict_float, env, line_source, device_code_lines).inject(flattened); } } // namespace Internal diff --git a/src/OffloadGPULoops.h b/src/OffloadGPULoops.h index bdba3d4e3027..59f5ed15622a 100644 --- a/src/OffloadGPULoops.h +++ b/src/OffloadGPULoops.h @@ -19,10 +19,19 @@ struct Target; namespace Internal { +struct StmtSourceMap; +struct IRPosition; + /** Pull loops marked with GPU device APIs to a separate - * module, and call them through the appropriate host runtime module. */ + * module, and call them through the appropriate host runtime module. If + * line_source is set, a printing of s or of IR that s was lowered from, + * device_code_lines gets, for the device code in the Buffer of each name: + * where in line_source each of its lines came from. Device code generators + * that don't keep track of that have no entry. */ Stmt inject_gpu_offload(const Stmt &s, const Target &host_target, bool any_strict_float, - const std::map &env); + const std::map &env, + const StmtSourceMap *line_source = nullptr, + std::map> *device_code_lines = nullptr); } // namespace Internal } // namespace Halide diff --git a/src/StmtToHTML.cpp b/src/StmtToHTML.cpp index aacc010505ff..0e811c736f1f 100644 --- a/src/StmtToHTML.cpp +++ b/src/StmtToHTML.cpp @@ -96,12 +96,6 @@ struct AssemblyMap { std::vector stmt_nodes; }; -/** Where code came from in the stmt that is shown: its 1-based line, and its - * IR node as its StmtSourceMap::Location::order. Either is 0 if unknown. */ -struct IRPosition { - uint32_t line = 0, node = 0; -}; - // Writes the lines of the assembly worth showing to the stream, as the text // of a