Example usage for org.objectweb.asm Opcodes IFNULL

List of usage examples for org.objectweb.asm Opcodes IFNULL

Introduction

In this page you can find the example usage for org.objectweb.asm Opcodes IFNULL.

Prototype

int IFNULL

To view the source code for org.objectweb.asm Opcodes IFNULL.

Click Source Link

Usage

From source file:apb.processors.NotNullClassInstrumenter.java

License:Apache License

public MethodVisitor visitMethod(final int access, final String name, String desc, String signature,
        String[] exceptions) {/*from   ww  w .jav a2  s.co  m*/
    final Type[] args = Type.getArgumentTypes(desc);
    final Type returnType = Type.getReturnType(desc);

    MethodVisitor v = cv.visitMethod(access, name, desc, signature, exceptions);
    return new MethodAdapter(v) {
        @Override
        public AnnotationVisitor visitParameterAnnotation(int parameter, String anno, boolean visible) {
            final AnnotationVisitor result = mv.visitParameterAnnotation(parameter, anno, visible);

            if (NotNullClassInstrumenter.isReferenceType(args[parameter])
                    && anno.equals(NOT_NULL_ANNOATATION_SIGNATURE)) {
                notNullParams.add(parameter);
            }

            return result;
        }

        @Override
        public AnnotationVisitor visitAnnotation(String anno, boolean isRuntime) {
            final AnnotationVisitor av = mv.visitAnnotation(anno, isRuntime);

            if (isReferenceType(returnType) && anno.equals(NOT_NULL_ANNOATATION_SIGNATURE)) {
                isResultNotNull = true;
            }

            return av;
        }

        @Override
        public void visitCode() {
            if (isResultNotNull || !notNullParams.isEmpty()) {
                startGeneratedCodeLabel = new Label();
                mv.visitLabel(startGeneratedCodeLabel);
            }

            for (int nullParam : notNullParams) {
                int var = (access & 8) != 0 ? 0 : 1;

                for (int i = 0; i < nullParam; i++) {
                    var += args[i].getSize();
                }

                mv.visitVarInsn(Opcodes.ALOAD, var);
                Label end = new Label();
                mv.visitJumpInsn(Opcodes.IFNONNULL, end);
                generateThrow(
                        ILLEGAL_STATE_EXCEPTION_SIGNATURE, "Argument " + nullParam
                                + " for @NotNull parameter of " + className + "." + name + " must not be null",
                        end);
            }

            if (isResultNotNull) {
                final Label codeStart = new Label();
                mv.visitJumpInsn(Opcodes.GOTO, codeStart);
                throwLabel = new Label();
                mv.visitLabel(throwLabel);
                generateThrow(ILLEGAL_STATE_EXCEPTION_SIGNATURE,
                        "@NotNull method " + className + "." + name + " must not return null", codeStart);
            }
        }

        @Override
        public void visitLocalVariable(String name, String desc, String signature, Label start, Label end,
                int index) {
            boolean isStatic = (access & 8) != 0;
            boolean isParameter = isStatic ? index < args.length : index <= args.length;
            mv.visitLocalVariable(name, desc, signature,
                    !isParameter || startGeneratedCodeLabel == null ? start : startGeneratedCodeLabel, end,
                    index);
        }

        public void visitInsn(int opcode) {
            if (opcode == Opcodes.ARETURN && isResultNotNull) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitJumpInsn(Opcodes.IFNULL, throwLabel);
            }

            mv.visitInsn(opcode);
        }

        private void generateThrow(String exceptionClass, String descr, Label end) {
            mv.visitTypeInsn(Opcodes.NEW, exceptionClass);
            mv.visitInsn(Opcodes.DUP);
            mv.visitLdcInsn(descr);

            final String exceptionParamClass = "(Ljava/lang/String;)V";
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionClass, "<init>", exceptionParamClass);
            mv.visitInsn(Opcodes.ATHROW);
            mv.visitLabel(end);
            isModified = true;
        }

        private final List<Integer> notNullParams = new ArrayList<Integer>();
        private boolean isResultNotNull = false;
        public Label throwLabel;
        private Label startGeneratedCodeLabel;
    };
}

From source file:bytecode.InstructionExporter.java

License:Apache License

/**
 * Output conditional branch instructions, choosing between integer and
 * reference comparisons, and also abbreviating comparisons with 0 or
 * <code>null</code>.//w ww .  j  a  v a  2s. co  m
 *
 * @param instruction Comparison instruction.
 * @return .          <code>null</code>
 */
@Override
public Void visit(Condition instruction) {
    Label label = BlockExporter.getLabel(instruction.getDestination());

    // Produce integer instructions
    if (instruction.getOperandA().getType().isIntBased()) {
        // Comparisons with zero
        if (instruction.getOperandB().equals(new Constant(new Integer(0)))) {
            switch (instruction.getOperator()) {
            case EQ:
                mv.visitJumpInsn(Opcodes.IFEQ, label);
                break;
            case NE:
                mv.visitJumpInsn(Opcodes.IFNE, label);
                break;
            case LT:
                mv.visitJumpInsn(Opcodes.IFLT, label);
                break;
            case GE:
                mv.visitJumpInsn(Opcodes.IFGE, label);
                break;
            case GT:
                mv.visitJumpInsn(Opcodes.IFGT, label);
                break;
            case LE:
                mv.visitJumpInsn(Opcodes.IFLE, label);
                break;
            }
            // Direct comparisons
        } else {
            switch (instruction.getOperator()) {
            case EQ:
                mv.visitJumpInsn(Opcodes.IF_ICMPEQ, label);
                break;
            case NE:
                mv.visitJumpInsn(Opcodes.IF_ICMPNE, label);
                break;
            case LT:
                mv.visitJumpInsn(Opcodes.IF_ICMPLT, label);
                break;
            case GE:
                mv.visitJumpInsn(Opcodes.IF_ICMPGE, label);
                break;
            case GT:
                mv.visitJumpInsn(Opcodes.IF_ICMPGT, label);
                break;
            case LE:
                mv.visitJumpInsn(Opcodes.IF_ICMPLE, label);
                break;
            }
        }
        // Produce reference instructions
    } else if (instruction.getOperandA().getType().getSort() == Type.Sort.REF) {
        // Comparisons with null
        if (instruction.getOperandB().equals(new Constant(null))) {
            switch (instruction.getOperator()) {
            case EQ:
                mv.visitJumpInsn(Opcodes.IFNULL, label);
                break;
            case NE:
                mv.visitJumpInsn(Opcodes.IFNONNULL, label);
                break;
            }
            // Direct comparisons
        } else {
            switch (instruction.getOperator()) {
            case EQ:
                mv.visitJumpInsn(Opcodes.IF_ACMPEQ, label);
                break;
            case NE:
                mv.visitJumpInsn(Opcodes.IF_ACMPNE, label);
                break;
            }
        }
        // Flag up others.
    } else {
        throw new RuntimeException("Attempt to export condition of unknown type.");
    }

    return null;
}

From source file:bytecode.MethodImporter.java

License:Apache License

/**
 * Imports branch instructions, both conditional and unconditional.
 *
 * @param opcode Opcode./*from www .  ja v a  2  s .  c o m*/
 * @param label  Destination of branch.
 */
