code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include "common/common_types.h"

namespace Shader::Backend {

struct Bindings {
    u32 unified{};
    u32 uniform_buffer{};
    u32 storage_buffer{};
    u32 texture{};
    u32 image{};
    u32 texture_scaling_index{};
    u32 image_scaling_index{};
};

} // namespace Shader::Backend


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <algorithm>
#include <string>
#include <tuple>

#include "common/div_ceil.h"
#include "common/settings.h"
#include "shader_recompiler/backend/bindings.h"
#include "shader_recompiler/backend/glasm/emit_glasm.h"
#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"
#include "shader_recompiler/frontend/ir/ir_emitter.h"
#include "shader_recompiler/frontend/ir/program.h"
#include "shader_recompiler/profile.h"
#include "shader_recompiler/runtime_info.h"

namespace Shader::Backend::GLASM {
namespace {
template <class Func>
struct FuncTraits {};

template <class ReturnType_, class... Args>
struct FuncTraits<ReturnType_ (*)(Args...)> {
    using ReturnType = ReturnType_;

    static constexpr size_t NUM_ARGS = sizeof...(Args);

    template <size_t I>
    using ArgType = std::tuple_element_t<I, std::tuple<Args...>>;
};

template <typename T>
struct Identity {
    Identity(T data_) : data{data_} {}

    T Extract() {
        return data;
    }

    T data;
};

template <bool scalar>
class RegWrapper {
public:
    RegWrapper(EmitContext& ctx, const IR::Value& ir_value) : reg_alloc{ctx.reg_alloc} {
        const Value value{reg_alloc.Peek(ir_value)};
        if (value.type == Type::Register) {
            inst = ir_value.InstRecursive();
            reg = Register{value};
        } else {
            reg = value.type == Type::U64 ? reg_alloc.AllocLongReg() : reg_alloc.AllocReg();
        }
        switch (value.type) {
        case Type::Register:
        case Type::Void:
            break;
        case Type::U32:
            ctx.Add("MOV.U {}.x,{};", reg, value.imm_u32);
            break;
        case Type::U64:
            ctx.Add("MOV.U64 {}.x,{};", reg, value.imm_u64);
            break;
        }
    }

    auto Extract() {
        if (inst) {
            reg_alloc.Unref(*inst);
        } else {
            reg_alloc.FreeReg(reg);
        }
        return std::conditional_t<scalar, ScalarRegister, Register>{Value{reg}};
    }

private:
    RegAlloc& reg_alloc;
    IR::Inst* inst{};
    Register reg{};
};

template <typename ArgType>
class ValueWrapper {
public:
    ValueWrapper(EmitContext& ctx, const IR::Value& ir_value_)
        : reg_alloc{ctx.reg_alloc}, ir_value{ir_value_}, value{reg_alloc.Peek(ir_value)} {}

