Initial work

This commit is contained in:
gdk 2019-10-13 03:02:07 -03:00 committed by Thog
parent f617fb542a
commit 1876b346fe
518 changed files with 15170 additions and 12486 deletions

View file

@ -0,0 +1,15 @@
namespace Ryujinx.Graphics.Shader
{
public struct BufferDescriptor
{
public string Name { get; }
public int Slot { get; }
public BufferDescriptor(string name, int slot)
{
Name = name;
Slot = slot;
}
}
}

View file

@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.Text;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
class CodeGenContext
{
private const string Tab = " ";
public ShaderConfig Config { get; }
public List<BufferDescriptor> CBufferDescriptors { get; }
public List<BufferDescriptor> SBufferDescriptors { get; }
public List<TextureDescriptor> TextureDescriptors { get; }
public OperandManager OperandManager { get; }
private StringBuilder _sb;
private int _level;
private string _indentation;
public CodeGenContext(ShaderConfig config)
{
Config = config;
CBufferDescriptors = new List<BufferDescriptor>();
SBufferDescriptors = new List<BufferDescriptor>();
TextureDescriptors = new List<TextureDescriptor>();
OperandManager = new OperandManager();
_sb = new StringBuilder();
}
public void AppendLine()
{
_sb.AppendLine();
}
public void AppendLine(string str)
{
_sb.AppendLine(_indentation + str);
}
public string GetCode()
{
return _sb.ToString();
}
public void EnterScope()
{
AppendLine("{");
_level++;
UpdateIndentation();
}
public void LeaveScope(string suffix = "")
{
if (_level == 0)
{
return;
}
_level--;
UpdateIndentation();
AppendLine("}" + suffix);
}
private void UpdateIndentation()
{
_indentation = GetIndentation(_level);
}
private static string GetIndentation(int level)
{
string indentation = string.Empty;
for (int index = 0; index < level; index++)
{
indentation += Tab;
}
return indentation;
}
}
}

View file

@ -0,0 +1,319 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
static class Declarations
{
// At least 16 attributes are guaranteed by the spec.
public const int MaxAttributes = 16;
public static void Declare(CodeGenContext context, StructuredProgramInfo info)
{
context.AppendLine("#version 420 core");
context.AppendLine("#extension GL_ARB_shader_storage_buffer_object : enable");
if (context.Config.Stage == ShaderStage.Compute)
{
context.AppendLine("#extension GL_ARB_compute_shader : enable");
}
context.AppendLine();
context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
context.AppendLine();
if (context.Config.Stage == ShaderStage.Geometry)
{
string inPrimitive = "points";
if ((context.Config.Flags & TranslationFlags.Unspecialized) != 0)
{
inPrimitive = DefineNames.InputTopologyName;
}
context.AppendLine($"layout ({inPrimitive}) in;");
string outPrimitive = "triangle_strip";
switch (context.Config.OutputTopology)
{
case OutputTopology.LineStrip: outPrimitive = "line_strip"; break;
case OutputTopology.PointList: outPrimitive = "points"; break;
case OutputTopology.TriangleStrip: outPrimitive = "triangle_strip"; break;
}
int maxOutputVertices = context.Config.MaxOutputVertices;
context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
context.AppendLine();
}
context.AppendLine("layout (std140) uniform Extra");
context.EnterScope();
context.AppendLine("vec2 flip;");
context.AppendLine("int instance;");
context.LeaveScope(";");
context.AppendLine();
context.AppendLine($"precise float {DefaultNames.LocalMemoryName}[0x100];");
context.AppendLine();
if (info.CBuffers.Count != 0)
{
DeclareUniforms(context, info);
context.AppendLine();
}
if (info.SBuffers.Count != 0)
{
DeclareStorage(context, info);
context.AppendLine();
}
if (info.Samplers.Count != 0)
{
DeclareSamplers(context, info);
context.AppendLine();
}
if (context.Config.Stage != ShaderStage.Compute)
{
if (info.IAttributes.Count != 0)
{
DeclareInputAttributes(context, info);
context.AppendLine();
}
if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
{
DeclareOutputAttributes(context, info);
context.AppendLine();
}
}
else
{
string localSizeX = "1";
string localSizeY = "1";
string localSizeZ = "1";
if ((context.Config.Flags & TranslationFlags.Unspecialized) != 0)
{
localSizeX = DefineNames.LocalSizeX;
localSizeY = DefineNames.LocalSizeY;
localSizeZ = DefineNames.LocalSizeZ;
}
context.AppendLine(
$"layout (" +
$"local_size_x = {localSizeX}, " +
$"local_size_y = {localSizeY}, " +
$"local_size_z = {localSizeZ}) in;");
context.AppendLine();
}
}
public static void DeclareLocals(CodeGenContext context, StructuredProgramInfo info)
{
foreach (AstOperand decl in info.Locals)
{
string name = context.OperandManager.DeclareLocal(decl);
context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
}
}
private static string GetVarTypeName(VariableType type)
{
switch (type)
{
case VariableType.Bool: return "bool";
case VariableType.F32: return "precise float";
case VariableType.S32: return "int";
case VariableType.U32: return "uint";
}
throw new ArgumentException($"Invalid variable type \"{type}\".");
}
private static void DeclareUniforms(CodeGenContext context, StructuredProgramInfo info)
{
foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
{
string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
ubName += "_" + DefaultNames.UniformNamePrefix + cbufSlot;
context.CBufferDescriptors.Add(new BufferDescriptor(ubName, cbufSlot));
context.AppendLine("layout (std140) uniform " + ubName);
context.EnterScope();
string ubSize = "[" + NumberFormatter.FormatInt(context.Config.MaxCBufferSize / 16) + "]";
context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, cbufSlot) + ubSize + ";");
context.LeaveScope(";");
}
}
private static void DeclareStorage(CodeGenContext context, StructuredProgramInfo info)
{
foreach (int sbufSlot in info.SBuffers.OrderBy(x => x))
{
string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
sbName += "_" + DefaultNames.StorageNamePrefix + sbufSlot;
context.SBufferDescriptors.Add(new BufferDescriptor(sbName, sbufSlot));
context.AppendLine("layout (std430) buffer " + sbName);
context.EnterScope();
context.AppendLine("precise float " + OperandManager.GetSbName(context.Config.Stage, sbufSlot) + "[];");
context.LeaveScope(";");
}
}
private static void DeclareSamplers(CodeGenContext context, StructuredProgramInfo info)
{
Dictionary<string, AstTextureOperation> samplers = new Dictionary<string, AstTextureOperation>();
foreach (AstTextureOperation texOp in info.Samplers.OrderBy(x => x.Handle))
{
string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp);
if (!samplers.TryAdd(samplerName, texOp))
{
continue;
}
string samplerTypeName = GetSamplerTypeName(texOp.Target);
context.AppendLine("uniform " + samplerTypeName + " " + samplerName + ";");
}
foreach (KeyValuePair<string, AstTextureOperation> kv in samplers)
{
string samplerName = kv.Key;
AstTextureOperation texOp = kv.Value;
TextureDescriptor desc;
if ((texOp.Flags & TextureFlags.Bindless) != 0)
{
AstOperand operand = texOp.GetSource(0) as AstOperand;
desc = new TextureDescriptor(samplerName, texOp.Target, operand.CbufSlot, operand.CbufOffset);
}
else
{
desc = new TextureDescriptor(samplerName, texOp.Target, texOp.Handle);
}
context.TextureDescriptors.Add(desc);
}
}
private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
foreach (int attr in info.IAttributes.OrderBy(x => x))
{
string iq = info.InterpolationQualifiers[attr].ToGlslQualifier();
if (iq != string.Empty)
{
iq += " ";
}
context.AppendLine($"layout (location = {attr}) {iq}in vec4 {DefaultNames.IAttributePrefix}{attr}{suffix};");
}
}
private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
if (context.Config.Stage == ShaderStage.Fragment)
{
DeclareUsedOutputAttributes(context, info);
}
else
{
DeclareAllOutputAttributes(context, info);
}
}
private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
foreach (int attr in info.OAttributes.OrderBy(x => x))
{
context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
}
}
private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
{
for (int attr = 0; attr < MaxAttributes; attr++)
{
string iq = $"{DefineNames.OutQualifierPrefixName}{attr} ";
context.AppendLine($"layout (location = {attr}) {iq}out vec4 {DefaultNames.OAttributePrefix}{attr};");
}
foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
{
context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
}
}
private static string GetSamplerTypeName(TextureTarget type)
{
string typeName;
switch (type & TextureTarget.Mask)
{
case TextureTarget.Texture1D: typeName = "sampler1D"; break;
case TextureTarget.Texture2D: typeName = "sampler2D"; break;
case TextureTarget.Texture3D: typeName = "sampler3D"; break;
case TextureTarget.TextureCube: typeName = "samplerCube"; break;
default: throw new ArgumentException($"Invalid sampler type \"{type}\".");
}
if ((type & TextureTarget.Multisample) != 0)
{
typeName += "MS";
}
if ((type & TextureTarget.Array) != 0)
{
typeName += "Array";
}
if ((type & TextureTarget.Shadow) != 0)
{
typeName += "Shadow";
}
return typeName;
}
}
}

View file

@ -0,0 +1,22 @@
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
static class DefaultNames
{
public const string LocalNamePrefix = "temp";
public const string SamplerNamePrefix = "tex";
public const string IAttributePrefix = "in_attr";
public const string OAttributePrefix = "out_attr";
public const string StorageNamePrefix = "s";
public const string StorageNameSuffix = "data";
public const string UniformNamePrefix = "c";
public const string UniformNameSuffix = "data";
public const string LocalMemoryName = "local_mem";
public const string UndefinedName = "undef";
}
}

View file

@ -0,0 +1,141 @@
using Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using System;
using static Ryujinx.Graphics.Shader.CodeGen.Glsl.TypeConversion;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
static class GlslGenerator
{
public static GlslProgram Generate(StructuredProgramInfo info, ShaderConfig config)
{
CodeGenContext context = new CodeGenContext(config);
Declarations.Declare(context, info);
PrintMainBlock(context, info);
return new GlslProgram(
context.CBufferDescriptors.ToArray(),
context.SBufferDescriptors.ToArray(),
context.TextureDescriptors.ToArray(),
context.GetCode());
}
private static void PrintMainBlock(CodeGenContext context, StructuredProgramInfo info)
{
context.AppendLine("void main()");
context.EnterScope();
Declarations.DeclareLocals(context, info);
// Ensure that unused attributes are set, otherwise the downstream
// compiler may eliminate them.
// (Not needed for fragment shader as it is the last stage).
if (context.Config.Stage != ShaderStage.Compute &&
context.Config.Stage != ShaderStage.Fragment)
{
for (int attr = 0; attr < Declarations.MaxAttributes; attr++)
{
if (info.OAttributes.Contains(attr))
{
continue;
}
context.AppendLine($"{DefaultNames.OAttributePrefix}{attr} = vec4(0);");
}
}
PrintBlock(context, info.MainBlock);
context.LeaveScope();
}
private static void PrintBlock(CodeGenContext context, AstBlock block)
{
AstBlockVisitor visitor = new AstBlockVisitor(block);
visitor.BlockEntered += (sender, e) =>
{
switch (e.Block.Type)
{
case AstBlockType.DoWhile:
context.AppendLine("do");
break;
case AstBlockType.Else:
context.AppendLine("else");
break;
case AstBlockType.ElseIf:
context.AppendLine($"else if ({GetCondExpr(context, e.Block.Condition)})");
break;
case AstBlockType.If:
context.AppendLine($"if ({GetCondExpr(context, e.Block.Condition)})");
break;
default: throw new InvalidOperationException($"Found unexpected block type \"{e.Block.Type}\".");
}
context.EnterScope();
};
visitor.BlockLeft += (sender, e) =>
{
context.LeaveScope();
if (e.Block.Type == AstBlockType.DoWhile)
{
context.AppendLine($"while ({GetCondExpr(context, e.Block.Condition)});");
}
};
foreach (IAstNode node in visitor.Visit())
{
if (node is AstOperation operation)
{
context.AppendLine(InstGen.GetExpression(context, operation) + ";");
}
else if (node is AstAssignment assignment)
{
VariableType srcType = OperandManager.GetNodeDestType(assignment.Source);
VariableType dstType = OperandManager.GetNodeDestType(assignment.Destination);
string dest;
if (assignment.Destination is AstOperand operand && operand.Type == OperandType.Attribute)
{
dest = OperandManager.GetOutAttributeName(operand, context.Config.Stage);
}
else
{
dest = InstGen.GetExpression(context, assignment.Destination);
}
string src = ReinterpretCast(context, assignment.Source, srcType, dstType);
context.AppendLine(dest + " = " + src + ";");
}
else if (node is AstComment comment)
{
context.AppendLine("// " + comment.Comment);
}
else
{
throw new InvalidOperationException($"Found unexpected node type \"{node?.GetType().Name ?? "null"}\".");
}
}
}
private static string GetCondExpr(CodeGenContext context, IAstNode cond)
{
VariableType srcType = OperandManager.GetNodeDestType(cond);
return ReinterpretCast(context, cond, srcType, VariableType.Bool);
}
}
}