@Override
public void visitJumpInsn(final int opcode, final Label label) {
    BasicBlock section = getBasicBlock(label);

    switch (opcode) {
    // Unconditional Branch
    case Opcodes.GOTO:
        finishBlock(section);
        setCurrent(null);
        break;

    // Zero Test
    case Opcodes.IFEQ:
        createZeroCondition(Condition.Operator.EQ, section);
        break;
    case Opcodes.IFNE:
        createZeroCondition(Condition.Operator.NE, section);
        break;
    case Opcodes.IFLT:
        createZeroCondition(Condition.Operator.LT, section);
        break;
    case Opcodes.IFGE:
        createZeroCondition(Condition.Operator.GE, section);
        break;
    case Opcodes.IFGT:
        createZeroCondition(Condition.Operator.GT, section);
        break;
    case Opcodes.IFLE:
        createZeroCondition(Condition.Operator.LE, section);
        break;

    // Integer Comparison
    case Opcodes.IF_ICMPEQ:
        createCondition(Condition.Operator.EQ, section);
        break;
    case Opcodes.IF_ICMPNE:
        createCondition(Condition.Operator.NE, section);
        break;
    case Opcodes.IF_ICMPLT:
        createCondition(Condition.Operator.LT, section);
        break;
    case Opcodes.IF_ICMPGE:
        createCondition(Condition.Operator.GE, section);
        break;
    case Opcodes.IF_ICMPGT:
        createCondition(Condition.Operator.GT, section);
        break;
    case Opcodes.IF_ICMPLE:
        createCondition(Condition.Operator.LE, section);
        break;

    // Reference Comparisons
    case Opcodes.IF_ACMPEQ:
        createCondition(Condition.Operator.EQ, section);
        break;
    case Opcodes.IF_ACMPNE:
        createCondition(Condition.Operator.NE, section);
        break;
    case Opcodes.IFNULL:
        createNullCondition(Condition.Operator.EQ, section);
        break;
    case Opcodes.IFNONNULL:
        createNullCondition(Condition.Operator.NE, section);
        break;

    // TODO: JSR (paired with RET)
    case Opcodes.JSR:
        System.err.println("visitJumpInsn: JSR");
    }
}

From source file:cn.annoreg.asm.DelegateGenerator.java

License:Open Source License

public static MethodVisitor generateNonStaticMethod(ClassVisitor parentClass, MethodVisitor parent,
        String className, String methodName, String desc, final Side side) {

    //convert desc to a non-static method form
    String nonstaticDesc;/*from   w w w .  j  a v a  2  s.  co m*/
    {
        Type staticType = Type.getMethodType(desc);
        Type retType = staticType.getReturnType();
        Type[] argsType = staticType.getArgumentTypes();
        Type[] argsTypeWithThis = new Type[argsType.length + 1];
        argsTypeWithThis[0] = Type.getType('L' + className.replace('.', '/') + ';');
        System.arraycopy(argsType, 0, argsTypeWithThis, 1, argsType.length);
        nonstaticDesc = Type.getMethodDescriptor(retType, argsTypeWithThis);
    }

    //delegateName is a string used by both sides to identify a network-call delegate.
    final String delegateName = className + ":" + methodName + ":" + desc;
    final Type[] args = Type.getArgumentTypes(nonstaticDesc);
    final Type ret = Type.getReturnType(nonstaticDesc);

    //Check types
    for (Type t : args) {
        //TODO support these types
        if (!t.getDescriptor().startsWith("L") && !t.getDescriptor().startsWith("[")) {
            throw new RuntimeException("Unsupported argument type in network call. ");
        }
    }
    if (!ret.equals(Type.VOID_TYPE)) {
        throw new RuntimeException(
                "Unsupported return value type in network call. " + "Only void is supported.");
    }

    //Generate call to NetworkCallManager in parent.
    parent.visitCode();
    //First parameter
    parent.visitLdcInsn(delegateName);
    //Second parameter: object array
    pushIntegerConst(parent, args.length); //this (0) has been included
    parent.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
    for (int i = 0; i < args.length; ++i) {
        parent.visitInsn(Opcodes.DUP);
        pushIntegerConst(parent, i);
        parent.visitVarInsn(Opcodes.ALOAD, i);
        parent.visitInsn(Opcodes.AASTORE);
    }
    //Call cn.annoreg.mc.network.NetworkCallManager.onNetworkCall
    parent.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(NetworkCallManager.class),
            "onNetworkCall", "(Ljava/lang/String;[Ljava/lang/Object;)V");
    parent.visitInsn(Opcodes.RETURN);
    parent.visitMaxs(5, args.length);
    parent.visitEnd();

    //Create delegate object.
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
    final String delegateId = Integer.toString(delegateNextID++);
    final Type delegateClassType = Type.getType("cn/annoreg/asm/NetworkCallDelegate_" + delegateId);
    cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, delegateClassType.getInternalName(), null,
            Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(NetworkCallDelegate.class) });
    //package cn.annoreg.asm;
    //class NetworkCallDelegate_? implements NetworkCallDelegate {
    {
        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD, 0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    //public NetworkCallDelegate_?() {}

    final String delegateMethodName = methodName + "_delegate_" + delegateId;
    {
        MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke",
                Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object[].class)), null, null);
        mv.visitCode();

        //check if this is null
        mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this
        pushIntegerConst(mv, 0);
        mv.visitInsn(Opcodes.AALOAD);
        Label lblEnd = new Label();
        mv.visitJumpInsn(Opcodes.IFNULL, lblEnd);

        for (int i = 0; i < args.length; ++i) {
            mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this
            pushIntegerConst(mv, i);
            mv.visitInsn(Opcodes.AALOAD);
            mv.visitTypeInsn(Opcodes.CHECKCAST, args[i].getInternalName());
        }
        mv.visitMethodInsn(Opcodes.INVOKESTATIC,
                //delegateClassType.getInternalName(), 
                className.replace('.', '/'), delegateMethodName, nonstaticDesc);

        mv.visitLabel(lblEnd);

        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(args.length + 2, 2);
        mv.visitEnd();
    }
    //@Override public void invoke(Object[] args) {
    //    delegated((Type0) args[0], (Type1) args[1], ...);
    //}

    //The returned MethodVisitor will visit the original version of the method,
    //including its annotation, where we can get StorageOptions.
    return new MethodVisitor(Opcodes.ASM4, parentClass.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC,
            delegateMethodName, nonstaticDesc, null, null)) {

        //Remember storage options for each argument
        StorageOption.Option[] options = new StorageOption.Option[args.length];
        int targetIndex = -1;
        double sendRange = -1;
        StorageOption.Target.RangeOption range = StorageOption.Target.RangeOption.SINGLE;

        {
            for (int i = 0; i < options.length; ++i) {
                options[i] = StorageOption.Option.NULL; //set default value
            }
            options[0] = StorageOption.Option.INSTANCE;
        }

        @Override
        public AnnotationVisitor visitParameterAnnotation(int parameter_in_func, String desc, boolean visible) {
            final int parameter = parameter_in_func + 1; //skip this
            Type type = Type.getType(desc);
            if (type.equals(Type.getType(StorageOption.Data.class))) {
                options[parameter] = StorageOption.Option.DATA;
            } else if (type.equals(Type.getType(StorageOption.Instance.class))) {
                //INSTANCE as defualt
                options[parameter] = StorageOption.Option.INSTANCE;

                //Change to NULLABLE_INSTANCE if nullable set to true
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visit(String name, Object value) {
                        if (name.equals("nullable")) {
                            if ((Boolean) value == true) {
                                options[parameter] = StorageOption.Option.NULLABLE_INSTANCE;
                            }
                        }
                        super.visit(name, value);
                    }
                };
            } else if (type.equals(Type.getType(StorageOption.Update.class))) {
                options[parameter] = StorageOption.Option.UPDATE;
            } else if (type.equals(Type.getType(StorageOption.Null.class))) {
                options[parameter] = StorageOption.Option.NULL;
            } else if (type.equals(Type.getType(StorageOption.Target.class))) {
                if (!args[parameter].equals(Type.getType(EntityPlayer.class))) {
                    throw new RuntimeException("Target annotation can only be used on EntityPlayer.");
                }
                if (targetIndex != -1) {
                    throw new RuntimeException("You can not specify multiple targets.");
                }
                options[parameter] = StorageOption.Option.INSTANCE;
                targetIndex = parameter;
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visitEnum(String name, String desc, String value) {
                        super.visitEnum(name, desc, value);
                        range = StorageOption.Target.RangeOption.valueOf(value);
                    }
                };
            } else if (type.equals(Type.getType(StorageOption.RangedTarget.class))) {
                if (targetIndex != -1) {
                    throw new RuntimeException("You can not specify multiple targets.");
                }
                targetIndex = parameter;
                range = null;
                return new AnnotationVisitor(this.api,
                        super.visitParameterAnnotation(parameter, desc, visible)) {
                    @Override
                    public void visit(String name, Object value) {
                        super.visit(name, value);
                        sendRange = (double) value;
                    }
                };
            }
            return super.visitParameterAnnotation(parameter, desc, visible);
        }

        //TODO this option (from annotation)

        @Override
        public void visitEnd() {
            super.visitEnd();
            //This is the last method in the delegate class.
            //Finish the class and do the registration.
            cw.visitEnd();
            try {
                Class<?> clazz = classLoader.defineClass(delegateClassType.getClassName(), cw.toByteArray());
                NetworkCallDelegate delegateObj = (NetworkCallDelegate) clazz.newInstance();
                if (side == Side.CLIENT) {
                    NetworkCallManager.registerClientDelegateClass(delegateName, delegateObj, options,
                            targetIndex, range, sendRange);
                } else {
                    NetworkCallManager.registerServerDelegateClass(delegateName, delegateObj, options);
                }
            } catch (Throwable e) {
                throw new RuntimeException("Can not create delegate for network call.", e);
            }
        }
    };
    //public static void delegated(Type0 arg0, Type1, arg1, ...) {
    //    //Code generated by caller.
    //}
    //}
}

