Example usage for org.objectweb.asm Opcodes NEW

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

Introduction

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

Prototype

int NEW

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

Click Source Link

Usage

From source file:org.mbte.groovypp.compiler.bytecode.BytecodeExpr.java

License:Apache License

/**
 * box the primitive value on the stack//from   w  w w. j av  a2 s  .c om
 *
 * @param type
 * @param mv
 */
public void quickBoxIfNecessary(ClassNode type, MethodVisitor mv) {
    String descr = getTypeDescription(type);
    if (type == boolean_TYPE) {
        boxBoolean(mv);
    } else if (isPrimitiveType(type) && type != VOID_TYPE) {
        ClassNode wrapper = TypeUtil.wrapSafely(type);
        String internName = getClassInternalName(wrapper);
        mv.visitTypeInsn(Opcodes.NEW, internName);
        mv.visitInsn(Opcodes.DUP);
        if (type == double_TYPE || type == long_TYPE) {
            mv.visitInsn(Opcodes.DUP2_X2);
            mv.visitInsn(Opcodes.POP2);
        } else {
            mv.visitInsn(Opcodes.DUP2_X1);
            mv.visitInsn(Opcodes.POP2);
        }
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, internName, "<init>", "(" + descr + ")V");
    }
}

From source file:org.mbte.groovypp.compiler.bytecode.BytecodeExpr.java

License:Apache License

/**
 * load the constant on the operand stack. primitives auto-boxed.
 *//*from w  ww .  j  av  a  2s. com*/
void loadConstant(Object value, MethodVisitor mv) {
    if (value == null) {
        mv.visitInsn(Opcodes.ACONST_NULL);
    } else if (value instanceof String) {
        mv.visitLdcInsn(value);
    } else if (value instanceof Character) {
        String className = "java/lang/Character";
        mv.visitTypeInsn(Opcodes.NEW, className);
        mv.visitInsn(Opcodes.DUP);
        mv.visitLdcInsn(value);
        String methodType = "(C)V";
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, className, "<init>", methodType);
    } else if (value instanceof Number) {
        /** todo it would be more efficient to generate class constants */
        Number n = (Number) value;
        String className = BytecodeHelper.getClassInternalName(value.getClass().getName());
        mv.visitTypeInsn(Opcodes.NEW, className);
        mv.visitInsn(Opcodes.DUP);
        String methodType;
        if (n instanceof Integer) {
            //pushConstant(n.intValue());
            mv.visitLdcInsn(n);
            methodType = "(I)V";
        } else if (n instanceof Double) {
            mv.visitLdcInsn(n);
            methodType = "(D)V";
        } else if (n instanceof Float) {
            mv.visitLdcInsn(n);
            methodType = "(F)V";
        } else if (n instanceof Long) {
            mv.visitLdcInsn(n);
            methodType = "(J)V";
        } else if (n instanceof BigDecimal) {
            mv.visitLdcInsn(n.toString());
            methodType = "(Ljava/lang/String;)V";
        } else if (n instanceof BigInteger) {
            mv.visitLdcInsn(n.toString());
            methodType = "(Ljava/lang/String;)V";
        } else if (n instanceof Short) {
            mv.visitLdcInsn(n);
            methodType = "(S)V";
        } else if (n instanceof Byte) {
            mv.visitLdcInsn(n);
            methodType = "(B)V";
        } else {
            throw new ClassGeneratorException("Cannot generate bytecode for constant: " + value + " of type: "
                    + value.getClass().getName() + ".  Numeric constant type not supported.");
        }
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, className, "<init>", methodType);
    } else if (value instanceof Boolean) {
        Boolean bool = (Boolean) value;
        String text = (bool.booleanValue()) ? "TRUE" : "FALSE";
        mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/Boolean", text, "Ljava/lang/Boolean;");
    } else if (value instanceof Class) {
        Class vc = (Class) value;
        if (vc.getName().equals("java.lang.Void")) {
            // load nothing here for void
        } else {
            throw new ClassGeneratorException("Cannot generate bytecode for constant: " + value + " of type: "
                    + value.getClass().getName());
        }
    } else {
        throw new ClassGeneratorException(
                "Cannot generate bytecode for constant: " + value + " of type: " + value.getClass().getName());
    }
}

From source file:org.mbte.groovypp.compiler.ClosureUtil.java

License:Apache License