View file

@ -0,0 +1,23 @@
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
class GlslProgram
{
public BufferDescriptor[] CBufferDescriptors { get; }
public BufferDescriptor[] SBufferDescriptors { get; }
public TextureDescriptor[] TextureDescriptors { get; }
public string Code { get; }
public GlslProgram(
BufferDescriptor[] cBufferDescriptors,
BufferDescriptor[] sBufferDescriptors,
TextureDescriptor[] textureDescriptors,
string code)
{
CBufferDescriptors = cBufferDescriptors;
SBufferDescriptors = sBufferDescriptors;
TextureDescriptors = textureDescriptors;
Code = code;
}
}
}

View file

@ -0,0 +1,127 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using System;
using static Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions.InstGenHelper;
using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
static class InstGen
{
public static string GetExpression(CodeGenContext context, IAstNode node)
{
if (node is AstOperation operation)
{
return GetExpression(context, operation);
}
else if (node is AstOperand operand)
{
return context.OperandManager.GetExpression(operand, context.Config.Stage);
}
throw new ArgumentException($"Invalid node type \"{node?.GetType().Name ?? "null"}\".");
}
private static string GetExpression(CodeGenContext context, AstOperation operation)
{
Instruction inst = operation.Inst;
InstInfo info = GetInstructionInfo(inst);
if ((info.Type & InstType.Call) != 0)
{
int arity = (int)(info.Type & InstType.ArityMask);
string args = string.Empty;
for (int argIndex = 0; argIndex < arity; argIndex++)
{
if (argIndex != 0)
{
args += ", ";
}
VariableType dstType = GetSrcVarType(inst, argIndex);
args += GetSoureExpr(context, operation.GetSource(argIndex), dstType);
}
return info.OpName + "(" + args + ")";
}
else if ((info.Type & InstType.Op) != 0)
{
string op = info.OpName;
int arity = (int)(info.Type & InstType.ArityMask);
string[] expr = new string[arity];
for (int index = 0; index < arity; index++)
{
IAstNode src = operation.GetSource(index);
string srcExpr = GetSoureExpr(context, src, GetSrcVarType(inst, index));
bool isLhs = arity == 2 && index == 0;
expr[index] = Enclose(srcExpr, src, inst, info, isLhs);
}
switch (arity)
{
case 0:
return op;
case 1:
return op + expr[0];
case 2:
return $"{expr[0]} {op} {expr[1]}";
case 3:
return $"{expr[0]} {op[0]} {expr[1]} {op[1]} {expr[2]}";
}
}
else if ((info.Type & InstType.Special) != 0)
{
switch (inst)
{
case Instruction.LoadAttribute:
return InstGenMemory.LoadAttribute(context, operation);
case Instruction.LoadConstant:
return InstGenMemory.LoadConstant(context, operation);
case Instruction.LoadLocal:
return InstGenMemory.LoadLocal(context, operation);
case Instruction.LoadStorage:
return InstGenMemory.LoadStorage(context, operation);
case Instruction.PackHalf2x16:
return InstGenPacking.PackHalf2x16(context, operation);
case Instruction.StoreLocal:
return InstGenMemory.StoreLocal(context, operation);
case Instruction.StoreStorage:
return InstGenMemory.StoreStorage(context, operation);
case Instruction.TextureSample:
return InstGenMemory.TextureSample(context, operation);
case Instruction.TextureSize:
return InstGenMemory.TextureSize(context, operation);
case Instruction.UnpackHalf2x16:
return InstGenPacking.UnpackHalf2x16(context, operation);
}
}
return "0";
throw new InvalidOperationException($"Unexpected instruction type \"{info.Type}\".");
}
}
}

View file

@ -0,0 +1,175 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using static Ryujinx.Graphics.Shader.CodeGen.Glsl.TypeConversion;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
static class InstGenHelper
{
private static InstInfo[] _infoTbl;
static InstGenHelper()
{
_infoTbl = new InstInfo[(int)Instruction.Count];
Add(Instruction.Absolute, InstType.CallUnary, "abs");
Add(Instruction.Add, InstType.OpBinaryCom, "+", 2);
Add(Instruction.BitfieldExtractS32, InstType.CallTernary, "bitfieldExtract");
Add(Instruction.BitfieldExtractU32, InstType.CallTernary, "bitfieldExtract");
Add(Instruction.BitfieldInsert, InstType.CallQuaternary, "bitfieldInsert");
Add(Instruction.BitfieldReverse, InstType.CallUnary, "bitfieldReverse");
Add(Instruction.BitwiseAnd, InstType.OpBinaryCom, "&", 6);
Add(Instruction.BitwiseExclusiveOr, InstType.OpBinaryCom, "^", 7);
Add(Instruction.BitwiseNot, InstType.OpUnary, "~", 0);
Add(Instruction.BitwiseOr, InstType.OpBinaryCom, "|", 8);
Add(Instruction.Ceiling, InstType.CallUnary, "ceil");
Add(Instruction.Clamp, InstType.CallTernary, "clamp");
Add(Instruction.ClampU32, InstType.CallTernary, "clamp");
Add(Instruction.CompareEqual, InstType.OpBinaryCom, "==", 5);
Add(Instruction.CompareGreater, InstType.OpBinary, ">", 4);
Add(Instruction.CompareGreaterOrEqual, InstType.OpBinary, ">=", 4);
Add(Instruction.CompareGreaterOrEqualU32, InstType.OpBinary, ">=", 4);
Add(Instruction.CompareGreaterU32, InstType.OpBinary, ">", 4);
Add(Instruction.CompareLess, InstType.OpBinary, "<", 4);
Add(Instruction.CompareLessOrEqual, InstType.OpBinary, "<=", 4);
Add(Instruction.CompareLessOrEqualU32, InstType.OpBinary, "<=", 4);
Add(Instruction.CompareLessU32, InstType.OpBinary, "<", 4);
Add(Instruction.CompareNotEqual, InstType.OpBinaryCom, "!=", 5);
Add(Instruction.ConditionalSelect, InstType.OpTernary, "?:", 12);
Add(Instruction.ConvertFPToS32, InstType.CallUnary, "int");
Add(Instruction.ConvertS32ToFP, InstType.CallUnary, "float");
Add(Instruction.ConvertU32ToFP, InstType.CallUnary, "float");
Add(Instruction.Cosine, InstType.CallUnary, "cos");
Add(Instruction.Discard, InstType.OpNullary, "discard");
Add(Instruction.Divide, InstType.OpBinary, "/", 1);
Add(Instruction.EmitVertex, InstType.CallNullary, "EmitVertex");
Add(Instruction.EndPrimitive, InstType.CallNullary, "EndPrimitive");
Add(Instruction.ExponentB2, InstType.CallUnary, "exp2");
Add(Instruction.Floor, InstType.CallUnary, "floor");
Add(Instruction.FusedMultiplyAdd, InstType.CallTernary, "fma");
Add(Instruction.IsNan, InstType.CallUnary, "isnan");
Add(Instruction.LoadAttribute, InstType.Special);
Add(Instruction.LoadConstant, InstType.Special);
Add(Instruction.LoadLocal, InstType.Special);
Add(Instruction.LoadStorage, InstType.Special);
Add(Instruction.LogarithmB2, InstType.CallUnary, "log2");
Add(Instruction.LogicalAnd, InstType.OpBinaryCom, "&&", 9);
Add(Instruction.LogicalExclusiveOr, InstType.OpBinaryCom, "^^", 10);
Add(Instruction.LogicalNot, InstType.OpUnary, "!", 0);
Add(Instruction.LogicalOr, InstType.OpBinaryCom, "||", 11);
Add(Instruction.LoopBreak, InstType.OpNullary, "break");
Add(Instruction.LoopContinue, InstType.OpNullary, "continue");
Add(Instruction.PackHalf2x16, InstType.Special);
Add(Instruction.ShiftLeft, InstType.OpBinary, "<<", 3);
Add(Instruction.ShiftRightS32, InstType.OpBinary, ">>", 3);
Add(Instruction.ShiftRightU32, InstType.OpBinary, ">>", 3);
Add(Instruction.Maximum, InstType.CallBinary, "max");
Add(Instruction.MaximumU32, InstType.CallBinary, "max");
Add(Instruction.Minimum, InstType.CallBinary, "min");
Add(Instruction.MinimumU32, InstType.CallBinary, "min");
Add(Instruction.Multiply, InstType.OpBinaryCom, "*", 1);
Add(Instruction.Negate, InstType.OpUnary, "-", 0);
Add(Instruction.ReciprocalSquareRoot, InstType.CallUnary, "inversesqrt");
Add(Instruction.Return, InstType.OpNullary, "return");
Add(Instruction.Sine, InstType.CallUnary, "sin");
Add(Instruction.SquareRoot, InstType.CallUnary, "sqrt");
Add(Instruction.StoreLocal, InstType.Special);
Add(Instruction.StoreStorage, InstType.Special);
Add(Instruction.Subtract, InstType.OpBinary, "-", 2);
Add(Instruction.TextureSample, InstType.Special);
Add(Instruction.TextureSize, InstType.Special);
Add(Instruction.Truncate, InstType.CallUnary, "trunc");
Add(Instruction.UnpackHalf2x16, InstType.Special);
}
private static void Add(Instruction inst, InstType flags, string opName = null, int precedence = 0)
{
_infoTbl[(int)inst] = new InstInfo(flags, opName, precedence);
}
public static InstInfo GetInstructionInfo(Instruction inst)
{
return _infoTbl[(int)(inst & Instruction.Mask)];
}
public static string GetSoureExpr(CodeGenContext context, IAstNode node, VariableType dstType)
{
return ReinterpretCast(context, node, OperandManager.GetNodeDestType(node), dstType);
}
public static string Enclose(string expr, IAstNode node, Instruction pInst, bool isLhs)
{
InstInfo pInfo = GetInstructionInfo(pInst);
return Enclose(expr, node, pInst, pInfo, isLhs);
}
public static string Enclose(string expr, IAstNode node, Instruction pInst, InstInfo pInfo, bool isLhs = false)
{
if (NeedsParenthesis(node, pInst, pInfo, isLhs))
{
expr = "(" + expr + ")";
}
return expr;
}
public static bool NeedsParenthesis(IAstNode node, Instruction pInst, InstInfo pInfo, bool isLhs)
{
// If the node isn't a operation, then it can only be a operand,
// and those never needs to be surrounded in parenthesis.
if (!(node is AstOperation operation))
{
// This is sort of a special case, if this is a negative constant,
// and it is consumed by a unary operation, we need to put on the parenthesis,
// as in GLSL a sequence like --2 or ~-1 is not valid.
if (IsNegativeConst(node) && pInfo.Type == InstType.OpUnary)
{
return true;
}
return false;
}
if ((pInfo.Type & (InstType.Call | InstType.Special)) != 0)
{
return false;
}
InstInfo info = _infoTbl[(int)(operation.Inst & Instruction.Mask)];
if ((info.Type & (InstType.Call | InstType.Special)) != 0)
{
return false;
}
if (info.Precedence < pInfo.Precedence)
{
return false;
}
if (info.Precedence == pInfo.Precedence && isLhs)
{
return false;
}
if (pInst == operation.Inst && info.Type == InstType.OpBinaryCom)
{
return false;
}
return true;
}
private static bool IsNegativeConst(IAstNode node)
{
if (!(node is AstOperand operand))
{
return false;
}
return operand.Type == OperandType.Constant && operand.Value < 0;
}
}
}

View file

