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

#pragma once

#include <vector>

#include "common/common_types.h"
#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::SPIRV {

constexpr u32 NUM_TEXTURE_SCALING_WORDS = 4;
constexpr u32 NUM_IMAGE_SCALING_WORDS = 2;
constexpr u32 NUM_TEXTURE_AND_IMAGE_SCALING_WORDS =
    NUM_TEXTURE_SCALING_WORDS + NUM_IMAGE_SCALING_WORDS;

struct RescalingLayout {
    alignas(16) std::array<u32, NUM_TEXTURE_SCALING_WORDS> rescaling_textures;
    alignas(16) std::array<u32, NUM_IMAGE_SCALING_WORDS> rescaling_images;
    u32 down_factor;
};
struct RenderAreaLayout {
    std::array<f32, 4> render_area;
};
constexpr u32 RESCALING_LAYOUT_WORDS_OFFSET = offsetof(RescalingLayout, rescaling_textures);
constexpr u32 RESCALING_LAYOUT_DOWN_FACTOR_OFFSET = offsetof(RescalingLayout, down_factor);
constexpr u32 RENDERAREA_LAYOUT_OFFSET = offsetof(RenderAreaLayout, render_area);

[[nodiscard]] std::vector<u32> EmitSPIRV(const Profile& profile, const RuntimeInfo& runtime_info,
                                         IR::Program& program, Bindings& bindings);

[[nodiscard]] inline std::vector<u32> EmitSPIRV(const Profile& profile, IR::Program& program) {
    Bindings binding;
    return EmitSPIRV(profile, {}, program, binding);
}

} // namespace Shader::Backend::SPIRV


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

#include <bit>

#include "shader_recompiler/backend/spirv/emit_spirv.h"
#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {
namespace {
Id SharedPointer(EmitContext& ctx, Id offset, u32 index_offset = 0) {
    const Id shift_id{ctx.Const(2U)};
    Id index{ctx.OpShiftRightArithmetic(ctx.U32[1], offset, shift_id)};
    if (index_offset > 0) {
        index = ctx.OpIAdd(ctx.U32[1], index, ctx.Const(index_offset));
    }
    return ctx.profile.support_explicit_workgroup_layout
               ? ctx.OpAccessChain(ctx.shared_u32, ctx.shared_memory_u32, ctx.u32_zero_value, index)
               : ctx.OpAccessChain(ctx.shared_u32, ctx.shared_memory_u32, index);
}

Id StorageIndex(EmitContext& ctx, const IR::Value& offset, size_t element_size) {
    if (offset.IsImmediate()) {
        const u32 imm_offset{static_cast<u32>(offset.U32() / element_size)};
        return ctx.Const(imm_offset);
    }
    const u32 shift{static_cast<u32>(std::countr_zero(element_size))};
    const Id index{ctx.Def(offset)};
    if (shift == 0) {
        return index;
    }
    const Id shift_id{ctx.Const(shift)};
    return ctx.OpShiftRightLogical(ctx.U32[1], index, shift_id);
}

Id StoragePointer(EmitContext& ctx, const StorageTypeDefinition& type_def,
                  Id StorageDefinitions::*member_ptr, const IR::Value& binding,
                  const IR::Value& offset, size_t element_size) {
    if (!binding.IsImmediate()) {
        throw NotImplementedException("Dynamic storage buffer indexing");
    }
    const Id ssbo{ctx.ssbos[binding.U32()].*member_ptr};
    const Id index{StorageIndex(ctx, offset, element_size)};
    return ctx.OpAccessChain(type_def.element, ssbo, ctx.u32_zero_value, index);
}

std::pair<Id, Id> AtomicArgs(EmitContext& ctx) {
    const Id scope{ctx.Const(static_cast<u32>(spv::Scope::Device))};
    const Id semantics{ctx.u32_zero_value};
    return {scope, semantics};
}

Id SharedAtomicU32(EmitContext& ctx, Id offset, Id value,
                   Id (Sirit::Module::*atomic_func)(Id, Id, Id, Id, Id)) {
    const Id pointer{SharedPointer(ctx, offset)};
    const auto [scope, semantics]{AtomicArgs(ctx)};
    return (ctx.*atomic_func)(ctx.U32[1], pointer, scope, semantics, value);
}

Id StorageAtomicU32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset, Id value,
                    Id (Sirit::Module::*atomic_func)(Id, Id, Id, Id, Id)) {
    const Id pointer{StoragePointer(ctx, ctx.storage_types.U32, &StorageDefinitions::U32, binding,
                                    offset, sizeof(u32))};
    const auto [scope, semantics]{AtomicArgs(ctx)};
    return (ctx.*atomic_func)(ctx.U32[1], pointer, scope, semantics, value);
}

Id StorageAtomicU64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset, Id value,
                    Id (Sirit::Module::*atomic_func)(Id, Id, Id, Id, Id),
                    Id (Sirit::Module::*non_atomic_func)(Id, Id, Id)) {
    if (!ctx.profile.support_descriptor_aliasing) {
        LOG_WARNING(Shader_SPIRV, "Descriptor aliasing not supported, this cannot be atomic.");
        return ctx.ConstantNull(ctx.U64);
    }

    if (ctx.profile.support_int64_atomics) {
        const Id pointer{StoragePointer(ctx, ctx.storage_types.U64, &StorageDefinitions::U64,
                                        binding, offset, sizeof(u64))};
        const auto [scope, semantics]{AtomicArgs(ctx)};
        return (ctx.*atomic_func)(ctx.U64, pointer, scope, semantics, value);
    }
    LOG_WARNING(Shader_SPIRV, "Int64 atomics not supported, fallback to non-atomic");
    const Id pointer{StoragePointer(ctx, ctx.storage_types.U32x2, &StorageDefinitions::U32x2,
                                    binding, offset, sizeof(u32[2]))};
    const Id original_value{ctx.OpBitcast(ctx.U64, ctx.OpLoad(ctx.U32[2], pointer))};
    const Id result{(ctx.*non_atomic_func)(ctx.U64, value, original_value)};
    ctx.OpStore(pointer, ctx.OpBitcast(ctx.U32[2], result));
    return original_value;
}

Id StorageAtomicU32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset, Id value,
                      Id (Sirit::Module::*non_atomic_func)(Id, Id, Id)) {
    if (!ctx.profile.support_descriptor_aliasing) {
        LOG_WARNING(Shader_SPIRV, "Descriptor aliasing not supported, this cannot be atomic.");
        return ctx.ConstantNull(ctx.U32[2]);
    }

    LOG_WARNING(Shader_SPIRV, "Int64 atomics not supported, fallback to non-atomic");
    const Id pointer{StoragePointer(ctx, ctx.storage_types.U32x2, &StorageDefinitions::U32x2,
                                    binding, offset, sizeof(u32[2]))};
    const Id original_value{ctx.OpLoad(ctx.U32[2], pointer)};
    const Id result{(ctx.*non_atomic_func)(ctx.U32[2], value, original_value)};
    ctx.OpStore(pointer, result);
    return original_value;
}
} // Anonymous namespace

Id EmitSharedAtomicIAdd32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicIAdd);
}

Id EmitSharedAtomicSMin32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicSMin);
}

Id EmitSharedAtomicUMin32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicUMin);
}

Id EmitSharedAtomicSMax32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicSMax);
}

Id EmitSharedAtomicUMax32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicUMax);
}

Id EmitSharedAtomicInc32(EmitContext& ctx, Id offset, Id value) {
    const Id shift_id{ctx.Const(2U)};
    const Id index{ctx.OpShiftRightArithmetic(ctx.U32[1], offset, shift_id)};
    return ctx.OpFunctionCall(ctx.U32[1], ctx.increment_cas_shared, index, value);
}

Id EmitSharedAtomicDec32(EmitContext& ctx, Id offset, Id value) {
    const Id shift_id{ctx.Const(2U)};
    const Id index{ctx.OpShiftRightArithmetic(ctx.U32[1], offset, shift_id)};
    return ctx.OpFunctionCall(ctx.U32[1], ctx.decrement_cas_shared, index, value);
}

Id EmitSharedAtomicAnd32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicAnd);
}

Id EmitSharedAtomicOr32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicOr);
}

Id EmitSharedAtomicXor32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicXor);
}

Id EmitSharedAtomicExchange32(EmitContext& ctx, Id offset, Id value) {
    return SharedAtomicU32(ctx, offset, value, &Sirit::Module::OpAtomicExchange);
}

