Example usage for org.objectweb.asm Opcodes GETSTATIC

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

Introduction

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

Prototype

int GETSTATIC

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

Click Source Link

Usage

From source file:com.sun.fortress.compiler.OverloadSet.java

License:Open Source License

public void generateCall(MethodVisitor mv, int firstArgIndex, int one_if_method_closure) {
    if (!splitDone) {
        throw new CompilerError("Must split overload set before generating call(s)");
    }/*from  www  .ja va 2s .  co  m*/
    int l = specificDispatchOrder.length;

    TaggedFunctionName[] functionsToCall = new TaggedFunctionName[l];
    for (int i = 0; i < l; i++) {
        functionsToCall[i] = getFunctionToCall(specificDispatchOrder[i]);
    }

    //  create type structures for parameter types.
    TypeStructure[][] type_structures = new TypeStructure[l][];
    MultiMap[] spmaps = new MultiMap[l];
    TypeStructure[] return_type_structures = new TypeStructure[l];

    for (int i = 0; i < l; i++) {
        TaggedFunctionName f = functionsToCall[i];
        Functional eff = f.getF();
        List<Param> parameters = f.getParameters();
        MultiMap<String, TypeStructure> spmap = new MultiMap<String, TypeStructure>();
        spmaps[i] = spmap;
        List<StaticParam> staticParams = staticParametersOf(f.getF());

        Type rt = oa.getRangeType(eff);
        return_type_structures[i] = makeTypeStructure(rt, null, 1, 0, staticParams, eff);

        // skip parameters -- no 'this' for ordinary functions

        if (parameters.size() == 1 && oa.getDomainType(eff) instanceof TupleType) {
            TupleType tt = (TupleType) oa.getDomainType(eff);
            List<Type> tl = tt.getElements();
            int storeAtIndex = tl.size(); // DRC back this out + firstArgIndex;
            // little dubious here, not sure we are getting the
            // right type structures for generic methods.  what about 'self'
            TypeStructure[] f_type_structures = new TypeStructure[tl.size()];
            type_structures[i] = f_type_structures;

            for (int j = 0; j < tl.size(); j++) {
                Type t = STypesUtil.insertStaticParams(tl.get(j), tt.getInfo().getStaticParams());
                TypeStructure type_structure = makeTypeStructure(t, spmap, 1, storeAtIndex, staticParams, eff);
                f_type_structures[j] = type_structure;
                storeAtIndex = type_structure.successorIndex;
            }

        } else {

            int storeAtIndex = parameters.size(); // DRC back this out + firstArgIndex;
            TypeStructure[] f_type_structures = new TypeStructure[parameters.size()];
            type_structures[i] = f_type_structures;

            for (int j = 0; j < parameters.size(); j++) {
                if (j != selfIndex()) {
                    Type t = oa.getParamType(eff, j);
                    TypeStructure type_structure = makeTypeStructure(t, spmap, 1, storeAtIndex, staticParams,
                            eff);
                    f_type_structures[j] = type_structure;
                    storeAtIndex = type_structure.successorIndex;
                }
            }
        }
    }

    for (int i = 0; i < l; i++) {
        TaggedFunctionName f = functionsToCall[i];
        TypeStructure[] f_type_structures = type_structures[i];
        Label lookahead = null;
        boolean infer = false;

        List<StaticParam> staticParams = staticParametersOf(f.getF());
        boolean last_case = i == l - 1;

        /* Trust the static checker; no need to verify
         * applicability of the last one.
         * Also, static parameters will be provided by static checker for the last one
         */
        // Will need lookahead for the next one.
        lookahead = new Label();

        // if this was a generic method that needs inference, we need to include the receiver argument
        // in the inference even if the firstArgIndex is 1 so that we can include it in inference
        // and dispatch
        //KBN-WIP is there a cleaner way to do this?
        int offset = (f_type_structures.length == specificDispatchOrder[i].getParameters().size())
                ? firstArgIndex
                : 0;

        for (int j = 0; j < f_type_structures.length; j++) {
            if (j != selfIndex()) {
                //inference needed if the type structure contains generics TODO: do generics not appearing in the parameters make sense?  probably not, but might need to deal with them.
                if (f_type_structures[j].containsTypeVariables)
                    infer = true;
            }
        }

        if (infer || !last_case)
            for (int j = 0; j < f_type_structures.length; j++) {
                // Load actual parameter
                if (j != selfIndex()) {
                    mv.visitVarInsn(Opcodes.ALOAD, j + offset);
                    f_type_structures[j].emitInstanceOf(mv, lookahead, true);
                }
            }

        //Runtime inference for some cases
        if (infer) {
            @SuppressWarnings("unchecked")
            MultiMap<String, TypeStructure> staticTss = spmaps[i];

            int localCount = f_type_structures[f_type_structures.length - 1].successorIndex; //counter for use storing stuff such as lower bounds

            //create type structures for lower bounds
            Map<StaticParam, TypeStructure> lowerBounds = new HashMap<StaticParam, TypeStructure>();
            for (StaticParam sp : staticParams)
                lowerBounds.put(sp, makeParamTypeStructure(sp, localCount++, TypeStructure.COVARIANT));

            //gather different types of bounds into Multimaps for use later
            MultiMap<StaticParam, StaticParam> relativeLowerBounds = new MultiMap<StaticParam, StaticParam>(); //form X :> Y
            MultiMap<StaticParam, Type> genericUpperBounds = new MultiMap<StaticParam, Type>(); //form X <: GenericStem[\ ... \] where Y appears in ...
            MultiMap<StaticParam, Type> concreteUpperBounds = new MultiMap<StaticParam, Type>(); //form X <: T where T contains no type variables
            for (int outer = 0; outer < staticParams.size(); outer++) {
                StaticParam outerSP = staticParams.get(outer);
                for (BaseType bt : outerSP.getExtendsClause()) {
                    if (bt instanceof VarType) { // outerSP <: bt so outerSP will provide a lower bound on BT
                        String varName = ((VarType) bt).getName().getText();
                        boolean found = false;
                        for (int inner = 0; inner < outer && !found; inner++) {
                            StaticParam innerSP = staticParams.get(inner);
                            if (varName.equals(innerSP.getName().getText())) {
                                relativeLowerBounds.putItem(innerSP, outerSP); // outerSP provides a lower bound on innerSP
                                found = true;
                            }
                        }
                        if (!found)
                            throw new CompilerError(
                                    "Bad Scoping of static parameters found during runtime inference codegen:"
                                            + varName + " not declared before used in a bound");
                    } else if (bt instanceof AnyType) { //figure out if concrete or generic
                        //do nothing - no need to add meaningless upper bound
                    } else if (bt instanceof NamedType) {
                        if (isGeneric(bt))
                            genericUpperBounds.putItem(outerSP, bt);
                        else
                            concreteUpperBounds.putItem(outerSP, bt);
                    }
                }
            }

            //infer and load RTTIs
            for (int j = 0; j < staticParams.size(); j++) {
                StaticParam sp = staticParams.get(staticParams.size() - 1 - j); //reverse order due to left to right scoping
                Set<TypeStructure> instances = staticTss.get(sp.getName().getText());

                //sort static parameters by their variance and put into
                //arrays using their local variable number
                List<Integer> invariantInstances = new ArrayList<Integer>();
                List<Integer> covariantInstances = new ArrayList<Integer>();
                List<Integer> contravariantInstances = new ArrayList<Integer>();
                if (instances != null)
                    for (TypeStructure ts : instances) {
                        switch (ts.variance) {
                        case TypeStructure.INVARIANT:
                            invariantInstances.add(ts.localIndex);
                            break;
                        case TypeStructure.CONTRAVARIANT:
                            contravariantInstances.add(ts.localIndex);
                            break;
                        case TypeStructure.COVARIANT:
                            covariantInstances.add(ts.localIndex);
                            break;
                        default:
                            throw new CompilerError("Unexpected Variance on TypeStructure during "
                                    + "generic instantiation analysis for overload dispatch");
                        }
                    }

                // if any invariant instances, we must use that RTTI and check that 
                //1) any other invariant instances are the same type (each subtypes the other)
                //2) any covariant instances are subtypes of the invariant instance
                //3) any contravariant instances are supertypes of the invariant instance
                if (invariantInstances.size() > 0) {

                    //a valid instantiation must use the runtime type
                    //of all invariant instances (which must all be the same)
                    //thus, wlog, we can use the first invariant instance
                    int RTTItoUse = invariantInstances.get(0);

                    //1) for each other invariant instance, they must be the same
                    //which we test by checking that each subtypes the other
                    for (int k = 1; k < invariantInstances.size(); k++) {
                        int RTTIcompare = invariantInstances.get(k);
                        //RTTItoUse.runtimeSupertypeOf(RTTIcompare)
                        mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                        mv.visitVarInsn(Opcodes.ALOAD, RTTIcompare);
                        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                        mv.visitJumpInsn(Opcodes.IFEQ, lookahead); //if false fail
                        //RTTIcompare.runtimeSupertypeOf(RTTItoUse)
                        mv.visitVarInsn(Opcodes.ALOAD, RTTIcompare);
                        mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                        mv.visitJumpInsn(Opcodes.IFEQ, lookahead); //if false fail
                    }

                    //2) for each covariant instance, the runtime type (RTTIcompare) must be a
                    // subtype of the instantiated type (RTTItoUse)
                    for (int RTTIcompare : covariantInstances) {
                        //RTTItoUse.runtimeSupertypeOf(RTTIcompare)
                        mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                        mv.visitVarInsn(Opcodes.ALOAD, RTTIcompare);
                        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                        mv.visitJumpInsn(Opcodes.IFEQ, lookahead); //if false fail
                    }

                    //3) for each contravariant instance, the instantiated type (RTTItoUse) must be a 
                    // subtype of the runtime type (RTTIcompare)
                    for (int RTTIcompare : contravariantInstances) {
                        //RTTIcompare.runtimeSupertypeOf(RTTItoUse)
                        mv.visitVarInsn(Opcodes.ALOAD, RTTIcompare);
                        mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                        mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                        mv.visitJumpInsn(Opcodes.IFEQ, lookahead); //if false fail
                    }

                    //check lower bounds given by other variables
                    Set<StaticParam> relativeLB = relativeLowerBounds.get(sp);
                    if (relativeLB != null)
                        for (StaticParam lb : relativeLB) {
                            //RTTItoUse.runtimeSupertypeOf(otherLB)
                            int otherOffset = lowerBounds.get(lb).localIndex;
                            mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                            mv.visitVarInsn(Opcodes.ALOAD, otherOffset);
                            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                    Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                            mv.visitJumpInsn(Opcodes.IFEQ, lookahead); //if false fail
                        }

                    //verify meets upper bounds
                    Set<Type> concreteUB = concreteUpperBounds.get(sp);
                    if (concreteUB != null)
                        for (Type cub : concreteUB) {
                            //transform into RTTI
                            generateRTTIfromStaticType(mv, cub);
                            mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                    Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                            mv.visitJumpInsn(Opcodes.IFEQ, lookahead); //if false fail
                        }

                    //generate more bounds for generic upper bounds
                    Set<Type> genericUB = genericUpperBounds.get(sp);
                    if (genericUB != null)
                        for (Type gub : genericUB) {
                            TypeStructure newTS = makeTypeStructure(gub, staticTss, TypeStructure.COVARIANT,
                                    localCount, staticParams, null);
                            localCount = newTS.successorIndex;
                            mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                            newTS.emitInstanceOf(mv, lookahead, false); //fail if RTTItoUse doesn't have this structure
                        }

                    //checks out, so store the RTTI we will use into the lower bound for this parameter
                    mv.visitVarInsn(Opcodes.ALOAD, RTTItoUse);
                    int index = lowerBounds.get(sp).localIndex;
                    mv.visitVarInsn(Opcodes.ASTORE, index);

                } else if (contravariantInstances.size() == 0) { //we can do inference for covariant-only occurrences

                    boolean started = false;
                    if (covariantInstances.size() > 0) {
                        started = true;
                        mv.visitVarInsn(Opcodes.ALOAD, covariantInstances.get(0));

                        for (int k = 1; k < covariantInstances.size(); k++) {
                            mv.visitVarInsn(Opcodes.ALOAD, covariantInstances.get(k));
                            //TODO: allow unions
                            joinStackNoUnion(mv, lookahead); //fails if cannot join w/o union
                        }
                    }

                    //incorporate lower bounds 
                    Set<StaticParam> relativeLB = relativeLowerBounds.get(sp);
                    if (relativeLB != null)
                        for (StaticParam lb : relativeLB) {
                            mv.visitVarInsn(Opcodes.ALOAD, lowerBounds.get(lb).localIndex);
                            if (started) { //join it in
                                //TODO: allow unions
                                joinStackNoUnion(mv, lookahead);
                            } else { //start with this lower bound
                                started = true;
                            }
                        }

                    if (started) {

                        //verify meets upper bounds
                        Set<Type> concreteUB = concreteUpperBounds.get(sp);
                        if (concreteUB != null)
                            for (Type cub : concreteUB) {
                                Label cleanup = new Label();
                                Label next = new Label();

                                mv.visitInsn(Opcodes.DUP);
                                generateRTTIfromStaticType(mv, cub); //transform concrete bound into RTTI
                                mv.visitInsn(Opcodes.SWAP); // LB <: CUB
                                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Naming.RTTI_CONTAINER_TYPE,
                                        Naming.RTTI_SUBTYPE_METHOD_NAME, Naming.RTTI_SUBTYPE_METHOD_SIG);
                                mv.visitJumpInsn(Opcodes.IFEQ, cleanup);
                                mv.visitJumpInsn(Opcodes.GOTO, next);
                                mv.visitLabel(cleanup);
                                mv.visitInsn(Opcodes.POP);
                                mv.visitJumpInsn(Opcodes.GOTO, lookahead);
                                mv.visitLabel(next);
                            }

                        //checks out, so store to lower bound of sp
                        int index = lowerBounds.get(sp).localIndex;
                        mv.visitVarInsn(Opcodes.ASTORE, index);

                        //generate more bounds for generic upper bounds
                        Set<Type> genericUB = genericUpperBounds.get(sp);
                        if (genericUB != null)
                            for (Type gub : genericUB) {
                                TypeStructure newTS = makeTypeStructure(gub, staticTss, TypeStructure.COVARIANT,
                                        localCount, staticParams, null);
                                localCount = newTS.successorIndex;
                                mv.visitVarInsn(Opcodes.ALOAD, index);
                                newTS.emitInstanceOf(mv, lookahead, false); //fail if candidate doesn't have this structure
                            }

                    } else {
                        //Bottom is ok - no need to check upper bounds
                        //or generate lower bounds
                        mv.visitFieldInsn(Opcodes.GETSTATIC, Naming.RT_VALUES_PKG + "VoidRTTI",
                                Naming.RTTI_SINGLETON, Naming.RTTI_CONTAINER_DESC);
                        int index = lowerBounds.get(sp).localIndex;
                        mv.visitVarInsn(Opcodes.ASTORE, index);

                    }

                } else { //otherwise, we might need to do inference which is not implemented yet
                    throw new CompilerError("non-invariant inference with contravariance not implemented");
                }
            }

            //load instance cache table to avoid classloader when possible
            String tableName = this.generateClosureTableName(specificDispatchOrder[i]); //use original function for table name
            String tableOwner = this.generateClosureTableOwner(f);
            mv.visitFieldInsn(Opcodes.GETSTATIC, tableOwner, tableName, Naming.CACHE_TABLE_DESC);

            //load template class name
            String arrow = this.instanceArrowSchema(f); //NamingCzar.makeArrowDescriptor(f.getParameters(), f.getReturnType(),f.tagA);
            String functionName = this.functionName(f);

            String templateClass = Naming.genericFunctionPkgClass(Naming.dotToSep(f.tagA.getText()),
                    functionName, Naming.LEFT_OXFORD + Naming.RIGHT_OXFORD, arrow);

            if (otherOverloadKeys.contains(templateClass)) {
                templateClass = Naming.genericFunctionPkgClass(Naming.dotToSep(f.tagA.getText()),
                        NamingCzar.mangleAwayFromOverload(functionName),
                        Naming.LEFT_OXFORD + Naming.RIGHT_OXFORD, arrow);
                //templateClass = NamingCzar.mangleAwayFromOverload(templateClass);
            }

            mv.visitLdcInsn(templateClass);

            String ic_sig;
            if (staticParams.size() > 6) { //use an array
                //load the function: RThelpers.loadClosureClass:(BAlongTree,String,RTTI[])
                String paramList = Naming.CACHE_TABLE_DESC + NamingCzar.descString
                        + Naming.RTTI_CONTAINER_ARRAY_DESC;
                ic_sig = Naming.makeMethodDesc(paramList, Naming.internalToDesc(NamingCzar.internalObject));

                mv.visitLdcInsn(staticParams.size());
                mv.visitTypeInsn(Opcodes.ANEWARRAY, Naming.RTTI_CONTAINER_TYPE);

                //dup array enough times to store RTTIs into it  //know need at least 6 more
                mv.visitInsn(Opcodes.DUP); //first one to get arrays as top two elts on stack

                for (int numDups = staticParams.size() - 1; numDups > 0; numDups = numDups / 2)
                    mv.visitInsn(Opcodes.DUP2);
                if (staticParams.size() % 2 == 0)
                    mv.visitInsn(Opcodes.DUP); //if even, started halving with an odd number, so needs one last

                //store parameters into array
                for (int k = 0; k < staticParams.size(); k++) {
                    int index = lowerBounds.get(staticParams.get(k)).localIndex;
                    mv.visitLdcInsn(k); //index is the static param number
                    mv.visitVarInsn(Opcodes.ALOAD, index);
                    mv.visitInsn(Opcodes.AASTORE);
                }

                //array left on stack

            } else {
                //load the function: RTHelpers.loadClosureClass:(BAlongTree,(String,RTTI)^n)Object
                ic_sig = InstantiatingClassloader.jvmSignatureForOnePlusNTypes(
                        Naming.CACHE_TABLE_TYPE + ";L" + NamingCzar.internalString, staticParams.size(),
                        Naming.RTTI_CONTAINER_TYPE, Naming.internalToDesc(NamingCzar.internalObject));

                //load parameter RTTIs
                for (int k = 0; k < staticParams.size(); k++) {
                    int index = lowerBounds.get(staticParams.get(k)).localIndex;
                    mv.visitVarInsn(Opcodes.ALOAD, index);
                }

            }
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Naming.RT_HELPERS, "loadClosureClass", ic_sig);

            //cast to object arrow
            int numParams = f.getParameters().size();
            String objectAbstractArrow = NamingCzar.objectAbstractArrowTypeForNParams(numParams);
            InstantiatingClassloader.generalizedCastTo(mv, objectAbstractArrow);

            //if a method parameters converted
            //loadThisForMethods(mv);

            //load parameters
            for (int j = 0; j < f_type_structures.length; j++) {
                // Load actual parameter
                if (j != selfIndex()) {
                    mv.visitVarInsn(Opcodes.ALOAD, j); // DRC back this out+ one_if_method_closure); // + firstArgIndex); KBN if a method, parameters already converted
                    //no cast needed here - done by apply method
                }
            }

            //call apply method
            String objectArrow = NamingCzar.objectArrowTypeForNParams(numParams);
            String applySig = InstantiatingClassloader.jvmSignatureForNTypes(numParams,
                    NamingCzar.internalObject, Naming.internalToDesc(NamingCzar.internalObject));
            mv.visitMethodInsn(Opcodes.INVOKEINTERFACE, objectArrow, Naming.APPLY_METHOD, applySig);

            //cast to correct return type
            Type f_return = f.getReturnType();
            if (f_return instanceof BottomType) {
                CodeGen.castToBottom(mv);
            } else {
                String returnType = NamingCzar.makeBoxedTypeName(f_return, f.tagA);
                InstantiatingClassloader.generalizedCastTo(mv, returnType);
            }
        } else {

            //no inferences needed
            loadThisForMethods(mv);

            for (int j = 0; j < f_type_structures.length; j++) {
                // Load actual parameter
                if (j != selfIndex()) {
                    mv.visitVarInsn(Opcodes.ALOAD, j + firstArgIndex);
                    InstantiatingClassloader.generalizedCastTo(mv, f_type_structures[j].fullname);
                }
            }

            String sig = jvmSignatureFor(f);

            invokeParticularMethod(mv, f, sig);
            Type f_return = f.getReturnType();
            if (f_return instanceof BottomType) {
                CodeGen.castToBottom(mv);
            }
        }

        mv.visitInsn(Opcodes.ARETURN);

        if (lookahead != null)
            mv.visitLabel(lookahead);
    }
}