@ -0,0 +1,320 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using System;
using static Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions.InstGenHelper;
using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
static class InstGenMemory
{
public static string LoadAttribute(CodeGenContext context, AstOperation operation)
{
IAstNode src1 = operation.GetSource(0);
IAstNode src2 = operation.GetSource(1);
if (!(src1 is AstOperand attr) || attr.Type != OperandType.Attribute)
{
throw new InvalidOperationException("First source of LoadAttribute must be a attribute.");
}
string indexExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
return OperandManager.GetAttributeName(attr, context.Config.Stage, isOutAttr: false, indexExpr);
}
public static string LoadConstant(CodeGenContext context, AstOperation operation)
{
IAstNode src1 = operation.GetSource(0);
IAstNode src2 = operation.GetSource(1);
string offsetExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
offsetExpr = Enclose(offsetExpr, src2, Instruction.ShiftRightS32, isLhs: true);
return OperandManager.GetConstantBufferName(src1, offsetExpr, context.Config.Stage);
}
public static string LoadLocal(CodeGenContext context, AstOperation operation)
{
IAstNode src1 = operation.GetSource(0);
string offsetExpr = GetSoureExpr(context, src1, GetSrcVarType(operation.Inst, 0));
return $"{DefaultNames.LocalMemoryName}[{offsetExpr}]";
}
public static string LoadStorage(CodeGenContext context, AstOperation operation)
{
IAstNode src1 = operation.GetSource(0);
IAstNode src2 = operation.GetSource(1);
string offsetExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
return OperandManager.GetStorageBufferName(src1, offsetExpr, context.Config.Stage);
}
public static string StoreLocal(CodeGenContext context, AstOperation operation)
{
IAstNode src1 = operation.GetSource(0);
IAstNode src2 = operation.GetSource(1);
string offsetExpr = GetSoureExpr(context, src1, GetSrcVarType(operation.Inst, 0));
VariableType srcType = OperandManager.GetNodeDestType(src2);
string src = TypeConversion.ReinterpretCast(context, src2, srcType, VariableType.F32);
return $"{DefaultNames.LocalMemoryName}[{offsetExpr}] = {src}";
}
public static string StoreStorage(CodeGenContext context, AstOperation operation)
{
IAstNode src1 = operation.GetSource(0);
IAstNode src2 = operation.GetSource(1);
IAstNode src3 = operation.GetSource(2);
string offsetExpr = GetSoureExpr(context, src2, GetSrcVarType(operation.Inst, 1));
VariableType srcType = OperandManager.GetNodeDestType(src3);
string src = TypeConversion.ReinterpretCast(context, src3, srcType, VariableType.F32);
string sbName = OperandManager.GetStorageBufferName(src1, offsetExpr, context.Config.Stage);
return $"{sbName} = {src}";
}
public static string TextureSample(CodeGenContext context, AstOperation operation)
{
AstTextureOperation texOp = (AstTextureOperation)operation;
bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
bool isGather = (texOp.Flags & TextureFlags.Gather) != 0;
bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
bool hasLodBias = (texOp.Flags & TextureFlags.LodBias) != 0;
bool hasLodLevel = (texOp.Flags & TextureFlags.LodLevel) != 0;
bool hasOffset = (texOp.Flags & TextureFlags.Offset) != 0;
bool hasOffsets = (texOp.Flags & TextureFlags.Offsets) != 0;
bool isArray = (texOp.Target & TextureTarget.Array) != 0;
bool isMultisample = (texOp.Target & TextureTarget.Multisample) != 0;
bool isShadow = (texOp.Target & TextureTarget.Shadow) != 0;
// This combination is valid, but not available on GLSL.
// For now, ignore the LOD level and do a normal sample.
// TODO: How to implement it properly?
if (hasLodLevel && isArray && isShadow)
{
hasLodLevel = false;
}
string texCall = intCoords ? "texelFetch" : "texture";
if (isGather)
{
texCall += "Gather";
}
else if (hasLodLevel && !intCoords)
{
texCall += "Lod";
}
if (hasOffset)
{
texCall += "Offset";
}
else if (hasOffsets)
{
texCall += "Offsets";
}
string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp);
texCall += "(" + samplerName;
int coordsCount = texOp.Target.GetDimensions();
int pCount = coordsCount;
int arrayIndexElem = -1;
if (isArray)
{
arrayIndexElem = pCount++;
}
// The sampler 1D shadow overload expects a
// dummy value on the middle of the vector, who knows why...
bool hasDummy1DShadowElem = texOp.Target == (TextureTarget.Texture1D | TextureTarget.Shadow);
if (hasDummy1DShadowElem)
{
pCount++;
}
if (isShadow && !isGather)
{
pCount++;
}
// On textureGather*, the comparison value is
// always specified as an extra argument.
bool hasExtraCompareArg = isShadow && isGather;
if (pCount == 5)
{
pCount = 4;
hasExtraCompareArg = true;
}
int srcIndex = isBindless ? 1 : 0;
string Src(VariableType type)
{
return GetSoureExpr(context, texOp.GetSource(srcIndex++), type);
}
void Append(string str)
{
texCall += ", " + str;
}
VariableType coordType = intCoords ? VariableType.S32 : VariableType.F32;
string AssemblePVector(int count)
{
if (count > 1)
{
string[] elems = new string[count];
for (int index = 0; index < count; index++)
{
if (arrayIndexElem == index)
{
elems[index] = Src(VariableType.S32);
if (!intCoords)
{
elems[index] = "float(" + elems[index] + ")";
}
}
else if (index == 1 && hasDummy1DShadowElem)
{
elems[index] = NumberFormatter.FormatFloat(0);
}
else
{
elems[index] = Src(coordType);
}
}
string prefix = intCoords ? "i" : string.Empty;
return prefix + "vec" + count + "(" + string.Join(", ", elems) + ")";
}
else
{
return Src(coordType);
}
}
Append(AssemblePVector(pCount));
if (hasExtraCompareArg)
{
Append(Src(VariableType.F32));
}
if (isMultisample)
{
Append(Src(VariableType.S32));
}
else if (hasLodLevel)
{
Append(Src(coordType));
}
string AssembleOffsetVector(int count)
{
if (count > 1)
{
string[] elems = new string[count];
for (int index = 0; index < count; index++)
{
elems[index] = Src(VariableType.S32);
}
return "ivec" + count + "(" + string.Join(", ", elems) + ")";
}
else
{
return Src(VariableType.S32);
}
}
if (hasOffset)
{
Append(AssembleOffsetVector(coordsCount));
}
else if (hasOffsets)
{
texCall += $", ivec{coordsCount}[4](";
texCall += AssembleOffsetVector(coordsCount) + ", ";
texCall += AssembleOffsetVector(coordsCount) + ", ";
texCall += AssembleOffsetVector(coordsCount) + ", ";
texCall += AssembleOffsetVector(coordsCount) + ")";
}
if (hasLodBias)
{
Append(Src(VariableType.F32));
}
// textureGather* optional extra component index,
// not needed for shadow samplers.
if (isGather && !isShadow)
{
Append(Src(VariableType.S32));
}
texCall += ")" + (isGather || !isShadow ? GetMask(texOp.ComponentMask) : "");
return texCall;
}
public static string TextureSize(CodeGenContext context, AstOperation operation)
{
AstTextureOperation texOp = (AstTextureOperation)operation;
bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp);
IAstNode src0 = operation.GetSource(isBindless ? 1 : 0);
string src0Expr = GetSoureExpr(context, src0, GetSrcVarType(operation.Inst, 0));
return $"textureSize({samplerName}, {src0Expr}){GetMask(texOp.ComponentMask)}";
}
private static string GetMask(int compMask)
{
string mask = ".";
for (int index = 0; index < 4; index++)
{
if ((compMask & (1 << index)) != 0)
{
mask += "rgba".Substring(index, 1);
}
}
return mask;
}
}
}

View file

@ -0,0 +1,45 @@
using Ryujinx.Graphics.Shader.StructuredIr;
using static Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions.InstGenHelper;
using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
static class InstGenPacking
{
public static string PackHalf2x16(CodeGenContext context, AstOperation operation)
{
IAstNode src0 = operation.GetSource(0);
IAstNode src1 = operation.GetSource(1);
string src0Expr = GetSoureExpr(context, src0, GetSrcVarType(operation.Inst, 0));
string src1Expr = GetSoureExpr(context, src1, GetSrcVarType(operation.Inst, 1));
return $"packHalf2x16(vec2({src0Expr}, {src1Expr}))";
}
public static string UnpackHalf2x16(CodeGenContext context, AstOperation operation)
{
IAstNode src = operation.GetSource(0);
string srcExpr = GetSoureExpr(context, src, GetSrcVarType(operation.Inst, 0));
return $"unpackHalf2x16({srcExpr}){GetMask(operation.ComponentMask)}";
}
private static string GetMask(int compMask)
{
string mask = ".";
for (int index = 0; index < 2; index++)
{
if ((compMask & (1 << index)) != 0)
{
mask += "xy".Substring(index, 1);
}
}
return mask;
}
}
}

View file

@ -0,0 +1,18 @@
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
struct InstInfo
{
public InstType Type { get; }
public string OpName { get; }
public int Precedence { get; }
public InstInfo(InstType type, string opName, int precedence)
{
Type = type;
OpName = opName;
Precedence = precedence;
}
}
}

View file

@ -0,0 +1,27 @@
using System;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions
{
[Flags]
enum InstType
{
OpNullary = Op | 0,
OpUnary = Op | 1,
OpBinary = Op | 2,
OpTernary = Op | 3,
OpBinaryCom = OpBinary | Commutative,
CallNullary = Call | 0,
CallUnary = Call | 1,
CallBinary = Call | 2,
CallTernary = Call | 3,
CallQuaternary = Call | 4,
Commutative = 1 << 8,
Op = 1 << 9,
Call = 1 << 10,
Special = 1 << 11,
ArityMask = 0xff
}
}

View file

@ -0,0 +1,104 @@
using Ryujinx.Graphics.Shader.StructuredIr;
using System;
using System.Globalization;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
static class NumberFormatter
{
private const int MaxDecimal = 256;
public static bool TryFormat(int value, VariableType dstType, out string formatted)
{
if (dstType == VariableType.F32)
{
return TryFormatFloat(BitConverter.Int32BitsToSingle(value), out formatted);
}
else if (dstType == VariableType.S32)
{
formatted = FormatInt(value);
}
else if (dstType == VariableType.U32)
{
formatted = FormatUint((uint)value);
}
else if (dstType == VariableType.Bool)
{
formatted = value != 0 ? "true" : "false";
}
else
{
throw new ArgumentException($"Invalid variable type \"{dstType}\".");
}
return true;
}
public static string FormatFloat(float value)
{
if (!TryFormatFloat(value, out string formatted))
{
throw new ArgumentException("Failed to convert float value to string.");
}
return formatted;
}
public static bool TryFormatFloat(float value, out string formatted)
{
if (float.IsNaN(value) || float.IsInfinity(value))
{
formatted = null;
return false;
}
formatted = value.ToString("G9", CultureInfo.InvariantCulture);
if (!(formatted.Contains('.') ||
formatted.Contains('e') ||
formatted.Contains('E')))
{
formatted += ".0";
}
return true;
}
public static string FormatInt(int value, VariableType dstType)
{
if (dstType == VariableType.S32)
{
return FormatInt(value);
}
else if (dstType == VariableType.U32)
{
return FormatUint((uint)value);
}
else
{
throw new ArgumentException($"Invalid variable type \"{dstType}\".");
}
}
public static string FormatInt(int value)
{
if (value <= MaxDecimal && value >= -MaxDecimal)
{
return value.ToString(CultureInfo.InvariantCulture);
}
return "0x" + value.ToString("X", CultureInfo.InvariantCulture);
}
public static string FormatUint(uint value)
{
if (value <= MaxDecimal && value >= 0)
{
return value.ToString(CultureInfo.InvariantCulture) + "u";
}
return "0x" + value.ToString("X", CultureInfo.InvariantCulture) + "u";
}
}
}

View file