From source file:co.paralleluniverse.fibers.instrument.InstrumentMethod.java

License:Open Source License

public void accept(MethodVisitor mv, boolean hasAnnotation) {
    db.log(LogLevel.INFO, "Instrumenting method %s#%s%s", className, mn.name, mn.desc);

    mv.visitAnnotation(ALREADY_INSTRUMENTED_DESC, true);
    final boolean handleProxyInvocations = HANDLE_PROXY_INVOCATIONS & hasSuspendableSuperCalls;
    mv.visitCode();// ww  w .jav a2  s. co m

    Label lMethodStart = new Label();
    Label lMethodStart2 = new Label();
    Label lMethodEnd = new Label();
    Label lCatchSEE = new Label();
    Label lCatchUTE = new Label();
    Label lCatchAll = new Label();
    Label[] lMethodCalls = new Label[numCodeBlocks - 1];

    for (int i = 1; i < numCodeBlocks; i++)
        lMethodCalls[i - 1] = new Label();

    mv.visitInsn(Opcodes.ACONST_NULL);
    mv.visitVarInsn(Opcodes.ASTORE, lvarInvocationReturnValue);

    //        if (verifyInstrumentation) {
    //            mv.visitInsn(Opcodes.ICONST_0);
    //            mv.visitVarInsn(Opcodes.ISTORE, lvarSuspendableCalled);
    //        }
    mv.visitTryCatchBlock(lMethodStart, lMethodEnd, lCatchSEE, EXCEPTION_NAME);
    if (handleProxyInvocations)
        mv.visitTryCatchBlock(lMethodStart, lMethodEnd, lCatchUTE, UNDECLARED_THROWABLE_NAME);

    // Prepare visitTryCatchBlocks for InvocationTargetException.
    // With reflective invocations, the SuspendExecution exception will be wrapped in InvocationTargetException. We need to catch it and unwrap it.
    // Note that the InvocationTargetException will be regenrated on every park, adding further overhead on top of the reflective call.
    // This must be done here, before all other visitTryCatchBlock, because the exception's handler
    // will be matched according to the order of in which visitTryCatchBlock has been called. Earlier calls take precedence.
    Label[][] refInvokeTryCatch = new Label[numCodeBlocks - 1][];
    for (int i = 1; i < numCodeBlocks; i++) {
        FrameInfo fi = codeBlocks[i];
        AbstractInsnNode in = mn.instructions.get(fi.endInstruction);
        if (mn.instructions.get(fi.endInstruction) instanceof MethodInsnNode) {
            MethodInsnNode min = (MethodInsnNode) in;
            if (isReflectInvocation(min.owner, min.name)) {
                Label[] ls = new Label[3];
                for (int k = 0; k < 3; k++)
                    ls[k] = new Label();
                refInvokeTryCatch[i - 1] = ls;
                mv.visitTryCatchBlock(ls[0], ls[1], ls[2], "java/lang/reflect/InvocationTargetException");
            }
        }
    }

    for (Object o : mn.tryCatchBlocks) {
        TryCatchBlockNode tcb = (TryCatchBlockNode) o;
        if (EXCEPTION_NAME.equals(tcb.type) && !hasAnnotation) // we allow catch of SuspendExecution in method annotated with @Suspendable.
            throw new UnableToInstrumentException("catch for SuspendExecution", className, mn.name, mn.desc);
        if (handleProxyInvocations && UNDECLARED_THROWABLE_NAME.equals(tcb.type)) // we allow catch of SuspendExecution in method annotated with @Suspendable.
            throw new UnableToInstrumentException("catch for UndeclaredThrowableException", className, mn.name,
                    mn.desc);
        //          if (INTERRUPTED_EXCEPTION_NAME.equals(tcb.type))
        //              throw new UnableToInstrumentException("catch for " + InterruptedException.class.getSimpleName(), className, mn.name, mn.desc);

        tcb.accept(mv);
    }

    if (mn.visibleParameterAnnotations != null)
        dumpParameterAnnotations(mv, mn.visibleParameterAnnotations, true);

    if (mn.invisibleParameterAnnotations != null)
        dumpParameterAnnotations(mv, mn.invisibleParameterAnnotations, false);

    if (mn.visibleAnnotations != null) {
        for (Object o : mn.visibleAnnotations) {
            AnnotationNode an = (AnnotationNode) o;
            an.accept(mv.visitAnnotation(an.desc, true));
        }
    }

    mv.visitTryCatchBlock(lMethodStart, lMethodEnd, lCatchAll, null);

    mv.visitMethodInsn(Opcodes.INVOKESTATIC, STACK_NAME, "getStack", "()L" + STACK_NAME + ";");
    mv.visitInsn(Opcodes.DUP);
    mv.visitVarInsn(Opcodes.ASTORE, lvarStack);

    // println(mv, "STACK: ", lvarStack);
    // dumpStack(mv);
    if (DUAL) {
        mv.visitJumpInsn(Opcodes.IFNULL, lMethodStart);
        mv.visitVarInsn(Opcodes.ALOAD, lvarStack);
    }

    emitStoreResumed(mv, true); // we'll assume we have been resumed

    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, STACK_NAME, "nextMethodEntry", "()I");
    mv.visitTableSwitchInsn(1, numCodeBlocks - 1, lMethodStart2, lMethodCalls);

    mv.visitLabel(lMethodStart2);

    // the following code handles the case of an instrumented method called not as part of a suspendable code path
    // isFirstInStack will return false in that case.
    mv.visitVarInsn(Opcodes.ALOAD, lvarStack);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, STACK_NAME, "isFirstInStackOrPushed", "()Z");
    mv.visitJumpInsn(Opcodes.IFNE, lMethodStart); // if true
    mv.visitInsn(Opcodes.ACONST_NULL);
    mv.visitVarInsn(Opcodes.ASTORE, lvarStack);

    mv.visitLabel(lMethodStart);

    emitStoreResumed(mv, false); // no, we have not been resumed

    dumpCodeBlock(mv, 0, 0);

    for (int i = 1; i < numCodeBlocks; i++) {
        FrameInfo fi = codeBlocks[i];

        MethodInsnNode min = (MethodInsnNode) (mn.instructions.get(fi.endInstruction));
        if (isYieldMethod(min.owner, min.name)) { // special case - call to yield
            if (min.getOpcode() != Opcodes.INVOKESTATIC)
                throw new UnableToInstrumentException("invalid call to suspending method.", className, mn.name,
                        mn.desc);

            final int numYieldArgs = TypeAnalyzer.getNumArguments(min.desc);
            final boolean yieldReturnsValue = (Type.getReturnType(min.desc) != Type.VOID_TYPE);

            emitStoreState(mv, i, fi, numYieldArgs); // we preserve the arguments for the call to yield on the operand stack
            emitStoreResumed(mv, false); // we have not been resumed
            // emitSuspendableCalled(mv);

            min.accept(mv); // we call the yield method
            if (yieldReturnsValue)
                mv.visitInsn(Opcodes.POP); // we ignore the returned value...
            mv.visitLabel(lMethodCalls[i - 1]); // we resume AFTER the call

            final Label afterPostRestore = new Label();
            mv.visitVarInsn(Opcodes.ILOAD, lvarResumed);
            mv.visitJumpInsn(Opcodes.IFEQ, afterPostRestore);
            emitPostRestore(mv);
            mv.visitLabel(afterPostRestore);

            emitRestoreState(mv, i, fi, numYieldArgs);
            if (yieldReturnsValue)
                mv.visitVarInsn(Opcodes.ILOAD, lvarResumed); // ... and replace the returned value with the value of resumed

            dumpCodeBlock(mv, i, 1); // skip the call
        } else {
            final Label lbl = new Label();
            if (DUAL) {
                mv.visitVarInsn(Opcodes.ALOAD, lvarStack);
                mv.visitJumpInsn(Opcodes.IFNULL, lbl);
            }

            // normal case - call to a suspendable method - resume before the call
            emitStoreState(mv, i, fi, 0);
            emitStoreResumed(mv, false); // we have not been resumed
            // emitPreemptionPoint(mv, PREEMPTION_CALL);

            mv.visitLabel(lMethodCalls[i - 1]);
            emitRestoreState(mv, i, fi, 0);

            if (DUAL)
                mv.visitLabel(lbl);

            if (isReflectInvocation(min.owner, min.name)) {
                // We catch the InvocationTargetException and unwrap it if it wraps a SuspendExecution exception.
                Label[] ls = refInvokeTryCatch[i - 1];
                final Label startTry = ls[0];
                final Label endTry = ls[1];
                final Label startCatch = ls[2];
                final Label endCatch = new Label();
                final Label notSuspendExecution = new Label();

                // mv.visitTryCatchBlock(startTry, endTry, startCatch, "java/lang/reflect/InvocationTargetException");
                mv.visitLabel(startTry); // try {
                min.accept(mv); //   method.invoke()
                mv.visitVarInsn(Opcodes.ASTORE, lvarInvocationReturnValue); // save return value
                mv.visitLabel(endTry); // }
                mv.visitJumpInsn(Opcodes.GOTO, endCatch);
                mv.visitLabel(startCatch); // catch(InvocationTargetException ex) {
                mv.visitInsn(Opcodes.DUP);
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable", "getCause",
                        "()Ljava/lang/Throwable;");
                mv.visitTypeInsn(Opcodes.INSTANCEOF, EXCEPTION_NAME);
                mv.visitJumpInsn(Opcodes.IFEQ, notSuspendExecution);
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable", "getCause",
                        "()Ljava/lang/Throwable;");
                mv.visitLabel(notSuspendExecution);
                mv.visitInsn(Opcodes.ATHROW);
                mv.visitLabel(endCatch);

                mv.visitVarInsn(Opcodes.ALOAD, lvarInvocationReturnValue); // restore return value
                dumpCodeBlock(mv, i, 1); // skip the call
            } else {
                // emitSuspendableCalled(mv);
                dumpCodeBlock(mv, i, 0);
            }
        }
    }

    mv.visitLabel(lMethodEnd);

    if (handleProxyInvocations) {
        mv.visitLabel(lCatchUTE);
        mv.visitInsn(Opcodes.DUP);

        // println(mv, "CTCH: ");
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable", "getCause", "()Ljava/lang/Throwable;");
        // println(mv, "CAUSE: ");
        mv.visitTypeInsn(Opcodes.INSTANCEOF, EXCEPTION_NAME);
        mv.visitJumpInsn(Opcodes.IFEQ, lCatchAll);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/Throwable", "getCause", "()Ljava/lang/Throwable;");
        mv.visitJumpInsn(Opcodes.GOTO, lCatchSEE);
    }

    mv.visitLabel(lCatchAll);
    emitPopMethod(mv);
    mv.visitLabel(lCatchSEE);

    // println(mv, "THROW: ");
    mv.visitInsn(Opcodes.ATHROW); // rethrow shared between catchAll and catchSSE

    if (mn.localVariables != null) {
        for (Object o : mn.localVariables)
            ((LocalVariableNode) o).accept(mv);
    }

    mv.visitMaxs(mn.maxStack + ADD_OPERANDS, mn.maxLocals + NUM_LOCALS + additionalLocals);
    mv.visitEnd();
}