From source file:com.sun.fortress.compiler.OverloadSet.java

License:Open Source License

private void generateRTTIfromStaticType(MethodVisitor mv, Type t) {
    if (t instanceof TraitType) {
        List<StaticArg> args = ((TraitType) t).getArgs();
        if (args != null && args.size() > 0) {
            //recurse
            for (StaticArg sa : args) {
                if (sa instanceof TypeArg) {
                    generateRTTIfromStaticType(mv, ((TypeArg) sa).getTypeArg());
                } else {
                    throw new CompilerError("Expected TypeArg for RTTI generation");
                }//from   w  w  w  . jav  a  2 s  . c o  m
            }
            //find component for type and call factory
            String typeName = NamingCzar.jvmTypeDesc(t, this.ifNone, false);
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, typeName + Naming.RTTI_CLASS_SUFFIX, Naming.RTTI_FACTORY,
                    Naming.rttiFactorySig(args.size()));
        } else {
            //find component for type and grab singleton RTTI
            String typeName = NamingCzar.jvmTypeDesc(t, this.ifNone, false);
            mv.visitFieldInsn(Opcodes.GETSTATIC, typeName + Naming.RTTI_CLASS_SUFFIX, Naming.RTTI_SINGLETON,
                    Naming.RTTI_CONTAINER_DESC);
        }
    } else {
        throw new CompilerError("Expected Trait Type for RTTI generation");
    }
}