    ArgType Extract() {
        if (!ir_value.IsImmediate()) {
            reg_alloc.Unref(*ir_value.InstRecursive());
        }
        return value;
    }

private:
    RegAlloc& reg_alloc;
    const IR::Value& ir_value;
    ArgType value;
};

template <typename ArgType>
auto Arg(EmitContext& ctx, const IR::Value& arg) {
    if constexpr (std::is_same_v<ArgType, Register>) {
        return RegWrapper<false>{ctx, arg};
    } else if constexpr (std::is_same_v<ArgType, ScalarRegister>) {
        return RegWrapper<true>{ctx, arg};
    } else if constexpr (std::is_base_of_v<Value, ArgType>) {
        return ValueWrapper<ArgType>{ctx, arg};
    } else if constexpr (std::is_same_v<ArgType, const IR::Value&>) {
        return Identity<const IR::Value&>{arg};
    } else if constexpr (std::is_same_v<ArgType, u32>) {
        return Identity{arg.U32()};
    } else if constexpr (std::is_same_v<ArgType, IR::Attribute>) {
        return Identity{arg.Attribute()};
    } else if constexpr (std::is_same_v<ArgType, IR::Patch>) {
        return Identity{arg.Patch()};
    } else if constexpr (std::is_same_v<ArgType, IR::Reg>) {
        return Identity{arg.Reg()};
    }
}

template <auto func, bool is_first_arg_inst>
struct InvokeCall {
    template <typename... Args>
    InvokeCall(EmitContext& ctx, IR::Inst* inst, Args&&... args) {
        if constexpr (is_first_arg_inst) {
            func(ctx, *inst, args.Extract()...);
        } else {
            func(ctx, args.Extract()...);
        }
    }
};

template <auto func, bool is_first_arg_inst, size_t... I>
void Invoke(EmitContext& ctx, IR::Inst* inst, std::index_sequence<I...>) {
    using Traits = FuncTraits<decltype(func)>;
    if constexpr (is_first_arg_inst) {
        InvokeCall<func, is_first_arg_inst>{
            ctx, inst, Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...};
    } else {
        InvokeCall<func, is_first_arg_inst>{
            ctx, inst, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...};
    }
}

template <auto func>
void Invoke(EmitContext& ctx, IR::Inst* inst) {
    using Traits = FuncTraits<decltype(func)>;
    static_assert(Traits::NUM_ARGS >= 1, "Insufficient arguments");
    if constexpr (Traits::NUM_ARGS == 1) {
        Invoke<func, false>(ctx, inst, std::make_index_sequence<0>{});
    } else {
        using FirstArgType = typename Traits::template ArgType<1>;
        static constexpr bool is_first_arg_inst = std::is_same_v<FirstArgType, IR::Inst&>;
        using Indices = std::make_index_sequence<Traits::NUM_ARGS - (is_first_arg_inst ? 2 : 1)>;
        Invoke<func, is_first_arg_inst>(ctx, inst, Indices{});
    }
}

void EmitInst(EmitContext& ctx, IR::Inst* inst) {
    switch (inst->GetOpcode()) {
#define OPCODE(name, result_type, ...)                                                             \
    case IR::Opcode::name:                                                                         \
        return Invoke<&Emit##name>(ctx, inst);
#include "shader_recompiler/frontend/ir/opcodes.inc"
#undef OPCODE
    }
    throw LogicError("Invalid opcode {}", inst->GetOpcode());
}

bool IsReference(IR::Inst& inst) {
    return inst.GetOpcode() == IR::Opcode::Reference;
}

void PrecolorInst(IR::Inst& phi) {
    // Insert phi moves before references to avoid overwriting other phis
    const size_t num_args{phi.NumArgs()};
    for (size_t i = 0; i < num_args; ++i) {
        IR::Block& phi_block{*phi.PhiBlock(i)};
        auto it{std::find_if_not(phi_block.rbegin(), phi_block.rend(), IsReference).base()};
        IR::IREmitter ir{phi_block, it};
        const IR::Value arg{phi.Arg(i)};
        if (arg.IsImmediate()) {
            ir.PhiMove(phi, arg);
        } else {
            ir.PhiMove(phi, IR::Value{&RegAlloc::AliasInst(*arg.Inst())});
        }
    }
    for (size_t i = 0; i < num_args; ++i) {
        IR::IREmitter{*phi.PhiBlock(i)}.Reference(IR::Value{&phi});
    }
}

void Precolor(const IR::Program& program) {
    for (IR::Block* const block : program.blocks) {
        for (IR::Inst& phi : block->Instructions()) {
            if (!IR::IsPhi(phi)) {
                break;
            }
            PrecolorInst(phi);
        }
    }
}

void EmitCode(EmitContext& ctx, const IR::Program& program) {
    const auto eval{
        [&](const IR::U1& cond) { return ScalarS32{ctx.reg_alloc.Consume(IR::Value{cond})}; }};
    for (const IR::AbstractSyntaxNode& node : program.syntax_list) {
        switch (node.type) {
        case IR::AbstractSyntaxNode::Type::Block:
            for (IR::Inst& inst : node.data.block->Instructions()) {
                EmitInst(ctx, &inst);
            }
            break;
        case IR::AbstractSyntaxNode::Type::If:
            ctx.Add("MOV.S.CC RC,{};"
                    "IF NE.x;",
                    eval(node.data.if_node.cond));
            break;
        case IR::AbstractSyntaxNode::Type::EndIf:
            ctx.Add("ENDIF;");
            break;
        case IR::AbstractSyntaxNode::Type::Loop:
            ctx.Add("REP;");
            break;
        case IR::AbstractSyntaxNode::Type::Repeat:
            if (!Settings::values.disable_shader_loop_safety_checks) {
                const u32 loop_index{ctx.num_safety_loop_vars++};
                const u32 vector_index{loop_index / 4};
                const char component{"xyzw"[loop_index % 4]};
                ctx.Add("SUB.S.CC loop{}.{},loop{}.{},1;"
                        "BRK(LT.{});",
                        vector_index, component, vector_index, component, component);
            }
            if (node.data.repeat.cond.IsImmediate()) {
                if (node.data.repeat.cond.U1()) {
                    ctx.Add("ENDREP;");
                } else {
                    ctx.Add("BRK;"
                            "ENDREP;");
                }
            } else {
                ctx.Add("MOV.S.CC RC,{};"
                        "BRK(EQ.x);"
                        "ENDREP;",
                        eval(node.data.repeat.cond));
            }
            break;
        case IR::AbstractSyntaxNode::Type::Break:
            if (node.data.break_node.cond.IsImmediate()) {
                if (node.data.break_node.cond.U1()) {
                    ctx.Add("BRK;");
                }
            } else {
                ctx.Add("MOV.S.CC RC,{};"
                        "BRK (NE.x);",
                        eval(node.data.break_node.cond));
            }
            break;
        case IR::AbstractSyntaxNode::Type::Return:
        case IR::AbstractSyntaxNode::Type::Unreachable:
            ctx.Add("RET;");
            break;
        }
    }
    if (!ctx.reg_alloc.IsEmpty()) {
        LOG_WARNING(Shader_GLASM, "Register leak after generating code");
    }
}

void SetupOptions(const IR::Program& program, const Profile& profile,
                  const RuntimeInfo& runtime_info, std::string& header) {
    const Info& info{program.info};
    const Stage stage{program.stage};

    // TODO: Track the shared atomic ops
    header += "OPTION NV_internal;"
              "OPTION NV_shader_storage_buffer;"
              "OPTION NV_gpu_program_fp64;";
    // TODO: Enable only when MS is used
    header += "OPTION NV_texture_multisample;";
    if (info.uses_int64_bit_atomics) {
        header += "OPTION NV_shader_atomic_int64;";
    }
    if (info.uses_atomic_f32_add) {
        header += "OPTION NV_shader_atomic_float;";
    }
    if (info.uses_atomic_f16x2_add || info.uses_atomic_f16x2_min || info.uses_atomic_f16x2_max) {
        header += "OPTION NV_shader_atomic_fp16_vector;";
    }
    if (info.uses_subgroup_invocation_id || info.uses_subgroup_mask || info.uses_subgroup_vote ||
        info.uses_fswzadd) {
        header += "OPTION NV_shader_thread_group;";
    }
    if (info.uses_subgroup_shuffles) {
        header += "OPTION NV_shader_thread_shuffle;";
    }
    if (info.uses_sparse_residency) {
        header += "OPTION EXT_sparse_texture2;";
    }
    const bool stores_viewport_layer{info.stores[IR::Attribute::ViewportIndex] ||
                                     info.stores[IR::Attribute::Layer]};
    if ((stage != Stage::Geometry && stores_viewport_layer) ||
        info.stores[IR::Attribute::ViewportMask]) {
        if (profile.support_viewport_index_layer_non_geometry) {
            header += "OPTION NV_viewport_array2;";
        }
    }
    if (program.is_geometry_passthrough && profile.support_geometry_shader_passthrough) {
        header += "OPTION NV_geometry_shader_passthrough;";
    }
    if (info.uses_typeless_image_reads && profile.support_typeless_image_loads) {
        header += "OPTION EXT_shader_image_load_formatted;";
    }
    if (profile.support_derivative_control) {
        header += "OPTION ARB_derivative_control;";
    }
    if (stage == Stage::Fragment && runtime_info.force_early_z != 0) {
        header += "OPTION NV_early_fragment_tests;";
    }
    if (stage == Stage::Fragment) {
        header += "OPTION ARB_draw_buffers;";
        header += "OPTION ARB_fragment_layer_viewport;";
    }
}

std::string_view StageHeader(Stage stage) {
    switch (stage) {
    case Stage::VertexA:
    case Stage::VertexB:
        return "!!NVvp5.0\n";
    case Stage::TessellationControl:
        return "!!NVtcp5.0\n";
    case Stage::TessellationEval:
        return "!!NVtep5.0\n";
    case Stage::Geometry:
        return "!!NVgp5.0\n";
    case Stage::Fragment:
        return "!!NVfp5.0\n";
    case Stage::Compute:
        return "!!NVcp5.0\n";
    }
    throw InvalidArgument("Invalid stage {}", stage);
}

std::string_view InputPrimitive(InputTopology topology) {
    switch (topology) {
    case InputTopology::Points:
        return "POINTS";
    case InputTopology::Lines:
        return "LINES";
    case InputTopology::LinesAdjacency:
        return "LINES_ADJACENCY";
    case InputTopology::Triangles:
        return "TRIANGLES";
    case InputTopology::TrianglesAdjacency:
        return "TRIANGLES_ADJACENCY";
    }
    throw InvalidArgument("Invalid input topology {}", topology);
}

std::string_view OutputPrimitive(OutputTopology topology) {
    switch (topology) {
    case OutputTopology::PointList:
        return "POINTS";
    case OutputTopology::LineStrip:
        return "LINE_STRIP";
    case OutputTopology::TriangleStrip:
        return "TRIANGLE_STRIP";
    }
    throw InvalidArgument("Invalid output topology {}", topology);
}

std::string_view GetTessMode(TessPrimitive primitive) {
    switch (primitive) {
    case TessPrimitive::Triangles:
        return "TRIANGLES";
    case TessPrimitive::Quads:
        return "QUADS";
    case TessPrimitive::Isolines:
        return "ISOLINES";
    }
    throw InvalidArgument("Invalid tessellation primitive {}", primitive);
}

std::string_view GetTessSpacing(TessSpacing spacing) {
    switch (spacing) {
    case TessSpacing::Equal:
        return "EQUAL";
    case TessSpacing::FractionalOdd:
        return "FRACTIONAL_ODD";
    case TessSpacing::FractionalEven:
        return "FRACTIONAL_EVEN";
    }
    throw InvalidArgument("Invalid tessellation spacing {}", spacing);
}
} // Anonymous namespace

std::string EmitGLASM(const Profile& profile, const RuntimeInfo& runtime_info, IR::Program& program,
                      Bindings& bindings) {
    EmitContext ctx{program, bindings, profile, runtime_info};
    Precolor(program);
    EmitCode(ctx, program);
    std::string header{StageHeader(program.stage)};
    SetupOptions(program, profile, runtime_info, header);
    switch (program.stage) {
    case Stage::TessellationControl:
        header += fmt::format("VERTICES_OUT {};", program.invocations);
        break;
    case Stage::TessellationEval:
        header += fmt::format("TESS_MODE {};"
                              "TESS_SPACING {};"
                              "TESS_VERTEX_ORDER {};",
                              GetTessMode(runtime_info.tess_primitive),
                              GetTessSpacing(runtime_info.tess_spacing),
                              runtime_info.tess_clockwise ? "CW" : "CCW");
        break;
    case Stage::Geometry:
        header += fmt::format("PRIMITIVE_IN {};", InputPrimitive(runtime_info.input_topology));
        if (program.is_geometry_passthrough) {
            if (profile.support_geometry_shader_passthrough) {
                for (size_t index = 0; index < IR::NUM_GENERICS; ++index) {
                    if (program.info.passthrough.Generic(index)) {
                        header += fmt::format("PASSTHROUGH result.attrib[{}];", index);
                    }
                }
                if (program.info.passthrough.AnyComponent(IR::Attribute::PositionX)) {
                    header += "PASSTHROUGH result.position;";
                }
            } else {
                LOG_WARNING(Shader_GLASM, "Passthrough geometry program used but not supported");
            }
        } else {
            header +=
                fmt::format("VERTICES_OUT {};"
                            "PRIMITIVE_OUT {};",
                            program.output_vertices, OutputPrimitive(program.output_topology));
        }
        break;
    case Stage::Compute:
        header += fmt::format("GROUP_SIZE {} {} {};", program.workgroup_size[0],
                              program.workgroup_size[1], program.workgroup_size[2]);
        break;
    default:
        break;
    }
    if (program.shared_memory_size > 0) {
        header += fmt::format("SHARED_MEMORY {};", program.shared_memory_size);
        header += fmt::format("SHARED shared_mem[]={{program.sharedmem}};");
    }
    if (program.info.uses_rescaling_uniform) {
        header += "PARAM scaling[1]={program.local[0..0]};";
    }
    if (program.info.uses_render_area) {
        header += "PARAM render_area[1]={program.local[1..1]};";
    }
    header += "TEMP ";
    for (size_t index = 0; index < ctx.reg_alloc.NumUsedRegisters(); ++index) {
        header += fmt::format("R{},", index);
    }
    if (program.local_memory_size > 0) {
        header += fmt::format("lmem[{}],", Common::DivCeil(program.local_memory_size, 4U));
    }
    if (program.info.uses_fswzadd) {
        header += "FSWZA[4],FSWZB[4],";
    }
    const u32 num_safety_loop_vectors{Common::DivCeil(ctx.num_safety_loop_vars, 4u)};
    for (u32 index = 0; index < num_safety_loop_vectors; ++index) {
        header += fmt::format("loop{},", index);
    }
    header += "RC;"
              "LONG TEMP ";
    for (size_t index = 0; index < ctx.reg_alloc.NumUsedLongRegisters(); ++index) {
        header += fmt::format("D{},", index);
    }
    header += "DC;";
    if (program.info.uses_fswzadd) {
        header += "MOV.F FSWZA[0],-1;"
                  "MOV.F FSWZA[1],1;"
                  "MOV.F FSWZA[2],-1;"
                  "MOV.F FSWZA[3],0;"
                  "MOV.F FSWZB[0],-1;"
                  "MOV.F FSWZB[1],-1;"
                  "MOV.F FSWZB[2],1;"
                  "MOV.F FSWZB[3],-1;";
    }
    for (u32 index = 0; index < num_safety_loop_vectors; ++index) {
        header += fmt::format("MOV.S loop{},{{0x2000,0x2000,0x2000,0x2000}};", index);
    }
    if (ctx.uses_y_direction) {
        header += "PARAM y_direction[1]={state.material.front.ambient};";
    }
    ctx.code.insert(0, header);
    ctx.code += "END";
    return ctx.code;
}

} // namespace Shader::Backend::GLASM