From source file:co.paralleluniverse.fibers.instrument.InstrumentMethod.java

License:Open Source License

private void emitPopMethod(MethodVisitor mv) {
    //        emitVerifyInstrumentation(mv);

    final Label lbl = new Label();
    if (DUAL) {//from   w  ww.  ja  v  a  2s  . com
        mv.visitVarInsn(Opcodes.ALOAD, lvarStack);
        mv.visitJumpInsn(Opcodes.IFNULL, lbl);
    }

    mv.visitVarInsn(Opcodes.ALOAD, lvarStack);
    mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, STACK_NAME, "popMethod", "()V");

    if (DUAL)
        mv.visitLabel(lbl);
}

From source file:com.alibaba.hotswap.processor.jdk.classloader.modifier.DefineClassMethodModifier.java

License:Open Source License

@Override
public void visitCode() {
    super.visitCode();

    mv.visitVarInsn(Opcodes.ALOAD, 1);/*from   w ww. j  ava 2 s  . c  o  m*/
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(HotswapConfiguration.class),
            "getClassPathInWorkspace", "(Ljava/lang/String;)Ljava/lang/String;");
    mv.visitInsn(Opcodes.DUP);
    Label old = new Label();
    mv.visitJumpInsn(Opcodes.IFNULL, old);

    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitVarInsn(Opcodes.ALOAD, 0);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(HotswapRuntime.class), "updateClassMeta",
            "(Ljava/lang/String;Ljava/lang/ClassLoader;)V");

    mv.visitVarInsn(Opcodes.ALOAD, 1); // className
    mv.visitInsn(Opcodes.SWAP);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(CustomerLoadClassBytes.class),
            "loadBytesFromPath", "(Ljava/lang/String;Ljava/lang/String;)[B");
    mv.visitVarInsn(Opcodes.ASTORE, 2);// store class bytes into 2
    mv.visitVarInsn(Opcodes.ALOAD, 2);// load class bytes
    mv.visitInsn(Opcodes.ARRAYLENGTH); // length of the class bytes
    mv.visitVarInsn(Opcodes.ISTORE, 4);// store length into 4

    Label end = new Label();
    mv.visitJumpInsn(Opcodes.GOTO, end);

    mv.visitLabel(old);
    mv.visitInsn(Opcodes.POP);

    mv.visitLabel(end);
}