@ -0,0 +1,298 @@
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using Ryujinx.Graphics.Shader.Translation;
using System;
using System.Collections.Generic;
using static Ryujinx.Graphics.Shader.StructuredIr.InstructionInfo;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
class OperandManager
{
private static string[] _stagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
private struct BuiltInAttribute
{
public string Name { get; }
public VariableType Type { get; }
public BuiltInAttribute(string name, VariableType type)
{
Name = name;
Type = type;
}
}
private static Dictionary<int, BuiltInAttribute> _builtInAttributes =
new Dictionary<int, BuiltInAttribute>()
{
{ AttributeConsts.Layer, new BuiltInAttribute("gl_Layer", VariableType.S32) },
{ AttributeConsts.PointSize, new BuiltInAttribute("gl_PointSize", VariableType.F32) },
{ AttributeConsts.PositionX, new BuiltInAttribute("gl_Position.x", VariableType.F32) },
{ AttributeConsts.PositionY, new BuiltInAttribute("gl_Position.y", VariableType.F32) },
{ AttributeConsts.PositionZ, new BuiltInAttribute("gl_Position.z", VariableType.F32) },
{ AttributeConsts.PositionW, new BuiltInAttribute("gl_Position.w", VariableType.F32) },
{ AttributeConsts.ClipDistance0, new BuiltInAttribute("gl_ClipDistance[0]", VariableType.F32) },
{ AttributeConsts.ClipDistance1, new BuiltInAttribute("gl_ClipDistance[1]", VariableType.F32) },
{ AttributeConsts.ClipDistance2, new BuiltInAttribute("gl_ClipDistance[2]", VariableType.F32) },
{ AttributeConsts.ClipDistance3, new BuiltInAttribute("gl_ClipDistance[3]", VariableType.F32) },
{ AttributeConsts.ClipDistance4, new BuiltInAttribute("gl_ClipDistance[4]", VariableType.F32) },
{ AttributeConsts.ClipDistance5, new BuiltInAttribute("gl_ClipDistance[5]", VariableType.F32) },
{ AttributeConsts.ClipDistance6, new BuiltInAttribute("gl_ClipDistance[6]", VariableType.F32) },
{ AttributeConsts.ClipDistance7, new BuiltInAttribute("gl_ClipDistance[7]", VariableType.F32) },
{ AttributeConsts.PointCoordX, new BuiltInAttribute("gl_PointCoord.x", VariableType.F32) },
{ AttributeConsts.PointCoordY, new BuiltInAttribute("gl_PointCoord.y", VariableType.F32) },
{ AttributeConsts.TessCoordX, new BuiltInAttribute("gl_TessCoord.x", VariableType.F32) },
{ AttributeConsts.TessCoordY, new BuiltInAttribute("gl_TessCoord.y", VariableType.F32) },
{ AttributeConsts.InstanceId, new BuiltInAttribute("gl_InstanceID", VariableType.S32) },
{ AttributeConsts.VertexId, new BuiltInAttribute("gl_VertexID", VariableType.S32) },
{ AttributeConsts.FrontFacing, new BuiltInAttribute("gl_FrontFacing", VariableType.Bool) },
// Special.
{ AttributeConsts.FragmentOutputDepth, new BuiltInAttribute("gl_FragDepth", VariableType.F32) },
{ AttributeConsts.ThreadIdX, new BuiltInAttribute("gl_LocalInvocationID.x", VariableType.U32) },
{ AttributeConsts.ThreadIdY, new BuiltInAttribute("gl_LocalInvocationID.y", VariableType.U32) },
{ AttributeConsts.ThreadIdZ, new BuiltInAttribute("gl_LocalInvocationID.z", VariableType.U32) },
{ AttributeConsts.CtaIdX, new BuiltInAttribute("gl_WorkGroupID.x", VariableType.U32) },
{ AttributeConsts.CtaIdY, new BuiltInAttribute("gl_WorkGroupID.y", VariableType.U32) },
{ AttributeConsts.CtaIdZ, new BuiltInAttribute("gl_WorkGroupID.z", VariableType.U32) },
};
private Dictionary<AstOperand, string> _locals;
public OperandManager()
{
_locals = new Dictionary<AstOperand, string>();
}
public string DeclareLocal(AstOperand operand)
{
string name = $"{DefaultNames.LocalNamePrefix}_{_locals.Count}";
_locals.Add(operand, name);
return name;
}
public string GetExpression(AstOperand operand, ShaderStage stage)
{
switch (operand.Type)
{
case OperandType.Attribute:
return GetAttributeName(operand, stage);
case OperandType.Constant:
return NumberFormatter.FormatInt(operand.Value);
case OperandType.ConstantBuffer:
return GetConstantBufferName(operand, stage);
case OperandType.LocalVariable:
return _locals[operand];
case OperandType.Undefined:
return DefaultNames.UndefinedName;
}
throw new ArgumentException($"Invalid operand type \"{operand.Type}\".");
}
public static string GetConstantBufferName(AstOperand cbuf, ShaderStage stage)
{
string ubName = GetUbName(stage, cbuf.CbufSlot);
ubName += "[" + (cbuf.CbufOffset >> 2) + "]";
return ubName + "." + GetSwizzleMask(cbuf.CbufOffset & 3);
}
public static string GetStorageBufferName(IAstNode slot, string offsetExpr, ShaderStage stage)
{
// Non-constant slots are not supported.
// It is expected that upstream stages are never going to generate non-constant
// slot access.
AstOperand operand = (AstOperand)slot;
string sbName = GetSbName(stage, operand.Value);
return $"{sbName}[{offsetExpr}]";
}
public static string GetConstantBufferName(IAstNode slot, string offsetExpr, ShaderStage stage)
{
// Non-constant slots are not supported.
// It is expected that upstream stages are never going to generate non-constant
// slot access.
AstOperand operand = (AstOperand)slot;
string ubName = GetUbName(stage, operand.Value);
string index0 = "[" + offsetExpr + " >> 2]";
string index1 = "[" + offsetExpr + " & 3]";
return ubName + index0 + index1;
}
public static string GetOutAttributeName(AstOperand attr, ShaderStage stage)
{
return GetAttributeName(attr, stage, isOutAttr: true);
}
public static string GetAttributeName(AstOperand attr, ShaderStage stage, bool isOutAttr = false, string indexExpr = "0")
{
int value = attr.Value;
string swzMask = GetSwizzleMask((value >> 2) & 3);
if (value >= AttributeConsts.UserAttributeBase &&
value < AttributeConsts.UserAttributeEnd)
{
value -= AttributeConsts.UserAttributeBase;
string prefix = isOutAttr
? DefaultNames.OAttributePrefix
: DefaultNames.IAttributePrefix;
string name = $"{prefix}{(value >> 4)}";
if (stage == ShaderStage.Geometry && !isOutAttr)
{
name += $"[{indexExpr}]";
}
name += "." + swzMask;
return name;
}
else
{
if (value >= AttributeConsts.FragmentOutputColorBase &&
value < AttributeConsts.FragmentOutputColorEnd)
{
value -= AttributeConsts.FragmentOutputColorBase;
return $"{DefaultNames.OAttributePrefix}{(value >> 4)}.{swzMask}";
}
else if (_builtInAttributes.TryGetValue(value & ~3, out BuiltInAttribute builtInAttr))
{
// TODO: There must be a better way to handle this...
if (stage == ShaderStage.Fragment)
{
switch (value & ~3)
{
case AttributeConsts.PositionX: return "gl_FragCoord.x";
case AttributeConsts.PositionY: return "gl_FragCoord.y";
case AttributeConsts.PositionZ: return "gl_FragCoord.z";
case AttributeConsts.PositionW: return "1.0";
}
}
string name = builtInAttr.Name;
if (stage == ShaderStage.Geometry && !isOutAttr)
{
name = $"gl_in[{indexExpr}].{name}";
}
return name;
}
}
// TODO: Warn about unknown built-in attribute.
return isOutAttr ? "// bad_attr0x" + value.ToString("X") : "0.0";
}
public static string GetSbName(ShaderStage stage, int slot)
{
string sbName = GetShaderStagePrefix(stage);
sbName += "_" + DefaultNames.StorageNamePrefix + slot;
return sbName + "_" + DefaultNames.StorageNameSuffix;
}
public static string GetUbName(ShaderStage stage, int slot)
{
string ubName = GetShaderStagePrefix(stage);
ubName += "_" + DefaultNames.UniformNamePrefix + slot;
return ubName + "_" + DefaultNames.UniformNameSuffix;
}
public static string GetSamplerName(ShaderStage stage, AstTextureOperation texOp)
{
string suffix;
if ((texOp.Flags & TextureFlags.Bindless) != 0)
{
AstOperand operand = texOp.GetSource(0) as AstOperand;
suffix = "_cb" + operand.CbufSlot + "_" + operand.CbufOffset;
}
else
{
suffix = (texOp.Handle - 8).ToString();
}
return GetShaderStagePrefix(stage) + "_" + DefaultNames.SamplerNamePrefix + suffix;
}
public static string GetShaderStagePrefix(ShaderStage stage)
{
int index = (int)stage;
if ((uint)index >= _stagePrefixes.Length)
{
return "invalid";
}
return _stagePrefixes[index];
}
private static string GetSwizzleMask(int value)
{
return "xyzw".Substring(value, 1);
}
public static VariableType GetNodeDestType(IAstNode node)
{
if (node is AstOperation operation)
{
// Load attribute basically just returns the attribute value.
// Some built-in attributes may have different types, so we need
// to return the type based on the attribute that is being read.
if (operation.Inst == Instruction.LoadAttribute)
{
return GetOperandVarType((AstOperand)operation.GetSource(0));
}
return GetDestVarType(operation.Inst);
}
else if (node is AstOperand operand)
{
return GetOperandVarType(operand);
}
else
{
throw new ArgumentException($"Invalid node type \"{node?.GetType().Name ?? "null"}\".");
}
}
private static VariableType GetOperandVarType(AstOperand operand)
{
if (operand.Type == OperandType.Attribute)
{
if (_builtInAttributes.TryGetValue(operand.Value & ~3, out BuiltInAttribute builtInAttr))
{
return builtInAttr.Type;
}
}
return OperandInfo.GetVarType(operand);
}
}
}

View file

@ -0,0 +1,85 @@
using Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using Ryujinx.Graphics.Shader.StructuredIr;
using System;
namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
{
static class TypeConversion
{
public static string ReinterpretCast(
CodeGenContext context,
IAstNode node,
VariableType srcType,
VariableType dstType)
{
if (node is AstOperand operand && operand.Type == OperandType.Constant)
{
if (NumberFormatter.TryFormat(operand.Value, dstType, out string formatted))
{
return formatted;
}
}
string expr = InstGen.GetExpression(context, node);
return ReinterpretCast(expr, node, srcType, dstType);
}
private static string ReinterpretCast(string expr, IAstNode node, VariableType srcType, VariableType dstType)
{
if (srcType == dstType)
{
return expr;
}
if (srcType == VariableType.F32)
{
switch (dstType)
{
case VariableType.S32: return $"floatBitsToInt({expr})";
case VariableType.U32: return $"floatBitsToUint({expr})";
}
}
else if (dstType == VariableType.F32)
{
switch (srcType)
{
case VariableType.Bool: return $"intBitsToFloat({ReinterpretBoolToInt(expr, node, VariableType.S32)})";
case VariableType.S32: return $"intBitsToFloat({expr})";
case VariableType.U32: return $"uintBitsToFloat({expr})";
}
}
else if (srcType == VariableType.Bool)
{
return ReinterpretBoolToInt(expr, node, dstType);
}
else if (dstType == VariableType.Bool)
{
expr = InstGenHelper.Enclose(expr, node, Instruction.CompareNotEqual, isLhs: true);
return $"({expr} != 0)";
}
else if (dstType == VariableType.S32)
{
return $"int({expr})";
}
else if (dstType == VariableType.U32)
{
return $"uint({expr})";
}
throw new ArgumentException($"Invalid reinterpret cast from \"{srcType}\" to \"{dstType}\".");
}
private static string ReinterpretBoolToInt(string expr, IAstNode node, VariableType dstType)
{
string trueExpr = NumberFormatter.FormatInt(IrConsts.True, dstType);
string falseExpr = NumberFormatter.FormatInt(IrConsts.False, dstType);
expr = InstGenHelper.Enclose(expr, node, Instruction.ConditionalSelect, isLhs: false);
return $"({expr} ? {trueExpr} : {falseExpr})";
}
}
}

View file

@ -0,0 +1,25 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
static class BitfieldExtensions
{
public static bool Extract(this int value, int lsb)
{
return ((int)(value >> lsb) & 1) != 0;
}
public static int Extract(this int value, int lsb, int length)
{
return (int)(value >> lsb) & (int)(uint.MaxValue >> (32 - length));
}
public static bool Extract(this long value, int lsb)
{
return ((int)(value >> lsb) & 1) != 0;
}
public static int Extract(this long value, int lsb, int length)
{
return (int)(value >> lsb) & (int)(uint.MaxValue >> (32 - length));
}
}
}

View file

