Ejemplo n.º 1
0
 static void SortSwitchSections(SwitchInstruction sw)
 {
     sw.Sections.ReplaceList(sw.Sections.OrderBy(s => s.Body switch {
         Branch b => b.TargetILOffset,
         Leave l => l.StartILOffset,
         _ => (int?)null
     }).ThenBy(s => s.Labels.Values.FirstOrDefault()));
Ejemplo n.º 2
0
        static void AdjustLabels(SwitchInstruction sw, ILTransformContext context)
        {
            if (sw.Value is BinaryNumericInstruction bop && !bop.CheckForOverflow && bop.Right.MatchLdcI(out long val))
            {
                // Move offset into labels:
                context.Step("Move offset into switch labels", bop);
                long offset;
                switch (bop.Operator)
                {
                case BinaryNumericOperator.Add:
                    offset = unchecked (-val);
                    break;

                case BinaryNumericOperator.Sub:
                    offset = val;
                    break;

                default:                         // unknown bop.Operator
                    return;
                }
                sw.Value = bop.Left;
                foreach (var section in sw.Sections)
                {
                    section.Labels = section.Labels.AddOffset(offset);
                }
            }
        }
Ejemplo n.º 3
0
        protected internal override Statement VisitSwitchInstruction(SwitchInstruction inst)
        {
            var oldBreakTarget = breakTarget;

            breakTarget = null;             // 'break' within a switch would only leave the switch

            var value = exprBuilder.Translate(inst.Value);
            var stmt  = new SwitchStatement()
            {
                Expression = value
            };

            foreach (var section in inst.Sections)
            {
                var astSection = new Syntax.SwitchSection();
                astSection.CaseLabels.AddRange(section.Labels.Values.Select(i => CreateTypedCaseLabel(i, value.Type)));
                ConvertSwitchSectionBody(astSection, section.Body);
                stmt.SwitchSections.Add(astSection);
            }

            if (inst.DefaultBody.OpCode != OpCode.Nop)
            {
                var astSection = new Syntax.SwitchSection();
                astSection.CaseLabels.Add(new CaseLabel());
                ConvertSwitchSectionBody(astSection, inst.DefaultBody);
                stmt.SwitchSections.Add(astSection);
            }

            breakTarget = oldBreakTarget;
            return(stmt);
        }
Ejemplo n.º 4
0
        public void VisitSwitchInstruction(SwitchInstruction si)
        {
            var dt = si.Expression.Accept(asc);

            desc.MeetDataType(si.Expression, dt);
            si.Expression.Accept(desc, si.Expression.TypeVariable);
        }
Ejemplo n.º 5
0
        public void ConstructorTest()
        {
            SwitchInstruction target = new SwitchInstruction();

            // TODO: Implement code to verify target
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Ejemplo n.º 6
0
        private static short[] FindStartInstructions(InstructionSequence seq)
        {
            int len = seq.Length();

            short[]       inststates = new short[len];
            HashSet <int> excSet     = new HashSet <int>();

            foreach (ExceptionHandler handler in seq.GetExceptionTable().GetHandlers())
            {
                excSet.Add(handler.from_instr);
                excSet.Add(handler.to_instr);
                excSet.Add(handler.handler_instr);
            }
            for (int i = 0; i < len; i++)
            {
                // exception blocks
                if (excSet.Contains(i))
                {
                    inststates[i] = 1;
                }
                Instruction instr = seq.GetInstr(i);
                switch (instr.group)
                {
                case Group_Jump:
                {
                    inststates[((JumpInstruction)instr).destination] = 1;
                    goto case Group_Return;
                }

                case Group_Return:
                {
                    if (i + 1 < len)
                    {
                        inststates[i + 1] = 1;
                    }
                    break;
                }

                case Group_Switch:
                {
                    SwitchInstruction swinstr = (SwitchInstruction)instr;
                    int[]             dests   = swinstr.GetDestinations();
                    for (int j = dests.Length - 1; j >= 0; j--)
                    {
                        inststates[dests[j]] = 1;
                    }
                    inststates[swinstr.GetDefaultDestination()] = 1;
                    if (i + 1 < len)
                    {
                        inststates[i + 1] = 1;
                    }
                    break;
                }
                }
            }
            // first instruction
            inststates[0] = 1;
            return(inststates);
        }
Ejemplo n.º 7
0
        public void ConstructorTest1()
        {
            ContextExpression expression = ContextExpression.HasMoreActions; // TODO: Initialize to an appropriate value

            SwitchInstruction target = new SwitchInstruction(expression);

            // TODO: Implement code to verify target
            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Ejemplo n.º 8
0
 public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction) {
   if (switchInstruction == null) return null;
   switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
   for (int i = 0, n = switchInstruction.Targets == null ? 0 : switchInstruction.Targets.Count; i < n; i++){
     Block target = switchInstruction.Targets[i];
     if (target == null) continue;
     this.StackLocalsAtEntry[target.UniqueKey] = this.localsStack.Clone();
   }
   return switchInstruction;
 }
Ejemplo n.º 9
0
        public void AcceptTest()
        {
            SwitchInstruction target = new SwitchInstruction();

            IVisitor visitor = null; // TODO: Initialize to an appropriate value

            target.Accept(visitor);

            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Ejemplo n.º 10
0
        static SwitchInstruction BuildLiftedSwitch(Block nullCaseBlock, SwitchInstruction switchInst, ILInstruction switchValue)
        {
            SwitchInstruction newSwitch = new SwitchInstruction(switchValue);

            newSwitch.IsLifted = true;
            newSwitch.Sections.AddRange(switchInst.Sections);
            newSwitch.Sections.Add(new SwitchSection {
                Body = new Branch(nullCaseBlock), HasNullLabel = true
            });
            return(newSwitch);
        }
Ejemplo n.º 11
0
        void ProcessBlock(Block block, ref bool blockContainerNeedsCleanup)
        {
            bool analysisSuccess = analysis.AnalyzeBlock(block);

            if (analysisSuccess && UseCSharpSwitch(out _))
            {
                // complex multi-block switch that can be combined into a single SwitchInstruction
                ILInstruction switchValue = new LdLoc(analysis.SwitchVariable);
                Debug.Assert(switchValue.ResultType.IsIntegerType() || switchValue.ResultType == StackType.Unknown);
                if (!(switchValue.ResultType == StackType.I4 || switchValue.ResultType == StackType.I8))
                {
                    // switchValue must have a result type of either I4 or I8
                    switchValue = new Conv(switchValue, PrimitiveType.I8, false, Sign.Signed);
                }
                var sw = new SwitchInstruction(switchValue);
                foreach (var section in analysis.Sections)
                {
                    sw.Sections.Add(new SwitchSection {
                        Labels = section.Key,
                        Body   = section.Value
                    });
                }
                if (block.Instructions.Last() is SwitchInstruction)
                {
                    // we'll replace the switch
                }
                else
                {
                    Debug.Assert(block.Instructions.SecondToLastOrDefault() is IfInstruction);
                    // Remove branch/leave after if; it's getting moved into a section.
                    block.Instructions.RemoveAt(block.Instructions.Count - 1);
                }
                sw.AddILRange(block.Instructions[block.Instructions.Count - 1]);
                block.Instructions[block.Instructions.Count - 1] = sw;

                // mark all inner blocks that were converted to the switch statement for deletion
                foreach (var innerBlock in analysis.InnerBlocks)
                {
                    Debug.Assert(innerBlock.Parent == block.Parent);
                    Debug.Assert(innerBlock != ((BlockContainer)block.Parent).EntryPoint);
                    innerBlock.Instructions.Clear();
                }

                controlFlowGraph           = null;       // control flow graph is no-longer valid
                blockContainerNeedsCleanup = true;
                SortSwitchSections(sw);
            }
            else
            {
                // 2nd pass of SimplifySwitchInstruction (after duplicating return blocks),
                // (1st pass was in ControlFlowSimplification)
                SimplifySwitchInstruction(block, context);
            }
        }
Ejemplo n.º 12
0
        public bool VisitSwitchInstruction(SwitchInstruction si)
        {
            var swPat = pattern as SwitchInstruction;

            if (swPat == null)
            {
                return(false);
            }
            matcher.Pattern = swPat.Expression;
            return(matcher.Match(si.Expression));
        }
Ejemplo n.º 13
0
 void InstructionVisitor.VisitSwitchInstruction(SwitchInstruction si)
 {
     Method("Switch");
     si.Expression.Accept(this);
     if (si.Targets.Length > 0)
     {
         writer.Write(", ");
         writer.Write(string.Join(",", si.Targets.Select(t => $"\"{t}\"")));
     }
     writer.Write(");");
 }
Ejemplo n.º 14
0
        public void CasesTest()
        {
            SwitchInstruction target = new SwitchInstruction();

            System.Collections.Generic.List <Composestar.StarLight.Entities.WeaveSpec.Instructions.CaseInstruction> val = null; // TODO: Assign to an appropriate value for the property

            target.Cases = val;


            Assert.AreEqual(val, target.Cases, "Composestar.StarLight.Entities.WeaveSpec.Instructions.Switch.Cases was not set co" +
                            "rrectly.");
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Ejemplo n.º 15
0
        public void ExpressionTest()
        {
            SwitchInstruction target = new SwitchInstruction();

            ContextExpression val = ContextExpression.HasMoreActions; // TODO: Assign to an appropriate value for the property

            target.Expression = val;


            Assert.AreEqual(val, target.Expression, "Composestar.StarLight.Entities.WeaveSpec.Instructions.Switch.Expression was not s" +
                            "et correctly.");
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
        protected override void VisitSwitchInstruction(SwitchInstruction instruction)
        {
            ControlState.EvaluationStack.PopValue(out CilValueUInt32 value);

            if (value.Value < instruction.SwitchLabels.Count)
            {
                var targetLabel = instruction.SwitchLabels[(int)value.Value];
                ControlState.Move(targetLabel.Offset, targetLabel.Id);
            }
            else
            {
                ControlState.MoveToNextInstruction();
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Builds structured control flow for the block associated with the control flow node.
        /// </summary>
        /// <remarks>
        /// After a block was processed, it should use structured control flow
        /// and have just a single 'regular' exit point (last branch instruction in the block)
        /// </remarks>
        public void Run(Block block, BlockTransformContext context)
        {
            this.context          = context;
            this.currentContainer = (BlockContainer)block.Parent;

            // We only embed blocks into this block if they aren't referenced anywhere else,
            // so those blocks are dominated by this block.
            // BlockILTransform thus guarantees that the blocks being embedded are already
            // fully processed.

            var cfgNode = context.ControlFlowNode;

            Debug.Assert(cfgNode.UserData == block);

            // Because this transform runs at the beginning of the block transforms,
            // we know that `block` is still a (non-extended) basic block.

            // Last instruction is one with unreachable endpoint
            // (guaranteed by combination of BlockContainer and Block invariants)
            Debug.Assert(block.Instructions.Last().HasFlag(InstructionFlags.EndPointUnreachable));
            ILInstruction exitInst = block.Instructions.Last();

            // Previous-to-last instruction might have conditional control flow,
            // usually an IfInstruction with a branch:
            IfInstruction ifInst = block.Instructions.SecondToLastOrDefault() as IfInstruction;

            if (ifInst != null && ifInst.FalseInst.OpCode == OpCode.Nop)
            {
                HandleIfInstruction(cfgNode, block, ifInst, ref exitInst);
            }
            else
            {
                SwitchInstruction switchInst = block.Instructions.SecondToLastOrDefault() as SwitchInstruction;
                if (switchInst != null)
                {
                    HandleSwitchInstruction(cfgNode, block, switchInst, ref exitInst);
                }
            }
            if (IsUsableBranchToChild(cfgNode, exitInst))
            {
                // "...; goto usableblock;"
                // -> embed target block in this block
                context.Step("Inline target block of unconditional branch", exitInst);
                var targetBlock = ((Branch)exitInst).TargetBlock;
                Debug.Assert(exitInst == block.Instructions.Last());
                block.Instructions.RemoveAt(block.Instructions.Count - 1);
                block.Instructions.AddRange(targetBlock.Instructions);
                targetBlock.Remove();
            }
        }
Ejemplo n.º 18
0
 private void HandleSwitchInstruction(ControlFlowNode cfgNode, Block block, SwitchInstruction sw, ref ILInstruction exitInst)
 {
     Debug.Assert(sw.DefaultBody is Nop);
     // First, move blocks into the switch section
     foreach (var section in sw.Sections)
     {
         if (IsUsableBranchToChild(cfgNode, section.Body))
         {
             // case ...: goto targetBlock;
             var targetBlock = ((Branch)section.Body).TargetBlock;
             targetBlock.Remove();
             section.Body = targetBlock;
         }
     }
     // Move the code following the switch into the default section
     if (IsUsableBranchToChild(cfgNode, exitInst))
     {
         // switch(...){} goto targetBlock;
         // ---> switch(..) { default: { targetBlock } }
         var targetBlock = ((Branch)exitInst).TargetBlock;
         targetBlock.Remove();
         sw.DefaultBody = targetBlock;
         if (IsBranchOrLeave(targetBlock.Instructions.Last()))
         {
             exitInst = block.Instructions[block.Instructions.Count - 1] = targetBlock.Instructions.Last();
             targetBlock.Instructions.RemoveAt(targetBlock.Instructions.Count - 1);
         }
         else
         {
             exitInst = null;
             block.Instructions.RemoveAt(block.Instructions.Count - 1);
         }
     }
     // Remove compatible exitInsts from switch sections:
     foreach (var section in sw.Sections)
     {
         Block sectionBlock = section.Body as Block;
         if (sectionBlock != null && exitInst == null && IsBranchOrLeave(sectionBlock.Instructions.Last()))
         {
             exitInst = sectionBlock.Instructions.Last();
             sectionBlock.Instructions.RemoveAt(sectionBlock.Instructions.Count - 1);
             block.Instructions.Add(exitInst);
         }
         else if (sectionBlock != null && DetectExitPoints.CompatibleExitInstruction(exitInst, sectionBlock.Instructions.Last()))
         {
             sectionBlock.Instructions.RemoveAt(sectionBlock.Instructions.Count - 1);
         }
     }
     sw.Sections.ReplaceList(sw.Sections.OrderBy(s => s.Body.ILRange.Start));
 }
Ejemplo n.º 19
0
 public void VisitSwitchInstruction(SwitchInstruction si)
 {
     writer.Indent();
     writer.WriteKeyword("switch");
     writer.Write(" (");
     si.Expression.Accept(this);
     writer.Write(") { ");
     foreach (Block b in si.Targets)
     {
         writer.Write("{0} ", b.Name);
     }
     writer.Write("}");
     writer.Terminate();
 }
Ejemplo n.º 20
0
        private bool AnalyzeSwitch(SwitchInstruction inst, LongSet inputValues, out LongSet anyMatchValues)
        {
            Debug.Assert(inst.DefaultBody is Nop);
            anyMatchValues = LongSet.Empty;
            long offset;

            if (MatchSwitchVar(inst.Value))
            {
                offset = 0;
            }
            else if (inst.Value is BinaryNumericInstruction bop)
            {
                if (bop.CheckForOverflow)
                {
                    return(false);
                }
                if (MatchSwitchVar(bop.Left) && bop.Right.MatchLdcI(out long val))
                {
                    switch (bop.Operator)
                    {
                    case BinaryNumericOperator.Add:
                        offset = unchecked (-val);
                        break;

                    case BinaryNumericOperator.Sub:
                        offset = val;
                        break;

                    default:                             // unknown bop.Operator
                        return(false);
                    }
                }
                else                     // unknown bop.Left
                {
                    return(false);
                }
            }
            else                 // unknown inst.Value
            {
                return(false);
            }
            foreach (var section in inst.Sections)
            {
                var matchValues = section.Labels.AddOffset(offset).IntersectWith(inputValues);
                AddSection(matchValues, section.Body);
                anyMatchValues = anyMatchValues.UnionWith(matchValues);
            }
            return(true);
        }
Ejemplo n.º 21
0
        void ProcessBlock(Block block, ref bool blockContainerNeedsCleanup)
        {
            bool analysisSuccess = analysis.AnalyzeBlock(block);
            KeyValuePair <LongSet, ILInstruction> defaultSection;

            if (analysisSuccess && UseCSharpSwitch(analysis, out defaultSection))
            {
                // complex multi-block switch that can be combined into a single SwitchInstruction

                var sw = new SwitchInstruction(new LdLoc(analysis.SwitchVariable));
                foreach (var section in analysis.Sections)
                {
                    sw.Sections.Add(new SwitchSection {
                        Labels = section.Key,
                        Body   = section.Value
                    });
                }
                if (block.Instructions.Last() is SwitchInstruction)
                {
                    // we'll replace the switch
                }
                else
                {
                    Debug.Assert(block.Instructions.SecondToLastOrDefault() is IfInstruction);
                    // Remove branch/leave after if; it's getting moved into a section.
                    block.Instructions.RemoveAt(block.Instructions.Count - 1);
                }
                block.Instructions[block.Instructions.Count - 1] = sw;

                // mark all inner blocks that were converted to the switch statement for deletion
                foreach (var innerBlock in analysis.InnerBlocks)
                {
                    Debug.Assert(innerBlock.Parent == block.Parent);
                    Debug.Assert(innerBlock != ((BlockContainer)block.Parent).EntryPoint);
                    innerBlock.Instructions.Clear();
                }
                blockContainerNeedsCleanup = true;
                SortSwitchSections(sw);
            }
            else
            {
                // 2nd pass of SimplifySwitchInstruction (after duplicating return blocks),
                // (1st pass was in ControlFlowSimplification)
                SimplifySwitchInstruction(block);
            }
        }
Ejemplo n.º 22
0
        protected internal override void VisitSwitchInstruction(SwitchInstruction inst)
        {
            DebugStartPoint(inst);
            inst.Value.AcceptVisitor(this);
            State beforeSections = state.Clone();

            inst.DefaultBody.AcceptVisitor(this);
            State afterSections = state.Clone();

            foreach (var section in inst.Sections)
            {
                state.ReplaceWith(beforeSections);
                section.AcceptVisitor(this);
                afterSections.JoinWith(state);
            }
            state = afterSections;
            DebugEndPoint(inst);
        }
Ejemplo n.º 23
0
 public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction)
 {
     if (switchInstruction == null)
     {
         return(null);
     }
     switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
     for (int i = 0, n = switchInstruction.Targets == null ? 0 : switchInstruction.Targets.Count; i < n; i++)
     {
         Block target = switchInstruction.Targets[i];
         if (target == null)
         {
             continue;
         }
         this.StackLocalsAtEntry[target.UniqueKey] = this.localsStack.Clone();
     }
     return(switchInstruction);
 }
Ejemplo n.º 24
0
 public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction)
 {
     if (switchInstruction == null)
     {
         return(null);
     }
     switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
     for (int i = 0, n = switchInstruction.Targets == null ? 0 : switchInstruction.Targets.Count; i < n; i++)
     {
         Block target = switchInstruction.Targets[i];
         if (target == null)
         {
             continue;
         }
         this.VisitBlock(target);
     }
     return(switchInstruction);
 }
Ejemplo n.º 25
0
        private static void ConnectBlocks(List <BasicBlock> lstbb, Dictionary <int, BasicBlock
                                                                               > mapInstrBlocks)
        {
            for (int i = 0; i < lstbb.Count; i++)
            {
                BasicBlock  block       = lstbb[i];
                Instruction instr       = block.GetLastInstruction();
                bool        fallthrough = instr.CanFallThrough();
                BasicBlock  bTemp;
                switch (instr.group)
                {
                case Group_Jump:
                {
                    int dest = ((JumpInstruction)instr).destination;
                    bTemp = mapInstrBlocks.GetOrNull(dest);
                    block.AddSuccessor(bTemp);
                    break;
                }

                case Group_Switch:
                {
                    SwitchInstruction sinstr = (SwitchInstruction)instr;
                    int[]             dests  = sinstr.GetDestinations();
                    bTemp = mapInstrBlocks.GetOrNull(((SwitchInstruction)instr).GetDefaultDestination
                                                         ());
                    block.AddSuccessor(bTemp);
                    foreach (int dest1 in dests)
                    {
                        bTemp = mapInstrBlocks.GetOrNull(dest1);
                        block.AddSuccessor(bTemp);
                    }
                    break;
                }
                }
                if (fallthrough && i < lstbb.Count - 1)
                {
                    BasicBlock defaultBlock = lstbb[i + 1];
                    block.AddSuccessor(defaultBlock);
                }
            }
        }
Ejemplo n.º 26
0
        private static string SwitchInstructionToString(SwitchInstruction sw,
                                                        Hashtable /*<Block,int>*/ b2id)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("switch (");
            sb.Append(expression2str(sw.Expression, true));
            sb.Append(") [");
            BlockList targets = sw.Targets;

            for (int i = 0, n = targets.Count; i < n; i++)
            {
                if (i > 0)
                {
                    sb.Append(",");
                }
                sb.Append(b2s(targets[i], b2id));
            }
            sb.Append("]");
            return(sb.ToString());
        }
Ejemplo n.º 27
0
            int GetFirstConditionalBranchTarget(ILInstruction instruction)
            {
                int returnValue;

                // register the branch target for re-run after normal control flow completes.
                if (instruction is SwitchInstruction)
                {
                    SwitchInstruction switchIL = instruction as SwitchInstruction;
                    // run the first "case" target and register other targets(including "default") for re-run
                    if (switchIL.Cases.Length > 1)
                    {
                        returnValue = switchIL.Next + switchIL.Cases[0];
                        branchTargetsToVisit[switchIL.Next] = new Stack <Vertex>(evaluationStack);

                        for (int i = 1; i < switchIL.Cases.Length; i++)
                        {
                            branchTargetsToVisit[switchIL.Next + switchIL.Cases[i]] = new Stack <Vertex>(evaluationStack);
                        }
                    }
                    else
                    {
                        returnValue = switchIL.Next;
                    }
                }
                else
                {
                    BranchInstruction branchIL = instruction as BranchInstruction;
                    if (branchIL.Offset > branchIL.Target)
                    {
                        returnValue = branchIL.Target;
                        branchTargetsToVisit[branchIL.Next] = new Stack <Vertex>(evaluationStack);
                    }
                    else
                    {
                        returnValue = branchIL.Next;
                        branchTargetsToVisit[branchIL.Target] = new Stack <Vertex>(evaluationStack);
                    }
                }
                return(returnValue);
            }
Ejemplo n.º 28
0
        void ProcessBlock(Block block, ref bool blockContainerNeedsCleanup)
        {
            bool analysisSuccess = analysis.AnalyzeBlock(block);
            KeyValuePair <LongSet, ILInstruction> defaultSection;

            if (analysisSuccess && UseCSharpSwitch(analysis, out defaultSection))
            {
                // complex multi-block switch that can be combined into a single SwitchInstruction

                var sw = new SwitchInstruction(new LdLoc(analysis.SwitchVariable));
                foreach (var section in analysis.Sections)
                {
                    if (!section.Key.SetEquals(defaultSection.Key))
                    {
                        sw.Sections.Add(new SwitchSection
                        {
                            Labels = section.Key,
                            Body   = section.Value
                        });
                    }
                }
                block.Instructions[block.Instructions.Count - 2] = sw;
                block.Instructions[block.Instructions.Count - 1] = defaultSection.Value;
                // mark all inner blocks that were converted to the switch statement for deletion
                foreach (var innerBlock in analysis.InnerBlocks)
                {
                    Debug.Assert(innerBlock.Parent == block.Parent);
                    Debug.Assert(innerBlock != ((BlockContainer)block.Parent).EntryPoint);
                    innerBlock.Instructions.Clear();
                }
                blockContainerNeedsCleanup = true;
            }
            else
            {
                // 2nd pass of SimplifySwitchInstruction (after duplicating return blocks),
                // (1st pass was in ControlFlowSimplification)
                SimplifySwitchInstruction(block);
            }
        }
        public override CILInstructionSwitch BuildNode(ParseTreeNode node)
        {
            var instructionSwitchParseTreeNode = node.GetFirstChildWithGrammarName(GrammarNames.INSTR_SWITCH);

            CILInstructionSwitch result = null;

            var switchParseTreeNode = instructionSwitchParseTreeNode?.GetFirstChildWithGrammarName(GrammarNames.keyword_switch);

            if (switchParseTreeNode != null)
            {
                result = new SwitchInstruction();
            }

            if (result != null)
            {
                var labelsParseTreeNode = node.GetFirstChildWithGrammarName(GrammarNames.labels);
                result.Labels = LabelsParseTreeNodeHelper.GetLabels(labelsParseTreeNode);

                return(result);
            }

            throw new ArgumentException("Cannot recognize CIL instruction switch.");
        }
Ejemplo n.º 30
0
 private static string SwitchInstructionToString(SwitchInstruction sw, 
   Hashtable/*<Block,int>*/ b2id) 
 {
   StringBuilder sb = new StringBuilder();
   sb.Append("switch (");
   sb.Append(expression2str(sw.Expression, true));
   sb.Append(") [");
   BlockList targets = sw.Targets;
   for(int i = 0, n = targets.Count; i < n; i++) {
     if(i > 0) sb.Append(",");
     sb.Append(b2s(targets[i], b2id));
   }
   sb.Append("]");
   return sb.ToString();
 }
Ejemplo n.º 31
0
 protected virtual void VisitSwitchInstruction(SwitchInstruction switchInstruction) {
   if (switchInstruction == null) return;
   this.Visit(switchInstruction.Expression);
   BlockList targets = switchInstruction.Targets;
   int n = targets != null ? targets.Count : 0;
   Label[] labelTable = new Label[n];
   for (int i = 0; i < n; i++)
     labelTable[i] = this.GetLabel(targets[i]);
   this.ILGenerator.Emit(OpCodes.Switch, labelTable);
 }
Ejemplo n.º 32
0
 public void VisitSwitchInstruction(SwitchInstruction si)
 {
     var dt = si.Expression.Accept(asc);
     desc.MeetDataType(si.Expression, dt);
     si.Expression.Accept(desc, si.Expression.TypeVariable);
 }
Ejemplo n.º 33
0
    public virtual Differences VisitSwitchInstruction(SwitchInstruction switchInstruction1, SwitchInstruction switchInstruction2){
      Differences differences = new Differences(switchInstruction1, switchInstruction2);
      if (switchInstruction1 == null || switchInstruction2 == null){
        if (switchInstruction1 != switchInstruction2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++;
        return differences;
      }
      SwitchInstruction changes = (SwitchInstruction)switchInstruction2.Clone();
      SwitchInstruction deletions = (SwitchInstruction)switchInstruction2.Clone();
      SwitchInstruction insertions = (SwitchInstruction)switchInstruction2.Clone();

      Differences diff = this.VisitExpression(switchInstruction1.Expression, switchInstruction2.Expression);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Expression = diff.Changes as Expression;
      deletions.Expression = diff.Deletions as Expression;
      insertions.Expression = diff.Insertions as Expression;
      Debug.Assert(diff.Changes == changes.Expression && diff.Deletions == deletions.Expression && diff.Insertions == insertions.Expression);
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      BlockList blockChanges, blockDeletions, blockInsertions;
      diff = this.VisitBlockList(switchInstruction1.Targets, switchInstruction2.Targets, out blockChanges, out blockDeletions, out blockInsertions);
      if (diff == null){Debug.Assert(false); return differences;}
      changes.Targets = blockChanges;
      deletions.Targets = blockDeletions;
      insertions.Targets = blockInsertions;
      differences.NumberOfDifferences += diff.NumberOfDifferences;
      differences.NumberOfSimilarities += diff.NumberOfSimilarities;

      if (differences.NumberOfDifferences == 0){
        differences.Changes = null;
        differences.Deletions = null;
        differences.Insertions = null;
      }else{
        differences.Changes = changes;
        differences.Deletions = deletions;
        differences.Insertions = insertions;
      }
      return differences;
    }
Ejemplo n.º 34
0
 void InstructionVisitor.VisitSwitchInstruction(SwitchInstruction si)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 35
0
 public void VisitSwitchInstruction(SwitchInstruction si)
 {
     d.VisitSwitchInstruction(si);
 }
Ejemplo n.º 36
0
		public void VisitSwitchInstruction(SwitchInstruction si)
		{
			writer.Indent();
			writer.WriteKeyword("switch");
            writer.Write(" (");
			si.Expression.Accept(this);
			writer.Write(") { ");
			foreach (Block b in si.Targets)
			{
				writer.Write("{0} ", b.Name);
			}
			writer.Write("}");
			writer.Terminate();
		}
Ejemplo n.º 37
0
 public Instruction VisitSwitchInstruction(SwitchInstruction si)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 38
0
 public virtual Statement VisitSwitchInstruction(SwitchInstruction switchInstruction1, SwitchInstruction switchInstruction2)
 {
     if (switchInstruction1 == null) return null;
     if (switchInstruction2 == null)
         switchInstruction1.Expression = this.VisitExpression(switchInstruction1.Expression, null);
     else
         switchInstruction1.Expression = this.VisitExpression(switchInstruction1.Expression, switchInstruction2.Expression);
     return switchInstruction1;
 }
Ejemplo n.º 39
0
 public virtual Statement VisitSwitchInstruction(SwitchInstruction switchInstruction, SwitchInstruction changes, SwitchInstruction deletions, SwitchInstruction insertions){
   this.UpdateSourceContext(switchInstruction, changes);
   if (switchInstruction == null) return changes;
   if (changes != null){
     if (deletions == null || insertions == null)
       Debug.Assert(false);
     else{
     }
   }else if (deletions != null)
     return null;
   return switchInstruction;
 }
Ejemplo n.º 40
0
 public virtual void VisitSwitchInstruction(SwitchInstruction switchInstruction)
 {
   if (switchInstruction == null) return;
   this.VisitExpression(switchInstruction.Expression);
 }
Ejemplo n.º 41
0
 public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction) {
   if (switchInstruction == null) return null;
   switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
   for (int i = 0, n = switchInstruction.Targets == null ? 0 : switchInstruction.Targets.Count; i < n; i++){
     Block target = switchInstruction.Targets[i];
     if (target == null) continue;
     this.VisitBlock(target);
   }
   return switchInstruction;
 }
Ejemplo n.º 42
0
 public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction)
 {
     if (switchInstruction == null) return null;
     switchInstruction = (SwitchInstruction)base.VisitSwitchInstruction((SwitchInstruction)switchInstruction.Clone());
     if (switchInstruction == null) return null;
     switchInstruction.Targets = this.VisitBlockList(switchInstruction.Targets);
     return switchInstruction;
 }
Ejemplo n.º 43
0
 public override Statement VisitTypeswitch(Typeswitch Typeswitch){
   if (Typeswitch == null) return null;
   Expression e = Typeswitch.Expression = this.VisitExpression(Typeswitch.Expression);
   if (e == null || e.Type == null) return null;
   Method getTag = this.GetTypeView(e.Type).GetMethod(StandardIds.GetTag);
   if (getTag == null) return null;
   Method getValue = this.GetTypeView(e.Type).GetMethod(StandardIds.GetValue);
   if (getValue == null) return null;
   TypeswitchCaseList oldCases = Typeswitch.Cases;
   if (oldCases == null) return null;
   int n = oldCases.Count;
   BlockList targets = new BlockList(n);
   StatementList statements = new StatementList(n+3);
   Block result = new Block(statements);
   Local unionTemp = e as Local;
   if (unionTemp == null){
     unionTemp = new Local(Identifier.Empty, e.Type);
     statements.Add(new AssignmentStatement(unionTemp, e, e.SourceContext));
   }
   Local objectTemp = new Local(Identifier.Empty, SystemTypes.Object);
   SwitchInstruction switchInstruction = new SwitchInstruction(new MethodCall(new MemberBinding(new UnaryExpression(unionTemp, NodeType.AddressOf, unionTemp.Type.GetReferenceType()), getTag), null), targets);
   switchInstruction.SourceContext = Typeswitch.SourceContext;
   Block nextStatement = new Block();
   this.exitTargets.Add(nextStatement);
   statements.Add(new AssignmentStatement(objectTemp, new MethodCall(new MemberBinding(new UnaryExpression(unionTemp, NodeType.AddressOf, unionTemp.Type.GetReferenceType()), getValue), null)));
   statements.Add(switchInstruction);
   this.VisitTypeswitchCaseList(oldCases, targets, statements, nextStatement, objectTemp);
   statements.Add(nextStatement);
   this.exitTargets.Count--;
   return result;
 }
Ejemplo n.º 44
0
 public virtual Statement VisitSwitchInstruction(SwitchInstruction switchInstruction){
   if (switchInstruction == null) return null;
   switchInstruction.Expression = this.VisitExpression(switchInstruction.Expression);
   return switchInstruction;
 }
Ejemplo n.º 45
0
 public DataType VisitSwitchInstruction(SwitchInstruction si)
 {
     si.Expression.Accept(this);
     return(VoidType.Instance);
 }
Ejemplo n.º 46
0
		public override void VisitSwitchInstruction(SwitchInstruction si)
		{
			isCritical = true;
		}
Ejemplo n.º 47
0
		public virtual void VisitSwitchInstruction(SwitchInstruction si)
		{
			si.Expression.Accept(this);
		}
Ejemplo n.º 48
0
 public override Statement VisitSwitchInstruction(SwitchInstruction switchInstruction) 
 {
   throw new ApplicationException("unimplemented");
 }