From source file:com.sun.fortress.runtimeSystem.MethodInstantiater.java

License:Open Source License

public void visitFieldInsn(int opcode, String owner, String name, String orig_desc) {
    owner = xlation.getTypeName(owner);//from  w  w  w  .j  a va  2  s. c o m
    name = xlation.getTypeName(name);
    String desc = xlation.getFieldDesc(orig_desc);
    if (owner.endsWith(FACTORY_SUFFIX) && name.equals(Naming.RTTI_SINGLETON)) {
        rttiReference(owner);
    } else if (opcode == Opcodes.PUTSTATIC && name.equals(Naming.CLOSURE_FIELD_NAME)) {
        String unwrapped_desc = xlation.getFieldDesc(orig_desc, true);
        String wrapped_desc = xlation.getFieldDesc(orig_desc, false);
        if (!wrapped_desc.equals(unwrapped_desc)) {
            /* This is a hack; when a closure looks different depending on
             * how its descriptor translates (wrapped vs not), that means that
             * there will be a second closure field, and it needs to be initialized.
             */
            mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, unwrapped_desc);
            mv.visitFieldInsn(Opcodes.GETSTATIC, owner, name, unwrapped_desc);
            mv.visitFieldInsn(Opcodes.PUTSTATIC, owner, name, wrapped_desc);

        } else {
            mv.visitFieldInsn(opcode, owner, name, desc);
        }
    } else {
        mv.visitFieldInsn(opcode, owner, name, desc);
    }
}