Id EmitSharedAtomicExchange64(EmitContext& ctx, Id offset, Id value) {
    if (ctx.profile.support_int64_atomics && ctx.profile.support_explicit_workgroup_layout) {
        const Id shift_id{ctx.Const(3U)};
        const Id index{ctx.OpShiftRightArithmetic(ctx.U32[1], offset, shift_id)};
        const Id pointer{
            ctx.OpAccessChain(ctx.shared_u64, ctx.shared_memory_u64, ctx.u32_zero_value, index)};
        const auto [scope, semantics]{AtomicArgs(ctx)};
        return ctx.OpAtomicExchange(ctx.U64, pointer, scope, semantics, value);
    }
    LOG_WARNING(Shader_SPIRV, "Int64 atomics not supported, fallback to non-atomic");
    const Id pointer_1{SharedPointer(ctx, offset, 0)};
    const Id pointer_2{SharedPointer(ctx, offset, 1)};
    const Id value_1{ctx.OpLoad(ctx.U32[1], pointer_1)};
    const Id value_2{ctx.OpLoad(ctx.U32[1], pointer_2)};
    const Id new_vector{ctx.OpBitcast(ctx.U32[2], value)};
    ctx.OpStore(pointer_1, ctx.OpCompositeExtract(ctx.U32[1], new_vector, 0U));
    ctx.OpStore(pointer_2, ctx.OpCompositeExtract(ctx.U32[1], new_vector, 1U));
    return ctx.OpBitcast(ctx.U64, ctx.OpCompositeConstruct(ctx.U32[2], value_1, value_2));
}

Id EmitSharedAtomicExchange32x2(EmitContext& ctx, Id offset, Id value) {
    LOG_WARNING(Shader_SPIRV, "Int64 atomics not supported, fallback to non-atomic");
    const Id pointer_1{SharedPointer(ctx, offset, 0)};
    const Id pointer_2{SharedPointer(ctx, offset, 1)};
    const Id value_1{ctx.OpLoad(ctx.U32[1], pointer_1)};
    const Id value_2{ctx.OpLoad(ctx.U32[1], pointer_2)};
    const Id new_vector{ctx.OpBitcast(ctx.U32[2], value)};
    ctx.OpStore(pointer_1, ctx.OpCompositeExtract(ctx.U32[1], new_vector, 0U));
    ctx.OpStore(pointer_2, ctx.OpCompositeExtract(ctx.U32[1], new_vector, 1U));
    return ctx.OpCompositeConstruct(ctx.U32[2], value_1, value_2);
}

Id EmitStorageAtomicIAdd32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicIAdd);
}

Id EmitStorageAtomicSMin32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicSMin);
}

Id EmitStorageAtomicUMin32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicUMin);
}

Id EmitStorageAtomicSMax32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicSMax);
}

Id EmitStorageAtomicUMax32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicUMax);
}

Id EmitStorageAtomicInc32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                          Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    return ctx.OpFunctionCall(ctx.U32[1], ctx.increment_cas_ssbo, base_index, value, ssbo);
}

Id EmitStorageAtomicDec32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                          Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    return ctx.OpFunctionCall(ctx.U32[1], ctx.decrement_cas_ssbo, base_index, value, ssbo);
}

Id EmitStorageAtomicAnd32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                          Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicAnd);
}

Id EmitStorageAtomicOr32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                         Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicOr);
}

Id EmitStorageAtomicXor32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                          Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicXor);
}

Id EmitStorageAtomicExchange32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                               Id value) {
    return StorageAtomicU32(ctx, binding, offset, value, &Sirit::Module::OpAtomicExchange);
}

Id EmitStorageAtomicIAdd64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicIAdd,
                            &Sirit::Module::OpIAdd);
}

Id EmitStorageAtomicSMin64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicSMin,
                            &Sirit::Module::OpSMin);
}

Id EmitStorageAtomicUMin64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicUMin,
                            &Sirit::Module::OpUMin);
}

Id EmitStorageAtomicSMax64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicSMax,
                            &Sirit::Module::OpSMax);
}

Id EmitStorageAtomicUMax64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicUMax,
                            &Sirit::Module::OpUMax);
}

Id EmitStorageAtomicAnd64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                          Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicAnd,
                            &Sirit::Module::OpBitwiseAnd);
}

Id EmitStorageAtomicOr64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                         Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicOr,
                            &Sirit::Module::OpBitwiseOr);
}

Id EmitStorageAtomicXor64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                          Id value) {
    return StorageAtomicU64(ctx, binding, offset, value, &Sirit::Module::OpAtomicXor,
                            &Sirit::Module::OpBitwiseXor);
}

Id EmitStorageAtomicExchange64(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                               Id value) {
    if (ctx.profile.support_int64_atomics) {
        const Id pointer{StoragePointer(ctx, ctx.storage_types.U64, &StorageDefinitions::U64,
                                        binding, offset, sizeof(u64))};
        const auto [scope, semantics]{AtomicArgs(ctx)};
        return ctx.OpAtomicExchange(ctx.U64, pointer, scope, semantics, value);
    }
    LOG_WARNING(Shader_SPIRV, "Int64 atomics not supported, fallback to non-atomic");
    const Id pointer{StoragePointer(ctx, ctx.storage_types.U32x2, &StorageDefinitions::U32x2,
                                    binding, offset, sizeof(u32[2]))};
    const Id original{ctx.OpBitcast(ctx.U64, ctx.OpLoad(ctx.U32[2], pointer))};
    ctx.OpStore(pointer, value);
    return original;
}

Id EmitStorageAtomicIAdd32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpIAdd);
}

Id EmitStorageAtomicSMin32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpSMin);
}

Id EmitStorageAtomicUMin32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpUMin);
}

Id EmitStorageAtomicSMax32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpSMax);
}

Id EmitStorageAtomicUMax32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpUMax);
}

Id EmitStorageAtomicAnd32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                            Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpBitwiseAnd);
}

Id EmitStorageAtomicOr32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpBitwiseOr);
}

Id EmitStorageAtomicXor32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                            Id value) {
    return StorageAtomicU32x2(ctx, binding, offset, value, &Sirit::Module::OpBitwiseXor);
}

Id EmitStorageAtomicExchange32x2(EmitContext& ctx, const IR::Value& binding,
                                 const IR::Value& offset, Id value) {
    LOG_WARNING(Shader_SPIRV, "Int64 atomics not supported, fallback to non-atomic");
    const Id pointer{StoragePointer(ctx, ctx.storage_types.U32x2, &StorageDefinitions::U32x2,
                                    binding, offset, sizeof(u32[2]))};
    const Id original{ctx.OpLoad(ctx.U32[2], pointer)};
    ctx.OpStore(pointer, value);
    return original;
}

Id EmitStorageAtomicAddF32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                           Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    return ctx.OpFunctionCall(ctx.F32[1], ctx.f32_add_cas, base_index, value, ssbo);
}

Id EmitStorageAtomicAddF16x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    const Id result{ctx.OpFunctionCall(ctx.F16[2], ctx.f16x2_add_cas, base_index, value, ssbo)};
    return ctx.OpBitcast(ctx.U32[1], result);
}

Id EmitStorageAtomicAddF32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    const Id result{ctx.OpFunctionCall(ctx.F32[2], ctx.f32x2_add_cas, base_index, value, ssbo)};
    return ctx.OpPackHalf2x16(ctx.U32[1], result);
}

Id EmitStorageAtomicMinF16x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    const Id result{ctx.OpFunctionCall(ctx.F16[2], ctx.f16x2_min_cas, base_index, value, ssbo)};
    return ctx.OpBitcast(ctx.U32[1], result);
}

Id EmitStorageAtomicMinF32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    const Id result{ctx.OpFunctionCall(ctx.F32[2], ctx.f32x2_min_cas, base_index, value, ssbo)};
    return ctx.OpPackHalf2x16(ctx.U32[1], result);
}

Id EmitStorageAtomicMaxF16x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    const Id result{ctx.OpFunctionCall(ctx.F16[2], ctx.f16x2_max_cas, base_index, value, ssbo)};
    return ctx.OpBitcast(ctx.U32[1], result);
}

Id EmitStorageAtomicMaxF32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset,
                             Id value) {
    const Id ssbo{ctx.ssbos[binding.U32()].U32};
    const Id base_index{StorageIndex(ctx, offset, sizeof(u32))};
    const Id result{ctx.OpFunctionCall(ctx.F32[2], ctx.f32x2_max_cas, base_index, value, ssbo)};
    return ctx.OpPackHalf2x16(ctx.U32[1], result);
}

Id EmitGlobalAtomicIAdd32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicSMin32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicUMin32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicSMax32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicUMax32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicInc32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicDec32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicAnd32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicOr32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicXor32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicExchange32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicIAdd64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicSMin64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicUMin64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicSMax64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicUMax64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicInc64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicDec64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicAnd64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicOr64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicXor64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicExchange64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicIAdd32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicSMin32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicUMin32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicSMax32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicUMax32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicInc32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicDec32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicAnd32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicOr32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicXor32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicExchange32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicAddF32(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicAddF16x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicAddF32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicMinF16x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicMinF32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicMaxF16x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitGlobalAtomicMaxF32x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

} // namespace Shader::Backend::SPIRV

