Exemple #1
0
        public void GetAndSet()
        {
            var rs = new RegisterSet(Pow(2, 4));

            rs.Set(0, 11);
            Assert.That(rs.Get(0), Is.EqualTo(11));
        }
Exemple #2
0
        public void GetAndSet_WithSmallBits()
        {
            var rs = new RegisterSet(6);

            rs.Set(0, 11);
            Assert.That(rs.Get(0), Is.EqualTo(11));
        }
Exemple #3
0
 public Ps1InstructionSet(RegisterSet gprRs, RegisterSet cop0Rs, RegisterSet cop2cRs, RegisterSet cop2dRs)
     : base(gprRs)
 {
     this.cop0Rs = cop0Rs;
     this.cop2cRs = cop2cRs;
     this.cop2dRs = cop2dRs;
 }
Exemple #4
0
        public void MergeUsingUpdate()
        {
            const int count = 32;
            var       rand  = new Random(2);
            var       rs    = new RegisterSet(count);
            var       rss   = new RegisterSet[5];

            for (var i = 0; i < rss.Length; ++i)
            {
                rss[i] = new RegisterSet(count);
                for (uint pos = 0; pos < rs.Count; ++pos)
                {
                    var val = (uint)rand.Next(10);
                    rs.UpdateIfGreater(pos, val);
                    rss[i].Set(pos, val);
                }
            }

            var merged = new RegisterSet(count);

            foreach (var t in rss)
            {
                for (uint pos = 0; pos < rs.Count; pos++)
                {
                    merged.UpdateIfGreater(pos, t.Get(pos));
                }
            }

            for (uint pos = 0; pos < rs.Count; pos++)
            {
                Assert.That(merged.Get(pos), Is.EqualTo(rs.Get(pos)));
            }
        }
Exemple #5
0
        private ConstantDeclaration ReadConstantDeclaration(BinaryReader ctabReader)
        {
            var ctabStream = ctabReader.BaseStream;

            // D3DXSHADER_CONSTANTINFO
            int         nameOffset    = ctabReader.ReadInt32();
            RegisterSet registerSet   = (RegisterSet)ctabReader.ReadInt16();
            short       registerIndex = ctabReader.ReadInt16();
            short       registerCount = ctabReader.ReadInt16();

            ctabStream.Position += sizeof(short); // Reserved
            int typeInfoOffset     = ctabReader.ReadInt32();
            int defaultValueOffset = ctabReader.ReadInt32();

            System.Diagnostics.Debug.Assert(defaultValueOffset == 0);

            ctabStream.Position = nameOffset;
            string name = ReadStringNullTerminated(ctabStream);

            // D3DXSHADER_TYPEINFO
            ctabStream.Position = typeInfoOffset;
            ParameterClass cl                     = (ParameterClass)ctabReader.ReadInt16();
            ParameterType  type                   = (ParameterType)ctabReader.ReadInt16();
            short          rows                   = ctabReader.ReadInt16();
            short          columns                = ctabReader.ReadInt16();
            short          numElements            = ctabReader.ReadInt16();
            short          numStructMembers       = ctabReader.ReadInt16();
            int            structMemberInfoOffset = ctabReader.ReadInt32();

            //System.Diagnostics.Debug.Assert(numElements == 1);
            System.Diagnostics.Debug.Assert(structMemberInfoOffset == 0);

            return(new ConstantDeclaration(name, registerSet, registerIndex, registerCount, cl, type, rows, columns));
        }
Exemple #6
0
        public static Instruction CreateBinaryInstruction(
            string mnemonic, OperationNode op, int exUnit,
            ValueNode vres, RegisterSet vresRegs,
            ValueNode v1, RegisterSet v1Regs,
            ValueNode v2, RegisterSet v2Regs)
        {
            InstructionPattern ip = new InstructionPattern();

            ip.AddNode(op);
            ip.AddNode(vres);
            ip.AddNode(v1);
            ip.AddNode(v2);
            ip.AddEdge(op, vres);
            ip.AddEdge(v1, op);
            ip.AddEdge(v2, op);

            ip.OperandValues.Add(v1);
            ip.OperandValues.Add(v2);
            ip.ResultValue = vres;

            Instruction i = new Instruction(mnemonic, ip);

            i.ExecutionUnit = exUnit;
            i.ResultRegisters = vresRegs;
            i.OperandsRegisters[0] = v1Regs;
            i.OperandsRegisters[1] = v2Regs;

            return i;
        }
Exemple #7
0
        private void ProcessConstants(IShaderDom shader)
        {
            RegisterSet registers = asm.CommonRegisters;

            for (int i = 0; i < registers.RegisterCount; i++)
            {
                Register reg = registers.GetRegister(i);
                if (reg.Category == RegisterCategory.Float4 ||
                    reg.Category == RegisterCategory.Boolean)
                {
                    if (reg.Semantic == null)
                    {
                        this.attributeNames.Add(reg.Name);
                    }
                    else
                    {
                        ExtractSemantic(shader, reg);
                    }
                }
                else if (reg.Semantic != null && reg.Category != RegisterCategory.Texture)
                {
                    throw new CompileException(string.Format("Error parsing semantic for '{1} {0}'. Semantic bound types may only be processed as Float4 or Texture registers", reg.Name, reg.Type));
                }
            }
        }
