MethodHandleImpl.java 60.9 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * 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.
24 25
 */

26
package java.lang.invoke;
27

28
import sun.invoke.util.VerifyType;
29 30 31 32 33
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
34 35 36
import sun.invoke.empty.Empty;
import sun.invoke.util.ValueConversions;
import sun.invoke.util.Wrapper;
37
import sun.misc.Unsafe;
38 39
import static java.lang.invoke.MethodHandleStatics.*;
import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
40 41

/**
42
 * Trusted implementation code for MethodHandle.
43 44
 * @author jrose
 */
45
/*non-public*/ abstract class MethodHandleImpl {
46 47 48 49
    /// Factory methods to create method handles:

    private static final MemberName.Factory LOOKUP = MemberName.Factory.INSTANCE;

50
    static void initStatics() {
51 52 53 54
        // Trigger preceding sequence.
    }

    /** Look up a given method.
55
     * Callable only from sun.invoke and related packages.
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
     * <p>
     * The resulting method handle type will be of the given type,
     * with a receiver type {@code rcvc} prepended if the member is not static.
     * <p>
     * Access checks are made as of the given lookup class.
     * In particular, if the method is protected and {@code defc} is in a
     * different package from the lookup class, then {@code rcvc} must be
     * the lookup class or a subclass.
     * @param token Proof that the lookup class has access to this package.
     * @param member Resolved method or constructor to call.
     * @param name Name of the desired method.
     * @param rcvc Receiver type of desired non-static method (else null)
     * @param doDispatch whether the method handle will test the receiver type
     * @param lookupClass access-check relative to this class
     * @return a direct handle to the matching method
71
     * @throws IllegalAccessException if the given method cannot be accessed by the lookup class
72
     */
73 74
    static
    MethodHandle findMethod(MemberName method,
75
                            boolean doDispatch, Class<?> lookupClass) throws IllegalAccessException {
76
        MethodType mtype = method.getMethodType();
77
        if (!method.isStatic()) {
78 79
            // adjust the advertised receiver type to be exactly the one requested
            // (in the case of invokespecial, this will be the calling class)
80
            Class<?> recvType = method.getDeclaringClass();
81
            mtype = mtype.insertParameterTypes(0, recvType);
82 83 84
        }
        DirectMethodHandle mh = new DirectMethodHandle(mtype, method, doDispatch, lookupClass);
        if (!mh.isValid())
85
            throw method.makeAccessException("no access", lookupClass);
86
        assert(mh.type() == mtype);
87 88 89 90
        if (!method.isVarargs())
            return mh;
        else
            return mh.asVarargsCollector(mtype.parameterType(mtype.parameterCount()-1));
91 92
    }

93 94
    static
    MethodHandle makeAllocator(MethodHandle rawConstructor) {
95
        MethodType rawConType = rawConstructor.type();
96
        Class<?> allocateClass = rawConType.parameterType(0);
97
        // Wrap the raw (unsafe) constructor with the allocation of a suitable object.
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        if (AdapterMethodHandle.canCollectArguments(rawConType, MethodType.methodType(allocateClass), 0, true)) {
            // allocator(arg...)
            // [fold]=> cookedConstructor(obj=allocate(C), arg...)
            // [dup,collect]=> identity(obj, void=rawConstructor(obj, arg...))
            MethodHandle returner = MethodHandles.identity(allocateClass);
            MethodType ctype = rawConType.insertParameterTypes(0, allocateClass).changeReturnType(allocateClass);
            MethodHandle  cookedConstructor = AdapterMethodHandle.makeCollectArguments(returner, rawConstructor, 1, false);
            assert(cookedConstructor.type().equals(ctype));
            ctype = ctype.dropParameterTypes(0, 1);
            cookedConstructor = AdapterMethodHandle.makeCollectArguments(cookedConstructor, returner, 0, true);
            MethodHandle allocator = new AllocateObject(allocateClass);
            // allocate() => new C(void)
            assert(allocator.type().equals(MethodType.methodType(allocateClass)));
            ctype = ctype.dropParameterTypes(0, 1);
            MethodHandle fold = foldArguments(cookedConstructor, ctype, 0, allocator);
            return fold;
        }
        assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
116
        MethodHandle allocator
117
            = AllocateObject.make(allocateClass, rawConstructor);
118 119 120 121 122
        assert(allocator.type()
               .equals(rawConType.dropParameterTypes(0, 1).changeReturnType(rawConType.parameterType(0))));
        return allocator;
    }

123
    static final class AllocateObject<C> extends BoundMethodHandle {
124 125 126 127 128 129 130
        private static final Unsafe unsafe = Unsafe.getUnsafe();

        private final Class<C> allocateClass;
        private final MethodHandle rawConstructor;

        private AllocateObject(MethodHandle invoker,
                               Class<C> allocateClass, MethodHandle rawConstructor) {
131
            super(invoker);
132 133
            this.allocateClass = allocateClass;
            this.rawConstructor = rawConstructor;
134 135 136 137 138 139 140
            assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
        }
        // for allocation only:
        private AllocateObject(Class<C> allocateClass) {
            super(ALLOCATE.asType(MethodType.methodType(allocateClass, AllocateObject.class)));
            this.allocateClass = allocateClass;
            this.rawConstructor = null;
141
        }
142
        static MethodHandle make(Class<?> allocateClass, MethodHandle rawConstructor) {
143
            assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
144 145 146 147 148 149 150
            MethodType rawConType = rawConstructor.type();
            assert(rawConType.parameterType(0) == allocateClass);
            MethodType newType = rawConType.dropParameterTypes(0, 1).changeReturnType(allocateClass);
            int nargs = rawConType.parameterCount() - 1;
            if (nargs < INVOKES.length) {
                MethodHandle invoke = INVOKES[nargs];
                MethodType conType = CON_TYPES[nargs];
151
                MethodHandle gcon = convertArguments(rawConstructor, conType, rawConType, 0);
152 153 154
                if (gcon == null)  return null;
                MethodHandle galloc = new AllocateObject(invoke, allocateClass, gcon);
                assert(galloc.type() == newType.generic());
155
                return convertArguments(galloc, newType, galloc.type(), 0);
156 157 158
            } else {
                MethodHandle invoke = VARARGS_INVOKE;
                MethodType conType = CON_TYPES[nargs];
159
                MethodHandle gcon = spreadArgumentsFromPos(rawConstructor, conType, 1);
160 161
                if (gcon == null)  return null;
                MethodHandle galloc = new AllocateObject(invoke, allocateClass, gcon);
162
                return collectArguments(galloc, newType, 1, null);
163 164 165
            }
        }
        @Override
166
        String debugString() {
167
            return addTypeString(allocateClass.getSimpleName(), this);
168 169 170 171 172 173 174
        }
        @SuppressWarnings("unchecked")
        private C allocate() throws InstantiationException {
            return (C) unsafe.allocateInstance(allocateClass);
        }
        private C invoke_V(Object... av) throws Throwable {
            C obj = allocate();
175
            rawConstructor.invokeExact((Object)obj, av);
176 177 178 179
            return obj;
        }
        private C invoke_L0() throws Throwable {
            C obj = allocate();
180
            rawConstructor.invokeExact((Object)obj);
181 182 183 184
            return obj;
        }
        private C invoke_L1(Object a0) throws Throwable {
            C obj = allocate();
185
            rawConstructor.invokeExact((Object)obj, a0);
186 187 188 189
            return obj;
        }
        private C invoke_L2(Object a0, Object a1) throws Throwable {
            C obj = allocate();
190
            rawConstructor.invokeExact((Object)obj, a0, a1);
191 192 193 194
            return obj;
        }
        private C invoke_L3(Object a0, Object a1, Object a2) throws Throwable {
            C obj = allocate();
195
            rawConstructor.invokeExact((Object)obj, a0, a1, a2);
196 197 198 199
            return obj;
        }
        private C invoke_L4(Object a0, Object a1, Object a2, Object a3) throws Throwable {
            C obj = allocate();
200
            rawConstructor.invokeExact((Object)obj, a0, a1, a2, a3);
201 202 203 204
            return obj;
        }
        private C invoke_L5(Object a0, Object a1, Object a2, Object a3, Object a4) throws Throwable {
            C obj = allocate();
205
            rawConstructor.invokeExact((Object)obj, a0, a1, a2, a3, a4);
206 207 208 209
            return obj;
        }
        private C invoke_L6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) throws Throwable {
            C obj = allocate();
210
            rawConstructor.invokeExact((Object)obj, a0, a1, a2, a3, a4, a5);
211 212 213 214
            return obj;
        }
        private C invoke_L7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) throws Throwable {
            C obj = allocate();
215
            rawConstructor.invokeExact((Object)obj, a0, a1, a2, a3, a4, a5, a6);
216 217 218 219
            return obj;
        }
        private C invoke_L8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) throws Throwable {
            C obj = allocate();
220
            rawConstructor.invokeExact((Object)obj, a0, a1, a2, a3, a4, a5, a6, a7);
221 222 223 224 225 226 227 228 229 230 231
            return obj;
        }
        static MethodHandle[] makeInvokes() {
            ArrayList<MethodHandle> invokes = new ArrayList<MethodHandle>();
            MethodHandles.Lookup lookup = IMPL_LOOKUP;
            for (;;) {
                int nargs = invokes.size();
                String name = "invoke_L"+nargs;
                MethodHandle invoke = null;
                try {
                    invoke = lookup.findVirtual(AllocateObject.class, name, MethodType.genericMethodType(nargs));
232
                } catch (ReflectiveOperationException ex) {
233 234 235 236 237 238 239 240 241 242 243
                }
                if (invoke == null)  break;
                invokes.add(invoke);
            }
            assert(invokes.size() == 9);  // current number of methods
            return invokes.toArray(new MethodHandle[0]);
        };
        static final MethodHandle[] INVOKES = makeInvokes();
        // For testing use this:
        //static final MethodHandle[] INVOKES = Arrays.copyOf(makeInvokes(), 2);
        static final MethodHandle VARARGS_INVOKE;