@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
namespace Ryujinx.Graphics.Shader.Decoders
{
class Block
{
public ulong Address { get; set; }
public ulong EndAddress { get; set; }
public Block Next { get; set; }
public Block Branch { get; set; }
public List<OpCode> OpCodes { get; }
public List<OpCodeSsy> SsyOpCodes { get; }
public Block(ulong address)
{
Address = address;
OpCodes = new List<OpCode>();
SsyOpCodes = new List<OpCodeSsy>();
}
public void Split(Block rightBlock)
{
int splitIndex = BinarySearch(OpCodes, rightBlock.Address);
if (OpCodes[splitIndex].Address < rightBlock.Address)
{
splitIndex++;
}
int splitCount = OpCodes.Count - splitIndex;
if (splitCount <= 0)
{
throw new ArgumentException("Can't split at right block address.");
}
rightBlock.EndAddress = EndAddress;
rightBlock.Next = Next;
rightBlock.Branch = Branch;
rightBlock.OpCodes.AddRange(OpCodes.GetRange(splitIndex, splitCount));
rightBlock.UpdateSsyOpCodes();
EndAddress = rightBlock.Address;
Next = rightBlock;
Branch = null;
OpCodes.RemoveRange(splitIndex, splitCount);
UpdateSsyOpCodes();
}
private static int BinarySearch(List<OpCode> opCodes, ulong address)
{
int left = 0;
int middle = 0;
int right = opCodes.Count - 1;
while (left <= right)
{
int size = right - left;
middle = left + (size >> 1);
OpCode opCode = opCodes[middle];
if (address == opCode.Address)
{
break;
}
if (address < opCode.Address)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return middle;
}
public OpCode GetLastOp()
{
if (OpCodes.Count != 0)
{
return OpCodes[OpCodes.Count - 1];
}
return null;
}
public void UpdateSsyOpCodes()
{
SsyOpCodes.Clear();
for (int index = 0; index < OpCodes.Count; index++)
{
if (!(OpCodes[index] is OpCodeSsy op))
{
continue;
}
SsyOpCodes.Add(op);
}
}
}
}

View file

@ -0,0 +1,45 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum Condition
{
Less = 1 << 0,
Equal = 1 << 1,
Greater = 1 << 2,
Nan = 1 << 3,
Unsigned = 1 << 4,
Never = 0,
LessOrEqual = Less | Equal,
NotEqual = Less | Greater,
GreaterOrEqual = Greater | Equal,
Number = Greater | Equal | Less,
LessUnordered = Less | Nan,
EqualUnordered = Equal | Nan,
LessOrEqualUnordered = LessOrEqual | Nan,
GreaterUnordered = Greater | Nan,
NotEqualUnordered = NotEqual | Nan,
GreaterOrEqualUnordered = GreaterOrEqual | Nan,
Always = 0xf,
Off = Unsigned | Never,
Lower = Unsigned | Less,
Sff = Unsigned | Equal,
LowerOrSame = Unsigned | LessOrEqual,
Higher = Unsigned | Greater,
Sft = Unsigned | NotEqual,
HigherOrSame = Unsigned | GreaterOrEqual,
Oft = Unsigned | Always,
CsmTa = 0x18,
CsmTr = 0x19,
CsmMx = 0x1a,
FcsmTa = 0x1b,
FcsmTr = 0x1c,
FcsmMx = 0x1d,
Rle = 0x1e,
Rgt = 0x1f
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum ConditionalOperation
{
False = 0,
True = 1,
Zero = 2,
NotZero = 3
}
}

View file

@ -0,0 +1,407 @@
using Ryujinx.Graphics.Shader.Instructions;
using System;
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
namespace Ryujinx.Graphics.Shader.Decoders
{
static class Decoder
{
private delegate object OpActivator(InstEmitter emitter, ulong address, long opCode);
private static ConcurrentDictionary<Type, OpActivator> _opActivators;
static Decoder()
{
_opActivators = new ConcurrentDictionary<Type, OpActivator>();
}
public static Block[] Decode(Span<byte> code, ulong headerSize)
{
List<Block> blocks = new List<Block>();
Queue<Block> workQueue = new Queue<Block>();
Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
Block GetBlock(ulong blkAddress)
{
if (!visited.TryGetValue(blkAddress, out Block block))
{
block = new Block(blkAddress);
workQueue.Enqueue(block);
visited.Add(blkAddress, block);
}
return block;
}
ulong startAddress = headerSize;
GetBlock(startAddress);
while (workQueue.TryDequeue(out Block currBlock))
{
// Check if the current block is inside another block.
if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
{
Block nBlock = blocks[nBlkIndex];
if (nBlock.Address == currBlock.Address)
{
throw new InvalidOperationException("Found duplicate block address on the list.");
}
nBlock.Split(currBlock);
blocks.Insert(nBlkIndex + 1, currBlock);
continue;
}
// If we have a block after the current one, set the limit address.
ulong limitAddress = (ulong)code.Length;
if (nBlkIndex != blocks.Count)
{
Block nBlock = blocks[nBlkIndex];
int nextIndex = nBlkIndex + 1;
if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
{
limitAddress = blocks[nextIndex].Address;
}
else if (nBlock.Address > currBlock.Address)
{
limitAddress = blocks[nBlkIndex].Address;
}
}
FillBlock(code, currBlock, limitAddress, startAddress);
if (currBlock.OpCodes.Count != 0)
{
foreach (OpCodeSsy ssyOp in currBlock.SsyOpCodes)
{
GetBlock(ssyOp.GetAbsoluteAddress());
}
// Set child blocks. "Branch" is the block the branch instruction
// points to (when taken), "Next" is the block at the next address,
// executed when the branch is not taken. For Unconditional Branches
// or end of program, Next is null.
OpCode lastOp = currBlock.GetLastOp();
if (lastOp is OpCodeBranch op)
{
currBlock.Branch = GetBlock(op.GetAbsoluteAddress());
}
if (!IsUnconditionalBranch(lastOp))
{
currBlock.Next = GetBlock(currBlock.EndAddress);
}
}
// Insert the new block on the list (sorted by address).
if (blocks.Count != 0)
{
Block nBlock = blocks[nBlkIndex];
blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
}
else
{
blocks.Add(currBlock);
}
}
foreach (Block ssyBlock in blocks.Where(x => x.SsyOpCodes.Count != 0))
{
for (int ssyIndex = 0; ssyIndex < ssyBlock.SsyOpCodes.Count; ssyIndex++)
{
PropagateSsy(visited, ssyBlock, ssyIndex);
}
}
return blocks.ToArray();
}
private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
{
index = 0;
int left = 0;
int right = blocks.Count - 1;
while (left <= right)
{
int size = right - left;
int middle = left + (size >> 1);
Block block = blocks[middle];
index = middle;
if (address >= block.Address && address < block.EndAddress)
{
return true;
}
if (address < block.Address)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
return false;
}
private static void FillBlock(
Span<byte> code,
Block block,
ulong limitAddress,
ulong startAddress)
{
ulong address = block.Address;
do
{
if (address >= limitAddress)
{
break;
}
// Ignore scheduling instructions, which are written every 32 bytes.
if (((address - startAddress) & 0x1f) == 0)
{
address += 8;
continue;
}
uint word0 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)address));
uint word1 = BinaryPrimitives.ReadUInt32LittleEndian(code.Slice((int)address + 4));
ulong opAddress = address;
address += 8;
long opCode = word0 | (long)word1 << 32;
(InstEmitter emitter, Type opCodeType) = OpCodeTable.GetEmitter(opCode);
if (emitter == null)
{
// TODO: Warning, illegal encoding.
block.OpCodes.Add(new OpCode(null, opAddress, opCode));
continue;
}
OpCode op = MakeOpCode(opCodeType, emitter, opAddress, opCode);
block.OpCodes.Add(op);
}
while (!IsBranch(block.GetLastOp()));
block.EndAddress = address;
block.UpdateSsyOpCodes();
}
private static bool IsUnconditionalBranch(OpCode opCode)
{
return IsUnconditional(opCode) && IsBranch(opCode);
}
private static bool IsUnconditional(OpCode opCode)
{
if (opCode is OpCodeExit op && op.Condition != Condition.Always)
{
return false;
}
return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
}
private static bool IsBranch(OpCode opCode)
{
return (opCode is OpCodeBranch && opCode.Emitter != InstEmit.Ssy) ||
opCode is OpCodeSync ||
opCode is OpCodeExit;
}
private static OpCode MakeOpCode(Type type, InstEmitter emitter, ulong address, long opCode)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
return (OpCode)createInstance(emitter, address, opCode);
}
private static OpActivator CacheOpActivator(Type type)
{
Type[] argTypes = new Type[] { typeof(InstEmitter), typeof(ulong), typeof(long) };
DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
ILGenerator generator = mthd.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Ldarg_2);
generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
generator.Emit(OpCodes.Ret);
return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
}
private struct PathBlockState
{
public Block Block { get; }
private enum RestoreType
{
None,
PopSsy,
PushSync
}
private RestoreType _restoreType;
private ulong _restoreValue;
public bool ReturningFromVisit => _restoreType != RestoreType.None;
public PathBlockState(Block block)
{
Block = block;
_restoreType = RestoreType.None;
_restoreValue = 0;
}
public PathBlockState(int oldSsyStackSize)
{
Block = null;
_restoreType = RestoreType.PopSsy;
_restoreValue = (ulong)oldSsyStackSize;
}
public PathBlockState(ulong syncAddress)
{
Block = null;
_restoreType = RestoreType.PushSync;
_restoreValue = syncAddress;
}
public void RestoreStackState(Stack<ulong> ssyStack)
{
if (_restoreType == RestoreType.PushSync)
{
ssyStack.Push(_restoreValue);
}
else if (_restoreType == RestoreType.PopSsy)
{
while (ssyStack.Count > (uint)_restoreValue)
{
ssyStack.Pop();
}
}
}
}
private static void PropagateSsy(Dictionary<ulong, Block> blocks, Block ssyBlock, int ssyIndex)
{
OpCodeSsy ssyOp = ssyBlock.SsyOpCodes[ssyIndex];
Stack<PathBlockState> workQueue = new Stack<PathBlockState>();
HashSet<Block> visited = new HashSet<Block>();
Stack<ulong> ssyStack = new Stack<ulong>();
void Push(PathBlockState pbs)
{
if (pbs.Block == null || visited.Add(pbs.Block))
{
workQueue.Push(pbs);
}
}
Push(new PathBlockState(ssyBlock));
while (workQueue.TryPop(out PathBlockState pbs))
{
if (pbs.ReturningFromVisit)
{
pbs.RestoreStackState(ssyStack);
continue;
}
Block current = pbs.Block;
int ssyOpCodesCount = current.SsyOpCodes.Count;
if (ssyOpCodesCount != 0)
{
Push(new PathBlockState(ssyStack.Count));
for (int index = ssyIndex; index < ssyOpCodesCount; index++)
{
ssyStack.Push(current.SsyOpCodes[index].GetAbsoluteAddress());
}
}
ssyIndex = 0;
if (current.Next != null)
{
Push(new PathBlockState(current.Next));
}
if (current.Branch != null)
{
Push(new PathBlockState(current.Branch));
}
else if (current.GetLastOp() is OpCodeSync op)
{
ulong syncAddress = ssyStack.Pop();
if (ssyStack.Count == 0)
{
ssyStack.Push(syncAddress);
op.Targets.Add(ssyOp, op.Targets.Count);
ssyOp.Syncs.TryAdd(op, Local());
}
else
{
Push(new PathBlockState(syncAddress));
Push(new PathBlockState(blocks[syncAddress]));
}
}
}
}
}
}

View file

@ -0,0 +1,58 @@
using System;
namespace Ryujinx.Graphics.Shader.Decoders
{
static class DecoderHelper
{
public static int DecodeS20Immediate(long opCode)
{
int imm = opCode.Extract(20, 19);
bool sign = opCode.Extract(56);
if (sign)
{
imm = (imm << 13) >> 13;
}
return imm;
}
public static int Decode2xF10Immediate(long opCode)
{
int immH0 = opCode.Extract(20, 9);
int immH1 = opCode.Extract(30, 9);
bool negateH0 = opCode.Extract(29);
bool negateH1 = opCode.Extract(56);
if (negateH0)
{
immH0 |= 1 << 9;
}
if (negateH1)
{
immH1 |= 1 << 9;
}
return immH1 << 22 | immH0 << 6;
}
public static float DecodeF20Immediate(long opCode)
{
int imm = opCode.Extract(20, 19);
bool negate = opCode.Extract(56);
imm <<= 12;
if (negate)
{
imm |= 1 << 31;
}
return BitConverter.Int32BitsToSingle(imm);
}
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum FPHalfSwizzle
{
FP16 = 0,
FP32 = 1,
DupH0 = 2,
DupH1 = 3
}
}

View file

@ -0,0 +1,9 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum FPType
{
FP16 = 1,
FP32 = 2,
FP64 = 3
}
}

View file