Exemple #8
0
        public void GetAndSet_AllPositions()
        {
            var rs = new RegisterSet(Pow(2, 4));

            for (uint i = 0; i < Pow(2, 4); ++i)
            {
                rs.Set(i, i % 31);
                Assert.That(rs.Get(i), Is.EqualTo(i % 31));
            }
        }
 public ConstantDeclaration(string name, RegisterSet registerSet, short registerIndex, short registerCount,
                            ParameterClass parameterClass, ParameterType parameterType, int rows, int columns, int elements, List <float> defaultValue)
 {
     Name           = name;
     RegisterSet    = registerSet;
     RegisterIndex  = registerIndex;
     RegisterCount  = registerCount;
     ParameterClass = parameterClass;
     ParameterType  = parameterType;
     Rows           = rows;
     Columns        = columns;
     Elements       = elements;
     DefaultValue   = defaultValue;
 }
Exemple #10
0
        private int MaxSamplers(RegisterSet set)
        {
            int maxSampler = 0;

            for (int i = 0; i < set.RegisterCount; i++)
            {
                Register reg = set.GetRegister(i);
                if (reg.Category == RegisterCategory.Sampler)
                {
                    maxSampler = Math.Max(reg.Index, maxSampler);
                }
            }
            return(maxSampler);
        }