repo_name: litucks/torzu

license: mit


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <string>

#include "shader_recompiler/backend/bindings.h"
#include "shader_recompiler/frontend/ir/program.h"
#include "shader_recompiler/profile.h"
#include "shader_recompiler/runtime_info.h"

namespace Shader::Backend::GLASM {

constexpr u32 PROGRAM_LOCAL_PARAMETER_STORAGE_BUFFER_BASE = 1;

[[nodiscard]] std::string EmitGLASM(const Profile& profile, const RuntimeInfo& runtime_info,
                                    IR::Program& program, Bindings& bindings);

[[nodiscard]] inline std::string EmitGLASM(const Profile& profile, const RuntimeInfo& runtime_info,
                                           IR::Program& program) {
    Bindings binding;
    return EmitGLASM(profile, runtime_info, program, binding);
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"

namespace Shader::Backend::GLASM {

void EmitBarrier(EmitContext& ctx) {
    ctx.Add("BAR;");
}

void EmitWorkgroupMemoryBarrier(EmitContext& ctx) {
    ctx.Add("MEMBAR.CTA;");
}

void EmitDeviceMemoryBarrier(EmitContext& ctx) {
    ctx.Add("MEMBAR;");
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"
#include "shader_recompiler/frontend/ir/value.h"

namespace Shader::Backend::GLASM {

static void Alias(IR::Inst& inst, const IR::Value& value) {
    if (value.IsImmediate()) {
        return;
    }
    IR::Inst& value_inst{RegAlloc::AliasInst(*value.Inst())};
    value_inst.DestructiveAddUsage(inst.UseCount());
    value_inst.DestructiveRemoveUsage();
    inst.SetDefinition(value_inst.Definition<Id>());
}

void EmitIdentity(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitConditionRef(EmitContext& ctx, IR::Inst& inst, const IR::Value& value) {
    // Fake one usage to get a real register out of the condition
    inst.DestructiveAddUsage(1);
    const Register ret{ctx.reg_alloc.Define(inst)};
    const ScalarS32 input{ctx.reg_alloc.Consume(value)};
    if (ret != input) {
        ctx.Add("MOV.S {},{};", ret, input);
    }
}

void EmitBitCastU16F16(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitBitCastU32F32(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitBitCastU64F64(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitBitCastF16U16(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitBitCastF32U32(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitBitCastF64U64(EmitContext&, IR::Inst& inst, const IR::Value& value) {
    Alias(inst, value);
}

void EmitPackUint2x32(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.LongAdd("PK64.U {}.x,{};", inst, value);
}

void EmitUnpackUint2x32(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.Add("UP64.U {}.xy,{}.x;", inst, value);
}

void EmitPackFloat2x16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitUnpackFloat2x16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitPackHalf2x16(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.Add("PK2H {}.x,{};", inst, value);
}

void EmitUnpackHalf2x16(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.Add("UP2H {}.xy,{}.x;", inst, value);
}

void EmitPackDouble2x32(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.LongAdd("PK64 {}.x,{};", inst, value);
}

void EmitUnpackDouble2x32(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.Add("UP64 {}.xy,{}.x;", inst, value);
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"
#include "shader_recompiler/frontend/ir/value.h"

namespace Shader::Backend::GLASM {
namespace {
template <auto read_imm, char type, typename... Values>
void CompositeConstruct(EmitContext& ctx, IR::Inst& inst, Values&&... elements) {
    const Register ret{ctx.reg_alloc.Define(inst)};
    if (std::ranges::any_of(std::array{elements...},
                            [](const IR::Value& value) { return value.IsImmediate(); })) {
        using Type = std::invoke_result_t<decltype(read_imm), IR::Value>;
        const std::array<Type, 4> values{(elements.IsImmediate() ? (elements.*read_imm)() : 0)...};
        ctx.Add("MOV.{} {},{{{},{},{},{}}};", type, ret, fmt::to_string(values[0]),
                fmt::to_string(values[1]), fmt::to_string(values[2]), fmt::to_string(values[3]));
    }
    size_t index{};
    for (const IR::Value& element : {elements...}) {
        if (!element.IsImmediate()) {
            const ScalarU32 value{ctx.reg_alloc.Consume(element)};
            ctx.Add("MOV.{} {}.{},{};", type, ret, "xyzw"[index], value);
        }
        ++index;
    }
}

void CompositeExtract(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index, char type) {
    const Register ret{ctx.reg_alloc.Define(inst)};
    if (ret == composite && index == 0) {
        // No need to do anything here, the source and destination are the same register
        return;
    }
    ctx.Add("MOV.{} {}.x,{}.{};", type, ret, composite, "xyzw"[index]);
}

template <typename ObjectType>
void CompositeInsert(EmitContext& ctx, IR::Inst& inst, Register composite, ObjectType object,
                     u32 index, char type) {
    const Register ret{ctx.reg_alloc.Define(inst)};
    const char swizzle{"xyzw"[index]};
    if (ret != composite && ret == object) {
        // The object is aliased with the return value, so we have to use a temporary to insert
        ctx.Add("MOV.{} RC,{};"
                "MOV.{} RC.{},{};"
                "MOV.{} {},RC;",
                type, composite, type, swizzle, object, type, ret);
    } else if (ret != composite) {
        // The input composite is not aliased with the return value so we have to copy it before
        // hand. But the insert object is not aliased with the return value, so we don't have to
        // worry about that
        ctx.Add("MOV.{} {},{};"
                "MOV.{} {}.{},{};",
                type, ret, composite, type, ret, swizzle, object);
    } else {
        // The return value is aliased so we can just insert the object, it doesn't matter if it's
        // aliased
        ctx.Add("MOV.{} {}.{},{};", type, ret, swizzle, object);
    }
}
} // Anonymous namespace

void EmitCompositeConstructU32x2(EmitContext& ctx, IR::Inst& inst, const IR::Value& e1,
                                 const IR::Value& e2) {
    CompositeConstruct<&IR::Value::U32, 'U'>(ctx, inst, e1, e2);
}

void EmitCompositeConstructU32x3(EmitContext& ctx, IR::Inst& inst, const IR::Value& e1,
                                 const IR::Value& e2, const IR::Value& e3) {
    CompositeConstruct<&IR::Value::U32, 'U'>(ctx, inst, e1, e2, e3);
}

void EmitCompositeConstructU32x4(EmitContext& ctx, IR::Inst& inst, const IR::Value& e1,
                                 const IR::Value& e2, const IR::Value& e3, const IR::Value& e4) {
    CompositeConstruct<&IR::Value::U32, 'U'>(ctx, inst, e1, e2, e3, e4);
}

void EmitCompositeExtractU32x2(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index) {
    CompositeExtract(ctx, inst, composite, index, 'U');
}

void EmitCompositeExtractU32x3(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index) {
    CompositeExtract(ctx, inst, composite, index, 'U');
}

void EmitCompositeExtractU32x4(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index) {
    CompositeExtract(ctx, inst, composite, index, 'U');
}

void EmitCompositeInsertU32x2([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite,
                              [[maybe_unused]] ScalarU32 object, [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertU32x3([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite,
                              [[maybe_unused]] ScalarU32 object, [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertU32x4([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite,
                              [[maybe_unused]] ScalarU32 object, [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeConstructF16x2([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register e1,
                                 [[maybe_unused]] Register e2) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeConstructF16x3([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register e1,
                                 [[maybe_unused]] Register e2, [[maybe_unused]] Register e3) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeConstructF16x4([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register e1,
                                 [[maybe_unused]] Register e2, [[maybe_unused]] Register e3,
                                 [[maybe_unused]] Register e4) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeExtractF16x2([[maybe_unused]] EmitContext& ctx,
                               [[maybe_unused]] Register composite, [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeExtractF16x3([[maybe_unused]] EmitContext& ctx,
                               [[maybe_unused]] Register composite, [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeExtractF16x4([[maybe_unused]] EmitContext& ctx,
                               [[maybe_unused]] Register composite, [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertF16x2([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite, [[maybe_unused]] Register object,
                              [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertF16x3([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite, [[maybe_unused]] Register object,
                              [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertF16x4([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite, [[maybe_unused]] Register object,
                              [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeConstructF32x2(EmitContext& ctx, IR::Inst& inst, const IR::Value& e1,
                                 const IR::Value& e2) {
    CompositeConstruct<&IR::Value::F32, 'F'>(ctx, inst, e1, e2);
}

void EmitCompositeConstructF32x3(EmitContext& ctx, IR::Inst& inst, const IR::Value& e1,
                                 const IR::Value& e2, const IR::Value& e3) {
    CompositeConstruct<&IR::Value::F32, 'F'>(ctx, inst, e1, e2, e3);
}

void EmitCompositeConstructF32x4(EmitContext& ctx, IR::Inst& inst, const IR::Value& e1,
                                 const IR::Value& e2, const IR::Value& e3, const IR::Value& e4) {
    CompositeConstruct<&IR::Value::F32, 'F'>(ctx, inst, e1, e2, e3, e4);
}

void EmitCompositeExtractF32x2(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index) {
    CompositeExtract(ctx, inst, composite, index, 'F');
}

void EmitCompositeExtractF32x3(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index) {
    CompositeExtract(ctx, inst, composite, index, 'F');
}

void EmitCompositeExtractF32x4(EmitContext& ctx, IR::Inst& inst, Register composite, u32 index) {
    CompositeExtract(ctx, inst, composite, index, 'F');
}

void EmitCompositeInsertF32x2(EmitContext& ctx, IR::Inst& inst, Register composite,
                              ScalarF32 object, u32 index) {
    CompositeInsert(ctx, inst, composite, object, index, 'F');
}

void EmitCompositeInsertF32x3(EmitContext& ctx, IR::Inst& inst, Register composite,
                              ScalarF32 object, u32 index) {
    CompositeInsert(ctx, inst, composite, object, index, 'F');
}

void EmitCompositeInsertF32x4(EmitContext& ctx, IR::Inst& inst, Register composite,
                              ScalarF32 object, u32 index) {
    CompositeInsert(ctx, inst, composite, object, index, 'F');
}

void EmitCompositeConstructF64x2([[maybe_unused]] EmitContext& ctx) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeConstructF64x3([[maybe_unused]] EmitContext& ctx) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeConstructF64x4([[maybe_unused]] EmitContext& ctx) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeExtractF64x2([[maybe_unused]] EmitContext& ctx) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeExtractF64x3([[maybe_unused]] EmitContext& ctx) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeExtractF64x4([[maybe_unused]] EmitContext& ctx) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertF64x2([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite, [[maybe_unused]] Register object,
                              [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertF64x3([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite, [[maybe_unused]] Register object,
                              [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

void EmitCompositeInsertF64x4([[maybe_unused]] EmitContext& ctx,
                              [[maybe_unused]] Register composite, [[maybe_unused]] Register object,
                              [[maybe_unused]] u32 index) {
    throw NotImplementedException("GLASM instruction");
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <string_view>

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"
#include "shader_recompiler/frontend/ir/value.h"
#include "shader_recompiler/profile.h"
#include "shader_recompiler/shader_info.h"

namespace Shader::Backend::GLASM {
namespace {
void GetCbuf(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset,
             std::string_view size) {
    const Register ret{ctx.reg_alloc.Define(inst)};
    if (offset.type == Type::U32) {
        // Avoid reading arrays out of bounds, matching hardware's behavior
        if (offset.imm_u32 >= 0x10'000) {
            ctx.Add("MOV.S {},0;", ret);
            return;
        }
    }

    if (binding.IsImmediate()) {
        ctx.Add("LDC.{} {},c{}[{}];", size, ret, binding.U32(), offset);
        return;
    }

    const ScalarU32 idx{ctx.reg_alloc.Consume(binding)};
    for (u32 i = 0; i < Info::MAX_INDIRECT_CBUFS; i++) {
        ctx.Add("SEQ.S.CC RC.x,{},{};"
                "IF NE.x;"
                "LDC.{} {},c{}[{}];",
                idx, i, size, ret, i, offset);

        if (i != Info::MAX_INDIRECT_CBUFS - 1) {
            ctx.Add("ELSE;");
        }
    }

    for (u32 i = 0; i < Info::MAX_INDIRECT_CBUFS; i++) {
        ctx.Add("ENDIF;");
    }
}

bool IsInputArray(Stage stage) {
    return stage == Stage::Geometry || stage == Stage::TessellationControl ||
           stage == Stage::TessellationEval;
}

std::string VertexIndex(EmitContext& ctx, ScalarU32 vertex) {
    return IsInputArray(ctx.stage) ? fmt::format("[{}]", vertex) : "";
}

u32 TexCoordIndex(IR::Attribute attr) {
    return (static_cast<u32>(attr) - static_cast<u32>(IR::Attribute::FixedFncTexture0S)) / 4;
}
} // Anonymous namespace

void EmitGetCbufU8(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "U8");
}

void EmitGetCbufS8(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "S8");
}

void EmitGetCbufU16(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "U16");
}

void EmitGetCbufS16(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "S16");
}

void EmitGetCbufU32(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "U32");
}

void EmitGetCbufF32(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding, ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "F32");
}

void EmitGetCbufU32x2(EmitContext& ctx, IR::Inst& inst, const IR::Value& binding,
                      ScalarU32 offset) {
    GetCbuf(ctx, inst, binding, offset, "U32X2");
}

void EmitGetAttribute(EmitContext& ctx, IR::Inst& inst, IR::Attribute attr, ScalarU32 vertex) {
    const u32 element{static_cast<u32>(attr) % 4};
    const char swizzle{"xyzw"[element]};
    if (IR::IsGeneric(attr)) {
        const u32 index{IR::GenericAttributeIndex(attr)};
        ctx.Add("MOV.F {}.x,in_attr{}{}[0].{};", inst, index, VertexIndex(ctx, vertex), swizzle);
        return;
    }
    if (attr >= IR::Attribute::FixedFncTexture0S && attr <= IR::Attribute::FixedFncTexture9Q) {
        const u32 index{TexCoordIndex(attr)};
        ctx.Add("MOV.F {}.x,{}.texcoord[{}].{};", inst, ctx.attrib_name, index, swizzle);
        return;
    }
    switch (attr) {
    case IR::Attribute::PrimitiveId:
        ctx.Add("MOV.F {}.x,primitive.id;", inst);
        break;
    case IR::Attribute::Layer:
        ctx.Add("MOV.F {}.x,fragment.layer;", inst);
        break;
    case IR::Attribute::PositionX:
    case IR::Attribute::PositionY:
    case IR::Attribute::PositionZ:
    case IR::Attribute::PositionW:
        if (IsInputArray(ctx.stage)) {
            ctx.Add("MOV.F {}.x,vertex_position{}.{};", inst, VertexIndex(ctx, vertex), swizzle);
        } else {
            ctx.Add("MOV.F {}.x,{}.position.{};", inst, ctx.attrib_name, swizzle);
        }
        break;
    case IR::Attribute::ColorFrontDiffuseR:
    case IR::Attribute::ColorFrontDiffuseG:
    case IR::Attribute::ColorFrontDiffuseB:
    case IR::Attribute::ColorFrontDiffuseA:
        ctx.Add("MOV.F {}.x,{}.color.{};", inst, ctx.attrib_name, swizzle);
        break;
    case IR::Attribute::PointSpriteS:
    case IR::Attribute::PointSpriteT:
        ctx.Add("MOV.F {}.x,{}.pointcoord.{};", inst, ctx.attrib_name, swizzle);
        break;
    case IR::Attribute::TessellationEvaluationPointU:
    case IR::Attribute::TessellationEvaluationPointV:
        ctx.Add("MOV.F {}.x,vertex.tesscoord.{};", inst, swizzle);
        break;
    case IR::Attribute::InstanceId:
        ctx.Add("MOV.F {}.x,{}.instance;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::VertexId:
        ctx.Add("MOV.F {}.x,{}.id;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::BaseInstance:
        ctx.Add("MOV.F {}.x,{}.baseInstance;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::BaseVertex:
        ctx.Add("MOV.F {}.x,{}.baseVertex;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::DrawID:
        ctx.Add("MOV.F {}.x,{}.draw.id;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::FrontFace:
        ctx.Add("CMP.F {}.x,{}.facing.x,0,-1;", inst, ctx.attrib_name);
        break;
    default:
        throw NotImplementedException("Get attribute {}", attr);
    }
}

void EmitGetAttributeU32(EmitContext& ctx, IR::Inst& inst, IR::Attribute attr, ScalarU32) {
    switch (attr) {
    case IR::Attribute::PrimitiveId:
        ctx.Add("MOV.S {}.x,primitive.id;", inst);
        break;
    case IR::Attribute::InstanceId:
        ctx.Add("MOV.S {}.x,{}.instance;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::VertexId:
        ctx.Add("MOV.S {}.x,{}.id;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::BaseInstance:
        ctx.Add("MOV.S {}.x,{}.baseInstance;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::BaseVertex:
        ctx.Add("MOV.S {}.x,{}.baseVertex;", inst, ctx.attrib_name);
        break;
    case IR::Attribute::DrawID:
        ctx.Add("MOV.S {}.x,{}.draw.id;", inst, ctx.attrib_name);
        break;
    default:
        throw NotImplementedException("Get U32 attribute {}", attr);
    }
}

void EmitSetAttribute(EmitContext& ctx, IR::Attribute attr, ScalarF32 value,
                      [[maybe_unused]] ScalarU32 vertex) {
    const u32 element{static_cast<u32>(attr) % 4};
    const char swizzle{"xyzw"[element]};
    if (IR::IsGeneric(attr)) {
        const u32 index{IR::GenericAttributeIndex(attr)};
        ctx.Add("MOV.F out_attr{}[0].{},{};", index, swizzle, value);
        return;
    }
    if (attr >= IR::Attribute::FixedFncTexture0S && attr <= IR::Attribute::FixedFncTexture9R) {
        const u32 index{TexCoordIndex(attr)};
        ctx.Add("MOV.F result.texcoord[{}].{},{};", index, swizzle, value);
        return;
    }
    switch (attr) {
    case IR::Attribute::Layer:
        if (ctx.stage == Stage::Geometry || ctx.profile.support_viewport_index_layer_non_geometry) {
            ctx.Add("MOV.F result.layer.x,{};", value);
        } else {
            LOG_WARNING(Shader_GLASM,
                        "Layer stored outside of geometry shader not supported by device");
        }
        break;
    case IR::Attribute::ViewportIndex:
        if (ctx.stage == Stage::Geometry || ctx.profile.support_viewport_index_layer_non_geometry) {
            ctx.Add("MOV.F result.viewport.x,{};", value);
        } else {
            LOG_WARNING(Shader_GLASM,
                        "Viewport stored outside of geometry shader not supported by device");
        }
        break;
    case IR::Attribute::ViewportMask:
        // NV_viewport_array2 is required to access result.viewportmask, regardless of shader stage.
        if (ctx.profile.support_viewport_index_layer_non_geometry) {
            ctx.Add("MOV.F result.viewportmask[0].x,{};", value);
        } else {
            LOG_WARNING(Shader_GLASM, "Device does not support storing to ViewportMask");
        }
        break;
    case IR::Attribute::PointSize:
        ctx.Add("MOV.F result.pointsize.x,{};", value);
        break;
    case IR::Attribute::PositionX:
    case IR::Attribute::PositionY:
    case IR::Attribute::PositionZ:
    case IR::Attribute::PositionW:
        ctx.Add("MOV.F result.position.{},{};", swizzle, value);
        break;
    case IR::Attribute::ColorFrontDiffuseR:
    case IR::Attribute::ColorFrontDiffuseG:
    case IR::Attribute::ColorFrontDiffuseB:
    case IR::Attribute::ColorFrontDiffuseA:
        ctx.Add("MOV.F result.color.{},{};", swizzle, value);
        break;
    case IR::Attribute::ColorFrontSpecularR:
    case IR::Attribute::ColorFrontSpecularG:
    case IR::Attribute::ColorFrontSpecularB:
    case IR::Attribute::ColorFrontSpecularA:
        ctx.Add("MOV.F result.color.secondary.{},{};", swizzle, value);
        break;
    case IR::Attribute::ColorBackDiffuseR:
    case IR::Attribute::ColorBackDiffuseG:
    case IR::Attribute::ColorBackDiffuseB:
    case IR::Attribute::ColorBackDiffuseA:
        ctx.Add("MOV.F result.color.back.{},{};", swizzle, value);
        break;
    case IR::Attribute::ColorBackSpecularR:
    case IR::Attribute::ColorBackSpecularG:
    case IR::Attribute::ColorBackSpecularB:
    case IR::Attribute::ColorBackSpecularA:
        ctx.Add("MOV.F result.color.back.secondary.{},{};", swizzle, value);
        break;
    case IR::Attribute::FogCoordinate:
        ctx.Add("MOV.F result.fogcoord.x,{};", value);
        break;
    case IR::Attribute::ClipDistance0:
    case IR::Attribute::ClipDistance1:
    case IR::Attribute::ClipDistance2:
    case IR::Attribute::ClipDistance3:
    case IR::Attribute::ClipDistance4:
    case IR::Attribute::ClipDistance5:
    case IR::Attribute::ClipDistance6:
    case IR::Attribute::ClipDistance7: {
        const u32 index{static_cast<u32>(attr) - static_cast<u32>(IR::Attribute::ClipDistance0)};
        ctx.Add("MOV.F result.clip[{}].x,{};", index, value);
        break;
    }
    default:
        throw NotImplementedException("Set attribute {}", attr);
    }
}

void EmitGetAttributeIndexed(EmitContext& ctx, IR::Inst& inst, ScalarS32 offset, ScalarU32 vertex) {
    // RC.x = base_index
    // RC.y = masked_index
    // RC.z = compare_index
    ctx.Add("SHR.S RC.x,{},2;"
            "AND.S RC.y,RC.x,3;"
            "SHR.S RC.z,{},4;",
            offset, offset);

    const Register ret{ctx.reg_alloc.Define(inst)};
    u32 num_endifs{};
    const auto read{[&](u32 compare_index, const std::array<std::string, 4>& values) {
        ++num_endifs;
        ctx.Add("SEQ.S.CC RC.w,RC.z,{};" // compare_index
                "IF NE.w;"
                // X
                "SEQ.S.CC RC.w,RC.y,0;"
                "IF NE.w;"
                "MOV {}.x,{};"
                "ELSE;"
                // Y
                "SEQ.S.CC RC.w,RC.y,1;"
                "IF NE.w;"
                "MOV {}.x,{};"
                "ELSE;"
                // Z
                "SEQ.S.CC RC.w,RC.y,2;"
                "IF NE.w;"
                "MOV {}.x,{};"
                "ELSE;"
                // W
                "MOV {}.x,{};"
                "ENDIF;"
                "ENDIF;"
                "ENDIF;"
                "ELSE;",
                compare_index, ret, values[0], ret, values[1], ret, values[2], ret, values[3]);
    }};
    const auto read_swizzled{[&](u32 compare_index, std::string_view value) {
        const std::array values{fmt::format("{}.x", value), fmt::format("{}.y", value),
                                fmt::format("{}.z", value), fmt::format("{}.w", value)};
        read(compare_index, values);
    }};
    if (ctx.info.loads.AnyComponent(IR::Attribute::PositionX)) {
        const u32 index{static_cast<u32>(IR::Attribute::PositionX)};
        if (IsInputArray(ctx.stage)) {
            read_swizzled(index, fmt::format("vertex_position{}", VertexIndex(ctx, vertex)));
        } else {
            read_swizzled(index, fmt::format("{}.position", ctx.attrib_name));
        }
    }
    for (u32 index = 0; index < static_cast<u32>(IR::NUM_GENERICS); ++index) {
        if (!ctx.info.loads.Generic(index)) {
            continue;
        }
        read_swizzled(index, fmt::format("in_attr{}{}[0]", index, VertexIndex(ctx, vertex)));
    }
    for (u32 i = 0; i < num_endifs; ++i) {
        ctx.Add("ENDIF;");
    }
}

void EmitSetAttributeIndexed([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] ScalarU32 offset,
                             [[maybe_unused]] ScalarF32 value, [[maybe_unused]] ScalarU32 vertex) {
    throw NotImplementedException("GLASM instruction");
}

void EmitGetPatch(EmitContext& ctx, IR::Inst& inst, IR::Patch patch) {
    if (!IR::IsGeneric(patch)) {
        throw NotImplementedException("Non-generic patch load");
    }
    const u32 index{IR::GenericPatchIndex(patch)};
    const u32 element{IR::GenericPatchElement(patch)};
    const char swizzle{"xyzw"[element]};
    const std::string_view out{ctx.stage == Stage::TessellationControl ? ".out" : ""};
    ctx.Add("MOV.F {},primitive{}.patch.attrib[{}].{};", inst, out, index, swizzle);
}

void EmitSetPatch(EmitContext& ctx, IR::Patch patch, ScalarF32 value) {
    if (IR::IsGeneric(patch)) {
        const u32 index{IR::GenericPatchIndex(patch)};
        const u32 element{IR::GenericPatchElement(patch)};
        ctx.Add("MOV.F result.patch.attrib[{}].{},{};", index, "xyzw"[element], value);
        return;
    }
    switch (patch) {
    case IR::Patch::TessellationLodLeft:
    case IR::Patch::TessellationLodRight:
    case IR::Patch::TessellationLodTop:
    case IR::Patch::TessellationLodBottom: {
        const u32 index{static_cast<u32>(patch) - u32(IR::Patch::TessellationLodLeft)};
        ctx.Add("MOV.F result.patch.tessouter[{}].x,{};", index, value);
        break;
    }
    case IR::Patch::TessellationLodInteriorU:
        ctx.Add("MOV.F result.patch.tessinner[0].x,{};", value);
        break;
    case IR::Patch::TessellationLodInteriorV:
        ctx.Add("MOV.F result.patch.tessinner[1].x,{};", value);
        break;
    default:
        throw NotImplementedException("Patch {}", patch);
    }
}

void EmitSetFragColor(EmitContext& ctx, u32 index, u32 component, ScalarF32 value) {
    ctx.Add("MOV.F frag_color{}.{},{};", index, "xyzw"[component], value);
}

void EmitSetSampleMask(EmitContext& ctx, ScalarS32 value) {
    ctx.Add("MOV.S result.samplemask.x,{};", value);
}

void EmitSetFragDepth(EmitContext& ctx, ScalarF32 value) {
    ctx.Add("MOV.F result.depth.z,{};", value);
}

void EmitWorkgroupId(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.S {},invocation.groupid;", inst);
}

void EmitLocalInvocationId(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.S {},invocation.localid;", inst);
}

void EmitInvocationId(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.S {}.x,primitive_invocation.x;", inst);
}

void EmitInvocationInfo(EmitContext& ctx, IR::Inst& inst) {
    switch (ctx.stage) {
    case Stage::TessellationControl:
    case Stage::TessellationEval:
        ctx.Add("SHL.U {}.x,primitive.vertexcount,16;", inst);
        break;
    default:
        LOG_WARNING(Shader, "(STUBBED) called");
        ctx.Add("MOV.S {}.x,0x00ff0000;", inst);
    }
}

void EmitSampleId(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.S {}.x,fragment.sampleid.x;", inst);
}

void EmitIsHelperInvocation(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.S {}.x,fragment.helperthread.x;", inst);
}

void EmitSR_WScaleFactorXY(EmitContext& ctx, IR::Inst& inst) {
    LOG_WARNING(Shader, "(STUBBED) called");
}

void EmitSR_WScaleFactorZ(EmitContext& ctx, IR::Inst& inst) {
    LOG_WARNING(Shader, "(STUBBED) called");
}

void EmitYDirection(EmitContext& ctx, IR::Inst& inst) {
    ctx.uses_y_direction = true;
    ctx.Add("MOV.F {}.x,y_direction[0].w;", inst);
}

void EmitResolutionDownFactor(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.F {}.x,scaling[0].z;", inst);
}

void EmitRenderArea(EmitContext& ctx, IR::Inst& inst) {
    ctx.Add("MOV.F {},render_area[0];", inst);
}

void EmitLoadLocal(EmitContext& ctx, IR::Inst& inst, ScalarU32 word_offset) {
    ctx.Add("MOV.U {},lmem[{}].x;", inst, word_offset);
}

void EmitWriteLocal(EmitContext& ctx, ScalarU32 word_offset, ScalarU32 value) {
    ctx.Add("MOV.U lmem[{}].x,{};", word_offset, value);
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"

namespace Shader::Backend::GLASM {

void EmitJoin(EmitContext&) {
    throw NotImplementedException("Join shouldn't be emitted");
}

void EmitDemoteToHelperInvocation(EmitContext& ctx) {
    ctx.Add("KIL TR.x;");
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"
#include "shader_recompiler/frontend/ir/modifiers.h"
#include "shader_recompiler/frontend/ir/value.h"

namespace Shader::Backend::GLASM {
namespace {
std::string_view FpRounding(IR::FpRounding fp_rounding) {
    switch (fp_rounding) {
    case IR::FpRounding::DontCare:
        return "";
    case IR::FpRounding::RN:
        return ".ROUND";
    case IR::FpRounding::RZ:
        return ".TRUNC";
    case IR::FpRounding::RM:
        return ".FLR";
    case IR::FpRounding::RP:
        return ".CEIL";
    }
    throw InvalidArgument("Invalid floating-point rounding {}", fp_rounding);
}

template <typename InputType>
void Convert(EmitContext& ctx, IR::Inst& inst, InputType value, std::string_view dest,
             std::string_view src, bool is_long_result) {
    const std::string_view fp_rounding{FpRounding(inst.Flags<IR::FpControl>().rounding)};
    const auto ret{is_long_result ? ctx.reg_alloc.LongDefine(inst) : ctx.reg_alloc.Define(inst)};
    ctx.Add("CVT.{}.{}{} {}.x,{};", dest, src, fp_rounding, ret, value);
}
} // Anonymous namespace

void EmitConvertS16F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "S16", "F16", false);
}

void EmitConvertS16F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "S16", "F32", false);
}

void EmitConvertS16F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "S16", "F64", false);
}

void EmitConvertS32F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "S32", "F16", false);
}

void EmitConvertS32F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "S32", "F32", false);
}

void EmitConvertS32F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "S32", "F64", false);
}

void EmitConvertS64F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "S64", "F16", true);
}

void EmitConvertS64F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "S64", "F32", true);
}

void EmitConvertS64F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "S64", "F64", true);
}

void EmitConvertU16F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "U16", "F16", false);
}

void EmitConvertU16F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "U16", "F32", false);
}

void EmitConvertU16F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "U16", "F64", false);
}

void EmitConvertU32F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "U32", "F16", false);
}

void EmitConvertU32F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "U32", "F32", false);
}

void EmitConvertU32F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "U32", "F64", false);
}

void EmitConvertU64F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "U64", "F16", true);
}

void EmitConvertU64F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "U64", "F32", true);
}

void EmitConvertU64F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "U64", "F64", true);
}

void EmitConvertU64U32(EmitContext& ctx, IR::Inst& inst, ScalarU32 value) {
    Convert(ctx, inst, value, "U64", "U32", true);
}

void EmitConvertU32U64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "U32", "U64", false);
}

void EmitConvertF16F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "F16", "F32", false);
}

void EmitConvertF32F16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "F16", false);
}

void EmitConvertF32F64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Convert(ctx, inst, value, "F32", "F64", false);
}

void EmitConvertF64F32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Convert(ctx, inst, value, "F64", "F32", true);
}

void EmitConvertF16S8(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F16", "S8", false);
}

void EmitConvertF16S16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F16", "S16", false);
}

void EmitConvertF16S32(EmitContext& ctx, IR::Inst& inst, ScalarS32 value) {
    Convert(ctx, inst, value, "F16", "S32", false);
}

void EmitConvertF16S64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F16", "S64", false);
}

void EmitConvertF16U8(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F16", "U8", false);
}

void EmitConvertF16U16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F16", "U16", false);
}

void EmitConvertF16U32(EmitContext& ctx, IR::Inst& inst, ScalarU32 value) {
    Convert(ctx, inst, value, "F16", "U32", false);
}

void EmitConvertF16U64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F16", "U64", false);
}

void EmitConvertF32S8(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "S8", false);
}

void EmitConvertF32S16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "S16", false);
}

void EmitConvertF32S32(EmitContext& ctx, IR::Inst& inst, ScalarS32 value) {
    Convert(ctx, inst, value, "F32", "S32", false);
}

void EmitConvertF32S64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "S64", false);
}

void EmitConvertF32U8(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "U8", false);
}