244
        static final MethodHandle ALLOCATE;
245 246 247
        static {
            try {
                VARARGS_INVOKE = IMPL_LOOKUP.findVirtual(AllocateObject.class, "invoke_V", MethodType.genericMethodType(0, true));
248
                ALLOCATE = IMPL_LOOKUP.findVirtual(AllocateObject.class, "allocate", MethodType.genericMethodType(0));
249
            } catch (ReflectiveOperationException ex) {
250
                throw uncaughtException(ex);
251 252 253 254 255 256 257 258 259 260 261 262 263
            }
        }
        // Corresponding generic constructor types:
        static final MethodType[] CON_TYPES = new MethodType[INVOKES.length];
        static {
            for (int i = 0; i < INVOKES.length; i++)
                CON_TYPES[i] = makeConType(INVOKES[i]);
        }
        static final MethodType VARARGS_CON_TYPE = makeConType(VARARGS_INVOKE);
        static MethodType makeConType(MethodHandle invoke) {
            MethodType invType = invoke.type();
            return invType.changeParameterType(0, Object.class).changeReturnType(void.class);
        }
264 265
    }

266 267
    static
    MethodHandle accessField(MemberName member, boolean isSetter,
268 269
                             Class<?> lookupClass) {
        // Use sun. misc.Unsafe to dig up the dirt on the field.
270
        MethodHandle mh = new FieldAccessor(member, isSetter);
271
        return mh;
272 273
    }

274 275
    static
    MethodHandle accessArrayElement(Class<?> arrayClass, boolean isSetter) {
276 277
        if (!arrayClass.isArray())
            throw newIllegalArgumentException("not an array: "+arrayClass);
278 279 280 281 282 283 284 285 286 287
        Class<?> elemClass = arrayClass.getComponentType();
        MethodHandle[] mhs = FieldAccessor.ARRAY_CACHE.get(elemClass);
        if (mhs == null) {
            if (!FieldAccessor.doCache(elemClass))
                return FieldAccessor.ahandle(arrayClass, isSetter);
            mhs = new MethodHandle[] {
                FieldAccessor.ahandle(arrayClass, false),
                FieldAccessor.ahandle(arrayClass, true)
            };
            if (mhs[0].type().parameterType(0) == Class.class) {
288 289
                mhs[0] = mhs[0].bindTo(elemClass);
                mhs[1] = mhs[1].bindTo(elemClass);
290 291 292 293 294 295 296
            }
            synchronized (FieldAccessor.ARRAY_CACHE) {}  // memory barrier
            FieldAccessor.ARRAY_CACHE.put(elemClass, mhs);
        }
        return mhs[isSetter ? 1 : 0];
    }