From source file:com.sun.fortress.runtimeSystem.MethodInstantiater.java

License:Open Source License

/**
 * @param owner//w  w  w .j  a v a2  s.co m
 */
public void rttiReference(String owner) {
    int lox_index = owner.indexOf(Naming.LEFT_OXFORD);
    if (lox_index != -1) {
        int rox_index = owner.lastIndexOf(Naming.RIGHT_OXFORD);
        String stem = owner.substring(0, lox_index);
        List<String> parameters = RTHelpers.extractStringParameters(owner, lox_index, rox_index);

        // special case hack for tuples, and arrows
        if (stem.equals(Naming.TUPLE_TAG) || stem.equals("ConcreteTuple")) {
            stem = Naming.tupleRTTIclass(parameters.size());
        } else if (stem.equals(Naming.ARROW_TAG)
                || stem.equals(InstantiatingClassloader.ABSTRACT_ + Naming.ARROW_TAG)) {
            stem = Naming.arrowRTTIclass(parameters.size());
        } else if (stem.contains(Naming.ENVELOPE) && stem.endsWith(Naming.ARROW_TAG)) {
            stem = Naming.arrowRTTIclass(parameters.size());
        } else if (stem.equals(Naming.UNION)) {

        } else {
            // a real class that might have opr parameters.
            // Obtain the xldata for the original type
            Naming.XlationData xldata = icl.xlationForGeneric(owner.substring(0, rox_index + 1));
            List<Boolean> filter = xldata.isOprKind();
            List<String> opr_params = Useful.retain(parameters, filter);
            parameters = Useful.exclude(parameters, filter);
            stem = Naming.oprArgAnnotatedRTTI(stem, opr_params);
        }

        //recursive call
        for (String parameter : parameters) {
            rttiReference(parameter);
        }

        //call the factory
        String stem_rtti = Naming.stemClassToRTTIclass(stem);
        String fact_sig = Naming.rttiFactorySig(parameters.size());
        mv.visitMethodInsn(Opcodes.INVOKESTATIC, stem_rtti, Naming.RTTI_FACTORY, fact_sig);
    } else {
        //just get the field
        String ownerRTTIc = Naming.stemClassToRTTIclass(owner);
        if (ownerRTTIc.startsWith(Naming.SNOWMAN)) {
            ownerRTTIc = ownerRTTIc.replaceFirst(Naming.SNOWMAN, Naming.RT_VALUES_PKG + "FVoid");
        }
        mv.visitFieldInsn(Opcodes.GETSTATIC, ownerRTTIc, Naming.RTTI_SINGLETON, Naming.RTTI_CONTAINER_DESC);
    }
}