void EmitConvertF32U16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "U16", false);
}

void EmitConvertF32U32(EmitContext& ctx, IR::Inst& inst, ScalarU32 value) {
    Convert(ctx, inst, value, "F32", "U32", false);
}

void EmitConvertF32U64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F32", "U64", false);
}

void EmitConvertF64S8(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F64", "S8", true);
}

void EmitConvertF64S16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F64", "S16", true);
}

void EmitConvertF64S32(EmitContext& ctx, IR::Inst& inst, ScalarS32 value) {
    Convert(ctx, inst, value, "F64", "S32", true);
}

void EmitConvertF64S64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F64", "S64", true);
}

void EmitConvertF64U8(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F64", "U8", true);
}

void EmitConvertF64U16(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F64", "U16", true);
}

void EmitConvertF64U32(EmitContext& ctx, IR::Inst& inst, ScalarU32 value) {
    Convert(ctx, inst, value, "F64", "U32", true);
}

void EmitConvertF64U64(EmitContext& ctx, IR::Inst& inst, Register value) {
    Convert(ctx, inst, value, "F64", "U64", true);
}

} // namespace Shader::Backend::GLASM


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "shader_recompiler/backend/glasm/emit_glasm_instructions.h"
#include "shader_recompiler/backend/glasm/glasm_emit_context.h"
#include "shader_recompiler/frontend/ir/modifiers.h"
#include "shader_recompiler/frontend/ir/value.h"