297
    static final class FieldAccessor<C,V> extends BoundMethodHandle {
298 299 300 301 302
        private static final Unsafe unsafe = Unsafe.getUnsafe();
        final Object base;  // for static refs only
        final long offset;
        final String name;

303 304 305
        FieldAccessor(MemberName field, boolean isSetter) {
            super(fhandle(field.getDeclaringClass(), field.getFieldType(), isSetter, field.isStatic()));
            this.offset = (long) field.getVMIndex();
306 307 308
            this.name = field.getName();
            this.base = staticBase(field);
        }
309
        @Override
310
        String debugString() { return addTypeString(name, this); }
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

        int getFieldI(C obj) { return unsafe.getInt(obj, offset); }
        void setFieldI(C obj, int x) { unsafe.putInt(obj, offset, x); }
        long getFieldJ(C obj) { return unsafe.getLong(obj, offset); }
        void setFieldJ(C obj, long x) { unsafe.putLong(obj, offset, x); }
        float getFieldF(C obj) { return unsafe.getFloat(obj, offset); }
        void setFieldF(C obj, float x) { unsafe.putFloat(obj, offset, x); }
        double getFieldD(C obj) { return unsafe.getDouble(obj, offset); }
        void setFieldD(C obj, double x) { unsafe.putDouble(obj, offset, x); }
        boolean getFieldZ(C obj) { return unsafe.getBoolean(obj, offset); }
        void setFieldZ(C obj, boolean x) { unsafe.putBoolean(obj, offset, x); }
        byte getFieldB(C obj) { return unsafe.getByte(obj, offset); }
        void setFieldB(C obj, byte x) { unsafe.putByte(obj, offset, x); }
        short getFieldS(C obj) { return unsafe.getShort(obj, offset); }
        void setFieldS(C obj, short x) { unsafe.putShort(obj, offset, x); }
        char getFieldC(C obj) { return unsafe.getChar(obj, offset); }
        void setFieldC(C obj, char x) { unsafe.putChar(obj, offset, x); }
        @SuppressWarnings("unchecked")
        V getFieldL(C obj) { return (V) unsafe.getObject(obj, offset); }
        @SuppressWarnings("unchecked")
        void setFieldL(C obj, V x) { unsafe.putObject(obj, offset, x); }
        // cast (V) is OK here, since we wrap convertArguments around the MH.

        static Object staticBase(MemberName field) {
            if (!field.isStatic())  return null;
            Class c = field.getDeclaringClass();
            java.lang.reflect.Field f;
            try {
                // FIXME:  Should not have to create 'f' to get this value.
                f = c.getDeclaredField(field.getName());
341
                // Note:  Previous line might invalidly throw SecurityException (7042829)
342
                return unsafe.staticFieldBase(f);
343
            } catch (NoSuchFieldException ee) {
344
                throw uncaughtException(ee);
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
            }
        }

        int getStaticI() { return unsafe.getInt(base, offset); }
        void setStaticI(int x) { unsafe.putInt(base, offset, x); }
        long getStaticJ() { return unsafe.getLong(base, offset); }
        void setStaticJ(long x) { unsafe.putLong(base, offset, x); }
        float getStaticF() { return unsafe.getFloat(base, offset); }
        void setStaticF(float x) { unsafe.putFloat(base, offset, x); }
        double getStaticD() { return unsafe.getDouble(base, offset); }
        void setStaticD(double x) { unsafe.putDouble(base, offset, x); }
        boolean getStaticZ() { return unsafe.getBoolean(base, offset); }
        void setStaticZ(boolean x) { unsafe.putBoolean(base, offset, x); }
        byte getStaticB() { return unsafe.getByte(base, offset); }
        void setStaticB(byte x) { unsafe.putByte(base, offset, x); }
        short getStaticS() { return unsafe.getShort(base, offset); }
        void setStaticS(short x) { unsafe.putShort(base, offset, x); }
        char getStaticC() { return unsafe.getChar(base, offset); }
        void setStaticC(char x) { unsafe.putChar(base, offset, x); }
        V getStaticL() { return (V) unsafe.getObject(base, offset); }
        void setStaticL(V x) { unsafe.putObject(base, offset, x); }

        static String fname(Class<?> vclass, boolean isSetter, boolean isStatic) {
            String stem;
            if (!isStatic)
                stem = (!isSetter ? "getField" : "setField");
            else
                stem = (!isSetter ? "getStatic" : "setStatic");
            return stem + Wrapper.basicTypeChar(vclass);
        }
        static MethodType ftype(Class<?> cclass, Class<?> vclass, boolean isSetter, boolean isStatic) {
            MethodType type;
            if (!isStatic) {
                if (!isSetter)
                    return MethodType.methodType(vclass, cclass);
                else
                    return MethodType.methodType(void.class, cclass, vclass);
            } else {
                if (!isSetter)
                    return MethodType.methodType(vclass);
                else
                    return MethodType.methodType(void.class, vclass);
            }
        }
        static MethodHandle fhandle(Class<?> cclass, Class<?> vclass, boolean isSetter, boolean isStatic) {
            String name = FieldAccessor.fname(vclass, isSetter, isStatic);
            if (cclass.isPrimitive())  throw newIllegalArgumentException("primitive "+cclass);
            Class<?> ecclass = Object.class;  //erase this type
            Class<?> evclass = vclass;
            if (!evclass.isPrimitive())  evclass = Object.class;
            MethodType type = FieldAccessor.ftype(ecclass, evclass, isSetter, isStatic);
            MethodHandle mh;
            try {
                mh = IMPL_LOOKUP.findVirtual(FieldAccessor.class, name, type);
399
            } catch (ReflectiveOperationException ex) {
400
                throw uncaughtException(ex);
401 402 403 404
            }
            if (evclass != vclass || (!isStatic && ecclass != cclass)) {
                MethodType strongType = FieldAccessor.ftype(cclass, vclass, isSetter, isStatic);
                strongType = strongType.insertParameterTypes(0, FieldAccessor.class);
405
                mh = convertArguments(mh, strongType, 0);
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
            }
            return mh;
        }

        /// Support for array element access
        static final HashMap<Class<?>, MethodHandle[]> ARRAY_CACHE =
                new HashMap<Class<?>, MethodHandle[]>();
        // FIXME: Cache on the classes themselves, not here.
        static boolean doCache(Class<?> elemClass) {
            if (elemClass.isPrimitive())  return true;
            ClassLoader cl = elemClass.getClassLoader();
            return cl == null || cl == ClassLoader.getSystemClassLoader();
        }
        static int getElementI(int[] a, int i) { return a[i]; }
        static void setElementI(int[] a, int i, int x) { a[i] = x; }
        static long getElementJ(long[] a, int i) { return a[i]; }
        static void setElementJ(long[] a, int i, long x) { a[i] = x; }
        static float getElementF(float[] a, int i) { return a[i]; }
        static void setElementF(float[] a, int i, float x) { a[i] = x; }
        static double getElementD(double[] a, int i) { return a[i]; }
        static void setElementD(double[] a, int i, double x) { a[i] = x; }
        static boolean getElementZ(boolean[] a, int i) { return a[i]; }
        static void setElementZ(boolean[] a, int i, boolean x) { a[i] = x; }
        static byte getElementB(byte[] a, int i) { return a[i]; }
        static void setElementB(byte[] a, int i, byte x) { a[i] = x; }
        static short getElementS(short[] a, int i) { return a[i]; }
        static void setElementS(short[] a, int i, short x) { a[i] = x; }
        static char getElementC(char[] a, int i) { return a[i]; }
        static void setElementC(char[] a, int i, char x) { a[i] = x; }
        static Object getElementL(Object[] a, int i) { return a[i]; }
        static void setElementL(Object[] a, int i, Object x) { a[i] = x; }
        static <V> V getElementL(Class<V[]> aclass, V[] a, int i) { return aclass.cast(a)[i]; }
        static <V> void setElementL(Class<V[]> aclass, V[] a, int i, V x) { aclass.cast(a)[i] = x; }

        static String aname(Class<?> aclass, boolean isSetter) {
            Class<?> vclass = aclass.getComponentType();
            if (vclass == null)  throw new IllegalArgumentException();
            return (!isSetter ? "getElement" : "setElement") + Wrapper.basicTypeChar(vclass);
        }
        static MethodType atype(Class<?> aclass, boolean isSetter) {
            Class<?> vclass = aclass.getComponentType();
            if (!isSetter)
                return MethodType.methodType(vclass, aclass, int.class);
            else
                return MethodType.methodType(void.class, aclass, int.class, vclass);
        }
        static MethodHandle ahandle(Class<?> aclass, boolean isSetter) {
            Class<?> vclass = aclass.getComponentType();
            String name = FieldAccessor.aname(aclass, isSetter);
            Class<?> caclass = null;
            if (!vclass.isPrimitive() && vclass != Object.class) {
                caclass = aclass;
                aclass = Object[].class;
                vclass = Object.class;
            }
            MethodType type = FieldAccessor.atype(aclass, isSetter);
            if (caclass != null)
                type = type.insertParameterTypes(0, Class.class);
            MethodHandle mh;
            try {
                mh = IMPL_LOOKUP.findStatic(FieldAccessor.class, name, type);
467
            } catch (ReflectiveOperationException ex) {
468
                throw uncaughtException(ex);
469 470 471
            }
            if (caclass != null) {
                MethodType strongType = FieldAccessor.atype(caclass, isSetter);
472 473
                mh = mh.bindTo(caclass);
                mh = convertArguments(mh, strongType, 0);
474 475 476
            }
            return mh;
        }
477 478 479 480 481 482 483 484 485
    }

    /** Bind a predetermined first argument to the given direct method handle.
     * Callable only from MethodHandles.
     * @param token Proof that the caller has access to this package.
     * @param target Any direct method handle.
     * @param receiver Receiver (or first static method argument) to pre-bind.
     * @return a BoundMethodHandle for the given DirectMethodHandle, or null if it does not exist
     */