From source file:com.trigersoft.jaque.expression.ExpressionMethodVisitor.java

License:Apache License

@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
    Expression e;/*from   w  w w.  ja  v a  2  s  .  c o m*/
    switch (opcode) {
    case Opcodes.GETFIELD:
        try {
            e = Expression.get(_exprStack.pop(), name);
        } catch (NoSuchFieldException nsfe) {
            throw new RuntimeException(nsfe);
        }
        break;
    case Opcodes.GETSTATIC:
        try {
            e = Expression.get(_classVisitor.getClass(Type.getObjectType(owner)), name);
        } catch (NoSuchFieldException nsfe) {
            throw new RuntimeException(nsfe);
        }
        break;
    case Opcodes.PUTFIELD:
    case Opcodes.PUTSTATIC:
    default:
        throw notLambda(opcode);
    }

    _exprStack.push(e);
}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.DynamicBootstrapUnit.java

public void init() {
    ProgramValueTypeAdapter types = environment.getValueTypeAdapter();
    BytecodeExpression classSource = types.constant(getEnvironment());
    TypeWidget dynamicLinker = types.adaptInternal(DynamicLinker.class);
    FieldDefinition field = createField(dynamicLinker, "bootstrap");
    field.addModifier(Opcodes.ACC_STATIC | Opcodes.ACC_FINAL);
    MethodGenerator sl = createMethod("<clinit>");
    sl.setModifier(Opcodes.ACC_STATIC);//from  w  w  w .  j  a  v  a  2  s .c  om
    sl.add(classSource);
    sl.add(new BytecodeSequence() {
        @Override
        public void generate(CodeEmitter code) {
            final MethodVisitor mv = code.getMethodVisitor();
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Dynamic.class), "createDynamicLinker",
                    MethodType.methodType(DynamicLinker.class, ASMClassSource.class).toMethodDescriptorString(),
                    false);
            mv.visitFieldInsn(Opcodes.PUTSTATIC, Dynamic.DYNAMIC_INTERNAL_NAME, "bootstrap",
                    Type.getDescriptor(DynamicLinker.class));
            mv.visitInsn(Opcodes.RETURN);

        }
    });

    MethodGenerator mgen = createStaticMethod(Dynamic.DYNAMIC_BOOTSTRAP_METHOD);
    TypeWidget callSite = types.adaptInternal(CallSite.class);
    TypeWidget lookup = types.adaptInternal(MethodHandles.Lookup.class);
    TypeWidget methodType = types.adaptInternal(MethodType.class);
    mgen.setReturnType(callSite);
    AssignableValue lu = mgen.addArgument("lookup", lookup);
    AssignableValue name = mgen.addArgument("name", BaseTypeAdapter.STRING);
    AssignableValue sig = mgen.addArgument("sig", methodType);
    final String desc = MethodType.methodType(CallSite.class, // ...that will return a CallSite object, ...
            MethodHandles.Lookup.class, // ... when given a lookup object, ...
            String.class, // ... the operation name, ...
            MethodType.class, // ... and the signature at the call site.
            DynamicLinker.class).toMethodDescriptorString();

    mgen.add(lu.read());
    mgen.add(name.read());
    mgen.add(sig.read());

    mgen.add(new BytecodeSequence() {
        @Override
        public void generate(CodeEmitter code) {
            final MethodVisitor mv = code.getMethodVisitor();
            mv.visitFieldInsn(Opcodes.GETSTATIC, Dynamic.DYNAMIC_INTERNAL_NAME, "bootstrap",
                    Type.getDescriptor(DynamicLinker.class));
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Dynamic.class), "link", desc, false);
            mv.visitInsn(Opcodes.ARETURN);
        }
    });

}