repo_name: litucks/torzu

license: mit


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

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {
namespace {
void MemoryBarrier(EmitContext& ctx, spv::Scope scope) {
    const auto semantics{
        spv::MemorySemanticsMask::AcquireRelease | spv::MemorySemanticsMask::UniformMemory |
        spv::MemorySemanticsMask::WorkgroupMemory | spv::MemorySemanticsMask::AtomicCounterMemory |
        spv::MemorySemanticsMask::ImageMemory};
    ctx.OpMemoryBarrier(ctx.Const(static_cast<u32>(scope)), ctx.Const(static_cast<u32>(semantics)));
}
} // Anonymous namespace

void EmitBarrier(EmitContext& ctx) {
    const auto execution{spv::Scope::Workgroup};
    const auto memory{spv::Scope::Workgroup};
    const auto memory_semantics{spv::MemorySemanticsMask::AcquireRelease |
                                spv::MemorySemanticsMask::WorkgroupMemory};
    ctx.OpControlBarrier(ctx.Const(static_cast<u32>(execution)),
                         ctx.Const(static_cast<u32>(memory)),
                         ctx.Const(static_cast<u32>(memory_semantics)));
}

void EmitWorkgroupMemoryBarrier(EmitContext& ctx) {
    MemoryBarrier(ctx, spv::Scope::Workgroup);
}

void EmitDeviceMemoryBarrier(EmitContext& ctx) {
    MemoryBarrier(ctx, spv::Scope::Device);
}

} // namespace Shader::Backend::SPIRV


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

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {

void EmitBitCastU16F16(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitBitCastU32F32(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.U32[1], value);
}

void EmitBitCastU64F64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitBitCastF16U16(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitBitCastF32U32(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.F32[1], value);
}

void EmitBitCastF64U64(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitPackUint2x32(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.U64, value);
}

Id EmitUnpackUint2x32(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.U32[2], value);
}

Id EmitPackFloat2x16(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.U32[1], value);
}

Id EmitUnpackFloat2x16(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.F16[2], value);
}

Id EmitPackHalf2x16(EmitContext& ctx, Id value) {
    return ctx.OpPackHalf2x16(ctx.U32[1], value);
}

Id EmitUnpackHalf2x16(EmitContext& ctx, Id value) {
    return ctx.OpUnpackHalf2x16(ctx.F32[2], value);
}

Id EmitPackDouble2x32(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.F64[1], value);
}

Id EmitUnpackDouble2x32(EmitContext& ctx, Id value) {
    return ctx.OpBitcast(ctx.U32[2], value);
}

} // namespace Shader::Backend::SPIRV


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

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {

Id EmitCompositeConstructU32x2(EmitContext& ctx, Id e1, Id e2) {
    return ctx.OpCompositeConstruct(ctx.U32[2], e1, e2);
}

Id EmitCompositeConstructU32x3(EmitContext& ctx, Id e1, Id e2, Id e3) {
    return ctx.OpCompositeConstruct(ctx.U32[3], e1, e2, e3);
}

Id EmitCompositeConstructU32x4(EmitContext& ctx, Id e1, Id e2, Id e3, Id e4) {
    return ctx.OpCompositeConstruct(ctx.U32[4], e1, e2, e3, e4);
}

Id EmitCompositeExtractU32x2(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.U32[1], composite, index);
}

Id EmitCompositeExtractU32x3(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.U32[1], composite, index);
}

Id EmitCompositeExtractU32x4(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.U32[1], composite, index);
}

Id EmitCompositeInsertU32x2(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.U32[2], object, composite, index);
}

Id EmitCompositeInsertU32x3(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.U32[3], object, composite, index);
}

Id EmitCompositeInsertU32x4(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.U32[4], object, composite, index);
}

Id EmitCompositeConstructF16x2(EmitContext& ctx, Id e1, Id e2) {
    return ctx.OpCompositeConstruct(ctx.F16[2], e1, e2);
}

Id EmitCompositeConstructF16x3(EmitContext& ctx, Id e1, Id e2, Id e3) {
    return ctx.OpCompositeConstruct(ctx.F16[3], e1, e2, e3);
}

Id EmitCompositeConstructF16x4(EmitContext& ctx, Id e1, Id e2, Id e3, Id e4) {
    return ctx.OpCompositeConstruct(ctx.F16[4], e1, e2, e3, e4);
}

Id EmitCompositeExtractF16x2(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.F16[1], composite, index);
}

Id EmitCompositeExtractF16x3(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.F16[1], composite, index);
}

Id EmitCompositeExtractF16x4(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.F16[1], composite, index);
}

Id EmitCompositeInsertF16x2(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F16[2], object, composite, index);
}

Id EmitCompositeInsertF16x3(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F16[3], object, composite, index);
}

Id EmitCompositeInsertF16x4(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F16[4], object, composite, index);
}

Id EmitCompositeConstructF32x2(EmitContext& ctx, Id e1, Id e2) {
    return ctx.OpCompositeConstruct(ctx.F32[2], e1, e2);
}

Id EmitCompositeConstructF32x3(EmitContext& ctx, Id e1, Id e2, Id e3) {
    return ctx.OpCompositeConstruct(ctx.F32[3], e1, e2, e3);
}

Id EmitCompositeConstructF32x4(EmitContext& ctx, Id e1, Id e2, Id e3, Id e4) {
    return ctx.OpCompositeConstruct(ctx.F32[4], e1, e2, e3, e4);
}

Id EmitCompositeExtractF32x2(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.F32[1], composite, index);
}

Id EmitCompositeExtractF32x3(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.F32[1], composite, index);
}

Id EmitCompositeExtractF32x4(EmitContext& ctx, Id composite, u32 index) {
    return ctx.OpCompositeExtract(ctx.F32[1], composite, index);
}

Id EmitCompositeInsertF32x2(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F32[2], object, composite, index);
}

Id EmitCompositeInsertF32x3(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F32[3], object, composite, index);
}

Id EmitCompositeInsertF32x4(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F32[4], object, composite, index);
}

