/*
* Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.dyn;
import java.dyn.*;
import java.lang.reflect.*;
import sun.dyn.util.*;
/**
* Adapters which mediate between incoming calls which are generic
* and outgoing calls which are not. Any call can be represented generically
* boxing up its arguments, and (on return) unboxing the return value.
*
* A call is "generic" (in MethodHandle terms) if its MethodType features
* only Object arguments. A non-generic call therefore features
* primitives and/or reference types other than Object.
* An adapter has types for its incoming and outgoing calls.
* The incoming call type is simply determined by the adapter's type
* (the MethodType it presents to callers). The outgoing call type
* is determined by the adapter's target (a MethodHandle that the adapter
* either binds internally or else takes as a leading argument).
* (To stretch the term, adapter-like method handles may have multiple
* targets or be polymorphic across multiple call types.)
* @author jrose
*/
class FromGeneric {
// type for the outgoing call (may have primitives, etc.)
private final MethodType targetType;
// type of the outgoing call internal to the adapter
private final MethodType internalType;
// prototype adapter (clone and customize for each new target!)
private final Adapter adapter;
// entry point for adapter (Adapter mh, a...) => ...
private final MethodHandle entryPoint;
// unboxing invoker of type (MH, Object**N) => raw return value
// it makes up the difference of internalType => targetType
private final MethodHandle unboxingInvoker;
// conversion which boxes a the target's raw return value
private final MethodHandle returnConversion;
/** Compute and cache information common to all unboxing adapters
* that can call out to targets of the erasure-family of the given erased type.
*/
private FromGeneric(MethodType targetType) {
this.targetType = targetType;
MethodType internalType0;
// the target invoker will generally need casts on reference arguments
Adapter ad = findAdapter(internalType0 = targetType.erase());
if (ad != null) {
// Immediate hit to exactly the adapter we want,
// with no monkeying around with primitive types.
this.internalType = internalType0;
this.adapter = ad;
this.entryPoint = ad.prototypeEntryPoint();
this.returnConversion = computeReturnConversion(targetType, internalType0);
this.unboxingInvoker = computeUnboxingInvoker(targetType, internalType0);
return;
}
// outgoing primitive arguments will be wrapped; unwrap them
MethodType primsAsObj = MethodTypeImpl.of(targetType).primArgsAsBoxes();
MethodType objArgsRawRet = MethodTypeImpl.of(primsAsObj).primsAsInts();
if (objArgsRawRet != targetType)
ad = findAdapter(internalType0 = objArgsRawRet);
if (ad == null) {
ad = buildAdapterFromBytecodes(internalType0 = targetType);
}
this.internalType = internalType0;
this.adapter = ad;
MethodType tepType = targetType.insertParameterTypes(0, adapter.getClass());
this.entryPoint = ad.prototypeEntryPoint();
this.returnConversion = computeReturnConversion(targetType, internalType0);
this.unboxingInvoker = computeUnboxingInvoker(targetType, internalType0);
}
/**
* The typed target will be called according to targetType.
* The adapter code will in fact see the raw result from internalType,
* and must box it into an object. Produce a converter for this.
*/
private static MethodHandle computeReturnConversion(
MethodType targetType, MethodType internalType) {
Class> tret = targetType.returnType();
Class> iret = internalType.returnType();
Wrapper wrap = Wrapper.forBasicType(tret);
if (!iret.isPrimitive()) {
assert(iret == Object.class);
return ValueConversions.identity();
} else if (wrap.primitiveType() == iret) {
return ValueConversions.box(wrap, false);
} else {
assert(tret == double.class ? iret == long.class : iret == int.class);
return ValueConversions.boxRaw(wrap, false);
}
}
/**
* The typed target will need an exact invocation point; provide it here.
* The adapter will possibly need to make a slightly different call,
* so adapt the invoker. This way, the logic for making up the
* difference between what the adapter can call and what the target
* needs can be cached once per type.
*/
private static MethodHandle computeUnboxingInvoker(
MethodType targetType, MethodType internalType) {
// All the adapters we have here have reference-untyped internal calls.
assert(internalType == internalType.erase());
MethodHandle invoker = MethodHandles.exactInvoker(targetType);
// cast all narrow reference types, unbox all primitive arguments:
MethodType fixArgsType = internalType.changeReturnType(targetType.returnType());
MethodHandle fixArgs = AdapterMethodHandle.convertArguments(Access.TOKEN,
invoker, Invokers.invokerType(fixArgsType),
invoker.type(), null);
if (fixArgs == null)
throw new InternalError("bad fixArgs");
// reinterpret the calling sequence as raw:
MethodHandle retyper = AdapterMethodHandle.makeRetypeRaw(Access.TOKEN,
Invokers.invokerType(internalType), fixArgs);
if (retyper == null)
throw new InternalError("bad retyper");
return retyper;
}
Adapter makeInstance(MethodHandle typedTarget) {
MethodType type = typedTarget.type();
if (type == targetType) {
return adapter.makeInstance(entryPoint, unboxingInvoker, returnConversion, typedTarget);
}
// my erased-type is not exactly the same as the desired type
assert(type.erase() == targetType); // else we are busted
MethodHandle invoker = computeUnboxingInvoker(type, internalType);
return adapter.makeInstance(entryPoint, invoker, returnConversion, typedTarget);
}
/** Build an adapter of the given generic type, which invokes typedTarget
* on the incoming arguments, after unboxing as necessary.
* The return value is boxed if necessary.
* @param genericType the required type of the result
* @param typedTarget the target
* @return an adapter method handle
*/
public static MethodHandle make(MethodHandle typedTarget) {
MethodType type = typedTarget.type();
if (type == type.generic()) return typedTarget;
return FromGeneric.of(type).makeInstance(typedTarget);
}
/** Return the adapter information for this type's erasure. */
static FromGeneric of(MethodType type) {
MethodTypeImpl form = MethodTypeImpl.of(type);
FromGeneric fromGen = form.fromGeneric;
if (fromGen == null)
form.fromGeneric = fromGen = new FromGeneric(form.erasedType());
return fromGen;
}
public String toString() {
return "FromGeneric"+targetType;
}
/* Create an adapter that handles spreading calls for the given type. */
static Adapter findAdapter(MethodType internalType) {
MethodType entryType = internalType.generic();
MethodTypeImpl form = MethodTypeImpl.of(internalType);
Class> rtype = internalType.returnType();
int argc = form.parameterCount();
int lac = form.longPrimitiveParameterCount();
int iac = form.primitiveParameterCount() - lac;
String intsAndLongs = (iac > 0 ? "I"+iac : "")+(lac > 0 ? "J"+lac : "");
String rawReturn = String.valueOf(Wrapper.forPrimitiveType(rtype).basicTypeChar());
String cname0 = rawReturn + argc;
String cname1 = "A" + argc;
String[] cnames = { cname0+intsAndLongs, cname0, cname1+intsAndLongs, cname1 };
String iname = "invoke_"+cname0+intsAndLongs;
// e.g., D5I2, D5, L5I2, L5; invoke_D5
for (String cname : cnames) {
Class extends Adapter> acls = Adapter.findSubClass(cname);
if (acls == null) continue;
// see if it has the required invoke method
MethodHandle entryPoint = null;
try {
entryPoint = MethodHandleImpl.IMPL_LOOKUP.findSpecial(acls, iname, entryType, acls);
} catch (NoAccessException ex) {
}
if (entryPoint == null) continue;
Constructor extends Adapter> ctor = null;
try {
ctor = acls.getDeclaredConstructor(MethodHandle.class);
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
}
if (ctor == null) continue;
try {
// Produce an instance configured as a prototype.
return ctor.newInstance(entryPoint);
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException wex) {
Throwable ex = wex.getTargetException();
if (ex instanceof Error) throw (Error)ex;
if (ex instanceof RuntimeException) throw (RuntimeException)ex;
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
}
}
return null;
}
static Adapter buildAdapterFromBytecodes(MethodType internalType) {
throw new UnsupportedOperationException("NYI");
}
/**
* This adapter takes some untyped arguments, and returns an untyped result.
* Internally, it applies the invoker to the target, which causes the
* objects to be unboxed; the result is a raw type in L/I/J/F/D.
* This result is passed to convert, which is responsible for
* converting the raw result into a boxed object.
* The invoker is kept separate from the target because it can be
* generated once per type erasure family, and reused across adapters.
*/
static abstract class Adapter extends JavaMethodHandle {
/*
* class X<> extends Adapter {
* (MH, Object**N)=>raw(R) invoker;
* (any**N)=>R target;
* raw(R)=>Object convert;
* Object invoke(Object**N a) = convert(invoker(target, a...))
* }
*/
protected final MethodHandle invoker; // (MH, Object**N) => raw(R)
protected final MethodHandle convert; // raw(R) => Object
protected final MethodHandle target; // (any**N) => R
@Override
public String toString() {
return target.toString();
}
protected boolean isPrototype() { return target == null; }
protected Adapter(MethodHandle entryPoint) {
this(entryPoint, null, entryPoint, null);
assert(isPrototype());
}
protected MethodHandle prototypeEntryPoint() {
if (!isPrototype()) throw new InternalError();
return convert;
}
protected Adapter(MethodHandle entryPoint,
MethodHandle invoker, MethodHandle convert, MethodHandle target) {
super(entryPoint);
this.invoker = invoker;
this.convert = convert;
this.target = target;
}
/** Make a copy of self, with new fields. */
protected abstract Adapter makeInstance(MethodHandle entryPoint,
MethodHandle invoker, MethodHandle convert, MethodHandle target);
// { return new ThisType(entryPoint, convert, target); }
/// Conversions on the value returned from the target.
protected Object convert_L(Object result) throws Throwable { return convert.