From source file:com.yahoo.yqlplus.engine.internal.bytecode.EnumConstant.java

@Override
public void generate(CodeEmitter environment) {
    environment.getMethodVisitor().visitFieldInsn(Opcodes.GETSTATIC,
            Type.getInternalName(value.getDeclaringClass()), value.name(),
            Type.getDescriptor(value.getDeclaringClass()));
}

From source file:com.yahoo.yqlplus.engine.internal.compiler.BytecodeArithmeticExpression.java

@Override
public void generate(CodeEmitter code) {
    MethodVisitor mv = code.getMethodVisitor();
    Label isNull = new Label();
    TypeWidget mathType = getType().unboxed();

    if (!mathType.isPrimitive() || op == ArithmeticOperation.POW) {
        mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(Maths.class), "INSTANCE",
                Type.getDescriptor(Maths.class));
        mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(ArithmeticOperation.class), op.name(),
                Type.getDescriptor(ArithmeticOperation.class));
    }/*from www .j  av  a2  s.com*/

    CodeEmitter.Unification out = code.unifyAs(mathType, leftExpr, rightExpr, isNull, isNull, isNull);
    // now we have both sides unified as (if possible) a primitive type

    // compute the result
    if (mathType.isPrimitive()) {
        switch (op) {
        case ADD:
            mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.IADD));
            break;
        case SUB:
            mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.ISUB));
            break;
        case MULT:
            mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.IMUL));
            break;
        case DIV:
            mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.IDIV));
            break;
        case MOD:
            mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.IREM));
            break;
        case POW:
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Maths.class), "binaryMath",
                    Type.getMethodDescriptor(mathType.getJVMType(), Type.getType(ArithmeticOperation.class),
                            mathType.getJVMType(), mathType.getJVMType()),
                    false);
            break;
        default:
            throw new ProgramCompileException(loc, "Unknown BinaryMath operation: " + op);

        }
    } else if (mathType.getValueCoreType() == YQLCoreType.ANY) {
        String desc = Type.getMethodDescriptor(getType().getJVMType(), Type.getType(Maths.class),
                Type.getType(ArithmeticOperation.class), leftExpr.getType().boxed().getJVMType(),
                rightExpr.getType().boxed().getJVMType());
        mv.visitInvokeDynamicInsn("dyn:callMethod:binaryMath", desc, Dynamic.H_DYNALIB_BOOTSTRAP);
    } else {
        throw new ProgramCompileException(loc, "Math operation %s is not defined for type %s", op,
                mathType.getJVMType());
    }

    if (!getType().isPrimitive() && mathType.isPrimitive()) {
        code.box(mathType);
    }

    if (out.nullPossible) {
        Label done = new Label();
        mv.visitJumpInsn(Opcodes.GOTO, done);
        mv.visitLabel(isNull);
        if (!mathType.isPrimitive() || op == ArithmeticOperation.POW) {
            mv.visitInsn(Opcodes.POP2);
        }
        mv.visitInsn(Opcodes.ACONST_NULL);
        mv.visitLabel(done);
    }
}