void EmitCompositeConstructF64x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitCompositeConstructF64x3(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitCompositeConstructF64x4(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitCompositeExtractF64x2(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitCompositeExtractF64x3(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitCompositeExtractF64x4(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitCompositeInsertF64x2(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F64[2], object, composite, index);
}

Id EmitCompositeInsertF64x3(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F64[3], object, composite, index);
}

Id EmitCompositeInsertF64x4(EmitContext& ctx, Id composite, Id object, u32 index) {
    return ctx.OpCompositeInsert(ctx.F64[4], object, composite, index);
}

} // namespace Shader::Backend::SPIRV


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

#include <bit>
#include <tuple>
#include <utility>

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {
namespace {
template <typename... Args>
Id AttrPointer(EmitContext& ctx, Id pointer_type, Id vertex, Id base, Args&&... args) {
    switch (ctx.stage) {
    case Stage::TessellationControl:
    case Stage::TessellationEval:
    case Stage::Geometry:
        return ctx.OpAccessChain(pointer_type, base, vertex, std::forward<Args>(args)...);
    default:
        return ctx.OpAccessChain(pointer_type, base, std::forward<Args>(args)...);
    }
}

template <typename... Args>
Id OutputAccessChain(EmitContext& ctx, Id result_type, Id base, Args&&... args) {
    if (ctx.stage == Stage::TessellationControl) {
        const Id invocation_id{ctx.OpLoad(ctx.U32[1], ctx.invocation_id)};
        return ctx.OpAccessChain(result_type, base, invocation_id, std::forward<Args>(args)...);
    } else {
        return ctx.OpAccessChain(result_type, base, std::forward<Args>(args)...);
    }
}

struct OutAttr {
    OutAttr(Id pointer_) : pointer{pointer_} {}
    OutAttr(Id pointer_, Id type_) : pointer{pointer_}, type{type_} {}

    Id pointer{};
    Id type{};
};

std::optional<OutAttr> OutputAttrPointer(EmitContext& ctx, IR::Attribute attr) {
    if (IR::IsGeneric(attr)) {
        const u32 index{IR::GenericAttributeIndex(attr)};
        const u32 element{IR::GenericAttributeElement(attr)};
        const GenericElementInfo& info{ctx.output_generics.at(index).at(element)};
        if (info.num_components == 1) {
            return info.id;
        } else {
            const u32 index_element{element - info.first_element};
            const Id index_id{ctx.Const(index_element)};
            return OutputAccessChain(ctx, ctx.output_f32, info.id, index_id);
        }
    }
    switch (attr) {
    case IR::Attribute::PointSize:
        return ctx.output_point_size;
    case IR::Attribute::PositionX:
    case IR::Attribute::PositionY:
    case IR::Attribute::PositionZ:
    case IR::Attribute::PositionW: {
        const u32 element{static_cast<u32>(attr) % 4};
        const Id element_id{ctx.Const(element)};
        return OutputAccessChain(ctx, ctx.output_f32, ctx.output_position, element_id);
    }
    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 base{static_cast<u32>(IR::Attribute::ClipDistance0)};
        const u32 index{static_cast<u32>(attr) - base};
        if (index >= ctx.profile.max_user_clip_distances) {
            LOG_WARNING(Shader, "Ignoring clip distance store {} >= {} supported", index,
                        ctx.profile.max_user_clip_distances);
            return std::nullopt;
        }
        const Id clip_num{ctx.Const(index)};
        return OutputAccessChain(ctx, ctx.output_f32, ctx.clip_distances, clip_num);
    }
    case IR::Attribute::Layer:
        if (ctx.profile.support_viewport_index_layer_non_geometry ||
            ctx.stage == Shader::Stage::Geometry) {
            return OutAttr{ctx.layer, ctx.U32[1]};
        }
        return std::nullopt;
    case IR::Attribute::ViewportIndex:
        if (!ctx.profile.support_multi_viewport) {
            LOG_WARNING(Shader, "Ignoring viewport index store on non-supporting driver");
            return std::nullopt;
        }
        if (ctx.profile.support_viewport_index_layer_non_geometry ||
            ctx.stage == Shader::Stage::Geometry) {
            return OutAttr{ctx.viewport_index, ctx.U32[1]};
        }
        return std::nullopt;
    case IR::Attribute::ViewportMask:
        if (!ctx.profile.support_viewport_mask) {
            return std::nullopt;
        }
        return OutAttr{ctx.OpAccessChain(ctx.output_u32, ctx.viewport_mask, ctx.u32_zero_value),
                       ctx.U32[1]};
    default:
        throw NotImplementedException("Read attribute {}", attr);
    }
}

Id GetCbuf(EmitContext& ctx, Id result_type, Id UniformDefinitions::*member_ptr, u32 element_size,
           const IR::Value& binding, const IR::Value& offset, const Id indirect_func) {
    Id buffer_offset;
    const Id uniform_type{ctx.uniform_types.*member_ptr};
    if (offset.IsImmediate()) {
        // Hardware been proved to read the aligned offset (e.g. LDC.U32 at 6 will read offset 4)
        const Id imm_offset{ctx.Const(offset.U32() / element_size)};
        buffer_offset = imm_offset;
    } else if (element_size > 1) {
        const u32 log2_element_size{static_cast<u32>(std::countr_zero(element_size))};
        const Id shift{ctx.Const(log2_element_size)};
        buffer_offset = ctx.OpShiftRightLogical(ctx.U32[1], ctx.Def(offset), shift);
    } else {
        buffer_offset = ctx.Def(offset);
    }
    if (!binding.IsImmediate()) {
        return ctx.OpFunctionCall(result_type, indirect_func, ctx.Def(binding), buffer_offset);
    }

    const Id cbuf{ctx.cbufs[binding.U32()].*member_ptr};
    const Id access_chain{ctx.OpAccessChain(uniform_type, cbuf, ctx.u32_zero_value, buffer_offset)};
    const Id val = ctx.OpLoad(result_type, access_chain);

    if (offset.IsImmediate() || !ctx.profile.has_broken_robust) {
        return val;
    }

    const auto is_float = UniformDefinitions::IsFloat(member_ptr);
    const auto num_elements = UniformDefinitions::NumElements(member_ptr);
    const std::array zero_vec{
        is_float ? ctx.Const(0.0f) : ctx.Const(0u),
        is_float ? ctx.Const(0.0f) : ctx.Const(0u),
        is_float ? ctx.Const(0.0f) : ctx.Const(0u),
        is_float ? ctx.Const(0.0f) : ctx.Const(0u),
    };
    const Id cond = ctx.OpULessThanEqual(ctx.TypeBool(), buffer_offset, ctx.Const(0xFFFFu));
    const Id zero = ctx.OpCompositeConstruct(result_type, std::span(zero_vec.data(), num_elements));
    return ctx.OpSelect(result_type, cond, val, zero);
}

Id GetCbufU32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    return GetCbuf(ctx, ctx.U32[1], &UniformDefinitions::U32, sizeof(u32), binding, offset,
                   ctx.load_const_func_u32);
}

Id GetCbufU32x4(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    return GetCbuf(ctx, ctx.U32[4], &UniformDefinitions::U32x4, sizeof(u32[4]), binding, offset,
                   ctx.load_const_func_u32x4);
}

Id GetCbufElement(EmitContext& ctx, Id vector, const IR::Value& offset, u32 index_offset) {
    if (offset.IsImmediate()) {
        const u32 element{(offset.U32() / 4) % 4 + index_offset};
        return ctx.OpCompositeExtract(ctx.U32[1], vector, element);
    }
    const Id shift{ctx.OpShiftRightLogical(ctx.U32[1], ctx.Def(offset), ctx.Const(2u))};
    Id element{ctx.OpBitwiseAnd(ctx.U32[1], shift, ctx.Const(3u))};
    if (index_offset > 0) {
        element = ctx.OpIAdd(ctx.U32[1], element, ctx.Const(index_offset));
    }
    return ctx.OpVectorExtractDynamic(ctx.U32[1], vector, element);
}
} // Anonymous namespace

void EmitGetRegister(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitSetRegister(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitGetPred(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitSetPred(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitSetGotoVariable(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitGetGotoVariable(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitSetIndirectBranchVariable(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

void EmitGetIndirectBranchVariable(EmitContext&) {
    throw LogicError("Unreachable instruction");
}

Id EmitGetCbufU8(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing && ctx.profile.support_int8) {
        const Id load{GetCbuf(ctx, ctx.U8, &UniformDefinitions::U8, sizeof(u8), binding, offset,
                              ctx.load_const_func_u8)};
        return ctx.OpUConvert(ctx.U32[1], load);
    }
    Id element{};
    if (ctx.profile.support_descriptor_aliasing) {
        element = GetCbufU32(ctx, binding, offset);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        element = GetCbufElement(ctx, vector, offset, 0u);
    }
    const Id bit_offset{ctx.BitOffset8(offset)};
    return ctx.OpBitFieldUExtract(ctx.U32[1], element, bit_offset, ctx.Const(8u));
}

Id EmitGetCbufS8(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing && ctx.profile.support_int8) {
        const Id load{GetCbuf(ctx, ctx.S8, &UniformDefinitions::S8, sizeof(s8), binding, offset,
                              ctx.load_const_func_u8)};
        return ctx.OpSConvert(ctx.U32[1], load);
    }
    Id element{};
    if (ctx.profile.support_descriptor_aliasing) {
        element = GetCbufU32(ctx, binding, offset);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        element = GetCbufElement(ctx, vector, offset, 0u);
    }
    const Id bit_offset{ctx.BitOffset8(offset)};
    return ctx.OpBitFieldSExtract(ctx.U32[1], element, bit_offset, ctx.Const(8u));
}

Id EmitGetCbufU16(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing && ctx.profile.support_int16) {
        const Id load{GetCbuf(ctx, ctx.U16, &UniformDefinitions::U16, sizeof(u16), binding, offset,
                              ctx.load_const_func_u16)};
        return ctx.OpUConvert(ctx.U32[1], load);
    }
    Id element{};
    if (ctx.profile.support_descriptor_aliasing) {
        element = GetCbufU32(ctx, binding, offset);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        element = GetCbufElement(ctx, vector, offset, 0u);
    }
    const Id bit_offset{ctx.BitOffset16(offset)};
    return ctx.OpBitFieldUExtract(ctx.U32[1], element, bit_offset, ctx.Const(16u));
}

Id EmitGetCbufS16(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing && ctx.profile.support_int16) {
        const Id load{GetCbuf(ctx, ctx.S16, &UniformDefinitions::S16, sizeof(s16), binding, offset,
                              ctx.load_const_func_u16)};
        return ctx.OpSConvert(ctx.U32[1], load);
    }
    Id element{};
    if (ctx.profile.support_descriptor_aliasing) {
        element = GetCbufU32(ctx, binding, offset);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        element = GetCbufElement(ctx, vector, offset, 0u);
    }
    const Id bit_offset{ctx.BitOffset16(offset)};
    return ctx.OpBitFieldSExtract(ctx.U32[1], element, bit_offset, ctx.Const(16u));
}

Id EmitGetCbufU32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing) {
        return GetCbufU32(ctx, binding, offset);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        return GetCbufElement(ctx, vector, offset, 0u);
    }
}

Id EmitGetCbufF32(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing) {
        return GetCbuf(ctx, ctx.F32[1], &UniformDefinitions::F32, sizeof(f32), binding, offset,
                       ctx.load_const_func_f32);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        return ctx.OpBitcast(ctx.F32[1], GetCbufElement(ctx, vector, offset, 0u));
    }
}

Id EmitGetCbufU32x2(EmitContext& ctx, const IR::Value& binding, const IR::Value& offset) {
    if (ctx.profile.support_descriptor_aliasing) {
        return GetCbuf(ctx, ctx.U32[2], &UniformDefinitions::U32x2, sizeof(u32[2]), binding, offset,
                       ctx.load_const_func_u32x2);
    } else {
        const Id vector{GetCbufU32x4(ctx, binding, offset)};
        return ctx.OpCompositeConstruct(ctx.U32[2], GetCbufElement(ctx, vector, offset, 0u),
                                        GetCbufElement(ctx, vector, offset, 1u));
    }
}

Id EmitGetAttribute(EmitContext& ctx, IR::Attribute attr, Id vertex) {
    const u32 element{static_cast<u32>(attr) % 4};
    if (IR::IsGeneric(attr)) {
        const u32 index{IR::GenericAttributeIndex(attr)};
        const auto& generic{ctx.input_generics.at(index)};
        if (!ValidId(generic.id)) {
            // Attribute is disabled or varying component is not written
            return ctx.Const(element == 3 ? 1.0f : 0.0f);
        }
        const Id pointer{
            AttrPointer(ctx, generic.pointer_type, vertex, generic.id, ctx.Const(element))};
        const Id value{ctx.OpLoad(generic.component_type, pointer)};
        return [&ctx, generic, value]() {
            switch (generic.load_op) {
            case InputGenericLoadOp::Bitcast:
                return ctx.OpBitcast(ctx.F32[1], value);
            case InputGenericLoadOp::SToF:
                return ctx.OpConvertSToF(ctx.F32[1], value);
            case InputGenericLoadOp::UToF:
                return ctx.OpConvertUToF(ctx.F32[1], value);
            default:
                return value;
            };
        }();
    }
    switch (attr) {
    case IR::Attribute::PrimitiveId:
        return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.primitive_id));
    case IR::Attribute::Layer:
        return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.layer));
    case IR::Attribute::PositionX:
    case IR::Attribute::PositionY:
    case IR::Attribute::PositionZ:
    case IR::Attribute::PositionW:
        return ctx.OpLoad(
            ctx.F32[1],
            ctx.need_input_position_indirect
                ? AttrPointer(ctx, ctx.input_f32, vertex, ctx.input_position, ctx.u32_zero_value,
                              ctx.Const(element))
                : AttrPointer(ctx, ctx.input_f32, vertex, ctx.input_position, ctx.Const(element)));
    case IR::Attribute::InstanceId:
        if (ctx.profile.support_vertex_instance_id) {
            return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.instance_id));
        } else {
            const Id index{ctx.OpLoad(ctx.U32[1], ctx.instance_index)};
            const Id base{ctx.OpLoad(ctx.U32[1], ctx.base_instance)};
            return ctx.OpBitcast(ctx.F32[1], ctx.OpISub(ctx.U32[1], index, base));
        }
    case IR::Attribute::VertexId:
        if (ctx.profile.support_vertex_instance_id) {
            return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.vertex_id));
        } else {
            return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.vertex_index));
        }
    case IR::Attribute::BaseInstance:
        return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.base_instance));
    case IR::Attribute::BaseVertex:
        return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.base_vertex));
    case IR::Attribute::DrawID:
        return ctx.OpBitcast(ctx.F32[1], ctx.OpLoad(ctx.U32[1], ctx.draw_index));
    case IR::Attribute::FrontFace:
        return ctx.OpSelect(ctx.F32[1], ctx.OpLoad(ctx.U1, ctx.front_face),
                            ctx.OpBitcast(ctx.F32[1], ctx.Const(std::numeric_limits<u32>::max())),
                            ctx.f32_zero_value);
    case IR::Attribute::PointSpriteS:
        return ctx.OpLoad(ctx.F32[1],
                          ctx.OpAccessChain(ctx.input_f32, ctx.point_coord, ctx.u32_zero_value));
    case IR::Attribute::PointSpriteT:
        return ctx.OpLoad(ctx.F32[1],
                          ctx.OpAccessChain(ctx.input_f32, ctx.point_coord, ctx.Const(1U)));
    case IR::Attribute::TessellationEvaluationPointU:
        return ctx.OpLoad(ctx.F32[1],
                          ctx.OpAccessChain(ctx.input_f32, ctx.tess_coord, ctx.u32_zero_value));
    case IR::Attribute::TessellationEvaluationPointV:
        return ctx.OpLoad(ctx.F32[1],
                          ctx.OpAccessChain(ctx.input_f32, ctx.tess_coord, ctx.Const(1U)));
    default:
        throw NotImplementedException("Read attribute {}", attr);
    }
}