From source file:com.alibaba.hotswap.processor.jdk.classloader.modifier.FindClassMethodModifier.java

License:Open Source License

@Override
public void visitCode() {
    super.visitCode();

    Label normal = new Label();

    mv.visitVarInsn(Opcodes.ALOAD, 0);/*  w  ww. j a  v  a 2 s  .co m*/
    mv.visitVarInsn(Opcodes.ALOAD, 1);
    mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(ClassLoaderHelper.class), "tryLoadVClass",
            "(Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/Class;");
    mv.visitInsn(Opcodes.DUP);
    mv.visitJumpInsn(Opcodes.IFNULL, normal);
    mv.visitInsn(Opcodes.ARETURN);

    mv.visitLabel(normal);
    mv.visitInsn(Opcodes.POP);
}

From source file:com.android.build.gradle.internal.incremental.Redirection.java

License:Apache License

/**
 * Adds the instructions to do a generic redirection.
 * <p>//from   ww w  . jav  a2  s  .  co m
 * Note that the generated bytecode does not have a direct translation to code, but as an
 * example, the following code block gets inserted.
 * <code>
 * if ($change != null) {
 *   $change.access$dispatch($name, new object[] { arg0, ... argsN })
 *   $anyCodeInsertedbyRestore
 * }
 * $originalMethodBody
 *</code>
 * @param mv the method visitor to add the instructions to.
 * @param change the local variable containing the alternate implementation.
 */
void redirect(GeneratorAdapter mv, int change) {
    // code to check if a new implementation of the current class is available.
    Label l0 = new Label();
    mv.loadLocal(change);
    mv.visitJumpInsn(Opcodes.IFNULL, l0);

    doRedirect(mv, change);

    // Return
    if (type == Type.VOID_TYPE) {
        mv.pop();
    } else {
        ByteCodeUtils.unbox(mv, type);
    }
    mv.returnValue();

    // jump label for classes without any new implementation, just invoke the original
    // method implementation.
    mv.visitLabel(l0);
}

From source file:com.codename1.tools.translator.BytecodeMethod.java

License:Open Source License