From source file:com.yahoo.yqlplus.engine.internal.compiler.BytecodeNegateExpression.java

@Override
public void generate(CodeEmitter code) {
    MethodVisitor mv = code.getMethodVisitor();
    Label isNull = new Label();
    TypeWidget mathType = getType().unboxed();

    if (!mathType.isPrimitive()) {
        mv.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(Maths.class), "INSTANCE",
                Type.getDescriptor(Maths.class));
    }/*from ww w .j  a  v a 2  s.c  om*/

    boolean maybeNull = code.cast(mathType, leftExpr.getType(), isNull);
    // compute the result
    if (mathType.isPrimitive()) {
        mv.visitInsn(mathType.getJVMType().getOpcode(Opcodes.INEG));
    } else if (mathType.getValueCoreType() == YQLCoreType.ANY) {
        String desc = Type.getMethodDescriptor(getType().getJVMType(), Type.getType(Maths.class),
                leftExpr.getType().getJVMType());
        mv.visitInvokeDynamicInsn("dyn:callMethod:negate", desc, Dynamic.H_DYNALIB_BOOTSTRAP);
    } else {
        throw new ProgramCompileException(loc, "Math operation NEGATE is not defined for type %s",
                mathType.getJVMType());
    }

    if (!getType().isPrimitive() && mathType.isPrimitive()) {
        code.box(mathType);
    }

    if (maybeNull) {
        Label done = new Label();
        mv.visitJumpInsn(Opcodes.GOTO, done);
        mv.visitLabel(isNull);
        mv.visitInsn(Opcodes.ACONST_NULL);
        mv.visitLabel(done);
    }
}

