Mono.Cecil.Rocks.MethodBodyRocks.OptimizeBranch C# (CSharp) Method

OptimizeBranch() static private method

static private OptimizeBranch ( Instruction instruction ) : bool
instruction Mono.Cecil.Cil.Instruction
return bool
        static bool OptimizeBranch(Instruction instruction)
        {
            var offset = ((Instruction) instruction.Operand).Offset - (instruction.Offset + instruction.OpCode.Size + 4);
            if (!(offset >= -128 && offset <= 127))
                return false;

            switch (instruction.OpCode.Code) {
            case Code.Br:
                instruction.OpCode = OpCodes.Br_S;
                break;
            case Code.Brfalse:
                instruction.OpCode = OpCodes.Brfalse_S;
                break;
            case Code.Brtrue:
                instruction.OpCode = OpCodes.Brtrue_S;
                break;
            case Code.Beq:
                instruction.OpCode = OpCodes.Beq_S;
                break;
            case Code.Bge:
                instruction.OpCode = OpCodes.Bge_S;
                break;
            case Code.Bgt:
                instruction.OpCode = OpCodes.Bgt_S;
                break;
            case Code.Ble:
                instruction.OpCode = OpCodes.Ble_S;
                break;
            case Code.Blt:
                instruction.OpCode = OpCodes.Blt_S;
                break;
            case Code.Bne_Un:
                instruction.OpCode = OpCodes.Bne_Un_S;
                break;
            case Code.Bge_Un:
                instruction.OpCode = OpCodes.Bge_Un_S;
                break;
            case Code.Bgt_Un:
                instruction.OpCode = OpCodes.Bgt_Un_S;
                break;
            case Code.Ble_Un:
                instruction.OpCode = OpCodes.Ble_Un_S;
                break;
            case Code.Blt_Un:
                instruction.OpCode = OpCodes.Blt_Un_S;
                break;
            case Code.Leave:
                instruction.OpCode = OpCodes.Leave_S;
                break;
            }

            return true;
        }

Usage Example

 private static void OptimizeBranches(MethodBody body)
 {
     MethodBodyRocks.ComputeOffsets(body);
     foreach (Instruction instruction in body.Instructions)
     {
         if (instruction.OpCode.OperandType != OperandType.InlineBrTarget || !MethodBodyRocks.OptimizeBranch(instruction))
         {
             continue;
         }
         MethodBodyRocks.ComputeOffsets(body);
     }
 }