namespace Shader::Backend::GLASM {
namespace {
template <typename InputType>
void Compare(EmitContext& ctx, IR::Inst& inst, InputType lhs, InputType rhs, std::string_view op,
             std::string_view type, bool ordered, bool inequality = false) {
    const Register ret{ctx.reg_alloc.Define(inst)};
    ctx.Add("{}.{} RC.x,{},{};", op, type, lhs, rhs);
    if (ordered && inequality) {
        ctx.Add("SEQ.{} RC.y,{},{};"
                "SEQ.{} RC.z,{},{};"
                "AND.U RC.x,RC.x,RC.y;"
                "AND.U RC.x,RC.x,RC.z;"
                "SNE.S {}.x,RC.x,0;",
                type, lhs, lhs, type, rhs, rhs, ret);
    } else if (ordered) {
        ctx.Add("SNE.S {}.x,RC.x,0;", ret);
    } else {
        ctx.Add("SNE.{} RC.y,{},{};"
                "SNE.{} RC.z,{},{};"
                "OR.U RC.x,RC.x,RC.y;"
                "OR.U RC.x,RC.x,RC.z;"
                "SNE.S {}.x,RC.x,0;",
                type, lhs, lhs, type, rhs, rhs, ret);
    }
}

template <typename InputType>
void Clamp(EmitContext& ctx, Register ret, InputType value, InputType min_value,
           InputType max_value, std::string_view type) {
    // Call MAX first to properly clamp nan to min_value instead
    ctx.Add("MAX.{} RC.x,{},{};"
            "MIN.{} {}.x,RC.x,{};",
            type, min_value, value, type, ret, max_value);
}

std::string_view Precise(IR::Inst& inst) {
    const bool precise{inst.Flags<IR::FpControl>().no_contraction};
    return precise ? ".PREC" : "";
}
} // Anonymous namespace

void EmitFPAbs16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] IR::Inst& inst,
                 [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPAbs32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("MOV.F {}.x,|{}|;", inst, value);
}