Id EmitGetAttributeU32(EmitContext& ctx, IR::Attribute attr, Id) {
    switch (attr) {
    case IR::Attribute::PrimitiveId:
        return ctx.OpLoad(ctx.U32[1], ctx.primitive_id);
    case IR::Attribute::InstanceId:
        if (ctx.profile.support_vertex_instance_id) {
            return ctx.OpLoad(ctx.U32[1], ctx.instance_id);
        } else {
            const Id index{ctx.OpLoad(ctx.U32[1], ctx.instance_index)};
            const Id base{ctx.OpLoad(ctx.U32[1], ctx.base_instance)};
            return ctx.OpISub(ctx.U32[1], index, base);
        }
    case IR::Attribute::VertexId:
        if (ctx.profile.support_vertex_instance_id) {
            return ctx.OpLoad(ctx.U32[1], ctx.vertex_id);
        } else {
            return ctx.OpLoad(ctx.U32[1], ctx.vertex_index);
        }
    case IR::Attribute::BaseInstance:
        return ctx.OpLoad(ctx.U32[1], ctx.base_instance);
    case IR::Attribute::BaseVertex:
        return ctx.OpLoad(ctx.U32[1], ctx.base_vertex);
    case IR::Attribute::DrawID:
        return ctx.OpLoad(ctx.U32[1], ctx.draw_index);
    default:
        throw NotImplementedException("Read U32 attribute {}", attr);
    }
}

void EmitSetAttribute(EmitContext& ctx, IR::Attribute attr, Id value, [[maybe_unused]] Id vertex) {
    const std::optional<OutAttr> output{OutputAttrPointer(ctx, attr)};
    if (!output) {
        return;
    }
    if (Sirit::ValidId(output->type)) {
        value = ctx.OpBitcast(output->type, value);
    }
    ctx.OpStore(output->pointer, value);
}

Id EmitGetAttributeIndexed(EmitContext& ctx, Id offset, Id vertex) {
    switch (ctx.stage) {
    case Stage::TessellationControl:
    case Stage::TessellationEval:
    case Stage::Geometry:
        return ctx.OpFunctionCall(ctx.F32[1], ctx.indexed_load_func, offset, vertex);
    default:
        return ctx.OpFunctionCall(ctx.F32[1], ctx.indexed_load_func, offset);
    }
}

void EmitSetAttributeIndexed(EmitContext& ctx, Id offset, Id value, [[maybe_unused]] Id vertex) {
    ctx.OpFunctionCall(ctx.void_id, ctx.indexed_store_func, offset, value);
}

Id EmitGetPatch(EmitContext& ctx, IR::Patch patch) {
    if (!IR::IsGeneric(patch)) {
        throw NotImplementedException("Non-generic patch load");
    }
    const u32 index{IR::GenericPatchIndex(patch)};
    const Id element{ctx.Const(IR::GenericPatchElement(patch))};
    const Id type{ctx.stage == Stage::TessellationControl ? ctx.output_f32 : ctx.input_f32};
    const Id pointer{ctx.OpAccessChain(type, ctx.patches.at(index), element)};
    return ctx.OpLoad(ctx.F32[1], pointer);
}

void EmitSetPatch(EmitContext& ctx, IR::Patch patch, Id value) {
    const Id pointer{[&] {
        if (IR::IsGeneric(patch)) {
            const u32 index{IR::GenericPatchIndex(patch)};
            const Id element{ctx.Const(IR::GenericPatchElement(patch))};
            return ctx.OpAccessChain(ctx.output_f32, ctx.patches.at(index), element);
        }
        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)};
            const Id index_id{ctx.Const(index)};
            return ctx.OpAccessChain(ctx.output_f32, ctx.output_tess_level_outer, index_id);
        }
        case IR::Patch::TessellationLodInteriorU:
            return ctx.OpAccessChain(ctx.output_f32, ctx.output_tess_level_inner,
                                     ctx.u32_zero_value);
        case IR::Patch::TessellationLodInteriorV:
            return ctx.OpAccessChain(ctx.output_f32, ctx.output_tess_level_inner, ctx.Const(1u));
        default:
            throw NotImplementedException("Patch {}", patch);
        }
    }()};
    ctx.OpStore(pointer, value);
}