Exemple #11
0
 public void Merge(RegisterSet other)
 {
     for (var bucket = 0; bucket < M.Length; ++bucket)
     {
         uint word = 0;
         for (var j = 0; j < Log2BitsPerWord; ++j)
         {
             uint mask     = 0x1Fu << (RegisterSize * j);
             uint thisVal  = M[bucket] & mask;
             uint otherVal = other.M[bucket] & mask;
             word |= (thisVal < otherVal) ? otherVal : thisVal;
         }
         M[bucket] = word;
     }
 }
        public void Get_The_Current_Frame_Correctly()
        {
            // arrange
            var engBuilder = new DebugEngineProxyBuilder();

            engBuilder.WithExecuteResult("!positions", @">Thread ID=0x7590 - Position: 168CC:0
 Thread ID=0x12A0 - Position: 211F5:0
 Thread ID=0x6CDC - Position: 21D59:0
 Thread ID=0x2984 - Position: 21DFE:0
 Thread ID=0x3484 - Position: 21ECA:0
 Thread ID=0x60B4 - Position: 2414F:0
 Thread ID=0x1F54 - Position: 241DE:0
");
            engBuilder.With32Bit(false);
            engBuilder.WithThreadId(0x7590);
            var stackBuilder = new StackFacadeBuilder();
            var stackTrace   = new StackTrace(new List <StackFrame>());

            stackBuilder.WithGetCurrentStackTrace(stackTrace);

            var registerSet     = new RegisterSet();
            var registerBuilder = new RegisterFacadeBuilder();

            registerBuilder.WithGetCurrentRegisterSet(Register.All, registerSet);

            var disassemblyLine = new DisassemblyLine(0x00007ffa51315595, ByteArrayBuilder.StringToByteArray("4d3bd1"),
                                                      "cmp", "r10,r9");
            var disBuilder = new DisassemblyFacadeBuilder();

            disBuilder.WithGetDisassemblyLines(1, new[] { disassemblyLine });
            var facade = new TimeTravelFacade
            {
                DebugEngineProxy  = engBuilder.Build(),
                StackFacade       = stackBuilder.Build(),
                RegisterFacade    = registerBuilder.Build(),
                DisassemblyFacade = disBuilder.Build()
            };

            // act
            var frame = facade.GetCurrentFrame();

            // assert
            frame.Position.Should().Be(new Position(0x168CC, 0));
            frame.DisassemblyLine.Should().Be(disassemblyLine);
            frame.RegisterSet.Should().Be(registerSet);
            frame.StackTrace.Should().Be(stackTrace);
            frame.ThreadId.Should().Be(0x7590);
        }
Exemple #13
0
        protected void CreateAddressIncInstructions(IList mi, int eu)
        {
            for (int i = 0; i < AR.Count; i++) {

                RegisterSet rs = new RegisterSet();

                rs.Add(AR[i]);

                mi.Add(Utilities.CreateBinaryRightConstantInstruction(
                        "$0++",
                        new ConstOperationNode(), new AddOperationNode(), eu,
                        new AddressRegisterNode(), rs,
                        new AddressRegisterNode(), rs,
                        new IntConstantNode(4), null));
            }
        }
 public ConstantDeclaration(string name, RegisterSet registerSet, short registerIndex, short registerCount,
                            ParameterClass parameterClass, ParameterType parameterType, int rows, int columns, int elements, List <float> defaultValue)
 {
     Name          = name;
     RegisterSet   = registerSet;
     RegisterIndex = (ushort)registerIndex;
     RegisterCount = (ushort)registerCount;
     Type          = new ConstantType()
     {
         ParameterClass = parameterClass,
         ParameterType  = parameterType,
         Rows           = (uint)rows,
         Columns        = (uint)columns,
         Elements       = (uint)elements,
     };
     DefaultValue = defaultValue;
 }
        private ConstantDeclaration ReadConstantDeclaration(BinaryReader ctabReader)
        {
            var ctabStream = ctabReader.BaseStream;

            // D3DXSHADER_CONSTANTINFO
            int         nameOffset    = ctabReader.ReadInt32();
            RegisterSet registerSet   = (RegisterSet)ctabReader.ReadInt16();
            short       registerIndex = ctabReader.ReadInt16();
            short       registerCount = ctabReader.ReadInt16();

            ctabStream.Position += sizeof(short);             // Reserved
            int          typeInfoOffset     = ctabReader.ReadInt32();
            int          defaultValueOffset = ctabReader.ReadInt32();
            List <float> defaultValue       = new List <float>();;

            ctabStream.Position = nameOffset;
            string name = ReadStringNullTerminated(ctabStream);

            if (defaultValueOffset != 0)
            {
                //Note: thre are corrisponding def instructions. TODO: check that they are the same
                ctabStream.Position = defaultValueOffset;
                for (int i = 0; i < 4; i++)
                {
                    defaultValue.Add(ctabReader.ReadSingle());
                }
            }

            // D3DXSHADER_TYPEINFO
            ctabStream.Position = typeInfoOffset;
            ParameterClass cl                     = (ParameterClass)ctabReader.ReadInt16();
            ParameterType  type                   = (ParameterType)ctabReader.ReadInt16();
            short          rows                   = ctabReader.ReadInt16();
            short          columns                = ctabReader.ReadInt16();
            short          numElements            = ctabReader.ReadInt16();
            short          numStructMembers       = ctabReader.ReadInt16();
            int            structMemberInfoOffset = ctabReader.ReadInt32();

            //System.Diagnostics.Debug.Assert(numElements == 1);
            System.Diagnostics.Debug.Assert(structMemberInfoOffset == 0);

            return(new ConstantDeclaration(name, registerSet, registerIndex, registerCount, cl, type, rows, columns, numElements, defaultValue));
        }
Exemple #16
0
        public static Instruction CreateLeftTernaryInstruction(
            string mnemonic, OperationNode op1, OperationNode op2, int exUnit,
            ValueNode vres, RegisterSet vresRegs,
            ValueNode v1, RegisterSet v1Regs,
            ValueNode v2, RegisterSet v2Regs,
            ValueNode v3, RegisterSet v3Regs)
        {
            InstructionPattern ip = new InstructionPattern();

            ip.AddNode(op1);
            ip.AddNode(op2);
            ip.AddNode(vres);
            ip.AddNode(v1);
            ip.AddNode(v2);
            ip.AddNode(v3);

            ValueNode iv1 = new RegisterValueNode(v1.Datatype);

            ip.AddNode(iv1);

            ip.AddEdge(v1, op1);
            ip.AddEdge(v2, op1);
            ip.AddEdge(op1, iv1);
            ip.AddEdge(iv1, op2);
            ip.AddEdge(v3, op2);
            ip.AddEdge(op2, vres);

            ip.OperandValues.Add(v1);
            ip.OperandValues.Add(v2);
            ip.OperandValues.Add(v3);
            ip.ResultValue = vres;

            Instruction i = new Instruction(mnemonic, ip);

            i.ExecutionUnit = exUnit;
            i.ResultRegisters = vresRegs;
            i.OperandsRegisters[0] = v1Regs;
            i.OperandsRegisters[1] = v2Regs;
            i.OperandsRegisters[2] = v3Regs;

            return i;
        }
        public static string GetDescription(this RegisterSet value)
        {
            switch (value)
            {
            case RegisterSet.Bool:
                return("b");

            case RegisterSet.Float4:
                return("c");

            case RegisterSet.Int4:
                return("i");

            case RegisterSet.Sampler:
                return("s");

            default:
                throw new InvalidOperationException();
            }
        }
Exemple #18
0
#pragma warning disable IDE1006 // Naming Styles
        static void Main(string[] args)
#pragma warning restore IDE1006 // Naming Styles
        {
            Oscillator.InitClock();
            Oscillator.Tick += on_tick;
            RegisterSet      regs = new RegisterSet();
            BusInterfaceUnit biu  = new BusInterfaceUnit(regs);

            biu.SetMemory(0, 0b11000111);
            biu.SetMemory(1, 0b00000110);
            biu.SetMemory(2, 0x00);
            biu.SetMemory(3, 0x10);
            biu.SetMemory(4, 0x30);
            biu.SetMemory(5, 0x40);


            biu.WatchTicks();
            ExecutionUnit test = new ExecutionUnit(regs, biu);


            while (ticks < 40)
            {
            }
        }
Exemple #19
0
        public void Execute(IMemory mem, RegisterSet registerSet)
        {
            if (errorWhileParsing) return;

            if (!useRegister)
            {
                registerSet.Accu += registerSet.GetRegisterVal(register);
                return;
            }

            registerSet.Accu += value;
            return;
        }
Exemple #20
0
        protected void CreateMachineRegisters()
        {
            GR = new RegisterSet();
            AR = new RegisterSet();

            for (int i = 0; i < 8; i++) {
                GR.Add(new Register("GR" + i, Datatype.FloatValue));
                AR.Add(new Register("AR" + i, Datatype.AddressValue));
            }

            machineRegisters = new ArrayList();

            foreach (Register r in GR.Registers)
                machineRegisters.Add(r);

            foreach (Register r in AR.Registers)
                machineRegisters.Add(r);
        }
Exemple #21
0
        private void ShowRegisters( RegisterSet set )
        {
            CoreState state = this.Debugger.Host.CpuHook.GetCoreState( 0 );
            this.pcTextBox.Text = string.Format( "0x{0:X8}", state.ProgramCounter );

            if( this.CurrentRegisterSet != set )
            {
                this.CurrentRegisterSet = set;
                switch( set )
                {
                    case RegisterSet.Gpr:
                        this.registerToggleToolStripSplitButton.Text = "GPR";
                        break;
                    case RegisterSet.Fpu:
                        this.registerToggleToolStripSplitButton.Text = "FPU";
                        break;
                    case RegisterSet.Vfpu:
                        this.registerToggleToolStripSplitButton.Text = "VFPU";
                        break;
                }
            }

            RegisterBank bank;
            switch( set )
            {
                default:
                case RegisterSet.Gpr:
                    bank = RegisterBanks.General;
                    break;
                case RegisterSet.Fpu:
                    bank = RegisterBanks.Fpu;
                    break;
                case RegisterSet.Vfpu:
                    bank = RegisterBanks.Vfpu;
                    break;
            }

            this.registersListView.BeginUpdate();
            this.registersListView.Items.Clear();
            foreach( Register register in bank.Registers )
            {
                string prettyValue = string.Empty;
                string rawValue = string.Empty;
                switch( set )
                {
                    case RegisterSet.Gpr:
                        uint uv = this.Debugger.Host.CpuHook.GetRegister<uint>( set, register.Ordinal );
                        prettyValue = uv.ToString();
                        rawValue = string.Format( "{0:X8}", uv );
                        break;
                    case RegisterSet.Fpu:
                    case RegisterSet.Vfpu:
                        float fv = this.Debugger.Host.CpuHook.GetRegister<float>( set, register.Ordinal );
                        prettyValue = fv.ToString();
                        break;
                }
                ListViewItem item = new ListViewItem( new string[]{
                    register.ToString(), prettyValue, rawValue,
                } );
                this.registersListView.Items.Add( item );
            }
            this.registersListView.EndUpdate();
        }
Exemple #22
0
        public void Execute(IMemory mem, RegisterSet registerSet)
        {
            if (errorWhileParsing) return;

            registerSet.SetRegisterVal(registerNr, value);
        }
Exemple #23
0
 public RegisterBank( string name, RegisterSet set, Register[] registers )
 {
     this.Name = name;
     this.Set = set;
     this.Registers = registers;
     foreach( Register register in registers )
         register.Bank = this;
 }
Exemple #24
0
        private void CreateConstantSetters(IShaderDom shader, Action <CodeTypeMember, string> add, string name, CodeExpression assignmentField, CodeExpression assignmentArrayField)
        {
            /*
             * Something like:
             *
             * public void SetInvTargetSize(ref Microsoft.Xna.Framework.Vector2 value)
             * {
             *      this.vreg.SetVector2(130, ref value);
             * }
             *
             * public Microsoft.Xna.Framework.Vector2 InvTargetSize
             * {
             *      set
             *      {
             *              this.SetInvTargetSize(ref value);
             *      }
             * }*/

            Register reg;
            Type     dataType;
            bool     hasSetMethod;
            int      stride;

            if (!ExtractRegType(name, out reg, out dataType, out hasSetMethod, out stride))
            {
                return;
            }

            Type arrayOrSingleType = dataType;

            //right...

            //create the method of the given type.


            //public void SetInvTargetSize(ref Microsoft.Xna.Framework.Vector2 value)
            CodeStatementCollection methodStatements = new CodeStatementCollection();

            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(dataType, "value");

            if (reg.ArraySize == -1)
            {
                param.Direction = FieldDirection.Ref;
            }
            else
            {
                arrayOrSingleType = dataType.MakeArrayType();
                param.Type        = new CodeTypeReference(arrayOrSingleType);
            }

            CodeExpression valueRef = new CodeArgumentReferenceExpression(param.Name);

            //when there isn't a set method, there is just a set property
            if (!hasSetMethod)
            {
                valueRef = new CodePropertySetValueReferenceExpression();
            }

            //create the guts
            //depends on what constants use it...

            //eg:
            //this.vreg.SetVector2(130, ref value);

            Register sreg;

            if (dataType == typeof(bool))
            {
                //special case for booleans, assign the array directly.
                //looks like:
                //
                // if (preg_bool[index] != value)
                // {
                //  preg_bool[index] = value;
                //  preg_bool_changed = true;
                // }

                foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                {
                    RegisterSet    registers    = listing.Key.RegisterSet;
                    CodeExpression registersRef = listing.Value;

                    if (registers.TryGetRegister(name, out sreg))
                    {
                        if (listing.Key == asm.PixelShader)
                        {
                            CodeExpression arrayIndex = new CodeArrayIndexerExpression(shader.PixelShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index));

                            CodeStatement assign = new CodeAssignStatement(arrayIndex, new CodePropertySetValueReferenceExpression());
                            CodeStatement change = new CodeAssignStatement(shader.PixelShaderBooleanRegistersChangedRef, new CodePrimitiveExpression(true));

                            CodeStatement condition = new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(arrayIndex, CodeBinaryOperatorType.IdentityInequality, new CodePropertySetValueReferenceExpression()),
                                new CodeStatement[] { assign, change });

                            methodStatements.Add(condition);
                        }
                        if (listing.Key == asm.VertexShader)
                        {
                            CodeExpression arrayIndex = new CodeArrayIndexerExpression(shader.VertexShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index));

                            CodeStatement assign = new CodeAssignStatement(arrayIndex, new CodePropertySetValueReferenceExpression());
                            CodeStatement change = new CodeAssignStatement(shader.VertexShaderBooleanRegistersChangedRef, new CodePrimitiveExpression(true));

                            CodeStatement condition = new CodeConditionStatement(
                                new CodeBinaryOperatorExpression(arrayIndex, CodeBinaryOperatorType.IdentityInequality, new CodePropertySetValueReferenceExpression()),
                                new CodeStatement[] { assign, change });

                            methodStatements.Add(condition);
                        }
                    }
                }
            }
            else
            {
                string targetName = "Set" + dataType.Name;

                if (dataType == typeof(Matrix))
                {
                    targetName += stride;
                    targetName += "Transpose";
                }

                if (reg.ArraySize == -1)
                {
                    //not an array..

                    foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                    {
                        RegisterSet    registers    = listing.Key.RegisterSet;
                        CodeExpression registersRef = listing.Value;

                        if (registers.TryGetRegister(name, out sreg))
                        {
                            //set the regiser (eg, may be vertex shader register)
                            CodeExpression methodInvoke =
                                new CodeMethodInvokeExpression(registersRef, targetName,
                                                               new CodePrimitiveExpression(sreg.Index),
                                                               new CodeDirectionExpression(FieldDirection.Ref, valueRef));

                            methodStatements.Add(shader.ETS(methodInvoke));
                        }
                    }
                }
                else
                {
                    //is an array...
                    //simply call SetArray on the array object.
                    CodeExpression methodInvoke =
                        new CodeMethodInvokeExpression(assignmentArrayField, "SetArray",
                                                       valueRef);

                    methodStatements.Add(shader.ETS(methodInvoke));
                }
            }

            string upperName = Common.ToUpper(name);

            //there is always a setable property
            CodeMemberProperty property = new CodeMemberProperty();

            property.Name       = upperName;
            property.Type       = param.Type;
            property.Attributes = MemberAttributes.Final | MemberAttributes.Public;
            property.HasSet     = reg.ArraySize == -1;
            property.HasGet     = reg.ArraySize != -1;

            //there isn't always a set method
            CodeMemberMethod method = null;

            CodeStatement assignAttribute = null;

            if (hasSetMethod || reg.ArraySize != -1)
            {
                //create the method to set the value
                string methodName = "Set" + upperName;

                method            = new CodeMemberMethod();
                method.Name       = methodName;
                method.Attributes = MemberAttributes.Final | MemberAttributes.Public;

                method.Parameters.Add(param);
                method.Statements.AddRange(methodStatements);


                //create a property that calls the Set method if not an array, get method if it is an array

                if (reg.ArraySize == -1)
                {
                    //is not an array
                    CodeExpression invokeSetter =
                        new CodeMethodInvokeExpression(
                            shader.Instance, method.Name,
                            new CodeDirectionExpression(FieldDirection.Ref, new CodePropertySetValueReferenceExpression()));

                    property.SetStatements.Add(invokeSetter);
                }
                else
                {
                    //is an array, return the array object directly.
                    property.GetStatements.Add(new CodeMethodReturnStatement(assignmentArrayField));

                    //set the type of the property to IArray<float>, etc
                    Type interfaceType = typeof(Xen.Graphics.ShaderSystem.Constants.IArray <float>).GetGenericTypeDefinition();
                    interfaceType = interfaceType.MakeGenericType(dataType);

                    property.Type = new CodeTypeReference(interfaceType);
                }



                //call the method as well for attribute assign
                CodeExpression assignSetter =
                    new CodeMethodInvokeExpression(
                        shader.Instance, method.Name,
                        new CodeDirectionExpression(param.Direction, shader.AttributeAssignValue));

                assignAttribute = shader.ETS(assignSetter);
            }
            else
            {
                //create a property to directly set the value

                property.SetStatements.AddRange(methodStatements);

                //attribute assign sets the property
                assignAttribute = new CodeAssignStatement(
                    new CodePropertyReferenceExpression(shader.Instance, property.Name),
                    shader.AttributeAssignValue);
            }


            if (reg.ArraySize > 0)
            {
                if (method != null)
                {
                    add(method, string.Format("Set the shader array value '{0} {1}[{2}]'", reg.Type, reg.Name, reg.ArraySize));
                }
                add(property, string.Format("Get the array for the shader value '{0} {1}[{2}]'", reg.Type, reg.Name, reg.ArraySize));
            }
            else
            {
                if (method != null)
                {
                    add(method, string.Format("Set the shader value '{0} {1}'", reg.Type, reg.Name));
                }
                add(property, string.Format("Assign the shader value '{0} {1}'", reg.Type, reg.Name));
            }

            //create the attribute assignment value statement.

            List <CodeStatement> assignList;

            if (!attributeAssignment.TryGetValue(arrayOrSingleType, out assignList))
            {
                assignList = new List <CodeStatement>();
                attributeAssignment.Add(arrayOrSingleType, assignList);
            }

            //create the statement...

            CodeExpression assignIdsMatch =
                new CodeBinaryOperatorExpression(shader.AttributeAssignId, CodeBinaryOperatorType.IdentityEquality, assignmentField);

            CodeConditionStatement performAssign =
                new CodeConditionStatement(assignIdsMatch,
                                           assignAttribute,                                                   //call the assignment code
                                           new CodeMethodReturnStatement(new CodePrimitiveExpression(true))); //return true, set correctly.

            assignList.Add(performAssign);
        }