public static void instantiateClass(ClassNode type, CompilerTransformer compiler, Parameter[] constrParams,
        Expression superArgs, MethodVisitor mv) {
    TraitASTTransformFinal.improveAbstractMethods(type);
    type.getModule().addClass(type);//ww  w . j  ava 2 s .  c  o m

    final String classInternalName = BytecodeHelper.getClassInternalName(type);
    mv.visitTypeInsn(Opcodes.NEW, classInternalName);
    mv.visitInsn(Opcodes.DUP);

    final ConstructorNode constructorNode = type.getDeclaredConstructors().get(0);

    for (int i = 0; i != constrParams.length; i++) {
        String name = constrParams[i].getName();

        if ("this$0".equals(name)) {
            mv.visitVarInsn(Opcodes.ALOAD, 0);
        } else {
            final Register var = compiler.compileStack.getRegister(name, false);
            if (var != null) {
                FieldNode field = type.getDeclaredField(name);
                BytecodeExpr.load(field.getType(), var.getIndex(), mv);
                if (!constrParams[i].getType().equals(var.getType())
                        && !ClassHelper.isPrimitiveType(field.getType())) {
                    BytecodeExpr.checkCast(constrParams[i].getType(), mv);
                }
            } else {
                FieldNode field = compiler.methodNode.getDeclaringClass().getDeclaredField(name);
                mv.visitVarInsn(Opcodes.ALOAD, 0);
                if (field == null) // @Field
                    name = compiler.methodNode.getName() + "$" + name;
                mv.visitFieldInsn(Opcodes.GETFIELD,
                        BytecodeHelper.getClassInternalName(compiler.methodNode.getDeclaringClass()), name,
                        BytecodeHelper.getTypeDescription(constrParams[i].getType()));
            }
        }
    }

    if (superArgs != null) {
        final List<Expression> list = ((ArgumentListExpression) superArgs).getExpressions();
        for (int i = 0; i != list.size(); ++i)
            ((BytecodeExpr) list.get(i)).visit(mv);
    }

    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, classInternalName, "<init>",
            BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, constructorNode.getParameters()));
}

From source file:org.nanocontainer.picometer.PicoMeterMethodVisitor.java

License:Open Source License

public void visitTypeInsn(int opcode, String desc) {
    if (Opcodes.NEW == opcode) {
        lastType = desc;/*from  w  w  w . jav  a  2s . c o m*/
    } else {
        lastType = null;
    }
}

From source file:org.openquark.cal.internal.javamodel.AsmJavaBytecodeGenerator.java

License:Open Source License

/**
 * Encodes the Java code for a given Java operator expression.
 *   /*from  ww  w. j  a  va  2  s  .  c  om*/
 * @param operatorExpr the java operator expression  
 * @param context
 * @return JavaTypeName
 * @throws JavaGenerationException
 */
