[glsl] Add fuzzer for IR generator

Bug: 42251044
Change-Id: I71f90c9259d56da5dde969f4502a48e018f36efa
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/210056
Reviewed-by: dan sinclair <dsinclair@chromium.org>
Commit-Queue: James Price <jrprice@google.com>
diff --git a/src/tint/lang/glsl/writer/BUILD.cmake b/src/tint/lang/glsl/writer/BUILD.cmake
index 3b5925e..2252f6e 100644
--- a/src/tint/lang/glsl/writer/BUILD.cmake
+++ b/src/tint/lang/glsl/writer/BUILD.cmake
@@ -234,12 +234,15 @@
 # Condition: TINT_BUILD_GLSL_WRITER
 ################################################################################
 tint_add_target(tint_lang_glsl_writer_fuzz fuzz
+  lang/glsl/writer/writer_fuzz.cc
 )
 
 tint_target_add_dependencies(tint_lang_glsl_writer_fuzz fuzz
   tint_api_common
+  tint_cmd_fuzz_ir_fuzz
   tint_lang_core
   tint_lang_core_constant
+  tint_lang_core_ir
   tint_lang_core_type
   tint_lang_wgsl
   tint_lang_wgsl_ast
@@ -272,6 +275,7 @@
   tint_target_add_dependencies(tint_lang_glsl_writer_fuzz fuzz
     tint_lang_glsl_writer
     tint_lang_glsl_writer_common
+    tint_lang_glsl_writer_helpers
   )
 endif(TINT_BUILD_GLSL_WRITER)
 
diff --git a/src/tint/lang/glsl/writer/BUILD.gn b/src/tint/lang/glsl/writer/BUILD.gn
index fd304f2..b947965 100644
--- a/src/tint/lang/glsl/writer/BUILD.gn
+++ b/src/tint/lang/glsl/writer/BUILD.gn
@@ -204,12 +204,14 @@
 }
 if (tint_build_glsl_writer) {
   tint_fuzz_source_set("fuzz") {
-    sources = []
+    sources = [ "writer_fuzz.cc" ]
     deps = [
       "${dawn_root}/src/utils:utils",
       "${tint_src_dir}/api/common",
+      "${tint_src_dir}/cmd/fuzz/ir:fuzz",
       "${tint_src_dir}/lang/core",
       "${tint_src_dir}/lang/core/constant",
+      "${tint_src_dir}/lang/core/ir",
       "${tint_src_dir}/lang/core/type",
       "${tint_src_dir}/lang/wgsl",
       "${tint_src_dir}/lang/wgsl/ast",
@@ -238,6 +240,7 @@
       deps += [
         "${tint_src_dir}/lang/glsl/writer",
         "${tint_src_dir}/lang/glsl/writer/common",
+        "${tint_src_dir}/lang/glsl/writer/helpers",
       ]
     }
 
diff --git a/src/tint/lang/glsl/writer/helpers/BUILD.bazel b/src/tint/lang/glsl/writer/helpers/BUILD.bazel
index a5586e7..3468341 100644
--- a/src/tint/lang/glsl/writer/helpers/BUILD.bazel
+++ b/src/tint/lang/glsl/writer/helpers/BUILD.bazel
@@ -48,6 +48,7 @@
     "//src/tint/api/common",
     "//src/tint/lang/core",
     "//src/tint/lang/core/constant",
+    "//src/tint/lang/core/ir",
     "//src/tint/lang/core/type",
     "//src/tint/lang/wgsl",
     "//src/tint/lang/wgsl/ast",
diff --git a/src/tint/lang/glsl/writer/helpers/BUILD.cmake b/src/tint/lang/glsl/writer/helpers/BUILD.cmake
index c59c877..af47736 100644
--- a/src/tint/lang/glsl/writer/helpers/BUILD.cmake
+++ b/src/tint/lang/glsl/writer/helpers/BUILD.cmake
@@ -49,6 +49,7 @@
   tint_api_common
   tint_lang_core
   tint_lang_core_constant
+  tint_lang_core_ir
   tint_lang_core_type
   tint_lang_wgsl
   tint_lang_wgsl_ast
diff --git a/src/tint/lang/glsl/writer/helpers/BUILD.gn b/src/tint/lang/glsl/writer/helpers/BUILD.gn
index 93ecb1c..9a46e1a 100644
--- a/src/tint/lang/glsl/writer/helpers/BUILD.gn
+++ b/src/tint/lang/glsl/writer/helpers/BUILD.gn
@@ -49,6 +49,7 @@
       "${tint_src_dir}/api/common",
       "${tint_src_dir}/lang/core",
       "${tint_src_dir}/lang/core/constant",
+      "${tint_src_dir}/lang/core/ir",
       "${tint_src_dir}/lang/core/type",
       "${tint_src_dir}/lang/wgsl",
       "${tint_src_dir}/lang/wgsl/ast",
diff --git a/src/tint/lang/glsl/writer/helpers/generate_bindings.cc b/src/tint/lang/glsl/writer/helpers/generate_bindings.cc
index e5f9243..de61077 100644
--- a/src/tint/lang/glsl/writer/helpers/generate_bindings.cc
+++ b/src/tint/lang/glsl/writer/helpers/generate_bindings.cc
@@ -31,7 +31,10 @@
 #include <unordered_set>
 
 #include "src/tint/api/common/binding_point.h"
+#include "src/tint/lang/core/ir/module.h"
+#include "src/tint/lang/core/ir/var.h"
 #include "src/tint/lang/core/type/external_texture.h"
+#include "src/tint/lang/core/type/pointer.h"
 #include "src/tint/lang/core/type/storage_texture.h"
 #include "src/tint/lang/glsl/writer/common/options.h"
 #include "src/tint/lang/wgsl/ast/module.h"
@@ -41,6 +44,78 @@
 
 namespace tint::glsl::writer {
 
+Bindings GenerateBindings(const core::ir::Module& module) {
+    Bindings bindings{};
+
+    std::unordered_set<tint::BindingPoint> seen_binding_points;
+
+    // Collect next valid binding number per group
+    Hashmap<uint32_t, uint32_t, 4> group_to_next_binding_number;
+    Vector<tint::BindingPoint, 4> ext_tex_bps;
+    for (auto* inst : *module.root_block) {
+        auto* var = inst->As<core::ir::Var>();
+        if (auto bp = var->BindingPoint()) {
+            if (auto val = group_to_next_binding_number.Get(bp->group)) {
+                *val = std::max(*val, bp->binding + 1);
+            } else {
+                group_to_next_binding_number.Add(bp->group, bp->binding + 1);
+            }
+
+            auto* ptr_type = var->Result(0)->Type()->As<core::type::Pointer>();
+
+            // Store up the external textures, we'll add them in the next step
+            if (ptr_type->StoreType()->Is<core::type::ExternalTexture>()) {
+                ext_tex_bps.Push(*bp);
+                continue;
+            }
+
+            binding::BindingInfo info{bp->binding};
+            switch (ptr_type->AddressSpace()) {
+                case core::AddressSpace::kHandle:
+                    Switch(
+                        ptr_type->StoreType(),  //
+                        [&](const core::type::Sampler*) { bindings.sampler.emplace(*bp, info); },
+                        [&](const core::type::StorageTexture*) {
+                            bindings.storage_texture.emplace(*bp, info);
+                        },
+                        [&](const core::type::Texture*) { bindings.texture.emplace(*bp, info); });
+                    break;
+                case core::AddressSpace::kStorage:
+                    bindings.storage.emplace(*bp, info);
+                    break;
+                case core::AddressSpace::kUniform:
+                    bindings.uniform.emplace(*bp, info);
+                    break;
+
+                case core::AddressSpace::kUndefined:
+                case core::AddressSpace::kPixelLocal:
+                case core::AddressSpace::kPrivate:
+                case core::AddressSpace::kPushConstant:
+                case core::AddressSpace::kIn:
+                case core::AddressSpace::kOut:
+                case core::AddressSpace::kFunction:
+                case core::AddressSpace::kWorkgroup:
+                    break;
+            }
+        }
+    }
+
+    for (auto bp : ext_tex_bps) {
+        uint32_t g = bp.group;
+        uint32_t& next_num = group_to_next_binding_number.GetOrAddZero(g);
+
+        binding::BindingInfo plane0{bp.binding};
+        binding::BindingInfo plane1{next_num++};
+        binding::BindingInfo metadata{next_num++};
+
+        group_to_next_binding_number.Replace(g, next_num);
+
+        bindings.external_texture.emplace(bp, binding::ExternalTexture{metadata, plane0, plane1});
+    }
+
+    return bindings;
+}
+
 Bindings GenerateBindings(const Program& program) {
     // TODO(tint:1491): Use Inspector once we can get binding info for all
     // variables, not just those referenced by entry points.
diff --git a/src/tint/lang/glsl/writer/helpers/generate_bindings.h b/src/tint/lang/glsl/writer/helpers/generate_bindings.h
index a648b06..28e299c 100644
--- a/src/tint/lang/glsl/writer/helpers/generate_bindings.h
+++ b/src/tint/lang/glsl/writer/helpers/generate_bindings.h
@@ -34,10 +34,18 @@
 namespace tint {
 class Program;
 }
+namespace tint::core::ir {
+class Module;
+}  // namespace tint::core::ir
 
 namespace tint::glsl::writer {
 
 /// Generate the resource bindings
+/// @param module the module to generate from
+/// @returns the bindings
+Bindings GenerateBindings(const core::ir::Module& module);
+
+/// Generate the resource bindings
 /// @param program the program to generate from
 /// @returns the bindings
 Bindings GenerateBindings(const Program& program);
diff --git a/src/tint/lang/glsl/writer/writer_fuzz.cc b/src/tint/lang/glsl/writer/writer_fuzz.cc
new file mode 100644
index 0000000..89c2dfa
--- /dev/null
+++ b/src/tint/lang/glsl/writer/writer_fuzz.cc
@@ -0,0 +1,141 @@
+// Copyright 2024 The Dawn & Tint Authors
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this
+//    list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+//    this list of conditions and the following disclaimer in the documentation
+//    and/or other materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its
+//    contributors may be used to endorse or promote products derived from
+//    this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "src/tint/cmd/fuzz/ir/fuzz.h"
+#include "src/tint/lang/core/ir/module.h"
+#include "src/tint/lang/core/ir/var.h"
+#include "src/tint/lang/core/type/input_attachment.h"
+#include "src/tint/lang/core/type/pointer.h"
+#include "src/tint/lang/glsl/writer/helpers/generate_bindings.h"
+#include "src/tint/lang/glsl/writer/writer.h"
+
+namespace tint::glsl::writer {
+namespace {
+
+bool CanRun(const core::ir::Module& module, Options& options) {
+    // Make sure that every texture variable is in the texture_builtins_from_uniform binding list,
+    // otherwise TextureBuiltinsFromUniform will fail.
+    // Also make sure there is at most one user-declared push_constant, and make a note of its size.
+    uint32_t user_push_constant_size = 0;
+    for (auto* inst : *module.root_block) {
+        auto* var = inst->As<core::ir::Var>();
+
+        if (!var) {
+            continue;
+        }
+        auto* ptr = var->Result(0)->Type()->As<core::type::Pointer>();
+
+        if (ptr->StoreType()->Is<core::type::Texture>()) {
+            bool found = false;
+            auto binding_point = var->BindingPoint();
+            for (auto& bp :
+                 options.bindings.texture_builtins_from_uniform.ubo_bindingpoint_ordering) {
+                if (bp == binding_point) {
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) {
+                return false;
+            }
+        }
+
+        if (ptr->AddressSpace() == core::AddressSpace::kPushConstant) {
+            if (user_push_constant_size > 0) {
+                // We've already seen a user-declared push constant.
+                return false;
+            }
+            user_push_constant_size = tint::RoundUp(4u, ptr->StoreType()->Size());
+        }
+    }
+
+    static constexpr uint32_t kMaxOffset = 0x1000;
+    Hashset<uint32_t, 4> push_constant_word_offsets;
+    auto check_push_constant_offset = [&](uint32_t offset) {
+        // Excessive values can cause OOM / timeouts when padding structures in the printer.
+        if (offset > kMaxOffset) {
+            return false;
+        }
+        // Offset must be 4-byte aligned.
+        if (offset & 0x3) {
+            return false;
+        }
+        // Offset must not have already been used.
+        if (!push_constant_word_offsets.Add(offset >> 2)) {
+            return false;
+        }
+        // Offset must be after the user-defined push constants.
+        if (offset < user_push_constant_size) {
+            return false;
+        }
+        return true;
+    };
+
+    if (options.first_instance_offset &&
+        !check_push_constant_offset(*options.first_instance_offset)) {
+        return false;
+    }
+
+    if (options.first_vertex_offset && !check_push_constant_offset(*options.first_vertex_offset)) {
+        return false;
+    }
+
+    if (options.depth_range_offsets) {
+        if (!check_push_constant_offset(options.depth_range_offsets->max) ||
+            !check_push_constant_offset(options.depth_range_offsets->min)) {
+            return false;
+        }
+    }
+
+    // Make sure that there is at most one entry point.
+    bool has_entry_point = false;
+    for (auto& func : module.functions) {
+        if (func->Stage() != core::ir::Function::PipelineStage::kUndefined) {
+            if (has_entry_point) {
+                return false;
+            }
+            has_entry_point = true;
+        }
+    }
+
+    return true;
+}
+
+void IRFuzzer(core::ir::Module& module, Options options) {
+    if (!CanRun(module, options)) {
+        return;
+    }
+
+    options.bindings = GenerateBindings(module);
+
+    [[maybe_unused]] auto output = Generate(module, options, "");
+}
+
+}  // namespace
+}  // namespace tint::glsl::writer
+
+TINT_IR_MODULE_FUZZER(tint::glsl::writer::IRFuzzer);