Exemple #25
0
        public override void AddConstructor(IShaderDom shader, Action <CodeStatement> add)
        {
            //set the semantic change IDs to -1
            foreach (SemanticMapping mapping in semanticMapping)
            {
                for (int i = 0; i < mapping.ChangeRefs.Length; i++)
                {
                    CodeAssignStatement assign = new CodeAssignStatement(mapping.ChangeRefs[i], new CodePrimitiveExpression(-1));

                    add(assign);
                }
            }

            //init the array attributes
            for (int i = 0; i < attributeNames.Count; i++)
            {
                //if it's an array, it needs an array object...

                Register reg;
                Type     dataType;

                if (ExtractRegType(attributeNames[i], out reg, out dataType) && reg.ArraySize != -1)
                {
                    //things get a bit funky here.
                    //if the array is used by more than one register set, it must be wrapped up in a 'DualArray'
                    //so a call to 'SetValue' on the array gets passed to both copies.
                    //This can occur if both the vertex and pixel shader access a constant array, or a preshader, etc.
                    Type dualType = typeof(Xen.Graphics.ShaderSystem.Constants.DualArray <float>).GetGenericTypeDefinition();
                    dualType = dualType.MakeGenericType(dataType);

                    //this.attributeArrayFields[i].FieldName

                    CodeExpression initExpression = null;
                    Type           arrayType      = GetArrayType(reg);

                    foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                    {
                        Register       sreg;
                        RegisterSet    registers    = listing.Key.RegisterSet;
                        CodeExpression registersRef = listing.Value;

                        if (registers.TryGetRegister(reg.Name, out sreg))
                        {
                            CodeExpression create;

                            create = new CodeObjectCreateExpression(arrayType,
                                                                    registersRef, //vreg
                                                                    new CodePrimitiveExpression(sreg.Index),
                                                                    new CodePrimitiveExpression(sreg.Size));

                            if (initExpression == null)
                            {
                                initExpression = create;
                            }
                            else
                            {
                                //darn. wrap in a dual array.
                                initExpression = new CodeObjectCreateExpression(
                                    dualType,
                                    create, initExpression);
                            }
                        }
                    }

                    CodeAssignStatement assign = new CodeAssignStatement(this.attributeArrayFields[i], initExpression);
                    add(assign);
                }
            }

            //set the global change IDs to -1 (unless it's an array)...
            foreach (GlobalAttribute global in globals)
            {
                int changeRefIndex = 0;
                foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                {
                    Register       sreg;
                    RegisterSet    registers    = listing.Key.RegisterSet;
                    CodeExpression registersRef = listing.Value;

                    if (registers.TryGetRegister(global.Register.Name, out sreg) && sreg.Category != RegisterCategory.Boolean)
                    {
                        CodeAssignStatement assign = new CodeAssignStatement(global.ChangeRefs[changeRefIndex], new CodePrimitiveExpression(-1));

                        add(assign);


                        //arrays require the array wrapper to be initalised
                        if (global.Register.ArraySize != -1)
                        {
                            //arrays are stored differently.. eg as IArray<Matrix>
                            //eg:
                            //new Xen.Graphics.ShaderSystem.Constants.Matrix4Array(this.vreg, 217, 4);

                            Type arrayType = GetArrayType(global.Register);

                            CodeExpression create;

                            create = new CodeObjectCreateExpression(arrayType,
                                                                    registersRef, //vreg
                                                                    new CodePrimitiveExpression(sreg.Index),
                                                                    new CodePrimitiveExpression(sreg.Size));

                            assign = new CodeAssignStatement(global.ArrayRefs[changeRefIndex], create);
                            add(assign);
                        }

                        changeRefIndex++;
                    }
                }
            }
        }