boolean optimize() {
    int instructionCount = instructions.size();

    // optimize away a method that only contains the void return instruction e.g. blank constructors etc.
    if (instructionCount < 6) {
        int realCount = instructionCount;
        Instruction actual = null;/*from   ww w .  j av a 2s .  c om*/
        for (int iter = 0; iter < instructionCount; iter++) {
            Instruction current = instructions.get(iter);
            if (current instanceof LabelInstruction) {
                realCount--;
                continue;
            }
            if (current instanceof LineNumber) {
                realCount--;
                continue;
            }
            actual = current;
        }

        if (realCount == 1 && actual != null && actual.getOpcode() == Opcodes.RETURN) {
            return false;
        }
    }

    boolean astoreCalls = false;
    boolean hasInstructions = false;

    boolean hasTryCatch = false;
    for (int iter = 0; iter < instructionCount - 1; iter++) {
        Instruction current = instructions.get(iter);
        if (current instanceof TryCatch) {
            hasTryCatch = true;
        }
        current.setMethod(this);
        if (current.isOptimized()) {
            continue;
        }
        int currentOpcode = current.getOpcode();
        switch (currentOpcode) {
        case Opcodes.CHECKCAST: {
            // Remove the check cast for now as it gets in the way of other optimizations
            instructions.remove(iter);
            iter--;
            instructionCount--;
            break;
        }
        }
    }

    for (int iter = 0; iter < instructionCount - 1; iter++) {
        Instruction current = instructions.get(iter);
        if (current.isOptimized()) {
            // This instruction has already been optimized
            // we should skip it and proceed to the next one
            continue;
        }
        Instruction next = instructions.get(iter + 1);

        int currentOpcode = current.getOpcode();
        int nextOpcode = next.getOpcode();

        if (ArithmeticExpression.isArithmeticOp(current)) {
            int addedIndex = ArithmeticExpression.tryReduce(instructions, iter);
            if (addedIndex >= 0) {
                iter = addedIndex;
                instructionCount = instructions.size();
                continue;
            }
        }

        if (current instanceof Field) {
            int newIter = Field.tryReduce(instructions, iter);
            if (newIter >= 0) {
                iter = newIter;
                instructionCount = instructions.size();
                continue;
            }
        }

        switch (currentOpcode) {

        case Opcodes.ARRAYLENGTH: {
            if (!dependentClasses.contains("java_lang_NullPointerException")) {
                dependentClasses.add("java_lang_NullPointerException");
            }
            int newIter = ArrayLengthExpression.tryReduce(instructions, iter);
            if (newIter >= 0) {
                instructionCount = instructions.size();
                iter = newIter;
                continue;
            }
            break;
        }

        case Opcodes.DUP: {
            int newIter = DupExpression.tryReduce(instructions, iter);
            if (newIter >= 0) {
                iter = newIter;
                instructionCount = instructions.size();
                continue;
            }
            break;
        }

        case Opcodes.POP: {
            if (iter > 0) {
                Instruction prev = instructions.get(iter - 1);
                if (prev instanceof CustomInvoke) {
                    CustomInvoke inv = (CustomInvoke) prev;
                    if (inv.methodHasReturnValue()) {
                        inv.setNoReturn(true);
                        instructions.remove(iter);
                        iter--;
                        instructionCount--;
                        continue;
                    }
                }
            }
            break;
        }

        case Opcodes.ASTORE:
        case Opcodes.ISTORE:
        case Opcodes.DSTORE:
        case Opcodes.LSTORE:
        case Opcodes.FSTORE: {
            if (iter > 0 && current instanceof VarOp) {
                VarOp currentVarOp = (VarOp) current;
                Instruction prev = instructions.get(iter - 1);
                if (prev instanceof AssignableExpression) {
                    AssignableExpression expr = (AssignableExpression) prev;
                    StringBuilder sb = new StringBuilder();
                    if (currentVarOp.assignFrom(expr, sb)) {
                        instructions.remove(iter - 1);
                        instructions.remove(iter - 1);
                        instructions.add(iter - 1,
                                new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
                        iter = iter - 1;
                        instructionCount = instructions.size();
                        continue;
                    }

                } else if (prev instanceof CustomInvoke) {
                    CustomInvoke inv = (CustomInvoke) prev;
                    StringBuilder sb = new StringBuilder();
                    if (currentVarOp.assignFrom(inv, sb)) {
                        instructions.remove(iter - 1);
                        instructions.remove(iter - 1);
                        instructions.add(iter - 1,
                                new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
                        iter = iter - 1;
                        instructionCount = instructions.size();
                        continue;
                    }
                }
            }

            break;
        }

        case Opcodes.IRETURN:
        case Opcodes.FRETURN:
        case Opcodes.ARETURN:
        case Opcodes.LRETURN:
        case Opcodes.DRETURN: {
            if (iter > 0 && current instanceof BasicInstruction) {
                Instruction prev = instructions.get(iter - 1);
                if (prev instanceof AssignableExpression) {
                    AssignableExpression expr = (AssignableExpression) prev;
                    StringBuilder sb = new StringBuilder();
                    if (expr.assignTo(null, sb)) {
                        instructions.remove(iter - 1);
                        instructions.remove(iter - 1);
                        String exprString = sb.toString().trim();
                        String retVal = exprString;
                        sb.setLength(0);
                        if (!prev.isConstant()) {
                            sb.append("\n{\n    ");
                            switch (currentOpcode) {
                            case Opcodes.IRETURN:
                                sb.append("JAVA_INT");
                                break;
                            case Opcodes.FRETURN:
                                sb.append("JAVA_FLOAT");
                                break;
                            case Opcodes.ARETURN:
                                sb.append("JAVA_OBJECT");
                                break;
                            case Opcodes.LRETURN:
                                sb.append("JAVA_LONG");
                                break;
                            case Opcodes.DRETURN:
                                sb.append("JAVA_DOUBLE");
                                break;
                            }
                            sb.append(" ___returnValue=").append(exprString).append(";\n");
                            retVal = "___returnValue";
                        }
                        if (synchronizedMethod) {
                            if (staticMethod) {
                                sb.append("    monitorExit(threadStateData, (JAVA_OBJECT)&class__");
                                sb.append(getClsName());
                                sb.append(");\n");
                            } else {
                                sb.append("    monitorExit(threadStateData, __cn1ThisObject);\n");
                            }
                        }
                        if (hasTryCatch) {
                            sb.append(
                                    "    releaseForReturnInException(threadStateData, cn1LocalsBeginInThread, methodBlockOffset); return ")
                                    .append(retVal).append(";\n");
                        } else {
                            sb.append("    releaseForReturn(threadStateData, cn1LocalsBeginInThread); return ")
                                    .append(retVal).append(";\n");
                        }
                        if (!prev.isConstant()) {
                            sb.append("}\n");
                        }

                        instructions.add(iter - 1,
                                new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
                        iter--;
                        instructionCount = instructions.size();
                        continue;

                    }
                } else if (prev instanceof CustomInvoke) {

                    CustomInvoke expr = (CustomInvoke) prev;
                    String returnType = expr.getReturnValue();
                    if (returnType != null && !"JAVA_OBJECT".equals(returnType)) {
                        // We can't safely return a JAVA_OBJECT directly because it needs to be added 
                        // to the stack for the GC
                        StringBuilder sb = new StringBuilder();
                        if (expr.appendExpression(sb)) {
                            instructions.remove(iter - 1);
                            instructions.remove(iter - 1);
                            String exprString = sb.toString().trim();
                            String retVal = exprString;
                            sb.setLength(0);
                            if (!expr.isConstant()) {

                                sb.append("\n{\n    ");
                                switch (currentOpcode) {
                                case Opcodes.IRETURN:
                                    sb.append("JAVA_INT");
                                    break;
                                case Opcodes.FRETURN:
                                    sb.append("JAVA_FLOAT");
                                    break;
                                case Opcodes.ARETURN:
                                    sb.append("JAVA_OBJECT");
                                    break;
                                case Opcodes.LRETURN:
                                    sb.append("JAVA_LONG");
                                    break;
                                case Opcodes.DRETURN:
                                    sb.append("JAVA_DOUBLE");
                                    break;
                                }

                                sb.append(" ___returnValue=").append(exprString).append(";\n");
                                retVal = "___returnValue";
                            }
                            if (synchronizedMethod) {
                                if (staticMethod) {
                                    sb.append("    monitorExit(threadStateData, (JAVA_OBJECT)&class__");
                                    sb.append(getClsName());
                                    sb.append(");\n");
                                } else {
                                    sb.append("    monitorExit(threadStateData, __cn1ThisObject);\n");
                                }
                            }
                            if (hasTryCatch) {
                                sb.append(
                                        "    releaseForReturnInException(threadStateData, cn1LocalsBeginInThread, methodBlockOffset); return ")
                                        .append(retVal).append(";\n");
                            } else {
                                sb.append(
                                        "    releaseForReturn(threadStateData, cn1LocalsBeginInThread); return ")
                                        .append(retVal).append(";\n");
                            }
                            if (!expr.isConstant()) {
                                sb.append("}\n");
                            }

                            instructions.add(iter - 1,
                                    new CustomIntruction(sb.toString(), sb.toString(), dependentClasses));
                            iter--;
                            instructionCount = instructions.size();
                            continue;

                        }
                    }
                }
            }
            break;
        }

        case Opcodes.BASTORE:
        case Opcodes.SASTORE:
        case Opcodes.CASTORE:
        case Opcodes.AASTORE:
        case Opcodes.IASTORE:
        case Opcodes.DASTORE:
        case Opcodes.LASTORE:
        case Opcodes.FASTORE: {
            if (iter > 2 && current instanceof BasicInstruction) {
                StringBuilder devNull = new StringBuilder();
                String arrayLiteral = null;
                String indexLiteral = null;
                String valueLiteral = null;
                Instruction prev3 = instructions.get(iter - 3);
                if (prev3 instanceof AssignableExpression) {
                    if (((AssignableExpression) prev3).assignTo(null, devNull)) {
                        arrayLiteral = devNull.toString().trim();

                    }
                }
                devNull.setLength(0);
                Instruction prev2 = instructions.get(iter - 2);
                if (prev2 instanceof AssignableExpression) {
                    if (((AssignableExpression) prev2).assignTo(null, devNull)) {
                        indexLiteral = devNull.toString().trim();
                    }
                }
                devNull.setLength(0);
                Instruction prev1 = instructions.get(iter - 1);

                if (prev1 instanceof AssignableExpression) {
                    if (((AssignableExpression) prev1).assignTo(null, devNull)) {
                        valueLiteral = devNull.toString().trim();
                    }
                } else if (prev1 instanceof CustomInvoke) {
                    devNull.setLength(0);
                    if (((CustomInvoke) prev1).appendExpression(devNull)) {
                        valueLiteral = devNull.toString().trim();
                    }
                }

                if (arrayLiteral != null && indexLiteral != null && valueLiteral != null) {
                    String elementType = null;
                    switch (current.getOpcode()) {
                    case Opcodes.AASTORE:
                        elementType = "OBJECT";
                        break;
                    case Opcodes.IASTORE:
                        elementType = "INT";
                        break;
                    case Opcodes.DASTORE:
                        elementType = "DOUBLE";
                        break;

                    case Opcodes.LASTORE:
                        elementType = "LONG";
                        break;
                    case Opcodes.FASTORE:
                        elementType = "FLOAT";
                        break;
                    case Opcodes.CASTORE:
                        elementType = "CHAR";
                        break;
                    case Opcodes.BASTORE:
                        elementType = "BYTE";
                        break;
                    case Opcodes.SASTORE:
                        elementType = "SHORT";
                        break;

                    }
                    if (elementType == null) {
                        break;
                    }

                    instructions.remove(iter - 3);
                    instructions.remove(iter - 3);
                    instructions.remove(iter - 3);
                    instructions.remove(iter - 3);
                    String code = "    CN1_SET_ARRAY_ELEMENT_" + elementType + "(" + arrayLiteral + ", "
                            + indexLiteral + ", " + valueLiteral + ");\n";
                    instructions.add(iter - 3, new CustomIntruction(code, code, dependentClasses));
                    iter = iter - 3;
                    instructionCount = instructions.size();
                    continue;
                }
            }

            break;
        }

        case Opcodes.FALOAD:
        case Opcodes.BALOAD:
        case Opcodes.IALOAD:
        case Opcodes.LALOAD:
        case Opcodes.DALOAD:
        case Opcodes.AALOAD:
        case Opcodes.SALOAD:
        case Opcodes.CALOAD: {
            int newIter = ArrayLoadExpression.tryReduce(instructions, iter);
            if (newIter >= 0) {
                iter = newIter;
                instructionCount = instructions.size();
                continue;
            }
            break;
        }

        /* Try to optimize if statements that just use constants
           and local variables so that they don't need the intermediate
           push and pop from the stack.
        */
        case Opcodes.IF_ACMPEQ:
        case Opcodes.IF_ACMPNE:
        case Opcodes.IF_ICMPLE:
        case Opcodes.IF_ICMPLT:
        case Opcodes.IF_ICMPNE:
        case Opcodes.IF_ICMPGT:
        case Opcodes.IF_ICMPEQ:
        case Opcodes.IF_ICMPGE: {

            if (iter > 1) {
                Instruction leftArg = instructions.get(iter - 2);
                Instruction rightArg = instructions.get(iter - 1);

                String leftLiteral = null;
                String rightLiteral = null;

                if (leftArg instanceof AssignableExpression) {
                    StringBuilder sb = new StringBuilder();
                    if (((AssignableExpression) leftArg).assignTo(null, sb)) {
                        leftLiteral = sb.toString().trim();
                    }
                } else if (leftArg instanceof CustomInvoke) {
                    CustomInvoke inv = (CustomInvoke) leftArg;
                    StringBuilder sb = new StringBuilder();
                    if (!"JAVA_OBJECT".equals(inv.getReturnValue()) && inv.appendExpression(sb)) {
                        leftLiteral = sb.toString().trim();
                    }
                }
                if (rightArg instanceof AssignableExpression) {
                    StringBuilder sb = new StringBuilder();
                    if (((AssignableExpression) rightArg).assignTo(null, sb)) {
                        rightLiteral = sb.toString().trim();
                    }
                } else if (rightArg instanceof CustomInvoke) {
                    CustomInvoke inv = (CustomInvoke) rightArg;
                    StringBuilder sb = new StringBuilder();
                    if (!"JAVA_OBJECT".equals(inv.getReturnValue()) && inv.appendExpression(sb)) {
                        rightLiteral = sb.toString().trim();
                    }
                }

                if (rightLiteral != null && leftLiteral != null) {
                    Jump jmp = (Jump) current;
                    instructions.remove(iter - 2);
                    instructions.remove(iter - 2);
                    instructions.remove(iter - 2);
                    //instructions.remove(iter-2);
                    iter -= 2;
                    //instructionCount -= 2;
                    StringBuilder sb = new StringBuilder();
                    String operator = null;
                    String opName = null;
                    switch (currentOpcode) {
                    case Opcodes.IF_ICMPLE:
                        operator = "<=";
                        opName = "IF_ICMPLE";
                        break;
                    case Opcodes.IF_ICMPLT:
                        operator = "<";
                        opName = "IF_IMPLT";
                        break;
                    case Opcodes.IF_ICMPNE:
                        operator = "!=";
                        opName = "IF_ICMPNE";
                        break;
                    case Opcodes.IF_ICMPGT:
                        operator = ">";
                        opName = "IF_ICMPGT";
                        break;
                    case Opcodes.IF_ICMPGE:
                        operator = ">=";
                        opName = "IF_ICMPGE";
                        break;
                    case Opcodes.IF_ICMPEQ:
                        operator = "==";
                        opName = "IF_ICMPEQ";
                        break;
                    case Opcodes.IF_ACMPEQ:
                        operator = "==";
                        opName = "IF_ACMPEQ";
                        break;
                    case Opcodes.IF_ACMPNE:
                        operator = "!=";
                        opName = "IF_ACMPNE";
                        break;
                    default:
                        throw new RuntimeException(
                                "Invalid operator during optimization of integer comparison");
                    }

                    sb.append("if (").append(leftLiteral).append(operator).append(rightLiteral).append(") /* ")
                            .append(opName).append(" CustomJump */ ");
                    CustomJump newJump = CustomJump.create(jmp, sb.toString());
                    //jmp.setCustomCompareCode(sb.toString());
                    newJump.setOptimized(true);
                    instructions.add(iter, newJump);
                    instructionCount = instructions.size();

                }

            }
            break;
        }
        case Opcodes.IFNONNULL:
        case Opcodes.IFNULL:

        case Opcodes.IFLE:
        case Opcodes.IFLT:
        case Opcodes.IFNE:
        case Opcodes.IFGT:
        case Opcodes.IFEQ:
        case Opcodes.IFGE: {
            String rightArg = "0";
            if (currentOpcode == Opcodes.IFNONNULL || currentOpcode == Opcodes.IFNULL) {
                rightArg = "JAVA_NULL";
            }
            if (iter > 0) {
                Instruction leftArg = instructions.get(iter - 1);

                String leftLiteral = null;

                if (leftArg instanceof AssignableExpression) {
                    StringBuilder sb = new StringBuilder();
                    if (((AssignableExpression) leftArg).assignTo(null, sb)) {
                        leftLiteral = sb.toString().trim();
                    }
                } else if (leftArg instanceof CustomInvoke) {
                    CustomInvoke inv = (CustomInvoke) leftArg;
                    StringBuilder sb = new StringBuilder();
                    if (inv.appendExpression(sb)) {
                        leftLiteral = sb.toString().trim();
                    }
                }

                if (leftLiteral != null) {
                    Jump jmp = (Jump) current;
                    instructions.remove(iter - 1);
                    instructions.remove(iter - 1);
                    //instructions.remove(iter-2);
                    iter -= 1;
                    //instructionCount -= 2;
                    StringBuilder sb = new StringBuilder();
                    String operator = null;
                    String opName = null;
                    switch (currentOpcode) {
                    case Opcodes.IFLE:
                        operator = "<=";
                        opName = "IFLE";
                        break;
                    case Opcodes.IFLT:
                        operator = "<";
                        opName = "IFLT";
                        break;
                    case Opcodes.IFNE:
                        operator = "!=";
                        opName = "IFNE";
                        break;
                    case Opcodes.IFGT:
                        operator = ">";
                        opName = "IFGT";
                        break;
                    case Opcodes.IFGE:
                        operator = ">=";
                        opName = "IFGE";
                        break;
                    case Opcodes.IFEQ:
                        operator = "==";
                        opName = "IFEQ";
                        break;
                    case Opcodes.IFNULL:
                        operator = "==";
                        opName = "IFNULL";
                        break;
                    case Opcodes.IFNONNULL:
                        operator = "!=";
                        opName = "IFNONNULL";
                        break;
                    default:
                        throw new RuntimeException(
                                "Invalid operator during optimization of integer comparison");
                    }

                    sb.append("if (").append(leftLiteral).append(operator).append(rightArg).append(") /* ")
                            .append(opName).append(" CustomJump */ ");
                    CustomJump newJump = CustomJump.create(jmp, sb.toString());
                    //jmp.setCustomCompareCode(sb.toString());
                    newJump.setOptimized(true);
                    instructions.add(iter, newJump);
                    instructionCount = instructions.size();

                }

            }
            break;
        }

        case Opcodes.INVOKEVIRTUAL:
        case Opcodes.INVOKESTATIC:
        case Opcodes.INVOKESPECIAL:
        case Opcodes.INVOKEINTERFACE: {
            if (current instanceof Invoke) {
                Invoke inv = (Invoke) current;
                List<ByteCodeMethodArg> invocationArgs = inv.getArgs();
                int numArgs = invocationArgs.size();

                //if (current.getOpcode() != Opcodes.INVOKESTATIC) {
                //    numArgs++;
                //}
                if (iter >= numArgs) {
                    String[] argLiterals = new String[numArgs];
                    StringBuilder devNull = new StringBuilder();
                    for (int i = 0; i < numArgs; i++) {
                        devNull.setLength(0);
                        Instruction instr = instructions.get(iter - numArgs + i);
                        if (instr instanceof AssignableExpression
                                && ((AssignableExpression) instr).assignTo(null, devNull)) {
                            argLiterals[i] = devNull.toString().trim();
                        } else if (instr instanceof CustomInvoke) {
                            CustomInvoke cinv = (CustomInvoke) instr;
                            devNull.setLength(0);
                            if (!"JAVA_OBJECT".equals(cinv.getReturnValue())
                                    && cinv.appendExpression(devNull)) {
                                // We can't add invocations that return objects directly
                                // because they need to be added to the stack for GC
                                argLiterals[i] = devNull.toString().trim();
                            }
                        } else if (instr instanceof ArithmeticExpression) {
                            argLiterals[i] = ((ArithmeticExpression) instr).getExpressionAsString().trim();
                        } else if (instr instanceof VarOp) {
                            VarOp var = (VarOp) instr;
                            switch (instr.getOpcode()) {
                            case Opcodes.ALOAD: {
                                if (!isStatic() && var.getIndex() == 0) {
                                    argLiterals[i] = "__cn1ThisObject";
                                } else {
                                    argLiterals[i] = "locals[" + var.getIndex() + "].data.o";
                                }
                                break;
                            }
                            case Opcodes.ILOAD: {
                                argLiterals[i] = "ilocals_" + var.getIndex() + "_";
                                break;
                            }
                            case Opcodes.ACONST_NULL: {
                                argLiterals[i] = "JAVA_NULL";
                                break;
                            }
                            case Opcodes.DLOAD: {
                                argLiterals[i] = "dlocals_" + var.getIndex() + "_";
                                break;
                            }
                            case Opcodes.FLOAD: {
                                argLiterals[i] = "flocals_" + var.getIndex() + "_";
                                break;
                            }
                            case Opcodes.LLOAD: {
                                argLiterals[i] = "llocals_" + var.getIndex() + "_";
                                break;
                            }
                            case Opcodes.ICONST_0: {
                                argLiterals[i] = "0";
                                break;
                            }
                            case Opcodes.ICONST_1: {
                                argLiterals[i] = "1";
                                break;
                            }
                            case Opcodes.ICONST_2: {
                                argLiterals[i] = "2";
                                break;
                            }
                            case Opcodes.ICONST_3: {
                                argLiterals[i] = "3";
                                break;
                            }
                            case Opcodes.ICONST_4: {
                                argLiterals[i] = "4";
                                break;
                            }
                            case Opcodes.ICONST_5: {
                                argLiterals[i] = "5";
                                break;
                            }
                            case Opcodes.ICONST_M1: {
                                argLiterals[i] = "-1";
                                break;
                            }
                            case Opcodes.LCONST_0: {
                                argLiterals[i] = "(JAVA_LONG)0";
                                break;
                            }
                            case Opcodes.LCONST_1: {
                                argLiterals[i] = "(JAVA_LONG)1";
                                break;
                            }
                            case Opcodes.BIPUSH:
                            case Opcodes.SIPUSH: {
                                argLiterals[i] = String.valueOf(var.getIndex());

                                break;
                            }
                            }
                        } else {
                            switch (instr.getOpcode()) {

                            case Opcodes.ACONST_NULL: {
                                argLiterals[i] = "JAVA_NULL";
                                break;
                            }

                            case Opcodes.ICONST_0: {
                                argLiterals[i] = "0";
                                break;
                            }
                            case Opcodes.ICONST_1: {
                                argLiterals[i] = "1";
                                break;
                            }
                            case Opcodes.ICONST_2: {
                                argLiterals[i] = "2";
                                break;
                            }
                            case Opcodes.ICONST_3: {
                                argLiterals[i] = "3";
                                break;
                            }
                            case Opcodes.ICONST_4: {
                                argLiterals[i] = "4";
                                break;
                            }
                            case Opcodes.ICONST_5: {
                                argLiterals[i] = "5";
                                break;
                            }
                            case Opcodes.ICONST_M1: {
                                argLiterals[i] = "-1";
                                break;
                            }
                            case Opcodes.LCONST_0: {
                                argLiterals[i] = "(JAVA_LONG)0";
                                break;
                            }
                            case Opcodes.LCONST_1: {
                                argLiterals[i] = "(JAVA_LONG)1";
                                break;
                            }
                            case Opcodes.BIPUSH: {
                                if (instr instanceof BasicInstruction) {
                                    argLiterals[i] = String.valueOf(((BasicInstruction) instr).getValue());
                                }
                                break;
                            }
                            case Opcodes.LDC: {
                                if (instr instanceof Ldc) {
                                    Ldc ldc = (Ldc) instr;
                                    argLiterals[i] = ldc.getValueAsString();

                                }
                                break;
                            }

                            }

                        }
                    }

                    // Check to make sure that we have all the args as literals.
                    boolean missingLiteral = false;
                    for (String lit : argLiterals) {
                        if (lit == null) {
                            missingLiteral = true;
                            break;
                        }
                    }

                    // We have all of the arguments as literals.  Let's
                    // add them to our invoke instruction.
                    if (!missingLiteral) {
                        CustomInvoke newInvoke = CustomInvoke.create(inv);
                        instructions.remove(iter);
                        instructions.add(iter, newInvoke);
                        int newIter = iter;
                        for (int i = 0; i < numArgs; i++) {
                            instructions.remove(iter - numArgs);
                            newIter--;
                            newInvoke.setLiteralArg(i, argLiterals[i]);
                        }
                        if (inv.getOpcode() != Opcodes.INVOKESTATIC) {
                            Instruction ldTarget = instructions.get(iter - numArgs - 1);
                            if (ldTarget instanceof AssignableExpression) {
                                StringBuilder targetExprStr = new StringBuilder();
                                if (((AssignableExpression) ldTarget).assignTo(null, targetExprStr)) {
                                    newInvoke.setTargetObjectLiteral(targetExprStr.toString().trim());
                                    instructions.remove(iter - numArgs - 1);
                                    newIter--;

                                }

                            } else if (ldTarget instanceof CustomInvoke) {
                                // WE Can't pass a custom invoke as the target directly
                                // because it the return value needs to be added to the 
                                // stack for the GC
                            } else {
                                switch (ldTarget.getOpcode()) {
                                case Opcodes.ALOAD: {
                                    VarOp v = (VarOp) ldTarget;
                                    if (isStatic() && v.getIndex() == 0) {
                                        newInvoke.setTargetObjectLiteral("__cn1ThisObject");
                                    } else {
                                        newInvoke.setTargetObjectLiteral("locals[" + v.getIndex() + "].data.o");
                                    }
                                    instructions.remove(iter - numArgs - 1);
                                    newIter--;
                                    break;
                                }
                                }
                            }
                        }

                        newInvoke.setOptimized(true);
                        //iter = 0;
                        instructionCount = instructions.size();
                        iter = newIter;

                    }
                }
            }
            break;
        }

        }
        astoreCalls = astoreCalls || currentOpcode == Opcodes.ASTORE || currentOpcode == Opcodes.ISTORE
                || currentOpcode == Opcodes.LSTORE || currentOpcode == Opcodes.DSTORE
                || currentOpcode == Opcodes.FSTORE;

        hasInstructions = hasInstructions | current.getOpcode() != -1;
    }
    return hasInstructions;
}