Search in sources :

Example 1 with IfInstruction

use of org.apache.bcel.generic.IfInstruction in project jop by jop-devel.

the class PeepholeOptimizer method optimizeBoolExpressions.

/**
     * Optimize some boolean expressions.
     * <p>
     * This code is taken directly from the BCEL manual, chapter 3.3.8.
     * </p>
     *
     * @param il the instruction list to optimize.
     */
private void optimizeBoolExpressions(InstructionList il) {
    InstructionFinder f = new InstructionFinder(il);
    String pat = "IfInstruction ICONST_0 GOTO ICONST_1 NOP(IFEQ|IFNE)";
    CodeConstraint constraint = new CodeConstraint() {

        @Override
        public boolean checkCode(InstructionHandle[] match) {
            IfInstruction if1 = (IfInstruction) match[0].getInstruction();
            GOTO g = (GOTO) match[2].getInstruction();
            return (if1.getTarget() == match[3]) && (g.getTarget() == match[4]);
        }
    };
    for (Iterator e = f.search(pat, constraint); e.hasNext(); ) {
        InstructionHandle[] match = (InstructionHandle[]) e.next();
        IfInstruction if1 = (IfInstruction) match[0].getInstruction();
        IfInstruction if2 = (IfInstruction) match[5].getInstruction();
        // Update target
        if1.setTarget(if2.getTarget());
        try {
            il.delete(match[1], match[5]);
        } catch (TargetLostException ex) {
            for (InstructionHandle target : ex.getTargets()) {
                for (InstructionTargeter t : target.getTargeters()) {
                    t.updateTarget(target, match[0]);
                }
            }
        }
        matchBoolExpressions++;
    }
}
Also used : GOTO(org.apache.bcel.generic.GOTO) InstructionTargeter(org.apache.bcel.generic.InstructionTargeter) IfInstruction(org.apache.bcel.generic.IfInstruction) Iterator(java.util.Iterator) CodeConstraint(org.apache.bcel.util.InstructionFinder.CodeConstraint) InstructionFinder(org.apache.bcel.util.InstructionFinder) TargetLostException(org.apache.bcel.generic.TargetLostException) InstructionHandle(org.apache.bcel.generic.InstructionHandle)

Aggregations

Iterator (java.util.Iterator)1 GOTO (org.apache.bcel.generic.GOTO)1 IfInstruction (org.apache.bcel.generic.IfInstruction)1 InstructionHandle (org.apache.bcel.generic.InstructionHandle)1 InstructionTargeter (org.apache.bcel.generic.InstructionTargeter)1 TargetLostException (org.apache.bcel.generic.TargetLostException)1 InstructionFinder (org.apache.bcel.util.InstructionFinder)1 CodeConstraint (org.apache.bcel.util.InstructionFinder.CodeConstraint)1