From source file:com.yahoo.yqlplus.engine.internal.plan.types.base.AnyTypeWidget.java

@Override
public ComparisonAdapter getComparisionAdapter() {
    Preconditions.checkState(!isPrimitive(), "BaseTypeWidget should not be handling a primitive type");
    return new ComparisonAdapter() {
        @Override//from ww w. j ava2  s . c om
        public void coerceBoolean(CodeEmitter scope, Label isTrue, Label isFalse, Label isNull) {
            // null or true
            scope.nullTest(AnyTypeWidget.getInstance(), isNull);
            Label popTrue = new Label();
            scope.emitInstanceOf(AnyTypeWidget.getInstance(), Boolean.class, popTrue);
            final MethodVisitor mv = scope.getMethodVisitor();
            mv.visitMethodInsn(Opcodes.GETSTATIC, Type.getInternalName(Boolean.class), "TRUE",
                    Type.getMethodDescriptor(Type.getType(Boolean.class)), false);
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Boolean.class), "equals",
                    Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), false);
            mv.visitJumpInsn(Opcodes.IFEQ, isFalse);
            mv.visitJumpInsn(Opcodes.GOTO, isTrue);
            mv.visitLabel(popTrue);
            scope.pop(AnyTypeWidget.getInstance());
            mv.visitJumpInsn(Opcodes.GOTO, isTrue);
        }
    };
}