Exemple #26
0
        public override void AddBind(IShaderDom shader, Action <CodeStatement, string> add)
        {
            //bind the semantics bound attributes
            foreach (SemanticMapping mapping in semanticMapping)
            {
                //eg:
                //state.SetWorldMatrix(this.vreg.Matrix4Transpose(8), ref this.v_8);

                string method    = string.Format("Set{0}{1}", mapping.Type.Mapping, mapping.Type.Type.Name);
                bool   transpose = mapping.Type.Transpose ^ (mapping.Type.Type == typeof(Matrix));

                string registerTypeName = mapping.Type.Type.Name;
                if (mapping.Type.Type == typeof(Matrix))
                {
                    registerTypeName += (int)mapping.Register.Rank;
                }
                if (transpose)
                {
                    registerTypeName += "Transpose";
                }

                //for each register set, see if it uses this mapping

                int changeRefIndex = 0;
                foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                {
                    Register       sreg;
                    RegisterSet    registers    = listing.Key.RegisterSet;
                    CodeExpression registersRef = listing.Value;

                    if (registers.TryGetRegister(mapping.Register.Name, out sreg))
                    {
                        //it does.. so the constants need setting..
                        //state.SetWorldMatrix(this.vreg.Matrix4Transpose(8), ref this.v_8);

                        CodeExpression changeRef = new CodeDirectionExpression(FieldDirection.Ref, mapping.ChangeRefs[changeRefIndex]);

                        CodeExpression getRegister =                            //this.vreg.Matrix4Transpose(8)
                                                     new CodeMethodInvokeExpression(registersRef, registerTypeName, new CodePrimitiveExpression(sreg.Index));

                        //invoke
                        CodeExpression invokeSet =
                            new CodeMethodInvokeExpression(shader.ShaderSystemRef, method, getRegister, changeRef);

                        add(shader.ETS(invokeSet), changeRefIndex != 0 ? null : string.Format("Set the value for attribute '{0}'", mapping.Register.Name));

                        changeRefIndex++;
                    }
                }
            }

            //bind the shader globals

            foreach (GlobalAttribute global in globals)
            {
                string registerTypeName = global.Type.Name;
                if (global.Type == typeof(Matrix))
                {
                    registerTypeName += (int)global.Register.Rank;
                    registerTypeName += "Transpose";
                }

                int changeRefIndex = 0;
                foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                {
                    Register       sreg;
                    RegisterSet    registers    = listing.Key.RegisterSet;
                    CodeExpression registersRef = listing.Value;

                    if (registers.TryGetRegister(global.Register.Name, out sreg))
                    {
                        //special case the booleans, as they have different logic to set globally.
                        if (sreg.Category == RegisterCategory.Boolean)
                        {
                            if (global.Register.ArraySize != -1)
                            {
                                throw new CompileException("'GLOBAL' Boolean Arrays are not supported");
                            }

                            //this is a bit of a hack :-/
                            //need to figure out if this is a vertex or pixel boolean constant.
                            if (listing.Key == asm.VertexShader)
                            {
                                add(shader.ETS(
                                        new CodeMethodInvokeExpression(shader.ShaderSystemRef, "SetGlobal", shader.VertexShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index), global.GlobalIdRef, new CodeDirectionExpression(FieldDirection.Ref, shader.VertexShaderBooleanRegistersChangedRef))),
                                    string.Format("Set the value for global 'bool {0}'", global.Register.Name));
                            }
                            if (listing.Key == asm.PixelShader)
                            {
                                add(shader.ETS(
                                        new CodeMethodInvokeExpression(shader.ShaderSystemRef, "SetGlobal", shader.PixelShaderBooleanRegistersRef, new CodePrimitiveExpression(sreg.Index), global.GlobalIdRef, new CodeDirectionExpression(FieldDirection.Ref, shader.PixelShaderBooleanRegistersChangedRef))),
                                    string.Format("Set the value for global 'bool {0}'", global.Register.Name));
                            }
                        }
                        else
                        {
                            //eg:
                            //state.SetGlobal(this.vreg.Matrix4Transpose(8), ShadowShaderBlend.g_id0, ref this.g_0);

                            CodeExpression getRegister =                                //this.vreg.Matrix4Transpose(8)
                                                         new CodeMethodInvokeExpression(registersRef, registerTypeName, new CodePrimitiveExpression(sreg.Index));

                            CodeExpression changeParam = new CodeDirectionExpression(FieldDirection.Ref, global.ChangeRefs[changeRefIndex]);

                            CodeExpression invokeSet;

                            //logic changes for arrays

                            if (global.Register.ArraySize != -1)
                            {
                                invokeSet =
                                    new CodeMethodInvokeExpression(shader.ShaderSystemRef, "SetGlobal", global.ArrayRefs[changeRefIndex], global.GlobalIdRef, changeParam);
                                //state.SetGlobal(this.ga0, ShadowShaderBlend.g_id0, ref this.g_0);
                            }
                            else
                            {
                                //state.SetGlobal(this.vreg.Matrix4Transpose(8), ShadowShaderBlend.g_id0, ref this.g_0);
                                invokeSet =
                                    new CodeMethodInvokeExpression(shader.ShaderSystemRef, "SetGlobal", getRegister, global.GlobalIdRef, changeParam);
                            }

                            add(shader.ETS(invokeSet), changeRefIndex != 0 ? null : string.Format("Set the value for global '{0}'", global.Register.Name));

                            changeRefIndex++;
                        }
                    }
                }
            }
        }