void EmitFPAbs64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    ctx.LongAdd("MOV.F64 {}.x,|{}|;", inst, value);
}

void EmitFPAdd16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] IR::Inst& inst,
                 [[maybe_unused]] Register a, [[maybe_unused]] Register b) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPAdd32(EmitContext& ctx, IR::Inst& inst, ScalarF32 a, ScalarF32 b) {
    ctx.Add("ADD.F{} {}.x,{},{};", Precise(inst), ctx.reg_alloc.Define(inst), a, b);
}

void EmitFPAdd64(EmitContext& ctx, IR::Inst& inst, ScalarF64 a, ScalarF64 b) {
    ctx.Add("ADD.F64{} {}.x,{},{};", Precise(inst), ctx.reg_alloc.LongDefine(inst), a, b);
}

void EmitFPFma16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] IR::Inst& inst,
                 [[maybe_unused]] Register a, [[maybe_unused]] Register b,
                 [[maybe_unused]] Register c) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPFma32(EmitContext& ctx, IR::Inst& inst, ScalarF32 a, ScalarF32 b, ScalarF32 c) {
    ctx.Add("MAD.F{} {}.x,{},{},{};", Precise(inst), ctx.reg_alloc.Define(inst), a, b, c);
}

void EmitFPFma64(EmitContext& ctx, IR::Inst& inst, ScalarF64 a, ScalarF64 b, ScalarF64 c) {
    ctx.Add("MAD.F64{} {}.x,{},{},{};", Precise(inst), ctx.reg_alloc.LongDefine(inst), a, b, c);
}