486 487
    static
    MethodHandle bindReceiver(MethodHandle target, Object receiver) {
488 489 490
        if (target instanceof AdapterMethodHandle &&
            ((AdapterMethodHandle)target).conversionOp() == MethodHandleNatives.Constants.OP_RETYPE_ONLY
            ) {
491 492 493 494
            Object info = MethodHandleNatives.getTargetInfo(target);
            if (info instanceof DirectMethodHandle) {
                DirectMethodHandle dmh = (DirectMethodHandle) info;
                if (receiver == null ||
495 496 497
                    dmh.type().parameterType(0).isAssignableFrom(receiver.getClass())) {
                    MethodHandle bmh = new BoundMethodHandle(dmh, receiver, 0);
                    MethodType newType = target.type().dropParameterTypes(0, 1);
498
                    return convertArguments(bmh, newType, bmh.type(), 0);
499
                }
500 501
            }
        }
502 503 504 505 506 507 508 509 510 511 512 513
        if (target instanceof DirectMethodHandle)
            return new BoundMethodHandle((DirectMethodHandle)target, receiver, 0);
        return null;   // let caller try something else
    }

    /** Bind a predetermined argument to the given arbitrary method handle.
     * Callable only from MethodHandles.
     * @param token Proof that the caller has access to this package.
     * @param target Any method handle.
     * @param receiver Argument (which can be a boxed primitive) to pre-bind.
     * @return a suitable BoundMethodHandle
     */
514 515
    static
    MethodHandle bindArgument(MethodHandle target, int argnum, Object receiver) {
516
        return new BoundMethodHandle(target, receiver, argnum);
517 518
    }