@ -0,0 +1,13 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum FmulScale
{
None = 0,
Divide2 = 1,
Divide4 = 2,
Divide8 = 3,
Multiply8 = 4,
Multiply4 = 5,
Multiply2 = 6
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCode
{
InstEmitter Emitter { get; }
ulong Address { get; }
long RawOpCode { get; }
Register Predicate { get; }
bool InvertPredicate { get; }
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeAlu : IOpCodeRd, IOpCodeRa
{
Register Predicate39 { get; }
bool InvertP { get; }
bool Extended { get; }
bool SetCondCode { get; }
bool Saturate { get; }
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeCbuf : IOpCode
{
int Offset { get; }
int Slot { get; }
}
}

View file

@ -0,0 +1,12 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeFArith : IOpCodeAlu
{
RoundingMode RoundingMode { get; }
FmulScale Scale { get; }
bool FlushToZero { get; }
bool AbsoluteA { get; }
}
}

View file

@ -0,0 +1,13 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeHfma : IOpCode
{
bool NegateB { get; }
bool NegateC { get; }
bool Saturate { get; }
FPHalfSwizzle SwizzleA { get; }
FPHalfSwizzle SwizzleB { get; }
FPHalfSwizzle SwizzleC { get; }
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeImm : IOpCode
{
int Immediate { get; }
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeImmF : IOpCode
{
float Immediate { get; }
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeLop : IOpCodeAlu
{
LogicalOperation LogicalOp { get; }
bool InvertA { get; }
bool InvertB { get; }
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeRa : IOpCode
{
Register Ra { get; }
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeRc : IOpCode
{
Register Rc { get; }
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeRd : IOpCode
{
Register Rd { get; }
}
}

View file

@ -0,0 +1,7 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeReg : IOpCode
{
Register Rb { get; }
}
}

View file

@ -0,0 +1,8 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
interface IOpCodeRegCbuf : IOpCodeRc
{
int Offset { get; }
int Slot { get; }
}
}

View file

@ -0,0 +1,18 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum IntegerCondition
{
Less = 1 << 0,
Equal = 1 << 1,
Greater = 1 << 2,
Never = 0,
LessOrEqual = Less | Equal,
NotEqual = Less | Greater,
GreaterOrEqual = Greater | Equal,
Number = Greater | Equal | Less,
Always = 7
}
}

View file

@ -0,0 +1,9 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum IntegerHalfPart
{
B32 = 0,
H0 = 1,
H1 = 2
}
}

View file

@ -0,0 +1,9 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum IntegerShift
{
NoShift = 0,
ShiftRight = 1,
ShiftLeft = 2
}
}

View file

@ -0,0 +1,13 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum IntegerSize
{
U8 = 0,
S8 = 1,
U16 = 2,
S16 = 3,
B32 = 4,
B64 = 5,
B128 = 6
}
}

View file

@ -0,0 +1,14 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum IntegerType
{
U8 = 0,
U16 = 1,
U32 = 2,
U64 = 3,
S8 = 4,
S16 = 5,
S32 = 6,
S64 = 7
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum InterpolationMode
{
Pass,
Default,
Constant,
Sc
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum LogicalOperation
{
And = 0,
Or = 1,
ExclusiveOr = 2,
Passthrough = 3
}
}

View file

@ -0,0 +1,15 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum MufuOperation
{
Cosine = 0,
Sine = 1,
ExponentB2 = 2,
LogarithmB2 = 3,
Reciprocal = 4,
ReciprocalSquareRoot = 5,
Reciprocal64H = 6,
ReciprocalSquareRoot64H = 7,
SquareRoot = 8
}
}

View file

@ -0,0 +1,30 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCode
{
public InstEmitter Emitter { get; }
public ulong Address { get; }
public long RawOpCode { get; }
public Register Predicate { get; protected set; }
public bool InvertPredicate { get; protected set; }
// When inverted, the always true predicate == always false.
public bool NeverExecute => Predicate.Index == RegisterConsts.PredicateTrueIndex && InvertPredicate;
public OpCode(InstEmitter emitter, ulong address, long opCode)
{
Emitter = emitter;
Address = address;
RawOpCode = opCode;
Predicate = new Register(opCode.Extract(16, 3), RegisterType.Predicate);
InvertPredicate = opCode.Extract(19);
}
}
}

View file

@ -0,0 +1,34 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAlu : OpCode, IOpCodeAlu, IOpCodeRc
{
public Register Rd { get; }
public Register Ra { get; }
public Register Rc { get; }
public Register Predicate39 { get; }
public int ByteSelection { get; }
public bool InvertP { get; }
public bool Extended { get; protected set; }
public bool SetCondCode { get; protected set; }
public bool Saturate { get; protected set; }
public OpCodeAlu(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Rc = new Register(opCode.Extract(39, 8), RegisterType.Gpr);
Predicate39 = new Register(opCode.Extract(39, 3), RegisterType.Predicate);
ByteSelection = opCode.Extract(41, 2);
InvertP = opCode.Extract(42);
Extended = opCode.Extract(43);
SetCondCode = opCode.Extract(47);
Saturate = opCode.Extract(50);
}
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAluCbuf : OpCodeAlu, IOpCodeCbuf
{
public int Offset { get; }
public int Slot { get; }
public OpCodeAluCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAluImm : OpCodeAlu, IOpCodeImm
{
public int Immediate { get; }
public OpCodeAluImm(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.DecodeS20Immediate(opCode);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAluImm2x10 : OpCodeAlu, IOpCodeImm
{
public int Immediate { get; }
public OpCodeAluImm2x10(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.Decode2xF10Immediate(opCode);
}
}
}

View file

@ -0,0 +1,18 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAluImm32 : OpCodeAlu, IOpCodeImm
{
public int Immediate { get; }
public OpCodeAluImm32(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = opCode.Extract(20, 32);
SetCondCode = opCode.Extract(52);
Extended = opCode.Extract(53);
Saturate = opCode.Extract(54);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAluReg : OpCodeAlu, IOpCodeReg
{
public Register Rb { get; protected set; }
public OpCodeAluReg(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
}
}
}

View file

@ -0,0 +1,18 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAluRegCbuf : OpCodeAluReg, IOpCodeRegCbuf
{
public int Offset { get; }
public int Slot { get; }
public OpCodeAluRegCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
Rb = new Register(opCode.Extract(39, 8), RegisterType.Gpr);
}
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeAttribute : OpCodeAluReg
{
public int AttributeOffset { get; }
public int Count { get; }
public OpCodeAttribute(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
AttributeOffset = opCode.Extract(20, 10);
Count = opCode.Extract(47, 2) + 1;
}
}
}

View file

@ -0,0 +1,19 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeBranch : OpCode
{
public int Offset { get; }
public OpCodeBranch(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = ((int)(opCode >> 20) << 8) >> 8;
}
public ulong GetAbsoluteAddress()
{
return (ulong)((long)Address + (long)Offset + 8);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeExit : OpCode
{
public Condition Condition { get; }
public OpCodeExit(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Condition = (Condition)opCode.Extract(0, 5);
}
}
}

View file

@ -0,0 +1,24 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFArith : OpCodeAlu, IOpCodeFArith
{
public RoundingMode RoundingMode { get; }
public FmulScale Scale { get; }
public bool FlushToZero { get; }
public bool AbsoluteA { get; }
public OpCodeFArith(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
RoundingMode = (RoundingMode)opCode.Extract(39, 2);
Scale = (FmulScale)opCode.Extract(41, 3);
FlushToZero = opCode.Extract(44);
AbsoluteA = opCode.Extract(46);
}
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFArithCbuf : OpCodeFArith, IOpCodeCbuf
{
public int Offset { get; }
public int Slot { get; }
public OpCodeFArithCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFArithImm : OpCodeFArith, IOpCodeImmF
{
public float Immediate { get; }
public OpCodeFArithImm(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.DecodeF20Immediate(opCode);
}
}
}

View file

@ -0,0 +1,30 @@
using Ryujinx.Graphics.Shader.Instructions;
using System;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFArithImm32 : OpCodeAlu, IOpCodeFArith, IOpCodeImmF
{
public RoundingMode RoundingMode => RoundingMode.ToNearest;
public FmulScale Scale => FmulScale.None;
public bool FlushToZero { get; }
public bool AbsoluteA { get; }
public float Immediate { get; }
public OpCodeFArithImm32(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
int imm = opCode.Extract(20, 32);
Immediate = BitConverter.Int32BitsToSingle(imm);
SetCondCode = opCode.Extract(52);
AbsoluteA = opCode.Extract(54);
FlushToZero = opCode.Extract(55);
Saturate = false;
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFArithReg : OpCodeFArith, IOpCodeReg
{
public Register Rb { get; protected set; }
public OpCodeFArithReg(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
}
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFArithRegCbuf : OpCodeFArith, IOpCodeRegCbuf
{
public int Offset { get; }
public int Slot { get; }
public OpCodeFArithRegCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeFsetImm : OpCodeSet, IOpCodeImmF
{
public float Immediate { get; }
public OpCodeFsetImm(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.DecodeF20Immediate(opCode);
}
}
}

View file

@ -0,0 +1,22 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHfma : OpCode, IOpCodeRd, IOpCodeRa, IOpCodeRc
{
public Register Rd { get; }
public Register Ra { get; }
public Register Rc { get; protected set; }
public FPHalfSwizzle SwizzleA { get; }
public OpCodeHfma(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Rc = new Register(opCode.Extract(39, 8), RegisterType.Gpr);
SwizzleA = (FPHalfSwizzle)opCode.Extract(47, 2);
}
}
}

View file

@ -0,0 +1,30 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHfmaCbuf : OpCodeHfma, IOpCodeHfma, IOpCodeCbuf
{
public int Offset { get; }
public int Slot { get; }
public bool NegateB { get; }
public bool NegateC { get; }
public bool Saturate { get; }
public FPHalfSwizzle SwizzleB => FPHalfSwizzle.FP32;
public FPHalfSwizzle SwizzleC { get; }
public OpCodeHfmaCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
NegateC = opCode.Extract(51);
Saturate = opCode.Extract(52);
SwizzleC = (FPHalfSwizzle)opCode.Extract(53, 2);
NegateB = opCode.Extract(56);
}
}
}

View file

@ -0,0 +1,26 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHfmaImm2x10 : OpCodeHfma, IOpCodeHfma, IOpCodeImm
{
public int Immediate { get; }
public bool NegateB => false;
public bool NegateC { get; }
public bool Saturate { get; }
public FPHalfSwizzle SwizzleB => FPHalfSwizzle.FP16;
public FPHalfSwizzle SwizzleC { get; }
public OpCodeHfmaImm2x10(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.Decode2xF10Immediate(opCode);
NegateC = opCode.Extract(51);
Saturate = opCode.Extract(52);
SwizzleC = (FPHalfSwizzle)opCode.Extract(53, 2);
}
}
}

View file

@ -0,0 +1,25 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHfmaImm32 : OpCodeHfma, IOpCodeHfma, IOpCodeImm
{
public int Immediate { get; }
public bool NegateB => false;
public bool NegateC { get; }
public bool Saturate => false;
public FPHalfSwizzle SwizzleB => FPHalfSwizzle.FP16;
public FPHalfSwizzle SwizzleC => FPHalfSwizzle.FP16;
public OpCodeHfmaImm32(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = opCode.Extract(20, 32);
NegateC = opCode.Extract(52);
Rc = Rd;
}
}
}

View file

@ -0,0 +1,29 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHfmaReg : OpCodeHfma, IOpCodeHfma, IOpCodeReg
{
public Register Rb { get; }
public bool NegateB { get; }
public bool NegateC { get; }
public bool Saturate { get; }
public FPHalfSwizzle SwizzleB { get; }
public FPHalfSwizzle SwizzleC { get; }
public OpCodeHfmaReg(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
SwizzleB = (FPHalfSwizzle)opCode.Extract(28, 2);
NegateC = opCode.Extract(30);
NegateB = opCode.Extract(31);
Saturate = opCode.Extract(32);
SwizzleC = (FPHalfSwizzle)opCode.Extract(35, 2);
}
}
}

View file

@ -0,0 +1,30 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHfmaRegCbuf : OpCodeHfma, IOpCodeHfma, IOpCodeRegCbuf
{
public int Offset { get; }
public int Slot { get; }
public bool NegateB { get; }
public bool NegateC { get; }
public bool Saturate { get; }
public FPHalfSwizzle SwizzleB { get; }
public FPHalfSwizzle SwizzleC => FPHalfSwizzle.FP32;
public OpCodeHfmaRegCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
NegateC = opCode.Extract(51);
Saturate = opCode.Extract(52);
SwizzleB = (FPHalfSwizzle)opCode.Extract(53, 2);
NegateB = opCode.Extract(56);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeHsetImm2x10 : OpCodeSet, IOpCodeImm
{
public int Immediate { get; }
public OpCodeHsetImm2x10(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.Decode2xF10Immediate(opCode);
}
}
}

View file

@ -0,0 +1,20 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeIpa : OpCodeAluReg
{
public int AttributeOffset { get; }
public InterpolationMode Mode { get; }
public OpCodeIpa(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
AttributeOffset = opCode.Extract(28, 10);
Saturate = opCode.Extract(51);
Mode = (InterpolationMode)opCode.Extract(54, 2);
}
}
}

View file

@ -0,0 +1,26 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeLdc : OpCode, IOpCodeRd, IOpCodeRa, IOpCodeCbuf
{
public Register Rd { get; }
public Register Ra { get; }
public int Offset { get; }
public int Slot { get; }
public IntegerSize Size { get; }
public OpCodeLdc(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Offset = opCode.Extract(22, 14);
Slot = opCode.Extract(36, 5);
Size = (IntegerSize)opCode.Extract(48, 3);
}
}
}

View file