void EmitSetFragColor(EmitContext& ctx, u32 index, u32 component, Id value) {
    const Id component_id{ctx.Const(component)};
    const Id pointer{ctx.OpAccessChain(ctx.output_f32, ctx.frag_color.at(index), component_id)};
    ctx.OpStore(pointer, value);
}

void EmitSetSampleMask(EmitContext& ctx, Id value) {
    const Id pointer{ctx.OpAccessChain(ctx.output_u32, ctx.sample_mask, ctx.u32_zero_value)};
    ctx.OpStore(pointer, value);
}

void EmitSetFragDepth(EmitContext& ctx, Id value) {
    if (!ctx.runtime_info.convert_depth_mode || ctx.profile.support_native_ndc) {
        ctx.OpStore(ctx.frag_depth, value);
        return;
    }
    const Id unit{ctx.Const(0.5f)};
    const Id new_depth{ctx.OpFma(ctx.F32[1], value, unit, unit)};
    ctx.OpStore(ctx.frag_depth, new_depth);
}

void EmitGetZFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitGetSFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitGetCFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitGetOFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitSetZFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitSetSFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitSetCFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

void EmitSetOFlag(EmitContext&) {
    throw NotImplementedException("SPIR-V Instruction");
}

Id EmitWorkgroupId(EmitContext& ctx) {
    return ctx.OpLoad(ctx.U32[3], ctx.workgroup_id);
}

Id EmitLocalInvocationId(EmitContext& ctx) {
    return ctx.OpLoad(ctx.U32[3], ctx.local_invocation_id);
}

Id EmitInvocationId(EmitContext& ctx) {
    return ctx.OpLoad(ctx.U32[1], ctx.invocation_id);
}

Id EmitInvocationInfo(EmitContext& ctx) {
    switch (ctx.stage) {
    case Stage::TessellationControl:
    case Stage::TessellationEval:
        return ctx.OpShiftLeftLogical(ctx.U32[1], ctx.OpLoad(ctx.U32[1], ctx.patch_vertices_in),
                                      ctx.Const(16u));
    default:
        LOG_WARNING(Shader, "(STUBBED) called");
        return ctx.Const(0x00ff0000u);
    }
}

Id EmitSampleId(EmitContext& ctx) {
    return ctx.OpLoad(ctx.U32[1], ctx.sample_id);
}

Id EmitIsHelperInvocation(EmitContext& ctx) {
    return ctx.OpLoad(ctx.U1, ctx.is_helper_invocation);
}

Id EmitSR_WScaleFactorXY(EmitContext& ctx) {
    LOG_WARNING(Shader, "(STUBBED) called");
    return ctx.Const(0x00ff0000u);
}

Id EmitSR_WScaleFactorZ(EmitContext& ctx) {
    LOG_WARNING(Shader, "(STUBBED) called");
    return ctx.Const(0x00ff0000u);
}

Id EmitYDirection(EmitContext& ctx) {
    return ctx.Const(ctx.runtime_info.y_negate ? -1.0f : 1.0f);
}

Id EmitResolutionDownFactor(EmitContext& ctx) {
    if (ctx.profile.unified_descriptor_binding) {
        const Id pointer_type{ctx.TypePointer(spv::StorageClass::PushConstant, ctx.F32[1])};
        const Id index{ctx.Const(ctx.rescaling_downfactor_member_index)};
        const Id pointer{ctx.OpAccessChain(pointer_type, ctx.rescaling_push_constants, index)};
        return ctx.OpLoad(ctx.F32[1], pointer);
    } else {
        const Id composite{ctx.OpLoad(ctx.F32[4], ctx.rescaling_uniform_constant)};
        return ctx.OpCompositeExtract(ctx.F32[1], composite, 2u);
    }
}

Id EmitRenderArea(EmitContext& ctx) {
    if (ctx.profile.unified_descriptor_binding) {
        const Id pointer_type{ctx.TypePointer(spv::StorageClass::PushConstant, ctx.F32[4])};
        const Id index{ctx.Const(ctx.render_are_member_index)};
        const Id pointer{ctx.OpAccessChain(pointer_type, ctx.render_area_push_constant, index)};
        return ctx.OpLoad(ctx.F32[4], pointer);
    } else {
        throw NotImplementedException("SPIR-V Instruction");
    }
}

Id EmitLoadLocal(EmitContext& ctx, Id word_offset) {
    const Id pointer{ctx.OpAccessChain(ctx.private_u32, ctx.local_memory, word_offset)};
    return ctx.OpLoad(ctx.U32[1], pointer);
}

void EmitWriteLocal(EmitContext& ctx, Id word_offset, Id value) {
    const Id pointer{ctx.OpAccessChain(ctx.private_u32, ctx.local_memory, word_offset)};
    ctx.OpStore(pointer, value);
}

} // namespace Shader::Backend::SPIRV


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

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {

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

void EmitDemoteToHelperInvocation(EmitContext& ctx) {
    if (ctx.profile.support_demote_to_helper_invocation) {
        ctx.OpDemoteToHelperInvocation();
    } else {
        const Id kill_label{ctx.OpLabel()};
        const Id impossible_label{ctx.OpLabel()};
        ctx.OpSelectionMerge(impossible_label, spv::SelectionControlMask::MaskNone);
        ctx.OpBranchConditional(ctx.true_value, kill_label, impossible_label);
        ctx.AddLabel(kill_label);
        ctx.OpKill();
        ctx.AddLabel(impossible_label);
    }
}

} // namespace Shader::Backend::SPIRV


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

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"

namespace Shader::Backend::SPIRV {
namespace {
Id ExtractU16(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpUConvert(ctx.U16, value);
    } else {
        return ctx.OpBitFieldUExtract(ctx.U32[1], value, ctx.u32_zero_value, ctx.Const(16u));
    }
}

Id ExtractS16(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpSConvert(ctx.S16, value);
    } else {
        return ctx.OpBitFieldSExtract(ctx.U32[1], value, ctx.u32_zero_value, ctx.Const(16u));
    }
}

Id ExtractU8(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int8) {
        return ctx.OpUConvert(ctx.U8, value);
    } else {
        return ctx.OpBitFieldUExtract(ctx.U32[1], value, ctx.u32_zero_value, ctx.Const(8u));
    }
}

Id ExtractS8(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int8) {
        return ctx.OpSConvert(ctx.S8, value);
    } else {
        return ctx.OpBitFieldSExtract(ctx.U32[1], value, ctx.u32_zero_value, ctx.Const(8u));
    }
}
} // Anonymous namespace

Id EmitConvertS16F16(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpSConvert(ctx.U32[1], ctx.OpConvertFToS(ctx.U16, value));
    } else {
        return ExtractS16(ctx, ctx.OpConvertFToS(ctx.U32[1], value));
    }
}

Id EmitConvertS16F32(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpSConvert(ctx.U32[1], ctx.OpConvertFToS(ctx.U16, value));
    } else {
        return ExtractS16(ctx, ctx.OpConvertFToS(ctx.U32[1], value));
    }
}

Id EmitConvertS16F64(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpSConvert(ctx.U32[1], ctx.OpConvertFToS(ctx.U16, value));
    } else {
        return ExtractS16(ctx, ctx.OpConvertFToS(ctx.U32[1], value));
    }
}

Id EmitConvertS32F16(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToS(ctx.U32[1], value);
}

Id EmitConvertS32F32(EmitContext& ctx, Id value) {
    if (ctx.profile.has_broken_signed_operations) {
        return ctx.OpBitcast(ctx.U32[1], ctx.OpConvertFToS(ctx.S32[1], value));
    } else {
        return ctx.OpConvertFToS(ctx.U32[1], value);
    }
}

Id EmitConvertS32F64(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToS(ctx.U32[1], value);
}

Id EmitConvertS64F16(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToS(ctx.U64, value);
}

Id EmitConvertS64F32(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToS(ctx.U64, value);
}

Id EmitConvertS64F64(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToS(ctx.U64, value);
}

Id EmitConvertU16F16(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpUConvert(ctx.U32[1], ctx.OpConvertFToU(ctx.U16, value));
    } else {
        return ExtractU16(ctx, ctx.OpConvertFToU(ctx.U32[1], value));
    }
}

Id EmitConvertU16F32(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpUConvert(ctx.U32[1], ctx.OpConvertFToU(ctx.U16, value));
    } else {
        return ExtractU16(ctx, ctx.OpConvertFToU(ctx.U32[1], value));
    }
}