private static JavaTypeName encodeOperatorExpr(JavaExpression.OperatorExpression operatorExpr,
        GenerationContext context) throws JavaGenerationException {

    MethodVisitor mv = context.getMethodVisitor();

    JavaOperator operator = operatorExpr.getJavaOperator();
    String symbol = operator.getSymbol();
    JavaTypeName valueType = operator.getValueType();

    // Now carry out the operation according to its type.
    if (operator.isArithmeticOp()) {

        // Add the instructions to evaluate the first argument.
        JavaTypeName arg1Type = encodeExpr(operatorExpr.getArgument(0), context);

        if (operatorExpr instanceof OperatorExpression.Unary) {

            if (symbol.equals("-")) { // number negation

                mv.visitInsn(getNegateOpCode(arg1Type));
                return arg1Type;
            }

            throw new JavaGenerationException("Unknown unary arithmetic operator " + symbol + ".");
        }

        // Add an instruction to widen the argument if necessary.
        int wideningOpCode = getWideningOpCode(arg1Type, valueType);
        if (wideningOpCode != Opcodes.NOP) {
            mv.visitInsn(wideningOpCode);
        }

        // Add the instructions to evaluate the second argument.
        JavaTypeName arg2Type = encodeExpr(operatorExpr.getArgument(1), context);

        // Add an instruction to widen the argument if necessary.
        wideningOpCode = getWideningOpCode(arg2Type, valueType);
        if (wideningOpCode != Opcodes.NOP) {
            mv.visitInsn(wideningOpCode);
        }

        // Evaluate.
        mv.visitInsn(getArithmeticBinaryOpCode(symbol, valueType));

        return valueType;
    }

    if (operator.isBitOp()) {
        // Add the instructions to evaluate the first argument.
        JavaTypeName arg1Type = encodeExpr(operatorExpr.getArgument(0), context);

        // Add an instruction to widen the argument if necessary.
        int wideningOpCode = getWideningOpCode(arg1Type, valueType);
        if (wideningOpCode != Opcodes.NOP) {
            mv.visitInsn(wideningOpCode);
        }

        if (operatorExpr instanceof OperatorExpression.Unary) {
            if (symbol.equals("~")) { // number negation
                if (valueType == JavaTypeName.INT) {
                    mv.visitInsn(Opcodes.ICONST_M1);
                    mv.visitInsn(Opcodes.IXOR);
                    return valueType;
                } else if (valueType == JavaTypeName.LONG) {
                    encodePushLongValue(new Long(-1), context);
                    mv.visitInsn(Opcodes.LXOR);
                    return valueType;
                }
            }

            throw new JavaGenerationException("Unknown unary arithmetic operator " + symbol + ".");
        }

        // Add the instructions to evaluate the second argument.
        JavaTypeName arg2Type = encodeExpr(operatorExpr.getArgument(1), context);

        // If this is >>, >>>, or << we may need to narrow the second argument to an int
        if (symbol.equals(">>") || symbol.equals(">>>") || symbol.equals("<<")) {
            if (arg2Type == JavaTypeName.LONG) {
                mv.visitInsn(Opcodes.L2I);
            }
        } else {
            // Add an instruction to widen the argument if necessary.
            wideningOpCode = getWideningOpCode(arg2Type, valueType);
            if (wideningOpCode != Opcodes.NOP) {
                mv.visitInsn(wideningOpCode);
            }
        }

        // Evaluate.
        mv.visitInsn(getArithmeticBinaryOpCode(symbol, valueType));

        return valueType;

    }

    if (operator.isLogicalOp() || operator.isRelationalOp()) {

        // Logical op:    {"!", "&&", "||"}
        // Relational op: {">", ">=", "<", "<=", "==", "!="}

        Label trueContinuation = new Label();
        Label falseContinuation = new Label();

        encodeBooleanValuedOperatorHelper(operatorExpr, context, trueContinuation, falseContinuation);
        return encodeThenTrueElseFalse(trueContinuation, falseContinuation, context);
    }

    if (operator == JavaOperator.STRING_CONCATENATION) {

        // Create an uninitialized StringBuilder, duplicate the reference (so we can invoke the initializer).
        mv.visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder");
        mv.visitInsn(Opcodes.DUP);

        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V");

        // append the first arg.
        JavaTypeName firstArgType = encodeExpr(operatorExpr.getArgument(0), context);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                getAppendJVMDescriptor(firstArgType));

        // Append the results of evaluation of the second arg.
        // Note that, conveniently, StringBuilder has an append() method for all the different types.
        JavaTypeName secondArgType = encodeExpr(operatorExpr.getArgument(1), context);
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "append",
                getAppendJVMDescriptor(secondArgType));

        // Call toString() on the result.           
        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/lang/StringBuilder", "toString",
                "()Ljava/lang/String;");

        return JavaTypeName.STRING;
    }

    return encodeTernaryOperatorExpr((OperatorExpression.Ternary) operatorExpr, context);
}

From source file:org.openquark.cal.internal.javamodel.AsmJavaBytecodeGenerator.java

License:Open Source License

/**
 * Create the Java code for a given class instance creation expression. The new object reference will be pushed onto
 * the operand stack. /*from   w w  w. j a va  2 s .  c o m*/
 * 
 * @param cice the class instance creation expression
 * @param context 
 * @return JavaTypeName    
 * @throws JavaGenerationException
 */