@ -0,0 +1,28 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeLop : OpCodeAlu, IOpCodeLop
{
public bool InvertA { get; protected set; }
public bool InvertB { get; protected set; }
public LogicalOperation LogicalOp { get; }
public ConditionalOperation CondOp { get; }
public Register Predicate48 { get; }
public OpCodeLop(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
InvertA = opCode.Extract(39);
InvertB = opCode.Extract(40);
LogicalOp = (LogicalOperation)opCode.Extract(41, 2);
CondOp = (ConditionalOperation)opCode.Extract(44, 2);
Predicate48 = new Register(opCode.Extract(48, 3), RegisterType.Predicate);
}
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeLopCbuf : OpCodeLop, IOpCodeCbuf
{
public int Offset { get; }
public int Slot { get; }
public OpCodeLopCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeLopImm : OpCodeLop, IOpCodeImm
{
public int Immediate { get; }
public OpCodeLopImm(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.DecodeS20Immediate(opCode);
}
}
}

View file

@ -0,0 +1,22 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeLopImm32 : OpCodeAluImm32, IOpCodeLop, IOpCodeImm
{
public LogicalOperation LogicalOp { get; }
public bool InvertA { get; }
public bool InvertB { get; }
public OpCodeLopImm32(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
LogicalOp = (LogicalOperation)opCode.Extract(53, 2);
InvertA = opCode.Extract(55);
InvertB = opCode.Extract(56);
Extended = opCode.Extract(57);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeLopReg : OpCodeLop, IOpCodeReg
{
public Register Rb { get; }
public OpCodeLopReg(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
}
}
}

View file

@ -0,0 +1,28 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeMemory : OpCode, IOpCodeRd, IOpCodeRa
{
public Register Rd { get; }
public Register Ra { get; }
public int Offset { get; }
public bool Extended { get; }
public IntegerSize Size { get; }
public OpCodeMemory(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Offset = opCode.Extract(20, 24);
Extended = opCode.Extract(45);
Size = (IntegerSize)opCode.Extract(48, 3);
}
}
}

View file

@ -0,0 +1,20 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodePsetp : OpCodeSet
{
public Register Predicate12 { get; }
public Register Predicate29 { get; }
public LogicalOperation LogicalOpAB { get; }
public OpCodePsetp(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Predicate12 = new Register(opCode.Extract(12, 3), RegisterType.Predicate);
Predicate29 = new Register(opCode.Extract(29, 3), RegisterType.Predicate);
LogicalOpAB = (LogicalOperation)opCode.Extract(24, 2);
}
}
}

View file

@ -0,0 +1,26 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeSet : OpCodeAlu
{
public Register Predicate0 { get; }
public Register Predicate3 { get; }
public bool NegateP { get; }
public LogicalOperation LogicalOp { get; }
public bool FlushToZero { get; }
public OpCodeSet(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Predicate0 = new Register(opCode.Extract(0, 3), RegisterType.Predicate);
Predicate3 = new Register(opCode.Extract(3, 3), RegisterType.Predicate);
LogicalOp = (LogicalOperation)opCode.Extract(45, 2);
FlushToZero = opCode.Extract(47);
}
}
}

View file

@ -0,0 +1,16 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeSetCbuf : OpCodeSet, IOpCodeCbuf
{
public int Offset { get; }
public int Slot { get; }
public OpCodeSetCbuf(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Offset = opCode.Extract(20, 14);
Slot = opCode.Extract(34, 5);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeSetImm : OpCodeSet, IOpCodeImm
{
public int Immediate { get; }
public OpCodeSetImm(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Immediate = DecoderHelper.DecodeS20Immediate(opCode);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeSetReg : OpCodeSet, IOpCodeReg
{
public Register Rb { get; protected set; }
public OpCodeSetReg(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
}
}
}

View file

@ -0,0 +1,20 @@
using Ryujinx.Graphics.Shader.Instructions;
using Ryujinx.Graphics.Shader.IntermediateRepresentation;
using System.Collections.Generic;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeSsy : OpCodeBranch
{
public Dictionary<OpCodeSync, Operand> Syncs { get; }
public OpCodeSsy(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Syncs = new Dictionary<OpCodeSync, Operand>();
Predicate = new Register(RegisterConsts.PredicateTrueIndex, RegisterType.Predicate);
InvertPredicate = false;
}
}
}

View file

@ -0,0 +1,15 @@
using Ryujinx.Graphics.Shader.Instructions;
using System.Collections.Generic;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeSync : OpCode
{
public Dictionary<OpCodeSsy, int> Targets { get; }
public OpCodeSync(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Targets = new Dictionary<OpCodeSsy, int>();
}
}
}

View file

@ -0,0 +1,227 @@
using Ryujinx.Graphics.Shader.Instructions;
using System;
namespace Ryujinx.Graphics.Shader.Decoders
{
static class OpCodeTable
{
private const int EncodingBits = 14;
private class TableEntry
{
public InstEmitter Emitter { get; }
public Type OpCodeType { get; }
public int XBits { get; }
public TableEntry(InstEmitter emitter, Type opCodeType, int xBits)
{
Emitter = emitter;
OpCodeType = opCodeType;
XBits = xBits;
}
}
private static TableEntry[] _opCodes;
static OpCodeTable()
{
_opCodes = new TableEntry[1 << EncodingBits];
#region Instructions
Set("1110111111011x", InstEmit.Ald, typeof(OpCodeAttribute));
Set("1110111111110x", InstEmit.Ast, typeof(OpCodeAttribute));
Set("0100110000000x", InstEmit.Bfe, typeof(OpCodeAluCbuf));
Set("0011100x00000x", InstEmit.Bfe, typeof(OpCodeAluImm));
Set("0101110000000x", InstEmit.Bfe, typeof(OpCodeAluReg));
Set("111000100100xx", InstEmit.Bra, typeof(OpCodeBranch));
Set("0101000010100x", InstEmit.Csetp, typeof(OpCodePsetp));
Set("111000110000xx", InstEmit.Exit, typeof(OpCodeExit));
Set("0100110010101x", InstEmit.F2F, typeof(OpCodeFArithCbuf));
Set("0011100x10101x", InstEmit.F2F, typeof(OpCodeFArithImm));
Set("0101110010101x", InstEmit.F2F, typeof(OpCodeFArithReg));
Set("0100110010110x", InstEmit.F2I, typeof(OpCodeFArithCbuf));
Set("0011100x10110x", InstEmit.F2I, typeof(OpCodeFArithImm));
Set("0101110010110x", InstEmit.F2I, typeof(OpCodeFArithReg));
Set("0100110001011x", InstEmit.Fadd, typeof(OpCodeFArithCbuf));
Set("0011100x01011x", InstEmit.Fadd, typeof(OpCodeFArithImm));
Set("000010xxxxxxxx", InstEmit.Fadd, typeof(OpCodeFArithImm32));
Set("0101110001011x", InstEmit.Fadd, typeof(OpCodeFArithReg));
Set("010010011xxxxx", InstEmit.Ffma, typeof(OpCodeFArithCbuf));
Set("0011001x1xxxxx", InstEmit.Ffma, typeof(OpCodeFArithImm));
Set("010100011xxxxx", InstEmit.Ffma, typeof(OpCodeFArithRegCbuf));
Set("010110011xxxxx", InstEmit.Ffma, typeof(OpCodeFArithReg));
Set("0100110001100x", InstEmit.Fmnmx, typeof(OpCodeFArithCbuf));
Set("0011100x01100x", InstEmit.Fmnmx, typeof(OpCodeFArithImm));
Set("0101110001100x", InstEmit.Fmnmx, typeof(OpCodeFArithReg));
Set("0100110001101x", InstEmit.Fmul, typeof(OpCodeFArithCbuf));
Set("0011100x01101x", InstEmit.Fmul, typeof(OpCodeFArithImm));
Set("00011110xxxxxx", InstEmit.Fmul, typeof(OpCodeFArithImm32));
Set("0101110001101x", InstEmit.Fmul, typeof(OpCodeFArithReg));
Set("0100100xxxxxxx", InstEmit.Fset, typeof(OpCodeSetCbuf));
Set("0011000xxxxxxx", InstEmit.Fset, typeof(OpCodeFsetImm));
Set("01011000xxxxxx", InstEmit.Fset, typeof(OpCodeSetReg));
Set("010010111011xx", InstEmit.Fsetp, typeof(OpCodeSetCbuf));
Set("0011011x1011xx", InstEmit.Fsetp, typeof(OpCodeFsetImm));
Set("010110111011xx", InstEmit.Fsetp, typeof(OpCodeSetReg));
Set("0111101x1xxxxx", InstEmit.Hadd2, typeof(OpCodeAluCbuf));
Set("0111101x0xxxxx", InstEmit.Hadd2, typeof(OpCodeAluImm2x10));
Set("0010110xxxxxxx", InstEmit.Hadd2, typeof(OpCodeAluImm32));
Set("0101110100010x", InstEmit.Hadd2, typeof(OpCodeAluReg));
Set("01110xxx1xxxxx", InstEmit.Hfma2, typeof(OpCodeHfmaCbuf));
Set("01110xxx0xxxxx", InstEmit.Hfma2, typeof(OpCodeHfmaImm2x10));
Set("0010100xxxxxxx", InstEmit.Hfma2, typeof(OpCodeHfmaImm32));
Set("0101110100000x", InstEmit.Hfma2, typeof(OpCodeHfmaReg));
Set("01100xxx1xxxxx", InstEmit.Hfma2, typeof(OpCodeHfmaRegCbuf));
Set("0111100x1xxxxx", InstEmit.Hmul2, typeof(OpCodeAluCbuf));
Set("0111100x0xxxxx", InstEmit.Hmul2, typeof(OpCodeAluImm2x10));
Set("0010101xxxxxxx", InstEmit.Hmul2, typeof(OpCodeAluImm32));
Set("0101110100001x", InstEmit.Hmul2, typeof(OpCodeAluReg));
Set("0111111x1xxxxx", InstEmit.Hsetp2, typeof(OpCodeSetCbuf));
Set("0111111x0xxxxx", InstEmit.Hsetp2, typeof(OpCodeHsetImm2x10));
Set("0101110100100x", InstEmit.Hsetp2, typeof(OpCodeSetReg));
Set("0100110010111x", InstEmit.I2F, typeof(OpCodeAluCbuf));
Set("0011100x10111x", InstEmit.I2F, typeof(OpCodeAluImm));
Set("0101110010111x", InstEmit.I2F, typeof(OpCodeAluReg));
Set("0100110011100x", InstEmit.I2I, typeof(OpCodeAluCbuf));
Set("0011100x11100x", InstEmit.I2I, typeof(OpCodeAluImm));
Set("0101110011100x", InstEmit.I2I, typeof(OpCodeAluReg));
Set("0100110000010x", InstEmit.Iadd, typeof(OpCodeAluCbuf));
Set("0011100000010x", InstEmit.Iadd, typeof(OpCodeAluImm));
Set("0001110x0xxxxx", InstEmit.Iadd, typeof(OpCodeAluImm32));
Set("0101110000010x", InstEmit.Iadd, typeof(OpCodeAluReg));
Set("010011001100xx", InstEmit.Iadd3, typeof(OpCodeAluCbuf));
Set("001110001100xx", InstEmit.Iadd3, typeof(OpCodeAluImm));
Set("010111001100xx", InstEmit.Iadd3, typeof(OpCodeAluReg));
Set("0100110000100x", InstEmit.Imnmx, typeof(OpCodeAluCbuf));
Set("0011100x00100x", InstEmit.Imnmx, typeof(OpCodeAluImm));
Set("0101110000100x", InstEmit.Imnmx, typeof(OpCodeAluReg));
Set("11100000xxxxxx", InstEmit.Ipa, typeof(OpCodeIpa));
Set("1110111111010x", InstEmit.Isberd, typeof(OpCodeAlu));
Set("0100110000011x", InstEmit.Iscadd, typeof(OpCodeAluCbuf));
Set("0011100x00011x", InstEmit.Iscadd, typeof(OpCodeAluImm));
Set("000101xxxxxxxx", InstEmit.Iscadd, typeof(OpCodeAluImm32));
Set("0101110000011x", InstEmit.Iscadd, typeof(OpCodeAluReg));
Set("010010110101xx", InstEmit.Iset, typeof(OpCodeSetCbuf));
Set("001101100101xx", InstEmit.Iset, typeof(OpCodeSetImm));
Set("010110110101xx", InstEmit.Iset, typeof(OpCodeSetReg));
Set("010010110110xx", InstEmit.Isetp, typeof(OpCodeSetCbuf));
Set("0011011x0110xx", InstEmit.Isetp, typeof(OpCodeSetImm));
Set("010110110110xx", InstEmit.Isetp, typeof(OpCodeSetReg));
Set("111000110011xx", InstEmit.Kil, typeof(OpCodeExit));
Set("1110111101000x", InstEmit.Ld, typeof(OpCodeMemory));
Set("1110111110010x", InstEmit.Ldc, typeof(OpCodeLdc));
Set("1110111011010x", InstEmit.Ldg, typeof(OpCodeMemory));
Set("0100110001000x", InstEmit.Lop, typeof(OpCodeLopCbuf));
Set("0011100001000x", InstEmit.Lop, typeof(OpCodeLopImm));
Set("000001xxxxxxxx", InstEmit.Lop, typeof(OpCodeLopImm32));
Set("0101110001000x", InstEmit.Lop, typeof(OpCodeLopReg));
Set("0010000xxxxxxx", InstEmit.Lop3, typeof(OpCodeLopCbuf));
Set("001111xxxxxxxx", InstEmit.Lop3, typeof(OpCodeLopImm));
Set("0101101111100x", InstEmit.Lop3, typeof(OpCodeLopReg));
Set("0100110010011x", InstEmit.Mov, typeof(OpCodeAluCbuf));
Set("0011100x10011x", InstEmit.Mov, typeof(OpCodeAluImm));
Set("000000010000xx", InstEmit.Mov, typeof(OpCodeAluImm32));
Set("0101110010011x", InstEmit.Mov, typeof(OpCodeAluReg));
Set("0101000010000x", InstEmit.Mufu, typeof(OpCodeFArith));
Set("1111101111100x", InstEmit.Out, typeof(OpCode));
Set("0101000010010x", InstEmit.Psetp, typeof(OpCodePsetp));
Set("0100110010010x", InstEmit.Rro, typeof(OpCodeFArithCbuf));
Set("0011100x10010x", InstEmit.Rro, typeof(OpCodeFArithImm));
Set("0101110010010x", InstEmit.Rro, typeof(OpCodeFArithReg));
Set("1111000011001x", InstEmit.S2r, typeof(OpCodeAlu));
Set("0100110010100x", InstEmit.Sel, typeof(OpCodeAluCbuf));
Set("0011100x10100x", InstEmit.Sel, typeof(OpCodeAluImm));
Set("0101110010100x", InstEmit.Sel, typeof(OpCodeAluReg));
Set("0100110001001x", InstEmit.Shl, typeof(OpCodeAluCbuf));
Set("0011100x01001x", InstEmit.Shl, typeof(OpCodeAluImm));
Set("0101110001001x", InstEmit.Shl, typeof(OpCodeAluReg));
Set("0100110000101x", InstEmit.Shr, typeof(OpCodeAluCbuf));
Set("0011100x00101x", InstEmit.Shr, typeof(OpCodeAluImm));
Set("0101110000101x", InstEmit.Shr, typeof(OpCodeAluReg));
Set("111000101001xx", InstEmit.Ssy, typeof(OpCodeSsy));
Set("1110111101010x", InstEmit.St, typeof(OpCodeMemory));
Set("1110111011011x", InstEmit.Stg, typeof(OpCodeMemory));
Set("1111000011111x", InstEmit.Sync, typeof(OpCodeSync));
Set("110000xxxx111x", InstEmit.Tex, typeof(OpCodeTex));
Set("1101111010111x", InstEmit.TexB, typeof(OpCodeTexB));
Set("1101x00xxxxxxx", InstEmit.Texs, typeof(OpCodeTexs));
Set("1101x01xxxxxxx", InstEmit.Texs, typeof(OpCodeTlds));
Set("1101x11100xxxx", InstEmit.Texs, typeof(OpCodeTld4s));
Set("11011100xx111x", InstEmit.Tld, typeof(OpCodeTld));
Set("11011101xx111x", InstEmit.TldB, typeof(OpCodeTld));
Set("110010xxxx111x", InstEmit.Tld4, typeof(OpCodeTld4));
Set("1101111101001x", InstEmit.Txq, typeof(OpCodeTex));
Set("1101111101010x", InstEmit.TxqB, typeof(OpCodeTex));
Set("01011111xxxxxx", InstEmit.Vmad, typeof(OpCodeVideo));
Set("0100111xxxxxxx", InstEmit.Xmad, typeof(OpCodeAluCbuf));
Set("0011011x00xxxx", InstEmit.Xmad, typeof(OpCodeAluImm));
Set("010100010xxxxx", InstEmit.Xmad, typeof(OpCodeAluRegCbuf));
Set("0101101100xxxx", InstEmit.Xmad, typeof(OpCodeAluReg));
#endregion
}
private static void Set(string encoding, InstEmitter emitter, Type opCodeType)
{
if (encoding.Length != EncodingBits)
{
throw new ArgumentException(nameof(encoding));
}
int bit = encoding.Length - 1;
int value = 0;
int xMask = 0;
int xBits = 0;
int[] xPos = new int[encoding.Length];
for (int index = 0; index < encoding.Length; index++, bit--)
{
char chr = encoding[index];
if (chr == '1')
{
value |= 1 << bit;
}
else if (chr == 'x')
{
xMask |= 1 << bit;
xPos[xBits++] = bit;
}
}
xMask = ~xMask;
TableEntry entry = new TableEntry(emitter, opCodeType, xBits);
for (int index = 0; index < (1 << xBits); index++)
{
value &= xMask;
for (int x = 0; x < xBits; x++)
{
value |= ((index >> x) & 1) << xPos[x];
}
if (_opCodes[value] == null || _opCodes[value].XBits > xBits)
{
_opCodes[value] = entry;
}
}
}
public static (InstEmitter emitter, Type opCodeType) GetEmitter(long opCode)
{
TableEntry entry = _opCodes[(ulong)opCode >> (64 - EncodingBits)];
if (entry != null)
{
return (entry.Emitter, entry.OpCodeType);
}
return (null, null);
}
}
}

View file

@ -0,0 +1,14 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTex : OpCodeTexture
{
public OpCodeTex(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
HasDepthCompare = opCode.Extract(50);
HasOffset = opCode.Extract(54);
}
}
}