Exemple #27
0
        //pull a semantic bound register
        private void ExtractSemantic(IShaderDom shader, Register reg)
        {
            string semantic = reg.Semantic;

            Type dataType = null;

            switch (reg.Rank)
            {
            case RegisterRank.FloatNx1:
            {
                switch (reg.Type)
                {
                case "float":
                case "float1":                                //?
                    dataType = typeof(Single);
                    break;

                case "float2":
                    dataType = typeof(Vector2);
                    break;

                case "float3":
                    dataType = typeof(Vector3);
                    break;

                case "float4":
                    dataType = typeof(Vector4);
                    break;
                }
            }
            break;

            case RegisterRank.FloatNx2:
            case RegisterRank.FloatNx3:
            case RegisterRank.FloatNx4:
                dataType = typeof(Matrix);
                break;

            case RegisterRank.IntNx1:
            case RegisterRank.IntNx2:
            case RegisterRank.IntNx3:
            case RegisterRank.IntNx4:
            {
                //ints are almost always mapped to floats for semantic bound types (EG vertex count)
                //since the register category has been validated to Float4, this is the case here
                switch (reg.Type)
                {
                case "int":
                case "int1":                                //?
                    dataType = typeof(Single);
                    break;

                case "int2":
                    dataType = typeof(Vector2);
                    break;

                case "int3":
                    dataType = typeof(Vector3);
                    break;

                case "int4":
                    dataType = typeof(Vector4);
                    break;
                }
            }
            break;

            case RegisterRank.Bool:
                dataType = typeof(Single);
                break;
            }

            if (reg.Category == RegisterCategory.Boolean)
            {
                dataType = typeof(bool);
            }


            if (semantic.Length == 6 && semantic.Equals("global", StringComparison.InvariantCultureIgnoreCase))
            {
                //special case global value.

                if (dataType == null)
                {
                    throw new CompileException(string.Format("Error parsing semantic for '{0}'. Global values of type '{1}' are not supported.", reg.Name, reg.Type));
                }

                GlobalAttribute global = new GlobalAttribute();
                global.Register = reg;
                global.Type     = dataType;

                global.GlobalIdRef = new CodeFieldReferenceExpression(shader.ShaderClassEx, string.Format("gid{0}", globals.Count));

                List <CodeFieldReferenceExpression> globalRefs = new List <CodeFieldReferenceExpression>();
                List <CodeFieldReferenceExpression> arrayRefs  = new List <CodeFieldReferenceExpression>();

                foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
                {
                    Register       sreg;
                    RegisterSet    registers    = listing.Key.RegisterSet;
                    CodeExpression registersRef = listing.Value;

                    if (registers.TryGetRegister(reg.Name, out sreg))
                    {
                        if (sreg.Category != RegisterCategory.Boolean)
                        {
                            string refId = string.Format("gc{0}", globalRefCount);
                            globalRefs.Add(new CodeFieldReferenceExpression(shader.Instance, refId));

                            if (reg.ArraySize != -1)
                            {
                                refId = string.Format("ga{0}", globalRefCount);
                                arrayRefs.Add(new CodeFieldReferenceExpression(shader.Instance, refId));
                            }
                            globalRefCount++;
                        }
                    }
                }

                global.ChangeRefs = globalRefs.ToArray();
                global.ArrayRefs  = arrayRefs.ToArray();

                globals.Add(global);
                return;
            }

            if (reg.ArraySize != -1)
            {
                //INVALID. EXTERMINATE.
                throw new CompileException(string.Format("Shader attribute '{0}' is defined as an array and has a semantic '{1}'. Semantics other than 'GLOBAL' are invalid for Array types.", reg.Name, reg.Semantic));
            }

            bool isTranspose = semantic.Length > 9 && semantic.EndsWith("transpose", StringComparison.InvariantCultureIgnoreCase);

            if (isTranspose)
            {
                semantic = semantic.Substring(0, semantic.Length - 9);
            }

            SemanticType?dataSemanticType = null;

            foreach (SemanticType semanticType in semanticTypes)
            {
                if (semanticType.Transpose == isTranspose &&
                    semanticType.Type == dataType &&
                    semanticType.Mapping.Equals(semantic, StringComparison.InvariantCultureIgnoreCase))
                {
                    dataSemanticType = semanticType;
                    break;
                }
            }

            if (dataSemanticType == null)
            {
                //INVALID. EXTERMINATE.
                throw new CompileException(string.Format("Shader attribute '{0}' has unrecognised semantic '{1}'.", reg.Name, reg.Semantic));
            }

            //create the mapping...
            SemanticMapping mapping = new SemanticMapping();

            mapping.Register = reg;
            mapping.Type     = dataSemanticType.Value;

            //figure out how often this semantic is used..
            List <CodeFieldReferenceExpression> changeRefs = new List <CodeFieldReferenceExpression>();

            foreach (KeyValuePair <AsmListing, CodeExpression> listing in listingRegisters)
            {
                Register       sreg;
                RegisterSet    registers    = listing.Key.RegisterSet;
                CodeExpression registersRef = listing.Value;

                if (registers.TryGetRegister(reg.Name, out sreg))
                {
                    string changeId = string.Format("sc{0}", semanticMappingRefCount++);
                    changeRefs.Add(new CodeFieldReferenceExpression(shader.Instance, changeId));
                }
            }

            mapping.ChangeRefs = changeRefs.ToArray();

            this.semanticMapping.Add(mapping);
        }