Id EmitConvertU16F64(EmitContext& ctx, Id value) {
    if (ctx.profile.support_int16) {
        return ctx.OpUConvert(ctx.U32[1], ctx.OpConvertFToU(ctx.U16, value));
    } else {
        return ExtractU16(ctx, ctx.OpConvertFToU(ctx.U32[1], value));
    }
}

Id EmitConvertU32F16(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToU(ctx.U32[1], value);
}

Id EmitConvertU32F32(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToU(ctx.U32[1], value);
}

Id EmitConvertU32F64(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToU(ctx.U32[1], value);
}

Id EmitConvertU64F16(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToU(ctx.U64, value);
}

Id EmitConvertU64F32(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToU(ctx.U64, value);
}

Id EmitConvertU64F64(EmitContext& ctx, Id value) {
    return ctx.OpConvertFToU(ctx.U64, value);
}

Id EmitConvertU64U32(EmitContext& ctx, Id value) {
    return ctx.OpUConvert(ctx.U64, value);
}

Id EmitConvertU32U64(EmitContext& ctx, Id value) {
    return ctx.OpUConvert(ctx.U32[1], value);
}

Id EmitConvertF16F32(EmitContext& ctx, Id value) {
    return ctx.OpFConvert(ctx.F16[1], value);
}

Id EmitConvertF32F16(EmitContext& ctx, Id value) {
    return ctx.OpFConvert(ctx.F32[1], value);
}

Id EmitConvertF32F64(EmitContext& ctx, Id value) {
    return ctx.OpFConvert(ctx.F32[1], value);
}

Id EmitConvertF64F32(EmitContext& ctx, Id value) {
    return ctx.OpFConvert(ctx.F64[1], value);
}

Id EmitConvertF16S8(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F16[1], ExtractS8(ctx, value));
}

Id EmitConvertF16S16(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F16[1], ExtractS16(ctx, value));
}

Id EmitConvertF16S32(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F16[1], value);
}

Id EmitConvertF16S64(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F16[1], value);
}

Id EmitConvertF16U8(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F16[1], ExtractU8(ctx, value));
}

Id EmitConvertF16U16(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F16[1], ExtractU16(ctx, value));
}

Id EmitConvertF16U32(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F16[1], value);
}

Id EmitConvertF16U64(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F16[1], value);
}

Id EmitConvertF32S8(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F32[1], ExtractS8(ctx, value));
}

Id EmitConvertF32S16(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F32[1], ExtractS16(ctx, value));
}

Id EmitConvertF32S32(EmitContext& ctx, Id value) {
    if (ctx.profile.has_broken_signed_operations) {
        value = ctx.OpBitcast(ctx.S32[1], value);
    }
    return ctx.OpConvertSToF(ctx.F32[1], value);
}

Id EmitConvertF32S64(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F32[1], value);
}

Id EmitConvertF32U8(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F32[1], ExtractU8(ctx, value));
}

Id EmitConvertF32U16(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F32[1], ExtractU16(ctx, value));
}

Id EmitConvertF32U32(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F32[1], value);
}

Id EmitConvertF32U64(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F32[1], value);
}

Id EmitConvertF64S8(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F64[1], ExtractS8(ctx, value));
}

Id EmitConvertF64S16(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F64[1], ExtractS16(ctx, value));
}

Id EmitConvertF64S32(EmitContext& ctx, Id value) {
    if (ctx.profile.has_broken_signed_operations) {
        value = ctx.OpBitcast(ctx.S32[1], value);
    }
    return ctx.OpConvertSToF(ctx.F64[1], value);
}

Id EmitConvertF64S64(EmitContext& ctx, Id value) {
    return ctx.OpConvertSToF(ctx.F64[1], value);
}

Id EmitConvertF64U8(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F64[1], ExtractU8(ctx, value));
}

Id EmitConvertF64U16(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F64[1], ExtractU16(ctx, value));
}

Id EmitConvertF64U32(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F64[1], value);
}

Id EmitConvertF64U64(EmitContext& ctx, Id value) {
    return ctx.OpConvertUToF(ctx.F64[1], value);
}

} // namespace Shader::Backend::SPIRV


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

#include "shader_recompiler/backend/spirv/emit_spirv_instructions.h"
#include "shader_recompiler/backend/spirv/spirv_emit_context.h"
#include "shader_recompiler/frontend/ir/modifiers.h"