519
    static MethodHandle permuteArguments(MethodHandle target,
520 521 522
                                                MethodType newType,
                                                MethodType oldType,
                                                int[] permutationOrNull) {
523
        assert(oldType.parameterCount() == target.type().parameterCount());
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
        int outargs = oldType.parameterCount(), inargs = newType.parameterCount();
        if (permutationOrNull.length != outargs)
            throw newIllegalArgumentException("wrong number of arguments in permutation");
        // Make the individual outgoing argument types match up first.
        Class<?>[] callTypeArgs = new Class<?>[outargs];
        for (int i = 0; i < outargs; i++)
            callTypeArgs[i] = newType.parameterType(permutationOrNull[i]);
        MethodType callType = MethodType.methodType(oldType.returnType(), callTypeArgs);
        target = convertArguments(target, callType, oldType, 0);
        assert(target != null);
        oldType = target.type();
        List<Integer> goal = new ArrayList<Integer>();  // i*TOKEN
        List<Integer> state = new ArrayList<Integer>(); // i*TOKEN
        List<Integer> drops = new ArrayList<Integer>(); // not tokens
        List<Integer> dups = new ArrayList<Integer>();  // not tokens
        final int TOKEN = 10; // to mark items which are symbolic only
        // state represents the argument values coming into target
        for (int i = 0; i < outargs; i++) {
            state.add(permutationOrNull[i] * TOKEN);
        }
        // goal represents the desired state
        for (int i = 0; i < inargs; i++) {
            if (state.contains(i * TOKEN)) {
                goal.add(i * TOKEN);
            } else {
                // adapter must initially drop all unused arguments
                drops.add(i);
551
            }
552 553 554 555 556 557 558 559 560 561 562 563
        }
        // detect duplications
        while (state.size() > goal.size()) {
            for (int i2 = 0; i2 < state.size(); i2++) {
                int arg1 = state.get(i2);
                int i1 = state.indexOf(arg1);
                if (i1 != i2) {
                    // found duplicate occurrence at i2
                    int arg2 = (inargs++) * TOKEN;
                    state.set(i2, arg2);
                    dups.add(goal.indexOf(arg1));
                    goal.add(arg2);
564 565
                }
            }
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
        }
        assert(state.size() == goal.size());
        int size = goal.size();
        while (!state.equals(goal)) {
            // Look for a maximal sequence of adjacent misplaced arguments,
            // and try to rotate them into place.
            int bestRotArg = -10 * TOKEN, bestRotLen = 0;
            int thisRotArg = -10 * TOKEN, thisRotLen = 0;
            for (int i = 0; i < size; i++) {
                int arg = state.get(i);
                // Does this argument match the current run?
                if (arg == thisRotArg + TOKEN) {
                    thisRotArg = arg;
                    thisRotLen += 1;
                    if (bestRotLen < thisRotLen) {
                        bestRotLen = thisRotLen;
                        bestRotArg = thisRotArg;
583
                    }
584 585 586 587 588 589 590 591 592 593
                } else {
                    // The old sequence (if any) stops here.
                    thisRotLen = 0;
                    thisRotArg = -10 * TOKEN;
                    // But maybe a new one starts here also.
                    int wantArg = goal.get(i);
                    final int MAX_ARG_ROTATION = AdapterMethodHandle.MAX_ARG_ROTATION;
                    if (arg != wantArg &&
                        arg >= wantArg - TOKEN * MAX_ARG_ROTATION &&
                        arg <= wantArg + TOKEN * MAX_ARG_ROTATION) {
594
                        thisRotArg = arg;
595
                        thisRotLen = 1;
596 597
                    }
                }
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
            }
            if (bestRotLen >= 2) {
                // Do a rotation if it can improve argument positioning
                // by at least 2 arguments.  This is not always optimal,
                // but it seems to catch common cases.
                int dstEnd = state.indexOf(bestRotArg);
                int srcEnd = goal.indexOf(bestRotArg);
                int rotBy = dstEnd - srcEnd;
                int dstBeg = dstEnd - (bestRotLen - 1);
                int srcBeg = srcEnd - (bestRotLen - 1);
                assert((dstEnd | dstBeg | srcEnd | srcBeg) >= 0); // no negs
                // Make a span which covers both source and destination.
                int rotBeg = Math.min(dstBeg, srcBeg);
                int rotEnd = Math.max(dstEnd, srcEnd);
                int score = 0;
                for (int i = rotBeg; i <= rotEnd; i++) {
                    if ((int)state.get(i) != (int)goal.get(i))
                        score += 1;
616
                }
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
                List<Integer> rotSpan = state.subList(rotBeg, rotEnd+1);
                Collections.rotate(rotSpan, -rotBy);  // reverse direction
                for (int i = rotBeg; i <= rotEnd; i++) {
                    if ((int)state.get(i) != (int)goal.get(i))
                        score -= 1;
                }
                if (score >= 2) {
                    // Improved at least two argument positions.  Do it.
                    List<Class<?>> ptypes = Arrays.asList(oldType.parameterArray());
                    Collections.rotate(ptypes.subList(rotBeg, rotEnd+1), -rotBy);
                    MethodType rotType = MethodType.methodType(oldType.returnType(), ptypes);
                    MethodHandle nextTarget
                            = AdapterMethodHandle.makeRotateArguments(rotType, target,
                                    rotBeg, rotSpan.size(), rotBy);
                    if (nextTarget != null) {
                        //System.out.println("Rot: "+rotSpan+" by "+rotBy);
                        target = nextTarget;
                        oldType = rotType;
                        continue;
636 637
                    }
                }
638 639
                // Else de-rotate, and drop through to the swap-fest.
                Collections.rotate(rotSpan, rotBy);
640
            }
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

            // Now swap like the wind!
            List<Class<?>> ptypes = Arrays.asList(oldType.parameterArray());
            for (int i = 0; i < size; i++) {
                // What argument do I want here?
                int arg = goal.get(i);
                if (arg != state.get(i)) {
                    // Where is it now?
                    int j = state.indexOf(arg);
                    Collections.swap(ptypes, i, j);
                    MethodType swapType = MethodType.methodType(oldType.returnType(), ptypes);
                    target = AdapterMethodHandle.makeSwapArguments(swapType, target, i, j);
                    if (target == null)  throw newIllegalArgumentException("cannot swap");
                    assert(target.type() == swapType);
                    oldType = swapType;
                    Collections.swap(state, i, j);
657 658
                }
            }
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
            // One pass of swapping must finish the job.
            assert(state.equals(goal));
        }
        while (!dups.isEmpty()) {
            // Grab a contiguous trailing sequence of dups.
            int grab = dups.size() - 1;
            int dupArgPos = dups.get(grab), dupArgCount = 1;
            while (grab - 1 >= 0) {
                int dup0 = dups.get(grab - 1);
                if (dup0 != dupArgPos - 1)  break;
                dupArgPos -= 1;
                dupArgCount += 1;
                grab -= 1;
            }
            //if (dupArgCount > 1)  System.out.println("Dup: "+dups.subList(grab, dups.size()));
            dups.subList(grab, dups.size()).clear();
            // In the new target type drop that many args from the tail:
            List<Class<?>> ptypes = oldType.parameterList();
            ptypes = ptypes.subList(0, ptypes.size() - dupArgCount);
            MethodType dupType = MethodType.methodType(oldType.returnType(), ptypes);
            target = AdapterMethodHandle.makeDupArguments(dupType, target, dupArgPos, dupArgCount);
            if (target == null)
                throw newIllegalArgumentException("cannot dup");
            oldType = target.type();
        }
        while (!drops.isEmpty()) {
            // Grab a contiguous initial sequence of drops.
            int dropArgPos = drops.get(0), dropArgCount = 1;
            while (dropArgCount < drops.size()) {
                int drop1 = drops.get(dropArgCount);
                if (drop1 != dropArgPos + dropArgCount)  break;
                dropArgCount += 1;
691
            }
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
            //if (dropArgCount > 1)  System.out.println("Drop: "+drops.subList(0, dropArgCount));
            drops.subList(0, dropArgCount).clear();
            List<Class<?>> dropTypes = newType.parameterList()
                    .subList(dropArgPos, dropArgPos + dropArgCount);
            MethodType dropType = oldType.insertParameterTypes(dropArgPos, dropTypes);
            target = AdapterMethodHandle.makeDropArguments(dropType, target, dropArgPos, dropArgCount);
            if (target == null)  throw newIllegalArgumentException("cannot drop");
            oldType = target.type();
        }
        return convertArguments(target, newType, oldType, 0);
    }

    /*non-public*/ static
    MethodHandle convertArguments(MethodHandle target, MethodType newType, int level) {
        MethodType oldType = target.type();
        if (oldType.equals(newType))
            return target;
        assert(level > 1 || oldType.isConvertibleTo(newType));
        MethodHandle retFilter = null;
        Class<?> oldRT = oldType.returnType();
        Class<?> newRT = newType.returnType();
        if (!VerifyType.isNullConversion(oldRT, newRT)) {
            if (oldRT == void.class) {
                Wrapper wrap = newRT.isPrimitive() ? Wrapper.forPrimitiveType(newRT) : Wrapper.OBJECT;
                retFilter = ValueConversions.zeroConstantFunction(wrap);
            } else {
                retFilter = MethodHandles.identity(newRT);
                retFilter = convertArguments(retFilter, retFilter.type().changeParameterType(0, oldRT), level);
            }
            newType = newType.changeReturnType(oldRT);
        }
        MethodHandle res = null;
        Exception ex = null;
        try {
            res = convertArguments(target, newType, oldType, level);
        } catch (IllegalArgumentException ex1) {
            ex = ex1;
729
        }
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
        if (res == null) {
            WrongMethodTypeException wmt = new WrongMethodTypeException("cannot convert to "+newType+": "+target);
            wmt.initCause(ex);
            throw wmt;
        }
        if (retFilter != null)
            res = MethodHandles.filterReturnValue(res, retFilter);
        return res;
    }

    static MethodHandle convertArguments(MethodHandle target,
                                                MethodType newType,
                                                MethodType oldType,
                                                int level) {
        assert(oldType.parameterCount() == target.type().parameterCount());
745 746 747
        if (newType == oldType)
            return target;
        if (oldType.parameterCount() != newType.parameterCount())
748 749
            throw newIllegalArgumentException("mismatched parameter count", oldType, newType);
        MethodHandle res = AdapterMethodHandle.makePairwiseConvert(newType, target, level);
750 751
        if (res != null)
            return res;
752 753
        // We can come here in the case of target(int)void => (Object)void,
        // because the unboxing logic for Object => int is complex.
754
        int argc = oldType.parameterCount();
755
        assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
756 757 758 759 760
        // The JVM can't do it directly, so fill in the gap with a Java adapter.
        // TO DO: figure out what to put here from case-by-case experience
        // Use a heavier method:  Convert all the arguments to Object,
        // then back to the desired types.  We might have to use Java-based
        // method handles to do this.
761
        MethodType objType = MethodType.genericMethodType(argc);
762
        MethodHandle objTarget = AdapterMethodHandle.makePairwiseConvert(objType, target, level);
763 764
        if (objTarget == null)
            objTarget = FromGeneric.make(target);
765
        res = AdapterMethodHandle.makePairwiseConvert(newType, objTarget, level);
766 767 768 769 770
        if (res != null)
            return res;
        return ToGeneric.make(newType, objTarget);
    }

771 772 773 774 775 776 777 778 779
    static MethodHandle spreadArguments(MethodHandle target, Class<?> arrayType, int arrayLength) {
        MethodType oldType = target.type();
        int nargs = oldType.parameterCount();
        int keepPosArgs = nargs - arrayLength;
        MethodType newType = oldType
                .dropParameterTypes(keepPosArgs, nargs)
                .insertParameterTypes(keepPosArgs, arrayType);
        return spreadArguments(target, newType, keepPosArgs, arrayType, arrayLength);
    }
780
    static MethodHandle spreadArgumentsFromPos(MethodHandle target, MethodType newType, int spreadArgPos) {
781 782 783
        int arrayLength = target.type().parameterCount() - spreadArgPos;
        return spreadArguments(target, newType, spreadArgPos, Object[].class, arrayLength);
    }