void EmitFPMax32(EmitContext& ctx, IR::Inst& inst, ScalarF32 a, ScalarF32 b) {
    ctx.Add("MAX.F {}.x,{},{};", inst, a, b);
}

void EmitFPMax64(EmitContext& ctx, IR::Inst& inst, ScalarF64 a, ScalarF64 b) {
    ctx.LongAdd("MAX.F64 {}.x,{},{};", inst, a, b);
}

void EmitFPMin32(EmitContext& ctx, IR::Inst& inst, ScalarF32 a, ScalarF32 b) {
    ctx.Add("MIN.F {}.x,{},{};", inst, a, b);
}

void EmitFPMin64(EmitContext& ctx, IR::Inst& inst, ScalarF64 a, ScalarF64 b) {
    ctx.LongAdd("MIN.F64 {}.x,{},{};", inst, a, b);
}

void EmitFPMul16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] IR::Inst& inst,
                 [[maybe_unused]] Register a, [[maybe_unused]] Register b) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPMul32(EmitContext& ctx, IR::Inst& inst, ScalarF32 a, ScalarF32 b) {
    ctx.Add("MUL.F{} {}.x,{},{};", Precise(inst), ctx.reg_alloc.Define(inst), a, b);
}

void EmitFPMul64(EmitContext& ctx, IR::Inst& inst, ScalarF64 a, ScalarF64 b) {
    ctx.Add("MUL.F64{} {}.x,{},{};", Precise(inst), ctx.reg_alloc.LongDefine(inst), a, b);
}