namespace Shader::Backend::SPIRV {
namespace {
Id Decorate(EmitContext& ctx, IR::Inst* inst, Id op) {
    const auto flags{inst->Flags<IR::FpControl>()};
    if (flags.no_contraction) {
        ctx.Decorate(op, spv::Decoration::NoContraction);
    }
    return op;
}

Id Clamp(EmitContext& ctx, Id type, Id value, Id zero, Id one) {
    if (ctx.profile.has_broken_spirv_clamp) {
        return ctx.OpFMin(type, ctx.OpFMax(type, value, zero), one);
    } else {
        return ctx.OpFClamp(type, value, zero, one);
    }
}

Id FPOrdNotEqual(EmitContext& ctx, Id lhs, Id rhs) {
    if (ctx.profile.ignore_nan_fp_comparisons) {
        const Id comp{ctx.OpFOrdEqual(ctx.U1, lhs, rhs)};
        const Id lhs_not_nan{ctx.OpLogicalNot(ctx.U1, ctx.OpIsNan(ctx.U1, lhs))};
        const Id rhs_not_nan{ctx.OpLogicalNot(ctx.U1, ctx.OpIsNan(ctx.U1, rhs))};
        return ctx.OpLogicalAnd(ctx.U1, ctx.OpLogicalAnd(ctx.U1, comp, lhs_not_nan), rhs_not_nan);
    } else {
        return ctx.OpFOrdNotEqual(ctx.U1, lhs, rhs);
    }
}

Id FPUnordCompare(Id (EmitContext::*comp_func)(Id, Id, Id), EmitContext& ctx, Id lhs, Id rhs) {
    if (ctx.profile.ignore_nan_fp_comparisons) {
        const Id lhs_nan{ctx.OpIsNan(ctx.U1, lhs)};
        const Id rhs_nan{ctx.OpIsNan(ctx.U1, rhs)};
        const Id comp{(ctx.*comp_func)(ctx.U1, lhs, rhs)};
        return ctx.OpLogicalOr(ctx.U1, ctx.OpLogicalOr(ctx.U1, comp, lhs_nan), rhs_nan);
    } else {
        return (ctx.*comp_func)(ctx.U1, lhs, rhs);
    }
}
} // Anonymous namespace

Id EmitFPAbs16(EmitContext& ctx, Id value) {
    return ctx.OpFAbs(ctx.F16[1], value);
}

Id EmitFPAbs32(EmitContext& ctx, Id value) {
    return ctx.OpFAbs(ctx.F32[1], value);
}

Id EmitFPAbs64(EmitContext& ctx, Id value) {
    return ctx.OpFAbs(ctx.F64[1], value);
}

Id EmitFPAdd16(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
    return Decorate(ctx, inst, ctx.OpFAdd(ctx.F16[1], a, b));
}

Id EmitFPAdd32(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
    return Decorate(ctx, inst, ctx.OpFAdd(ctx.F32[1], a, b));
}

Id EmitFPAdd64(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
    return Decorate(ctx, inst, ctx.OpFAdd(ctx.F64[1], a, b));
}

Id EmitFPFma16(EmitContext& ctx, IR::Inst* inst, Id a, Id b, Id c) {
    return Decorate(ctx, inst, ctx.OpFma(ctx.F16[1], a, b, c));
}

Id EmitFPFma32(EmitContext& ctx, IR::Inst* inst, Id a, Id b, Id c) {
    return Decorate(ctx, inst, ctx.OpFma(ctx.F32[1], a, b, c));
}

Id EmitFPFma64(EmitContext& ctx, IR::Inst* inst, Id a, Id b, Id c) {
    return Decorate(ctx, inst, ctx.OpFma(ctx.F64[1], a, b, c));
}

Id EmitFPMax32(EmitContext& ctx, Id a, Id b) {
    return ctx.OpFMax(ctx.F32[1], a, b);
}

Id EmitFPMax64(EmitContext& ctx, Id a, Id b) {
    return ctx.OpFMax(ctx.F64[1], a, b);
}

Id EmitFPMin32(EmitContext& ctx, Id a, Id b) {
    return ctx.OpFMin(ctx.F32[1], a, b);
}

Id EmitFPMin64(EmitContext& ctx, Id a, Id b) {
    return ctx.OpFMin(ctx.F64[1], a, b);
}

Id EmitFPMul16(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
    return Decorate(ctx, inst, ctx.OpFMul(ctx.F16[1], a, b));
}

Id EmitFPMul32(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
    return Decorate(ctx, inst, ctx.OpFMul(ctx.F32[1], a, b));
}

Id EmitFPMul64(EmitContext& ctx, IR::Inst* inst, Id a, Id b) {
    return Decorate(ctx, inst, ctx.OpFMul(ctx.F64[1], a, b));
}

Id EmitFPNeg16(EmitContext& ctx, Id value) {
    return ctx.OpFNegate(ctx.F16[1], value);
}

Id EmitFPNeg32(EmitContext& ctx, Id value) {
    return ctx.OpFNegate(ctx.F32[1], value);
}

Id EmitFPNeg64(EmitContext& ctx, Id value) {
    return ctx.OpFNegate(ctx.F64[1], value);
}

Id EmitFPSin(EmitContext& ctx, Id value) {
    return ctx.OpSin(ctx.F32[1], value);
}

Id EmitFPCos(EmitContext& ctx, Id value) {
    return ctx.OpCos(ctx.F32[1], value);
}

Id EmitFPExp2(EmitContext& ctx, Id value) {
    return ctx.OpExp2(ctx.F32[1], value);
}

Id EmitFPLog2(EmitContext& ctx, Id value) {
    return ctx.OpLog2(ctx.F32[1], value);
}

Id EmitFPRecip32(EmitContext& ctx, Id value) {
    return ctx.OpFDiv(ctx.F32[1], ctx.Const(1.0f), value);
}

Id EmitFPRecip64(EmitContext& ctx, Id value) {
    return ctx.OpFDiv(ctx.F64[1], ctx.Constant(ctx.F64[1], 1.0f), value);
}

Id EmitFPRecipSqrt32(EmitContext& ctx, Id value) {
    return ctx.OpInverseSqrt(ctx.F32[1], value);
}

Id EmitFPRecipSqrt64(EmitContext& ctx, Id value) {
    return ctx.OpInverseSqrt(ctx.F64[1], value);
}

Id EmitFPSqrt(EmitContext& ctx, Id value) {
    return ctx.OpSqrt(ctx.F32[1], value);
}

Id EmitFPSaturate16(EmitContext& ctx, Id value) {
    const Id zero{ctx.Constant(ctx.F16[1], u16{0})};
    const Id one{ctx.Constant(ctx.F16[1], u16{0x3c00})};
    return Clamp(ctx, ctx.F16[1], value, zero, one);
}

Id EmitFPSaturate32(EmitContext& ctx, Id value) {
    const Id zero{ctx.Const(f32{0.0})};
    const Id one{ctx.Const(f32{1.0})};
    return Clamp(ctx, ctx.F32[1], value, zero, one);
}

Id EmitFPSaturate64(EmitContext& ctx, Id value) {
    const Id zero{ctx.Constant(ctx.F64[1], f64{0.0})};
    const Id one{ctx.Constant(ctx.F64[1], f64{1.0})};
    return Clamp(ctx, ctx.F64[1], value, zero, one);
}

Id EmitFPClamp16(EmitContext& ctx, Id value, Id min_value, Id max_value) {
    return Clamp(ctx, ctx.F16[1], value, min_value, max_value);
}

Id EmitFPClamp32(EmitContext& ctx, Id value, Id min_value, Id max_value) {
    return Clamp(ctx, ctx.F32[1], value, min_value, max_value);
}

Id EmitFPClamp64(EmitContext& ctx, Id value, Id min_value, Id max_value) {
    return Clamp(ctx, ctx.F64[1], value, min_value, max_value);
}

Id EmitFPRoundEven16(EmitContext& ctx, Id value) {
    return ctx.OpRoundEven(ctx.F16[1], value);
}

Id EmitFPRoundEven32(EmitContext& ctx, Id value) {
    return ctx.OpRoundEven(ctx.F32[1], value);
}

Id EmitFPRoundEven64(EmitContext& ctx, Id value) {
    return ctx.OpRoundEven(ctx.F64[1], value);
}

Id EmitFPFloor16(EmitContext& ctx, Id value) {
    return ctx.OpFloor(ctx.F16[1], value);
}

Id EmitFPFloor32(EmitContext& ctx, Id value) {
    return ctx.OpFloor(ctx.F32[1], value);
}

Id EmitFPFloor64(EmitContext& ctx, Id value) {
    return ctx.OpFloor(ctx.F64[1], value);
}

Id EmitFPCeil16(EmitContext& ctx, Id value) {
    return ctx.OpCeil(ctx.F16[1], value);
}

Id EmitFPCeil32(EmitContext& ctx, Id value) {
    return ctx.OpCeil(ctx.F32[1], value);
}

Id EmitFPCeil64(EmitContext& ctx, Id value) {
    return ctx.OpCeil(ctx.F64[1], value);
}

Id EmitFPTrunc16(EmitContext& ctx, Id value) {
    return ctx.OpTrunc(ctx.F16[1], value);
}

Id EmitFPTrunc32(EmitContext& ctx, Id value) {
    return ctx.OpTrunc(ctx.F32[1], value);
}

Id EmitFPTrunc64(EmitContext& ctx, Id value) {
    return ctx.OpTrunc(ctx.F64[1], value);
}

Id EmitFPOrdEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdEqual(ctx.U1, lhs, rhs);
}

Id EmitFPUnordEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordEqual, ctx, lhs, rhs);
}

Id EmitFPUnordEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordEqual, ctx, lhs, rhs);
}

Id EmitFPUnordEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordEqual, ctx, lhs, rhs);
}

Id EmitFPOrdNotEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return FPOrdNotEqual(ctx, lhs, rhs);
}

Id EmitFPOrdNotEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return FPOrdNotEqual(ctx, lhs, rhs);
}

Id EmitFPOrdNotEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return FPOrdNotEqual(ctx, lhs, rhs);
}

Id EmitFPUnordNotEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFUnordNotEqual(ctx.U1, lhs, rhs);
}

Id EmitFPUnordNotEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFUnordNotEqual(ctx.U1, lhs, rhs);
}

Id EmitFPUnordNotEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFUnordNotEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdLessThan16(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdLessThan(ctx.U1, lhs, rhs);
}

Id EmitFPOrdLessThan32(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdLessThan(ctx.U1, lhs, rhs);
}

Id EmitFPOrdLessThan64(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdLessThan(ctx.U1, lhs, rhs);
}

Id EmitFPUnordLessThan16(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordLessThan, ctx, lhs, rhs);
}

Id EmitFPUnordLessThan32(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordLessThan, ctx, lhs, rhs);
}

Id EmitFPUnordLessThan64(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordLessThan, ctx, lhs, rhs);
}

Id EmitFPOrdGreaterThan16(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdGreaterThan(ctx.U1, lhs, rhs);
}

Id EmitFPOrdGreaterThan32(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdGreaterThan(ctx.U1, lhs, rhs);
}

Id EmitFPOrdGreaterThan64(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdGreaterThan(ctx.U1, lhs, rhs);
}

Id EmitFPUnordGreaterThan16(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordGreaterThan, ctx, lhs, rhs);
}

Id EmitFPUnordGreaterThan32(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordGreaterThan, ctx, lhs, rhs);
}

Id EmitFPUnordGreaterThan64(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordGreaterThan, ctx, lhs, rhs);
}

Id EmitFPOrdLessThanEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdLessThanEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdLessThanEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdLessThanEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdLessThanEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdLessThanEqual(ctx.U1, lhs, rhs);
}

Id EmitFPUnordLessThanEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordLessThanEqual, ctx, lhs, rhs);
}

Id EmitFPUnordLessThanEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordLessThanEqual, ctx, lhs, rhs);
}

Id EmitFPUnordLessThanEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordLessThanEqual, ctx, lhs, rhs);
}

Id EmitFPOrdGreaterThanEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdGreaterThanEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdGreaterThanEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdGreaterThanEqual(ctx.U1, lhs, rhs);
}

Id EmitFPOrdGreaterThanEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return ctx.OpFOrdGreaterThanEqual(ctx.U1, lhs, rhs);
}

Id EmitFPUnordGreaterThanEqual16(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordGreaterThanEqual, ctx, lhs, rhs);
}

Id EmitFPUnordGreaterThanEqual32(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordGreaterThanEqual, ctx, lhs, rhs);
}

Id EmitFPUnordGreaterThanEqual64(EmitContext& ctx, Id lhs, Id rhs) {
    return FPUnordCompare(&EmitContext::OpFUnordGreaterThanEqual, ctx, lhs, rhs);
}

Id EmitFPIsNan16(EmitContext& ctx, Id value) {
    return ctx.OpIsNan(ctx.U1, value);
}

Id EmitFPIsNan32(EmitContext& ctx, Id value) {
    return ctx.OpIsNan(ctx.U1, value);
}

Id EmitFPIsNan64(EmitContext& ctx, Id value) {
    return ctx.OpIsNan(ctx.U1, value);
}

} // namespace Shader::Backend::SPIRV