784
    static MethodHandle spreadArguments(MethodHandle target,
785
                                               MethodType newType,
786 787 788
                                               int spreadArgPos,
                                               Class<?> arrayType,
                                               int arrayLength) {
789 790 791
        // TO DO: maybe allow the restarg to be Object and implicitly cast to Object[]
        MethodType oldType = target.type();
        // spread the last argument of newType to oldType
792 793
        assert(arrayLength == oldType.parameterCount() - spreadArgPos);
        assert(newType.parameterType(spreadArgPos) == arrayType);
794
        return AdapterMethodHandle.makeSpreadArguments(newType, target, arrayType, spreadArgPos, arrayLength);
795 796
    }

797 798 799 800 801
    static MethodHandle collectArguments(MethodHandle target,
                                                int collectArg,
                                                MethodHandle collector) {
        MethodType type = target.type();
        Class<?> collectType = collector.type().returnType();
802
        assert(collectType != void.class);  // else use foldArguments
803 804 805 806 807 808 809
        if (collectType != type.parameterType(collectArg))
            target = target.asType(type.changeParameterType(collectArg, collectType));
        MethodType newType = type
                .dropParameterTypes(collectArg, collectArg+1)
                .insertParameterTypes(collectArg, collector.type().parameterArray());
        return collectArguments(target, newType, collectArg, collector);
    }
810
    static MethodHandle collectArguments(MethodHandle target,
811
                                                MethodType newType,
812 813 814 815 816 817 818 819
                                                int collectArg,
                                                MethodHandle collector) {
        MethodType oldType = target.type();     // (a...,c)=>r
        //         newType                      // (a..., b...)=>r
        MethodType colType = collector.type();  // (b...)=>c
        //         oldType                      // (a..., b...)=>r
        assert(newType.parameterCount() == collectArg + colType.parameterCount());
        assert(oldType.parameterCount() == collectArg + 1);
820 821 822 823 824 825 826 827 828 829 830 831
        MethodHandle result = null;
        if (AdapterMethodHandle.canCollectArguments(oldType, colType, collectArg, false)) {
            result = AdapterMethodHandle.makeCollectArguments(target, collector, collectArg, false);
        }
        if (result == null) {
            assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
            MethodHandle gtarget = convertArguments(target, oldType.generic(), oldType, 0);
            MethodHandle gcollector = convertArguments(collector, colType.generic(), colType, 0);
            if (gtarget == null || gcollector == null)  return null;
            MethodHandle gresult = FilterGeneric.makeArgumentCollector(gcollector, gtarget);
            result = convertArguments(gresult, newType, gresult.type(), 0);
        }
832
        return result;
833
    }
834

835
    static MethodHandle filterArgument(MethodHandle target,
836 837 838 839 840 841 842
                                       int pos,
                                       MethodHandle filter) {
        MethodType ttype = target.type();
        MethodType ftype = filter.type();
        assert(ftype.parameterCount() == 1);
        MethodType rtype = ttype.changeParameterType(pos, ftype.parameterType(0));
        MethodType gttype = ttype.generic();
843
        if (ttype != gttype) {
844
            target = convertArguments(target, gttype, ttype, 0);
845 846
            ttype = gttype;
        }
847
        MethodType gftype = ftype.generic();
848
        if (ftype != gftype) {
849
            filter = convertArguments(filter, gftype, ftype, 0);
850 851
            ftype = gftype;
        }
852 853 854 855 856 857 858
        MethodHandle result = null;
        if (AdapterMethodHandle.canCollectArguments(ttype, ftype, pos, false)) {
            result = AdapterMethodHandle.makeCollectArguments(target, filter, pos, false);
        }
        if (result == null) {
            assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
            if (ftype == ttype) {
859
            // simple unary case
860 861 862 863
                result = FilterOneArgument.make(filter, target);
            } else {
                result = FilterGeneric.makeArgumentFilter(pos, filter, target);
            }
864
        }
865 866 867
        if (result.type() != rtype)
            result = result.asType(rtype);
        return result;
868 869
    }

870
    static MethodHandle foldArguments(MethodHandle target,
871 872 873
                                      MethodType newType,
                                      int foldPos,
                                      MethodHandle combiner) {
874 875
        MethodType oldType = target.type();
        MethodType ctype = combiner.type();
876 877 878 879 880 881 882 883 884 885 886
        if (AdapterMethodHandle.canCollectArguments(oldType, ctype, foldPos, true)) {
            MethodHandle res = AdapterMethodHandle.makeCollectArguments(target, combiner, foldPos, true);
            if (res != null)  return res;
        }
        assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
        if (foldPos != 0)  return null;
        MethodHandle gtarget = convertArguments(target, oldType.generic(), oldType, 0);
        MethodHandle gcombiner = convertArguments(combiner, ctype.generic(), ctype, 0);
        if (ctype.returnType() == void.class) {
            gtarget = dropArguments(gtarget, oldType.generic().insertParameterTypes(foldPos, Object.class), foldPos);
        }
887 888
        if (gtarget == null || gcombiner == null)  return null;
        MethodHandle gresult = FilterGeneric.makeArgumentFolder(gcombiner, gtarget);
889
        return convertArguments(gresult, newType, gresult.type(), 0);
890 891
    }

892 893
    static
    MethodHandle dropArguments(MethodHandle target,
894
                               MethodType newType, int argnum) {
895
        int drops = newType.parameterCount() - target.type().parameterCount();
896
        MethodHandle res = AdapterMethodHandle.makeDropArguments(newType, target, argnum, drops);
897 898
        if (res != null)
            return res;
899 900 901
        throw new UnsupportedOperationException("NYI");
    }