private static JavaTypeName encodeClassInstanceCreationExpr(
        final JavaExpression.ClassInstanceCreationExpression cice, final GenerationContext context)
        throws JavaGenerationException {

    final MethodVisitor mv = context.getMethodVisitor();
    final JavaTypeName classType = cice.getClassName();
    if (classType instanceof JavaTypeName.Reference.Array) {

        final JavaTypeName.Reference.Array arrayType = (JavaTypeName.Reference.Array) classType;
        final int nSizedDims = cice.getNArgs();
        if (nSizedDims == 1) {

            //for example, new String[10][][] will hit this case since it has 1 sized dimension (even though a multi-dimensional array is 
            //being created

            //push the size of the dimension
            encodeExpr(cice.getArg(0), context);

            final JavaTypeName arrayElementType = arrayType.getIncrementalElementType();
            switch (arrayElementType.getTag()) {

            case JavaTypeName.VOID_TAG:
                throw new JavaGenerationException("Cannot have an array of with void element types.");

            case JavaTypeName.BOOLEAN_TAG:
            case JavaTypeName.BYTE_TAG:
            case JavaTypeName.SHORT_TAG:
            case JavaTypeName.CHAR_TAG:
            case JavaTypeName.INT_TAG:
            case JavaTypeName.LONG_TAG:
            case JavaTypeName.DOUBLE_TAG:
            case JavaTypeName.FLOAT_TAG: {
                //push the instruction to create a 1-dimensonal array of primitive values
                mv.visitIntInsn(Opcodes.NEWARRAY, getNewArrayArgCode(arrayElementType));
                break;
            }

            case JavaTypeName.ARRAY_TAG:
            case JavaTypeName.OBJECT_TAG: {
                //push the instruction to create a 1-dimensonal array of reference values
                mv.visitTypeInsn(Opcodes.ANEWARRAY, arrayElementType.getJVMInternalName());
                break;
            }

            default: {
                throw new IllegalArgumentException();
            }
            }

            return arrayType;

        } else {
            //the case of multi-dimensional arrays where more than 1 sizing dimension is supplied.

            // push args onto the stack
            for (int i = 0; i < nSizedDims; i++) {
                encodeExpr(cice.getArg(i), context);
            }

            mv.visitMultiANewArrayInsn(arrayType.getJVMInternalName(), nSizedDims);

            return arrayType;
        }

    } else if (classType instanceof JavaTypeName.Reference.Object) {

        String internalClassName = classType.getJVMInternalName();

        // create uninitialized object, duplicate the ref.
        mv.visitTypeInsn(Opcodes.NEW, internalClassName);
        mv.visitInsn(Opcodes.DUP);

        // push args onto the stack
        for (int i = 0, nArgs = cice.getNArgs(); i < nArgs; i++) {
            encodeExpr(cice.getArg(i), context);
        }

        //descriptor for the constructor
        StringBuilder descriptor = new StringBuilder("(");
        for (int i = 0, nArgs = cice.getNArgs(); i < nArgs; ++i) {
            descriptor.append(cice.getParamType(i).getJVMDescriptor());
        }
        descriptor.append(")V");

        // initialize - consumes the args and the duplicate reference.
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, internalClassName, "<init>", descriptor.toString());

        return classType;

    } else {
        throw new JavaGenerationException("cannot create a new instance of a primitive type.");
    }
}

From source file:org.parboiled.compiler.notNullVerification.MyMethodAdapter.java

License:Apache License

private void generateThrow(String exceptionClass, String descr, Label end) {
    String exceptionParamClass = "(Ljava/lang/String;)V";
    mv.visitTypeInsn(Opcodes.NEW, exceptionClass);
    mv.visitInsn(Opcodes.DUP);/*from  w w  w . j  a v  a 2 s  .  c o  m*/
    mv.visitLdcInsn(descr);
    mv.visitMethodInsn(Opcodes.INVOKESPECIAL, exceptionClass, NotNullVerifyingInstrumenter.CONSTRUCTOR_NAME,
            exceptionParamClass);
    mv.visitInsn(Opcodes.ATHROW);
    mv.visitLabel(end);

    instrumenter.myIsModification = true;
}

From source file:org.pareto4j.inspector.collections.InspectorMethodVisitor.java

License:Apache License

@Override
public void visitTypeInsn(int opcode, String type) {
    if (opcode == Opcodes.NEW) {
        ///*from   ww w  .ja v a2  s. com*/
        for (DelegateTypes delegateTypes : Profile.modify) {
            if (type.equals(delegateTypes.jdk)) {
                super.visitTypeInsn(Opcodes.NEW, delegateTypes.delegate);
                count.get(delegateTypes).inc();
                seenNew = true;
                return;
            }
        }
    }
    super.visitTypeInsn(opcode, type);
}

From source file:org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator.java

License:Apache License

private static ZeroOperandMutation areturnMutation() {
    return new ZeroOperandMutation() {

        public void apply(final int opCode, final MethodVisitor mv) {

            // Strategy translated from jumble BCEL code
            // if result is non-null make it null, otherwise hard case
            // for moment throw runtime exception
            final Label l1 = new Label();
            mv.visitJumpInsn(Opcodes.IFNONNULL, l1);
            mv.visitTypeInsn(Opcodes.NEW, "java/lang/RuntimeException");
            mv.visitInsn(Opcodes.DUP);//from ww w  .ja  v  a 2s  .  com
            mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/RuntimeException", "<init>", "()V", false);
            mv.visitInsn(Opcodes.ATHROW);
            mv.visitLabel(l1);
            mv.visitInsn(Opcodes.ACONST_NULL);
            mv.visitInsn(Opcodes.ARETURN);
        }

        public String decribe(final int opCode, final MethodInfo methodInfo) {
            return "mutated return of Object value for " + methodInfo.getDescription()
                    + " to ( if (x != null) null else throw new RuntimeException )";
        }

    };
}

From source file:org.sonar.java.bytecode.se.BytecodeEGWalkerExecuteTest.java

License:Open Source License

@Test
public void test_new() throws Exception {
    ProgramState programState = execute(new Instruction(Opcodes.NEW, "java.lang.Object"));
    assertStack(programState,/*from www  .  j  a  va  2 s .  c  o  m*/
            new Constraint[][] { { ObjectConstraint.NOT_NULL, new TypedConstraint("java.lang.Object") } });
}