List of usage examples for org.objectweb.asm MethodVisitor visitTableSwitchInsn
public void visitTableSwitchInsn(final int min, final int max, final Label dflt, final Label... labels)
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 . j a va 2 s .c om 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:com.asakusafw.dag.compiler.builtin.BranchOperatorGenerator.java
License:Apache License
static void branch(MethodVisitor method, Context context, UserOperator operator, LocalVarRef input, Map<OperatorProperty, FieldRef> dependencies) { OperatorOutput[] outputs = outputs(context, operator); Label[] caseLabels = Stream.of(outputs).map(o -> new Label()).toArray(Label[]::new); Label defaultLabel = new Label(); Label endLabel = new Label(); method.visitMethodInsn(Opcodes.INVOKEVIRTUAL, typeOf(Enum.class).getInternalName(), "ordinal", Type.getMethodDescriptor(Type.INT_TYPE), false); method.visitTableSwitchInsn(0, caseLabels.length - 1, defaultLabel, caseLabels); for (int i = 0; i < outputs.length; i++) { method.visitLabel(caseLabels[i]); FieldRef ref = Invariants.requireNonNull(dependencies.get(outputs[i])); ref.load(method);//w w w . ja v a2 s .c om input.load(method); invokeResultAdd(method); method.visitJumpInsn(Opcodes.GOTO, endLabel); } method.visitLabel(defaultLabel); getNew(method, Descriptions.typeOf(AssertionError.class)); method.visitInsn(Opcodes.ATHROW); method.visitLabel(endLabel); }
From source file:com.asakusafw.dag.compiler.directio.OutputPatternSerDeGenerator.java
License:Apache License
private static void putGetProperty(ClassWriter writer, DataModelReference reference, OutputPattern pattern) { List<PropertyReference> properties = pattern.getResourcePattern().stream() .filter(s -> s.getKind() == OutputPattern.SourceKind.PROPERTY).map(CompiledSegment::getTarget) .collect(Collectors.toList()); if (properties.isEmpty()) { return;/* w ww . j av a 2s .com*/ } MethodVisitor v = writer.visitMethod(Opcodes.ACC_PUBLIC, "getProperty", Type.getMethodDescriptor(typeOf(Object.class), typeOf(Object.class), typeOf(int.class)), null, null); LocalVarRef object = cast(v, 1, reference.getDeclaration()); LocalVarRef index = new LocalVarRef(Opcodes.ILOAD, 2); Label[] caseLabels = properties.stream().map(o -> new Label()).toArray(Label[]::new); Label defaultLabel = new Label(); index.load(v); v.visitTableSwitchInsn(0, caseLabels.length - 1, defaultLabel, caseLabels); for (int i = 0, n = properties.size(); i < n; i++) { v.visitLabel(caseLabels[i]); PropertyReference property = properties.get(i); object.load(v); getOption(v, property); v.visitInsn(Opcodes.ARETURN); } v.visitLabel(defaultLabel); getNew(v, Descriptions.typeOf(AssertionError.class)); v.visitInsn(Opcodes.ATHROW); v.visitMaxs(0, 0); v.visitEnd(); }
From source file:com.google.gwtorm.protobuf.CodecGen.java
License:Apache License
private static void decodeMessage(final JavaColumnModel[] myFields, final MethodVisitor mv, final DecodeCGS cgs) throws OrmException { final Label nextField = new Label(); final Label end = new Label(); mv.visitLabel(nextField);/*from ww w . j av a 2 s . c om*/ // while (!ci.isAtEnd) { ... cgs.call("readTag", Type.INT_TYPE); mv.visitInsn(DUP); mv.visitVarInsn(ISTORE, cgs.tagVar); cgs.push(3); mv.visitInsn(IUSHR); final Label badField = new Label(); final int[] caseTags = new int[1 + myFields.length]; final Label[] caseLabels = new Label[caseTags.length]; caseTags[0] = 0; caseLabels[0] = new Label(); int gaps = 0; for (int i = 1; i < caseTags.length; i++) { caseTags[i] = myFields[i - 1].getColumnID(); caseLabels[i] = new Label(); gaps += caseTags[i] - (caseTags[i - 1] + 1); } if (2 * gaps / 3 <= myFields.length) { final int min = 0; final int max = caseTags[caseTags.length - 1]; final Label[] table = new Label[max + 1]; Arrays.fill(table, badField); for (int idx = 0; idx < caseTags.length; idx++) { table[caseTags[idx]] = caseLabels[idx]; } mv.visitTableSwitchInsn(min, max, badField, table); } else { mv.visitLookupSwitchInsn(badField, caseTags, caseLabels); } mv.visitLabel(caseLabels[0]); mv.visitJumpInsn(GOTO, end); for (int idx = 1; idx < caseTags.length; idx++) { final JavaColumnModel f = myFields[idx - 1]; mv.visitLabel(caseLabels[idx]); if (f.isNested()) { final Label load = new Label(); cgs.setFieldReference(f); cgs.pushFieldValue(); mv.visitJumpInsn(IFNONNULL, load); cgs.fieldSetBegin(); mv.visitTypeInsn(NEW, Type.getType(f.getNestedClass()).getInternalName()); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, Type.getType(f.getNestedClass()).getInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); cgs.fieldSetEnd(); // read the length, set a new limit, decode the message, validate // we stopped at the end of it as expected. // mv.visitLabel(load); final int limitVar = cgs.newLocal(); cgs.pushCodedInputStream(); cgs.call("readRawVarint32", Type.INT_TYPE); cgs.ncallInt("pushLimit", Type.INT_TYPE); mv.visitVarInsn(ISTORE, limitVar); decodeMessage(sort(f.getNestedColumns()), mv, cgs); cgs.pushCodedInputStream(); mv.visitVarInsn(ILOAD, limitVar); cgs.ncallInt("popLimit", Type.VOID_TYPE); cgs.freeLocal(limitVar); } else { decodeScalar(mv, cgs, f); } mv.visitJumpInsn(GOTO, nextField); } // default: mv.visitLabel(badField); cgs.pushCodedInputStream(); mv.visitVarInsn(ILOAD, cgs.tagVar); cgs.ncallInt("skipField", Type.BOOLEAN_TYPE); mv.visitInsn(POP); mv.visitJumpInsn(GOTO, nextField); mv.visitLabel(end); cgs.pushCodedInputStream(); cgs.push(0); cgs.ncallInt("checkLastTagWas", Type.VOID_TYPE); }
From source file:com.googlecode.d2j.converter.IR2JConverter.java
License:Apache License
private void reBuildInstructions(IrMethod ir, MethodVisitor asm) { asm = new LdcOptimizeAdapter(asm); int maxLocalIndex = 0; for (Local local : ir.locals) { maxLocalIndex = Math.max(maxLocalIndex, local._ls_index); }//from w w w .j a v a 2s . co m Map<String, Integer> lockMap = new HashMap<String, Integer>(); for (Stmt st : ir.stmts) { switch (st.st) { case LABEL: LabelStmt labelStmt = (LabelStmt) st; Label label = (Label) labelStmt.tag; asm.visitLabel(label); if (labelStmt.lineNumber >= 0) { asm.visitLineNumber(labelStmt.lineNumber, label); } break; case ASSIGN: { E2Stmt e2 = (E2Stmt) st; Value v1 = e2.op1; Value v2 = e2.op2; switch (v1.vt) { case LOCAL: Local local = ((Local) v1); int i = local._ls_index; if (v2.vt == VT.LOCAL && (i == ((Local) v2)._ls_index)) {// continue; } boolean skipOrg = false; if (v1.valueType.charAt(0) == 'I') {// check for IINC if (v2.vt == VT.ADD) { E2Expr e = (E2Expr) v2; if ((e.op1 == local && e.op2.vt == VT.CONSTANT) || (e.op2 == local && e.op1.vt == VT.CONSTANT)) { int increment = (Integer) ((Constant) (e.op1 == local ? e.op2 : e.op1)).value; if (increment >= Short.MIN_VALUE && increment <= Short.MAX_VALUE) { asm.visitIincInsn(i, increment); skipOrg = true; } } } else if (v2.vt == VT.SUB) { E2Expr e = (E2Expr) v2; if (e.op1 == local && e.op2.vt == VT.CONSTANT) { int increment = -(Integer) ((Constant) e.op2).value; if (increment >= Short.MIN_VALUE && increment <= Short.MAX_VALUE) { asm.visitIincInsn(i, increment); skipOrg = true; } } } } if (!skipOrg) { accept(v2, asm); if (i >= 0) { asm.visitVarInsn(getOpcode(v1, ISTORE), i); } else if (!v1.valueType.equals("V")) { // skip void type locals switch (v1.valueType.charAt(0)) { case 'J': case 'D': asm.visitInsn(POP2); break; default: asm.visitInsn(POP); break; } } } break; case STATIC_FIELD: { StaticFieldExpr fe = (StaticFieldExpr) v1; accept(v2, asm); insertI2x(v2.valueType, fe.type, asm); asm.visitFieldInsn(PUTSTATIC, toInternal(fe.owner), fe.name, fe.type); break; } case FIELD: { FieldExpr fe = (FieldExpr) v1; accept(fe.op, asm); accept(v2, asm); insertI2x(v2.valueType, fe.type, asm); asm.visitFieldInsn(PUTFIELD, toInternal(fe.owner), fe.name, fe.type); break; } case ARRAY: ArrayExpr ae = (ArrayExpr) v1; accept(ae.op1, asm); accept(ae.op2, asm); accept(v2, asm); String tp1 = ae.op1.valueType; String tp2 = ae.valueType; if (tp1.charAt(0) == '[') { String arrayElementType = tp1.substring(1); insertI2x(v2.valueType, arrayElementType, asm); asm.visitInsn(getOpcode(arrayElementType, IASTORE)); } else { asm.visitInsn(getOpcode(tp2, IASTORE)); } break; } } break; case IDENTITY: { E2Stmt e2 = (E2Stmt) st; if (e2.op2.vt == VT.EXCEPTION_REF) { int index = ((Local) e2.op1)._ls_index; if (index >= 0) { asm.visitVarInsn(ASTORE, index); } else { asm.visitInsn(POP); } } } break; case FILL_ARRAY_DATA: { E2Stmt e2 = (E2Stmt) st; Object arrayData = ((Constant) e2.getOp2()).value; int arraySize = Array.getLength(arrayData); String arrayValueType = e2.getOp1().valueType; String elementType; if (arrayValueType.charAt(0) == '[') { elementType = arrayValueType.substring(1); } else { elementType = "I"; } int iastoreOP = getOpcode(elementType, IASTORE); accept(e2.getOp1(), asm); for (int i = 0; i < arraySize; i++) { asm.visitInsn(DUP); asm.visitLdcInsn(i); asm.visitLdcInsn(Array.get(arrayData, i)); asm.visitInsn(iastoreOP); } asm.visitInsn(POP); } break; case GOTO: asm.visitJumpInsn(GOTO, (Label) ((GotoStmt) st).target.tag); break; case IF: reBuildJumpInstructions((IfStmt) st, asm); break; case LOCK: { Value v = ((UnopStmt) st).op; accept(v, asm); if (optimizeSynchronized) { switch (v.vt) { case LOCAL: // FIXME do we have to disable local due to OptSyncTest ? // break; case CONSTANT: { String key; if (v.vt == VT.LOCAL) { key = "L" + ((Local) v)._ls_index; } else { key = "C" + ((Constant) v).value; } Integer integer = lockMap.get(key); int nIndex = integer != null ? integer : ++maxLocalIndex; asm.visitInsn(DUP); asm.visitVarInsn(getOpcode(v, ISTORE), nIndex); lockMap.put(key, nIndex); } break; default: throw new RuntimeException(); } } asm.visitInsn(MONITORENTER); } break; case UNLOCK: { Value v = ((UnopStmt) st).op; if (optimizeSynchronized) { switch (v.vt) { case LOCAL: case CONSTANT: { String key; if (v.vt == VT.LOCAL) { key = "L" + ((Local) v)._ls_index; } else { key = "C" + ((Constant) v).value; } Integer integer = lockMap.get(key); if (integer != null) { asm.visitVarInsn(getOpcode(v, ILOAD), integer); } else { accept(v, asm); } } break; // TODO other default: { accept(v, asm); break; } } } else { accept(v, asm); } asm.visitInsn(MONITOREXIT); } break; case NOP: break; case RETURN: { Value v = ((UnopStmt) st).op; accept(v, asm); insertI2x(v.valueType, ir.ret, asm); asm.visitInsn(getOpcode(v, IRETURN)); } break; case RETURN_VOID: asm.visitInsn(RETURN); break; case LOOKUP_SWITCH: { LookupSwitchStmt lss = (LookupSwitchStmt) st; accept(lss.op, asm); Label targets[] = new Label[lss.targets.length]; for (int i = 0; i < targets.length; i++) { targets[i] = (Label) lss.targets[i].tag; } asm.visitLookupSwitchInsn((Label) lss.defaultTarget.tag, lss.lookupValues, targets); } break; case TABLE_SWITCH: { TableSwitchStmt tss = (TableSwitchStmt) st; accept(tss.op, asm); Label targets[] = new Label[tss.targets.length]; for (int i = 0; i < targets.length; i++) { targets[i] = (Label) tss.targets[i].tag; } asm.visitTableSwitchInsn(tss.lowIndex, tss.lowIndex + targets.length - 1, (Label) tss.defaultTarget.tag, targets); } break; case THROW: accept(((UnopStmt) st).op, asm); asm.visitInsn(ATHROW); break; case VOID_INVOKE: InvokeExpr invokeExpr = (InvokeExpr) st.getOp(); accept(invokeExpr, asm); String ret = invokeExpr.ret; if (invokeExpr.vt == VT.INVOKE_NEW) { asm.visitInsn(POP); } else if (!"V".equals(ret)) { switch (ret.charAt(0)) { case 'J': case 'D': asm.visitInsn(POP2); break; default: asm.visitInsn(POP); break; } } break; default: throw new RuntimeException("not support st: " + st.st); } } }
From source file:com.googlecode.ddom.weaver.asm.MethodVisitorTee.java
License:Apache License
public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels) { for (MethodVisitor visitor : visitors) { visitor.visitTableSwitchInsn(min, max, dflt, labels); }/* w w w.j a v a2 s . c om*/ }
From source file:com.sun.fortress.compiler.asmbytecodeoptimizer.TableSwitchInsn.java
License:Open Source License
public void toAsm(MethodVisitor mv) { mv.visitTableSwitchInsn(min, max, dflt, labels); }
From source file:erjang.ETuple.java
License:Apache License
private static void create_tuple_nth(int n_cells, ClassAdapter cw, String this_class_name) { MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "elm", "(I)" + ETERM_TYPE.getDescriptor(), null, null); mv.visitCode();// ww w . j a v a2s . c o m Label dflt = new Label(); Label[] labels = new Label[n_cells]; for (int i = 0; i < n_cells; i++) { labels[i] = new Label(); } mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitTableSwitchInsn(1, n_cells, dflt, labels); for (int zbase = 0; zbase < n_cells; zbase++) { mv.visitLabel(labels[zbase]); mv.visitVarInsn(Opcodes.ALOAD, 0); // load this String field = "elem" + (zbase + 1); mv.visitFieldInsn(Opcodes.GETFIELD, this_class_name, field, ETERM_TYPE.getDescriptor()); mv.visitInsn(Opcodes.ARETURN); } mv.visitLabel(dflt); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, ETUPLE_NAME, "bad_nth", "(I)" + ETERM_TYPE.getDescriptor()); mv.visitInsn(Opcodes.ARETURN); // make compiler happy mv.visitMaxs(3, 2); mv.visitEnd(); }
From source file:erjang.ETuple.java
License:Apache License
private static void create_tuple_set(int n_cells, ClassAdapter cw, String this_class_name) { MethodVisitor mv; mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "set", "(I" + ETERM_TYPE.getDescriptor() + ")V", null, null); mv.visitCode();/*from www. j a v a 2 s . c o m*/ Label dflt = new Label(); Label[] labels = new Label[n_cells]; for (int i = 0; i < n_cells; i++) { labels[i] = new Label(); } mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitTableSwitchInsn(1, n_cells, dflt, labels); for (int zbase = 0; zbase < n_cells; zbase++) { mv.visitLabel(labels[zbase]); mv.visitVarInsn(Opcodes.ALOAD, 0); // load this mv.visitVarInsn(Opcodes.ALOAD, 2); // load term String field = "elem" + (zbase + 1); mv.visitFieldInsn(Opcodes.PUTFIELD, this_class_name, field, ETERM_TYPE.getDescriptor()); mv.visitInsn(Opcodes.RETURN); } mv.visitLabel(dflt); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ILOAD, 1); mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, ETUPLE_NAME, "bad_nth", "(I)" + ETERM_TYPE.getDescriptor()); mv.visitInsn(Opcodes.POP); mv.visitInsn(Opcodes.RETURN); // make compiler happy mv.visitMaxs(3, 3); mv.visitEnd(); }
From source file:gnu.classpath.tools.rmic.ClassRmicCompiler.java
License:Open Source License
private void generateSkel() throws IOException { skelname = fullclassname + "_Skel"; String skelclassname = classname + "_Skel"; File file = new File(destination == null ? "" : destination + File.separator + skelname.replace('.', File.separatorChar) + ".class"); if (verbose)//from w ww. j ava 2 s .c o m System.out.println("[Generating class " + skelname + "]"); final ClassWriter skel = new ClassWriter(true); classInternalName = skelname.replace('.', '/'); skel.visit(Opcodes.V1_1, Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, classInternalName, Type.getInternalName(Object.class), null, new String[] { Type.getType(Skeleton.class).getInternalName() }); skel.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "interfaceHash", Type.LONG_TYPE.getDescriptor(), null, new Long(RMIHashes.getInterfaceHash(clazz))); skel.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_STATIC + Opcodes.ACC_FINAL, "operations", Type.getDescriptor(Operation[].class), null, null); MethodVisitor clinit = skel.visitMethod(Opcodes.ACC_STATIC, "<clinit>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}), null, null); fillOperationArray(clinit); clinit.visitInsn(Opcodes.RETURN); clinit.visitMaxs(-1, -1); // no arg public constructor MethodVisitor init = skel.visitMethod(Opcodes.ACC_PUBLIC, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {}), null, null); init.visitVarInsn(Opcodes.ALOAD, 0); init.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] {})); init.visitInsn(Opcodes.RETURN); init.visitMaxs(-1, -1); /* * public Operation[] getOperations() * returns a clone of the operations array */ MethodVisitor getOp = skel.visitMethod(Opcodes.ACC_PUBLIC, "getOperations", Type.getMethodDescriptor(Type.getType(Operation[].class), new Type[] {}), null, null); getOp.visitFieldInsn(Opcodes.GETSTATIC, classInternalName, "operations", Type.getDescriptor(Operation[].class)); getOp.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "clone", Type.getMethodDescriptor(Type.getType(Object.class), new Type[] {})); getOp.visitTypeInsn(Opcodes.CHECKCAST, typeArg(Operation[].class)); getOp.visitInsn(Opcodes.ARETURN); getOp.visitMaxs(-1, -1); // public void dispatch(Remote, RemoteCall, int opnum, long hash) MethodVisitor dispatch = skel.visitMethod(Opcodes.ACC_PUBLIC, "dispatch", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(Remote.class), Type.getType(RemoteCall.class), Type.INT_TYPE, Type.LONG_TYPE }), null, new String[] { Type.getInternalName(Exception.class) }); Variables var = new Variables(); var.declare("this"); var.declare("remoteobj"); var.declare("remotecall"); var.declare("opnum"); var.declareWide("hash"); /* * if opnum >= 0 * XXX it is unclear why there is handling of negative opnums */ dispatch.visitVarInsn(Opcodes.ILOAD, var.get("opnum")); Label nonNegativeOpnum = new Label(); Label opnumSet = new Label(); dispatch.visitJumpInsn(Opcodes.IFGE, nonNegativeOpnum); for (int i = 0; i < remotemethods.length; i++) { // assign opnum if hash matches supplied hash dispatch.visitVarInsn(Opcodes.LLOAD, var.get("hash")); dispatch.visitLdcInsn(new Long(remotemethods[i].hash)); Label notIt = new Label(); dispatch.visitInsn(Opcodes.LCMP); dispatch.visitJumpInsn(Opcodes.IFNE, notIt); // opnum = <opnum> dispatch.visitLdcInsn(new Integer(i)); dispatch.visitVarInsn(Opcodes.ISTORE, var.get("opnum")); dispatch.visitJumpInsn(Opcodes.GOTO, opnumSet); dispatch.visitLabel(notIt); } // throw new SkeletonMismatchException Label mismatch = new Label(); dispatch.visitJumpInsn(Opcodes.GOTO, mismatch); dispatch.visitLabel(nonNegativeOpnum); // if opnum is already set, check that the hash matches the interface dispatch.visitVarInsn(Opcodes.LLOAD, var.get("hash")); dispatch.visitFieldInsn(Opcodes.GETSTATIC, classInternalName, "interfaceHash", Type.LONG_TYPE.getDescriptor()); dispatch.visitInsn(Opcodes.LCMP); dispatch.visitJumpInsn(Opcodes.IFEQ, opnumSet); dispatch.visitLabel(mismatch); dispatch.visitTypeInsn(Opcodes.NEW, typeArg(SkeletonMismatchException.class)); dispatch.visitInsn(Opcodes.DUP); dispatch.visitLdcInsn("interface hash mismatch"); dispatch.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(SkeletonMismatchException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(String.class) })); dispatch.visitInsn(Opcodes.ATHROW); // opnum has been set dispatch.visitLabel(opnumSet); dispatch.visitVarInsn(Opcodes.ALOAD, var.get("remoteobj")); dispatch.visitTypeInsn(Opcodes.CHECKCAST, typeArg(clazz)); dispatch.visitVarInsn(Opcodes.ASTORE, var.get("remoteobj")); Label deflt = new Label(); Label[] methLabels = new Label[remotemethods.length]; for (int i = 0; i < methLabels.length; i++) methLabels[i] = new Label(); // switch on opnum dispatch.visitVarInsn(Opcodes.ILOAD, var.get("opnum")); dispatch.visitTableSwitchInsn(0, remotemethods.length - 1, deflt, methLabels); // Method dispatch for (int i = 0; i < remotemethods.length; i++) { dispatch.visitLabel(methLabels[i]); Method m = remotemethods[i].meth; generateMethodSkel(dispatch, m, var); } dispatch.visitLabel(deflt); dispatch.visitTypeInsn(Opcodes.NEW, typeArg(UnmarshalException.class)); dispatch.visitInsn(Opcodes.DUP); dispatch.visitLdcInsn("invalid method number"); dispatch.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(UnmarshalException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(String.class) })); dispatch.visitInsn(Opcodes.ATHROW); dispatch.visitMaxs(-1, -1); skel.visitEnd(); byte[] classData = skel.toByteArray(); if (!noWrite) { if (file.exists()) file.delete(); if (file.getParentFile() != null) file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); fos.write(classData); fos.flush(); fos.close(); } }