902
    private static class GuardWithTest extends BoundMethodHandle {
903
        private final MethodHandle test, target, fallback;
904 905
        private GuardWithTest(MethodHandle invoker,
                              MethodHandle test, MethodHandle target, MethodHandle fallback) {
906
            super(invoker);
907 908 909
            this.test = test;
            this.target = target;
            this.fallback = fallback;
910
            assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
911
        }
912
        // FIXME: Build the control flow out of foldArguments.
913
        static MethodHandle make(MethodHandle test, MethodHandle target, MethodHandle fallback) {
914
            assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
915 916 917 918 919 920
            MethodType type = target.type();
            int nargs = type.parameterCount();
            if (nargs < INVOKES.length) {
                MethodHandle invoke = INVOKES[nargs];
                MethodType gtype = type.generic();
                assert(invoke.type().dropParameterTypes(0,1) == gtype);
921 922 923
                MethodHandle gtest = convertArguments(test, gtype.changeReturnType(boolean.class), test.type(), 0);
                MethodHandle gtarget = convertArguments(target, gtype, type, 0);
                MethodHandle gfallback = convertArguments(fallback, gtype, type, 0);
924 925
                if (gtest == null || gtarget == null || gfallback == null)  return null;
                MethodHandle gguard = new GuardWithTest(invoke, gtest, gtarget, gfallback);
926
                return convertArguments(gguard, type, gtype, 0);
927 928 929 930
            } else {
                MethodHandle invoke = VARARGS_INVOKE;
                MethodType gtype = MethodType.genericMethodType(1);
                assert(invoke.type().dropParameterTypes(0,1) == gtype);
931 932 933
                MethodHandle gtest = spreadArgumentsFromPos(test, gtype.changeReturnType(boolean.class), 0);
                MethodHandle gtarget = spreadArgumentsFromPos(target, gtype, 0);
                MethodHandle gfallback = spreadArgumentsFromPos(fallback, gtype, 0);
934 935
                MethodHandle gguard = new GuardWithTest(invoke, gtest, gtarget, gfallback);
                if (gtest == null || gtarget == null || gfallback == null)  return null;
936
                return collectArguments(gguard, type, 0, null);
937 938
            }
        }
939
        @Override
940
        String debugString() {
941
            return addTypeString(target, this);
942 943
        }
        private Object invoke_V(Object... av) throws Throwable {
944 945 946
            if ((boolean) test.invokeExact(av))
                return target.invokeExact(av);
            return fallback.invokeExact(av);
947 948
        }
        private Object invoke_L0() throws Throwable {
949 950 951
            if ((boolean) test.invokeExact())
                return target.invokeExact();
            return fallback.invokeExact();
952 953
        }
        private Object invoke_L1(Object a0) throws Throwable {
954 955 956
            if ((boolean) test.invokeExact(a0))
                return target.invokeExact(a0);
            return fallback.invokeExact(a0);
957 958
        }
        private Object invoke_L2(Object a0, Object a1) throws Throwable {
959 960 961
            if ((boolean) test.invokeExact(a0, a1))
                return target.invokeExact(a0, a1);
            return fallback.invokeExact(a0, a1);
962 963
        }
        private Object invoke_L3(Object a0, Object a1, Object a2) throws Throwable {
964 965 966
            if ((boolean) test.invokeExact(a0, a1, a2))
                return target.invokeExact(a0, a1, a2);
            return fallback.invokeExact(a0, a1, a2);
967 968
        }
        private Object invoke_L4(Object a0, Object a1, Object a2, Object a3) throws Throwable {
969 970 971
            if ((boolean) test.invokeExact(a0, a1, a2, a3))
                return target.invokeExact(a0, a1, a2, a3);
            return fallback.invokeExact(a0, a1, a2, a3);
972 973
        }
        private Object invoke_L5(Object a0, Object a1, Object a2, Object a3, Object a4) throws Throwable {
974 975 976
            if ((boolean) test.invokeExact(a0, a1, a2, a3, a4))
                return target.invokeExact(a0, a1, a2, a3, a4);
            return fallback.invokeExact(a0, a1, a2, a3, a4);
977 978
        }
        private Object invoke_L6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) throws Throwable {
979 980 981
            if ((boolean) test.invokeExact(a0, a1, a2, a3, a4, a5))
                return target.invokeExact(a0, a1, a2, a3, a4, a5);
            return fallback.invokeExact(a0, a1, a2, a3, a4, a5);
982 983
        }
        private Object invoke_L7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) throws Throwable {
984 985 986
            if ((boolean) test.invokeExact(a0, a1, a2, a3, a4, a5, a6))
                return target.invokeExact(a0, a1, a2, a3, a4, a5, a6);
            return fallback.invokeExact(a0, a1, a2, a3, a4, a5, a6);
987 988
        }
        private Object invoke_L8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) throws Throwable {
989 990 991
            if ((boolean) test.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7))
                return target.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7);
            return fallback.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7);
992 993 994 995 996 997 998 999 1000 1001
        }
        static MethodHandle[] makeInvokes() {
            ArrayList<MethodHandle> invokes = new ArrayList<MethodHandle>();
            MethodHandles.Lookup lookup = IMPL_LOOKUP;
            for (;;) {
                int nargs = invokes.size();
                String name = "invoke_L"+nargs;
                MethodHandle invoke = null;
                try {
                    invoke = lookup.findVirtual(GuardWithTest.class, name, MethodType.genericMethodType(nargs));
1002
                } catch (ReflectiveOperationException ex) {
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
                }
                if (invoke == null)  break;
                invokes.add(invoke);
            }
            assert(invokes.size() == 9);  // current number of methods
            return invokes.toArray(new MethodHandle[0]);
        };
        static final MethodHandle[] INVOKES = makeInvokes();
        // For testing use this:
        //static final MethodHandle[] INVOKES = Arrays.copyOf(makeInvokes(), 2);
        static final MethodHandle VARARGS_INVOKE;
        static {
            try {
                VARARGS_INVOKE = IMPL_LOOKUP.findVirtual(GuardWithTest.class, "invoke_V", MethodType.genericMethodType(0, true));
1017
            } catch (ReflectiveOperationException ex) {
1018
                throw uncaughtException(ex);
1019 1020 1021 1022
            }
        }
    }

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
    static
    MethodHandle selectAlternative(boolean testResult, MethodHandle target, MethodHandle fallback) {
        return testResult ? target : fallback;
    }

    static MethodHandle SELECT_ALTERNATIVE;
    static MethodHandle selectAlternative() {
        if (SELECT_ALTERNATIVE != null)  return SELECT_ALTERNATIVE;
        try {
            SELECT_ALTERNATIVE
            = IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "selectAlternative",
                    MethodType.methodType(MethodHandle.class, boolean.class, MethodHandle.class, MethodHandle.class));
        } catch (ReflectiveOperationException ex) {
            throw new RuntimeException(ex);
        }
        return SELECT_ALTERNATIVE;
    }

1041 1042
    static
    MethodHandle makeGuardWithTest(MethodHandle test,
1043 1044
                                   MethodHandle target,
                                   MethodHandle fallback) {
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
        // gwt(arg...)
        // [fold]=> continueAfterTest(z=test(arg...), arg...)
        // [filter]=> (tf=select(z))(arg...)
        //    where select(z) = select(z, t, f).bindTo(t, f) => z ? t f
        // [tailcall]=> tf(arg...)
        assert(test.type().returnType() == boolean.class);
        MethodType foldTargetType = target.type().insertParameterTypes(0, boolean.class);
        if (AdapterMethodHandle.canCollectArguments(foldTargetType, test.type(), 0, true)) {
            // working backwards, as usual:
            assert(target.type().equals(fallback.type()));
            MethodHandle tailcall = MethodHandles.exactInvoker(target.type());
            MethodHandle select = selectAlternative();
            select = bindArgument(select, 2, fallback);
            select = bindArgument(select, 1, target);
            // select(z: boolean) => (z ? target : fallback)
            MethodHandle filter = filterArgument(tailcall, 0, select);
            assert(filter.type().parameterType(0) == boolean.class);
            MethodHandle fold = foldArguments(filter, filter.type().dropParameterTypes(0, 1), 0, test);
            return fold;
        }
        assert(MethodHandleNatives.workaroundWithoutRicochetFrames());  // this code is deprecated
1066
        return GuardWithTest.make(test, target, fallback);
1067 1068
    }