Exemple #28
0
        private void OnGDBPaused(StopReply response)
        {
            this.CurrentBreakpoint = null;
            this.CurrentObjectFile = null;

            // Update Registers
            this.registers = this.connector.ReadRegisters();
            var regs       = this.registers.Keys.ToArray();
            var trues      = regs.Select((_) => true).ToArray();
            this.Registers = new RegisterSet(regs, trues, new bool[regs.Length]);

            // Fire event
            if (this.RefreshRegisters != null)
            {
                // Do a batch update of all regs
                this.RefreshRegisters(this, new RegistersChangedEventArgs(
                    this.registers.Keys.Select((reg) => reg.Name).ToArray()));
            }

            // Update current address
            foreach (var pair in this.registers)
            {
                if (pair.Key.Type == RegisterType.InstructionPointer)
                {
                    this.CurrentAddress = Utils.LongFromBytes(pair.Value);
                    break;
                }
            }

            // Update breakpoint
            foreach (Breakpoint bp in this.breakpoints)
            {
                if (bp.Address == this.CurrentAddress)
                {
                    this.CurrentBreakpoint = bp; break;
                }
            }

            // Update object file
            foreach (ObjectCodeFile file in Application.Session.LoadedImages)
            {
                if (file.Sections[0].LoadMemoryAddress <= this.CurrentAddress &&
                    file.Sections[0].LoadMemoryAddress + file.Size > this.CurrentAddress)
                {
                    this.CurrentObjectFile = file; break;
                }
            }

            // If object file found, try and load current code unit
            if (this.CurrentObjectFile != null)
            {
                this.CurrentCodeUnit = this.CurrentObjectFile.GetCode(this.CurrentAddress);
            }

            // Fire stepped event
            if (this.Suspended != null) this.Suspended(this, null);

            // Qemu gets stuck on the current line unless the breakpoint is disabled
            if (this.CurrentBreakpoint != null)
            {
                this.ClearBreakpoint(this.CurrentBreakpoint.Address);
            }
        }