View file

@ -0,0 +1,20 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTexB : OpCodeTex
{
public OpCodeTexB(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
switch (opCode.Extract(37, 3))
{
case 0: LodMode = TextureLodMode.None; break;
case 1: LodMode = TextureLodMode.LodZero; break;
case 2: LodMode = TextureLodMode.LodBias; break;
case 3: LodMode = TextureLodMode.LodLevel; break;
case 6: LodMode = TextureLodMode.LodBiasA; break;
case 7: LodMode = TextureLodMode.LodLevelA; break;
}
}
}
}

View file

@ -0,0 +1,11 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTexs : OpCodeTextureScalar
{
public TextureTarget Target => (TextureTarget)RawType;
public OpCodeTexs(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode) { }
}
}

View file

@ -0,0 +1,42 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTexture : OpCode
{
public Register Rd { get; }
public Register Ra { get; }
public Register Rb { get; }
public bool IsArray { get; }
public TextureDimensions Dimensions { get; }
public int ComponentMask { get; }
public int Immediate { get; }
public TextureLodMode LodMode { get; protected set; }
public bool HasOffset { get; protected set; }
public bool HasDepthCompare { get; protected set; }
public bool IsMultisample { get; protected set; }
public OpCodeTexture(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
IsArray = opCode.Extract(28);
Dimensions = (TextureDimensions)opCode.Extract(29, 2);
ComponentMask = opCode.Extract(31, 4);
Immediate = opCode.Extract(36, 13);
LodMode = (TextureLodMode)opCode.Extract(55, 3);
}
}
}

View file

@ -0,0 +1,62 @@
// ReSharper disable InconsistentNaming
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTextureScalar : OpCode
{
#region "Component mask LUT"
private const int ____ = 0x0;
private const int R___ = 0x1;
private const int _G__ = 0x2;
private const int RG__ = 0x3;
private const int __B_ = 0x4;
private const int RGB_ = 0x7;
private const int ___A = 0x8;
private const int R__A = 0x9;
private const int _G_A = 0xa;
private const int RG_A = 0xb;
private const int __BA = 0xc;
private const int R_BA = 0xd;
private const int _GBA = 0xe;
private const int RGBA = 0xf;
private static int[,] _maskLut = new int[,]
{
{ R___, _G__, __B_, ___A, RG__, R__A, _G_A, __BA },
{ RGB_, RG_A, R_BA, _GBA, RGBA, ____, ____, ____ }
};
#endregion
public Register Rd0 { get; }
public Register Ra { get; }
public Register Rb { get; }
public Register Rd1 { get; }
public int Immediate { get; }
public int ComponentMask { get; protected set; }
protected int RawType;
public bool IsFp16 { get; }
public OpCodeTextureScalar(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd0 = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Rb = new Register(opCode.Extract(20, 8), RegisterType.Gpr);
Rd1 = new Register(opCode.Extract(28, 8), RegisterType.Gpr);
Immediate = opCode.Extract(36, 13);
int compSel = opCode.Extract(50, 3);
RawType = opCode.Extract(53, 4);
IsFp16 = !opCode.Extract(59);
ComponentMask = _maskLut[Rd1.IsRZ ? 0 : 1, compSel];
}
}
}

View file

@ -0,0 +1,20 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTld : OpCodeTexture
{
public OpCodeTld(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
HasOffset = opCode.Extract(35);
IsMultisample = opCode.Extract(50);
bool isLL = opCode.Extract(55);
LodMode = isLL
? TextureLodMode.LodLevel
: TextureLodMode.LodZero;
}
}
}

View file

@ -0,0 +1,20 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTld4 : OpCodeTexture
{
public TextureGatherOffset Offset { get; }
public int GatherCompIndex { get; }
public OpCodeTld4(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
HasDepthCompare = opCode.Extract(50);
Offset = (TextureGatherOffset)opCode.Extract(54, 2);
GatherCompIndex = opCode.Extract(56, 2);
}
}
}

View file

@ -0,0 +1,22 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTld4s : OpCodeTextureScalar
{
public bool HasDepthCompare { get; }
public bool HasOffset { get; }
public int GatherCompIndex { get; }
public OpCodeTld4s(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
HasDepthCompare = opCode.Extract(50);
HasOffset = opCode.Extract(51);
GatherCompIndex = opCode.Extract(52, 2);
ComponentMask = Rd1.IsRZ ? 3 : 0xf;
}
}
}

View file

@ -0,0 +1,11 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeTlds : OpCodeTextureScalar
{
public TexelLoadTarget Target => (TexelLoadTarget)RawType;
public OpCodeTlds(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode) { }
}
}

View file

@ -0,0 +1,24 @@
using Ryujinx.Graphics.Shader.Instructions;
namespace Ryujinx.Graphics.Shader.Decoders
{
class OpCodeVideo : OpCode, IOpCodeRd, IOpCodeRa, IOpCodeRc
{
public Register Rd { get; }
public Register Ra { get; }
public Register Rc { get; }
public bool SetCondCode { get; protected set; }
public bool Saturate { get; protected set; }
public OpCodeVideo(InstEmitter emitter, ulong address, long opCode) : base(emitter, address, opCode)
{
Rd = new Register(opCode.Extract(0, 8), RegisterType.Gpr);
Ra = new Register(opCode.Extract(8, 8), RegisterType.Gpr);
Rc = new Register(opCode.Extract(39, 8), RegisterType.Gpr);
SetCondCode = opCode.Extract(47);
Saturate = opCode.Extract(55);
}
}
}

View file

@ -0,0 +1,36 @@
using System;
namespace Ryujinx.Graphics.Shader.Decoders
{
struct Register : IEquatable<Register>
{
public int Index { get; }
public RegisterType Type { get; }
public bool IsRZ => Type == RegisterType.Gpr && Index == RegisterConsts.RegisterZeroIndex;
public bool IsPT => Type == RegisterType.Predicate && Index == RegisterConsts.PredicateTrueIndex;
public Register(int index, RegisterType type)
{
Index = index;
Type = type;
}
public override int GetHashCode()
{
return (ushort)Index | ((ushort)Type << 16);
}
public override bool Equals(object obj)
{
return obj is Register reg && Equals(reg);
}
public bool Equals(Register other)
{
return other.Index == Index &&
other.Type == Type;
}
}
}

View file

@ -0,0 +1,13 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
static class RegisterConsts
{
public const int GprsCount = 255;
public const int PredsCount = 7;
public const int FlagsCount = 4;
public const int TotalCount = GprsCount + PredsCount + FlagsCount;
public const int RegisterZeroIndex = GprsCount;
public const int PredicateTrueIndex = PredsCount;
}
}

View file

@ -0,0 +1,9 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum RegisterType
{
Flag,
Gpr,
Predicate,
}
}

View file

@ -0,0 +1,10 @@
namespace Ryujinx.Graphics.Shader.Decoders
{
enum RoundingMode
{
ToNearest = 0,
TowardsNegativeInfinity = 1,
TowardsPositiveInfinity = 2,
TowardsZero = 3
}
}

Some files were not shown because too many files have changed in this diff Show more