1069
    private static class GuardWithCatch extends BoundMethodHandle {
1070 1071 1072
        private final MethodHandle target;
        private final Class<? extends Throwable> exType;
        private final MethodHandle catcher;
1073
        GuardWithCatch(MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher) {
1074 1075
            this(INVOKES[target.type().parameterCount()], target, exType, catcher);
        }
1076 1077 1078
        // FIXME: Build the control flow out of foldArguments.
        GuardWithCatch(MethodHandle invoker,
                       MethodHandle target, Class<? extends Throwable> exType, MethodHandle catcher) {
1079
            super(invoker);
1080 1081 1082 1083 1084
            this.target = target;
            this.exType = exType;
            this.catcher = catcher;
        }
        @Override
1085
        String debugString() {
1086
            return addTypeString(target, this);
1087 1088 1089
        }
        private Object invoke_V(Object... av) throws Throwable {
            try {
1090
                return target.invokeExact(av);
1091 1092
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1093
                return catcher.invokeExact(t, av);
1094
            }
1095 1096 1097
        }
        private Object invoke_L0() throws Throwable {
            try {
1098
                return target.invokeExact();
1099 1100
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1101
                return catcher.invokeExact(t);
1102 1103 1104 1105
            }
        }
        private Object invoke_L1(Object a0) throws Throwable {
            try {
1106
                return target.invokeExact(a0);
1107 1108
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1109
                return catcher.invokeExact(t, a0);
1110 1111
            }
        }
1112 1113
        private Object invoke_L2(Object a0, Object a1) throws Throwable {
            try {
1114
                return target.invokeExact(a0, a1);
1115 1116
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1117
                return catcher.invokeExact(t, a0, a1);
1118 1119 1120 1121
            }
        }
        private Object invoke_L3(Object a0, Object a1, Object a2) throws Throwable {
            try {
1122
                return target.invokeExact(a0, a1, a2);
1123 1124
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1125
                return catcher.invokeExact(t, a0, a1, a2);
1126 1127 1128 1129
            }
        }
        private Object invoke_L4(Object a0, Object a1, Object a2, Object a3) throws Throwable {
            try {
1130
                return target.invokeExact(a0, a1, a2, a3);
1131 1132
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1133
                return catcher.invokeExact(t, a0, a1, a2, a3);
1134 1135 1136 1137
            }
        }
        private Object invoke_L5(Object a0, Object a1, Object a2, Object a3, Object a4) throws Throwable {
            try {
1138
                return target.invokeExact(a0, a1, a2, a3, a4);
1139 1140
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1141
                return catcher.invokeExact(t, a0, a1, a2, a3, a4);
1142 1143 1144 1145
            }
        }
        private Object invoke_L6(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5) throws Throwable {
            try {
1146
                return target.invokeExact(a0, a1, a2, a3, a4, a5);
1147 1148
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1149
                return catcher.invokeExact(t, a0, a1, a2, a3, a4, a5);
1150 1151 1152 1153
            }
        }
        private Object invoke_L7(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6) throws Throwable {
            try {
1154
                return target.invokeExact(a0, a1, a2, a3, a4, a5, a6);
1155 1156
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1157
                return catcher.invokeExact(t, a0, a1, a2, a3, a4, a5, a6);
1158 1159 1160 1161
            }
        }
        private Object invoke_L8(Object a0, Object a1, Object a2, Object a3, Object a4, Object a5, Object a6, Object a7) throws Throwable {
            try {
1162
                return target.invokeExact(a0, a1, a2, a3, a4, a5, a6, a7);
1163 1164
            } catch (Throwable t) {
                if (!exType.isInstance(t))  throw t;
1165
                return catcher.invokeExact(t, a0, a1, a2, a3, a4, a5, a6, a7);
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
            }
        }
        static MethodHandle[] makeInvokes() {
            ArrayList<MethodHandle> invokes = new ArrayList<MethodHandle>();
            MethodHandles.Lookup lookup = IMPL_LOOKUP;
            for (;;) {
                int nargs = invokes.size();
                String name = "invoke_L"+nargs;
                MethodHandle invoke = null;
                try {
                    invoke = lookup.findVirtual(GuardWithCatch.class, name, MethodType.genericMethodType(nargs));
1177
                } catch (ReflectiveOperationException ex) {
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
                }
                if (invoke == null)  break;
                invokes.add(invoke);
            }
            assert(invokes.size() == 9);  // current number of methods
            return invokes.toArray(new MethodHandle[0]);
        };
        static final MethodHandle[] INVOKES = makeInvokes();
        // For testing use this:
        //static final MethodHandle[] INVOKES = Arrays.copyOf(makeInvokes(), 2);
        static final MethodHandle VARARGS_INVOKE;
        static {
            try {
                VARARGS_INVOKE = IMPL_LOOKUP.findVirtual(GuardWithCatch.class, "invoke_V", MethodType.genericMethodType(0, true));
1192
            } catch (ReflectiveOperationException ex) {
1193
                throw uncaughtException(ex);
1194 1195 1196 1197 1198
            }
        }
    }


1199 1200
    static
    MethodHandle makeGuardWithCatch(MethodHandle target,
1201 1202 1203 1204 1205 1206 1207 1208
                                    Class<? extends Throwable> exType,
                                    MethodHandle catcher) {
        MethodType type = target.type();
        MethodType ctype = catcher.type();
        int nargs = type.parameterCount();
        if (nargs < GuardWithCatch.INVOKES.length) {
            MethodType gtype = type.generic();
            MethodType gcatchType = gtype.insertParameterTypes(0, Throwable.class);
1209 1210
            MethodHandle gtarget = convertArguments(target, gtype, type, 0);
            MethodHandle gcatcher = convertArguments(catcher, gcatchType, ctype, 0);
1211 1212
            MethodHandle gguard = new GuardWithCatch(gtarget, exType, gcatcher);
            if (gtarget == null || gcatcher == null || gguard == null)  return null;
1213
            return convertArguments(gguard, type, gtype, 0);
1214 1215 1216
        } else {
            MethodType gtype = MethodType.genericMethodType(0, true);
            MethodType gcatchType = gtype.insertParameterTypes(0, Throwable.class);
1217 1218 1219
            MethodHandle gtarget = spreadArgumentsFromPos(target, gtype, 0);
            catcher = catcher.asType(ctype.changeParameterType(0, Throwable.class));
            MethodHandle gcatcher = spreadArgumentsFromPos(catcher, gcatchType, 1);
1220 1221
            MethodHandle gguard = new GuardWithCatch(GuardWithCatch.VARARGS_INVOKE, gtarget, exType, gcatcher);
            if (gtarget == null || gcatcher == null || gguard == null)  return null;
1222
            return collectArguments(gguard, type, 0, ValueConversions.varargsArray(nargs)).asType(type);
1223
        }
1224 1225
    }

1226 1227 1228
    static
    MethodHandle throwException(MethodType type) {
        return AdapterMethodHandle.makeRetypeRaw(type, throwException());
1229 1230
    }

1231 1232 1233
    static MethodHandle THROW_EXCEPTION;
    static MethodHandle throwException() {
        if (THROW_EXCEPTION != null)  return THROW_EXCEPTION;
1234 1235
        try {
            THROW_EXCEPTION
1236 1237
            = IMPL_LOOKUP.findStatic(MethodHandleImpl.class, "throwException",
                    MethodType.methodType(Empty.class, Throwable.class));
1238
        } catch (ReflectiveOperationException ex) {
1239 1240
            throw new RuntimeException(ex);
        }
1241
        return THROW_EXCEPTION;
1242
    }
1243 1244
    static <T extends Throwable> Empty throwException(T t) throws T { throw t; }

1245
    // Linkage support:
1246
    static void registerBootstrap(Class<?> callerClass, MethodHandle bootstrapMethod) {
1247 1248
        MethodHandleNatives.registerBootstrap(callerClass, bootstrapMethod);
    }
1249
    static MethodHandle getBootstrap(Class<?> callerClass) {
1250 1251
        return MethodHandleNatives.getBootstrap(callerClass);
    }
1252
}