void EmitFPNeg16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPNeg32(EmitContext& ctx, IR::Inst& inst, ScalarRegister value) {
    ctx.Add("MOV.F {}.x,-{};", inst, value);
}

void EmitFPNeg64(EmitContext& ctx, IR::Inst& inst, Register value) {
    ctx.LongAdd("MOV.F64 {}.x,-{};", inst, value);
}

void EmitFPSin(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("SIN {}.x,{};", inst, value);
}

void EmitFPCos(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("COS {}.x,{};", inst, value);
}

void EmitFPExp2(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("EX2 {}.x,{};", inst, value);
}

void EmitFPLog2(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("LG2 {}.x,{};", inst, value);
}

void EmitFPRecip32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("RCP {}.x,{};", inst, value);
}

void EmitFPRecip64([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPRecipSqrt32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("RSQ {}.x,{};", inst, value);
}

void EmitFPRecipSqrt64([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPSqrt(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    const Register ret{ctx.reg_alloc.Define(inst)};
    ctx.Add("RSQ RC.x,{};RCP {}.x,RC.x;", value, ret);
}

void EmitFPSaturate16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPSaturate32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("MOV.F.SAT {}.x,{};", inst, value);
}

void EmitFPSaturate64([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPClamp16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value,
                   [[maybe_unused]] Register min_value, [[maybe_unused]] Register max_value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPClamp32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value, ScalarF32 min_value,
                   ScalarF32 max_value) {
    Clamp(ctx, ctx.reg_alloc.Define(inst), value, min_value, max_value, "F");
}

void EmitFPClamp64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value, ScalarF64 min_value,
                   ScalarF64 max_value) {
    Clamp(ctx, ctx.reg_alloc.LongDefine(inst), value, min_value, max_value, "F64");
}

void EmitFPRoundEven16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPRoundEven32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("ROUND.F {}.x,{};", inst, value);
}

void EmitFPRoundEven64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    ctx.LongAdd("ROUND.F64 {}.x,{};", inst, value);
}

void EmitFPFloor16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPFloor32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("FLR.F {}.x,{};", inst, value);
}

void EmitFPFloor64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    ctx.LongAdd("FLR.F64 {}.x,{};", inst, value);
}

void EmitFPCeil16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPCeil32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("CEIL.F {}.x,{};", inst, value);
}

void EmitFPCeil64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    ctx.LongAdd("CEIL.F64 {}.x,{};", inst, value);
}

void EmitFPTrunc16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPTrunc32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    ctx.Add("TRUNC.F {}.x,{};", inst, value);
}

void EmitFPTrunc64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    ctx.LongAdd("TRUNC.F64 {}.x,{};", inst, value);
}

void EmitFPOrdEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                      [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPOrdEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SEQ", "F", true);
}

void EmitFPOrdEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SEQ", "F64", true);
}

void EmitFPUnordEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                        [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPUnordEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SEQ", "F", false);
}

void EmitFPUnordEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SEQ", "F64", false);
}

void EmitFPOrdNotEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                         [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPOrdNotEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SNE", "F", true, true);
}

void EmitFPOrdNotEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SNE", "F64", true, true);
}

void EmitFPUnordNotEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                           [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPUnordNotEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SNE", "F", false, true);
}

void EmitFPUnordNotEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SNE", "F64", false, true);
}

void EmitFPOrdLessThan16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                         [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPOrdLessThan32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLT", "F", true);
}

void EmitFPOrdLessThan64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLT", "F64", true);
}

void EmitFPUnordLessThan16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                           [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPUnordLessThan32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLT", "F", false);
}

void EmitFPUnordLessThan64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLT", "F64", false);
}

void EmitFPOrdGreaterThan16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                            [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPOrdGreaterThan32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGT", "F", true);
}

void EmitFPOrdGreaterThan64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGT", "F64", true);
}

void EmitFPUnordGreaterThan16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                              [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPUnordGreaterThan32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGT", "F", false);
}

void EmitFPUnordGreaterThan64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGT", "F64", false);
}

void EmitFPOrdLessThanEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                              [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPOrdLessThanEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLE", "F", true);
}

void EmitFPOrdLessThanEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLE", "F64", true);
}

void EmitFPUnordLessThanEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                                [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPUnordLessThanEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLE", "F", false);
}

void EmitFPUnordLessThanEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SLE", "F64", false);
}

void EmitFPOrdGreaterThanEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                                 [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPOrdGreaterThanEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGE", "F", true);
}

void EmitFPOrdGreaterThanEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGE", "F64", true);
}

void EmitFPUnordGreaterThanEqual16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register lhs,
                                   [[maybe_unused]] Register rhs) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPUnordGreaterThanEqual32(EmitContext& ctx, IR::Inst& inst, ScalarF32 lhs, ScalarF32 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGE", "F", false);
}

void EmitFPUnordGreaterThanEqual64(EmitContext& ctx, IR::Inst& inst, ScalarF64 lhs, ScalarF64 rhs) {
    Compare(ctx, inst, lhs, rhs, "SGE", "F64", false);
}

void EmitFPIsNan16([[maybe_unused]] EmitContext& ctx, [[maybe_unused]] Register value) {
    throw NotImplementedException("GLASM instruction");
}

void EmitFPIsNan32(EmitContext& ctx, IR::Inst& inst, ScalarF32 value) {
    Compare(ctx, inst, value, value, "SNE", "F", true, false);
}

void EmitFPIsNan64(EmitContext& ctx, IR::Inst& inst, ScalarF64 value) {
    Compare(ctx, inst, value, value, "SNE", "F64", true, false);
}

} // namespace Shader::Backend::GLASM