Exemple #29
0
        /// <summary>
        /// Called when one or more registers have been refreshed.
        /// </summary>
        private void OnRegistersUpdated(RegistersChangedEventArgs e)
        {
            Register[] regs = this.connector.AvailableRegisters;

            // Update the register listing
            this.Registers = new RegisterSet(regs, regs.Select((_)=>true).ToArray(),
                new bool[regs.Length]);

            if (this.RefreshRegisters != null)
            {
                this.RefreshRegisters(this, e);
            }
        }
Exemple #30
0
        protected void CreateMachineRegisters()
        {
            X = new RegisterSet();
            Y = new RegisterSet();
            A = new RegisterSet();

            RX = new RegisterSet();
            RY = new RegisterSet();

            for (int i = 0; i < 4; i++) {
                X.Add(new Register("X" + i, Datatype.FloatValue));
                Y.Add(new Register("Y" + i, Datatype.FloatValue));
                A.Add(new Register("A" + i, Datatype.FloatValue));
            }

            for (int i = 0; i < 8; i++) {

                Register r = new Register("R" + i, Datatype.AddressValue);

                if (i < 4)
                    RX.Add(r);
                else
                    RY.Add(r);
            }

            R   = RX + RY;
            XA  = X + A;
            YA  = Y + A;
            XYA = X + Y + A;

            machineRegisters = new ArrayList();

            foreach (Register r in X.Registers)
                machineRegisters.Add(r);

            foreach (Register r in Y.Registers)
                machineRegisters.Add(r);

            foreach (Register r in R.Registers)
                machineRegisters.Add(r);
        }
Exemple #31
0
 public void Execute(IMemory mem, RegisterSet registerSet)
 {
     throw new NotImplementedException();
 }