Invokers.java revision 13482:a403a4a7a831
1/*
2 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * 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 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang.invoke;
27
28import jdk.internal.vm.annotation.DontInline;
29import jdk.internal.vm.annotation.ForceInline;
30import jdk.internal.vm.annotation.Stable;
31
32import java.lang.reflect.Array;
33import java.util.Arrays;
34
35import static java.lang.invoke.MethodHandleStatics.*;
36import static java.lang.invoke.MethodHandleNatives.Constants.*;
37import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
38import static java.lang.invoke.LambdaForm.*;
39
40/**
41 * Construction and caching of often-used invokers.
42 * @author jrose
43 */
44class Invokers {
45    // exact type (sans leading target MH) for the outgoing call
46    private final MethodType targetType;
47
48    // Cached adapter information:
49    private final @Stable MethodHandle[] invokers = new MethodHandle[INV_LIMIT];
50    // Indexes into invokers:
51    static final int
52            INV_EXACT          =  0,  // MethodHandles.exactInvoker
53            INV_GENERIC        =  1,  // MethodHandles.invoker (generic invocation)
54            INV_BASIC          =  2,  // MethodHandles.basicInvoker
55            INV_LIMIT          =  3;
56
57    /** Compute and cache information common to all collecting adapters
58     *  that implement members of the erasure-family of the given erased type.
59     */
60    /*non-public*/ Invokers(MethodType targetType) {
61        this.targetType = targetType;
62    }
63
64    /*non-public*/ MethodHandle exactInvoker() {
65        MethodHandle invoker = cachedInvoker(INV_EXACT);
66        if (invoker != null)  return invoker;
67        invoker = makeExactOrGeneralInvoker(true);
68        return setCachedInvoker(INV_EXACT, invoker);
69    }
70
71    /*non-public*/ MethodHandle genericInvoker() {
72        MethodHandle invoker = cachedInvoker(INV_GENERIC);
73        if (invoker != null)  return invoker;
74        invoker = makeExactOrGeneralInvoker(false);
75        return setCachedInvoker(INV_GENERIC, invoker);
76    }
77
78    /*non-public*/ MethodHandle basicInvoker() {
79        MethodHandle invoker = cachedInvoker(INV_BASIC);
80        if (invoker != null)  return invoker;
81        MethodType basicType = targetType.basicType();
82        if (basicType != targetType) {
83            // double cache; not used significantly
84            return setCachedInvoker(INV_BASIC, basicType.invokers().basicInvoker());
85        }
86        invoker = basicType.form().cachedMethodHandle(MethodTypeForm.MH_BASIC_INV);
87        if (invoker == null) {
88            MemberName method = invokeBasicMethod(basicType);
89            invoker = DirectMethodHandle.make(method);
90            assert(checkInvoker(invoker));
91            invoker = basicType.form().setCachedMethodHandle(MethodTypeForm.MH_BASIC_INV, invoker);
92        }
93        return setCachedInvoker(INV_BASIC, invoker);
94    }
95
96    private MethodHandle cachedInvoker(int idx) {
97        return invokers[idx];
98    }
99
100    private synchronized MethodHandle setCachedInvoker(int idx, final MethodHandle invoker) {
101        // Simulate a CAS, to avoid racy duplication of results.
102        MethodHandle prev = invokers[idx];
103        if (prev != null)  return prev;
104        return invokers[idx] = invoker;
105    }
106
107    private MethodHandle makeExactOrGeneralInvoker(boolean isExact) {
108        MethodType mtype = targetType;
109        MethodType invokerType = mtype.invokerType();
110        int which = (isExact ? MethodTypeForm.LF_EX_INVOKER : MethodTypeForm.LF_GEN_INVOKER);
111        LambdaForm lform = invokeHandleForm(mtype, false, which);
112        MethodHandle invoker = BoundMethodHandle.bindSingle(invokerType, lform, mtype);
113        String whichName = (isExact ? "invokeExact" : "invoke");
114        invoker = invoker.withInternalMemberName(MemberName.makeMethodHandleInvoke(whichName, mtype), false);
115        assert(checkInvoker(invoker));
116        maybeCompileToBytecode(invoker);
117        return invoker;
118    }
119
120    /** If the target type seems to be common enough, eagerly compile the invoker to bytecodes. */
121    private void maybeCompileToBytecode(MethodHandle invoker) {
122        final int EAGER_COMPILE_ARITY_LIMIT = 10;
123        if (targetType == targetType.erase() &&
124            targetType.parameterCount() < EAGER_COMPILE_ARITY_LIMIT) {
125            invoker.form.compileToBytecode();
126        }
127    }
128
129    // This next one is called from LambdaForm.NamedFunction.<init>.
130    /*non-public*/ static MemberName invokeBasicMethod(MethodType basicType) {
131        assert(basicType == basicType.basicType());
132        try {
133            //Lookup.findVirtual(MethodHandle.class, name, type);
134            return IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, MethodHandle.class, "invokeBasic", basicType);
135        } catch (ReflectiveOperationException ex) {
136            throw newInternalError("JVM cannot find invoker for "+basicType, ex);
137        }
138    }
139
140    private boolean checkInvoker(MethodHandle invoker) {
141        assert(targetType.invokerType().equals(invoker.type()))
142                : java.util.Arrays.asList(targetType, targetType.invokerType(), invoker);
143        assert(invoker.internalMemberName() == null ||
144               invoker.internalMemberName().getMethodType().equals(targetType));
145        assert(!invoker.isVarargsCollector());
146        return true;
147    }
148
149    /**
150     * Find or create an invoker which passes unchanged a given number of arguments
151     * and spreads the rest from a trailing array argument.
152     * The invoker target type is the post-spread type {@code (TYPEOF(uarg*), TYPEOF(sarg*))=>RT}.
153     * All the {@code sarg}s must have a common type {@code C}.  (If there are none, {@code Object} is assumed.}
154     * @param leadingArgCount the number of unchanged (non-spread) arguments
155     * @return {@code invoker.invokeExact(mh, uarg*, C[]{sarg*}) := (RT)mh.invoke(uarg*, sarg*)}
156     */
157    /*non-public*/ MethodHandle spreadInvoker(int leadingArgCount) {
158        int spreadArgCount = targetType.parameterCount() - leadingArgCount;
159        MethodType postSpreadType = targetType;
160        Class<?> argArrayType = impliedRestargType(postSpreadType, leadingArgCount);
161        if (postSpreadType.parameterSlotCount() <= MethodType.MAX_MH_INVOKER_ARITY) {
162            return genericInvoker().asSpreader(argArrayType, spreadArgCount);
163        }
164        // Cannot build a generic invoker here of type ginvoker.invoke(mh, a*[254]).
165        // Instead, factor sinvoker.invoke(mh, a) into ainvoker.invoke(filter(mh), a)
166        // where filter(mh) == mh.asSpreader(Object[], spreadArgCount)
167        MethodType preSpreadType = postSpreadType
168            .replaceParameterTypes(leadingArgCount, postSpreadType.parameterCount(), argArrayType);
169        MethodHandle arrayInvoker = MethodHandles.invoker(preSpreadType);
170        MethodHandle makeSpreader = MethodHandles.insertArguments(Lazy.MH_asSpreader, 1, argArrayType, spreadArgCount);
171        return MethodHandles.filterArgument(arrayInvoker, 0, makeSpreader);
172    }
173
174    private static Class<?> impliedRestargType(MethodType restargType, int fromPos) {
175        if (restargType.isGeneric())  return Object[].class;  // can be nothing else
176        int maxPos = restargType.parameterCount();
177        if (fromPos >= maxPos)  return Object[].class;  // reasonable default
178        Class<?> argType = restargType.parameterType(fromPos);
179        for (int i = fromPos+1; i < maxPos; i++) {
180            if (argType != restargType.parameterType(i))
181                throw newIllegalArgumentException("need homogeneous rest arguments", restargType);
182        }
183        if (argType == Object.class)  return Object[].class;
184        return Array.newInstance(argType, 0).getClass();
185    }
186
187    public String toString() {
188        return "Invokers"+targetType;
189    }
190
191    static MemberName methodHandleInvokeLinkerMethod(String name,
192                                                     MethodType mtype,
193                                                     Object[] appendixResult) {
194        int which;
195        switch (name) {
196        case "invokeExact":  which = MethodTypeForm.LF_EX_LINKER; break;
197        case "invoke":       which = MethodTypeForm.LF_GEN_LINKER; break;
198        default:             throw new InternalError("not invoker: "+name);
199        }
200        LambdaForm lform;
201        if (mtype.parameterSlotCount() <= MethodType.MAX_MH_ARITY - MH_LINKER_ARG_APPENDED) {
202            lform = invokeHandleForm(mtype, false, which);
203            appendixResult[0] = mtype;
204        } else {
205            lform = invokeHandleForm(mtype, true, which);
206        }
207        return lform.vmentry;
208    }
209
210    // argument count to account for trailing "appendix value" (typically the mtype)
211    private static final int MH_LINKER_ARG_APPENDED = 1;
212
213    /** Returns an adapter for invokeExact or generic invoke, as a MH or constant pool linker.
214     * If !customized, caller is responsible for supplying, during adapter execution,
215     * a copy of the exact mtype.  This is because the adapter might be generalized to
216     * a basic type.
217     * @param mtype the caller's method type (either basic or full-custom)
218     * @param customized whether to use a trailing appendix argument (to carry the mtype)
219     * @param which bit-encoded 0x01 whether it is a CP adapter ("linker") or MHs.invoker value ("invoker");
220     *                          0x02 whether it is for invokeExact or generic invoke
221     */
222    private static LambdaForm invokeHandleForm(MethodType mtype, boolean customized, int which) {
223        boolean isCached;
224        if (!customized) {
225            mtype = mtype.basicType();  // normalize Z to I, String to Object, etc.
226            isCached = true;
227        } else {
228            isCached = false;  // maybe cache if mtype == mtype.basicType()
229        }
230        boolean isLinker, isGeneric;
231        String debugName;
232        switch (which) {
233        case MethodTypeForm.LF_EX_LINKER:   isLinker = true;  isGeneric = false; debugName = "invokeExact_MT"; break;
234        case MethodTypeForm.LF_EX_INVOKER:  isLinker = false; isGeneric = false; debugName = "exactInvoker"; break;
235        case MethodTypeForm.LF_GEN_LINKER:  isLinker = true;  isGeneric = true;  debugName = "invoke_MT"; break;
236        case MethodTypeForm.LF_GEN_INVOKER: isLinker = false; isGeneric = true;  debugName = "invoker"; break;
237        default: throw new InternalError();
238        }
239        LambdaForm lform;
240        if (isCached) {
241            lform = mtype.form().cachedLambdaForm(which);
242            if (lform != null)  return lform;
243        }
244        // exactInvokerForm (Object,Object)Object
245        //   link with java.lang.invoke.MethodHandle.invokeBasic(MethodHandle,Object,Object)Object/invokeSpecial
246        final int THIS_MH      = 0;
247        final int CALL_MH      = THIS_MH + (isLinker ? 0 : 1);
248        final int ARG_BASE     = CALL_MH + 1;
249        final int OUTARG_LIMIT = ARG_BASE + mtype.parameterCount();
250        final int INARG_LIMIT  = OUTARG_LIMIT + (isLinker && !customized ? 1 : 0);
251        int nameCursor = OUTARG_LIMIT;
252        final int MTYPE_ARG    = customized ? -1 : nameCursor++;  // might be last in-argument
253        final int CHECK_TYPE   = nameCursor++;
254        final int CHECK_CUSTOM = (CUSTOMIZE_THRESHOLD >= 0) ? nameCursor++ : -1;
255        final int LINKER_CALL  = nameCursor++;
256        MethodType invokerFormType = mtype.invokerType();
257        if (isLinker) {
258            if (!customized)
259                invokerFormType = invokerFormType.appendParameterTypes(MemberName.class);
260        } else {
261            invokerFormType = invokerFormType.invokerType();
262        }
263        Name[] names = arguments(nameCursor - INARG_LIMIT, invokerFormType);
264        assert(names.length == nameCursor)
265                : Arrays.asList(mtype, customized, which, nameCursor, names.length);
266        if (MTYPE_ARG >= INARG_LIMIT) {
267            assert(names[MTYPE_ARG] == null);
268            BoundMethodHandle.SpeciesData speciesData = BoundMethodHandle.speciesData_L();
269            names[THIS_MH] = names[THIS_MH].withConstraint(speciesData);
270            NamedFunction getter = speciesData.getterFunction(0);
271            names[MTYPE_ARG] = new Name(getter, names[THIS_MH]);
272            // else if isLinker, then MTYPE is passed in from the caller (e.g., the JVM)
273        }
274
275        // Make the final call.  If isGeneric, then prepend the result of type checking.
276        MethodType outCallType = mtype.basicType();
277        Object[] outArgs = Arrays.copyOfRange(names, CALL_MH, OUTARG_LIMIT, Object[].class);
278        Object mtypeArg = (customized ? mtype : names[MTYPE_ARG]);
279        if (!isGeneric) {
280            names[CHECK_TYPE] = new Name(NF_checkExactType, names[CALL_MH], mtypeArg);
281            // mh.invokeExact(a*):R => checkExactType(mh, TYPEOF(a*:R)); mh.invokeBasic(a*)
282        } else {
283            names[CHECK_TYPE] = new Name(NF_checkGenericType, names[CALL_MH], mtypeArg);
284            // mh.invokeGeneric(a*):R => checkGenericType(mh, TYPEOF(a*:R)).invokeBasic(a*)
285            outArgs[0] = names[CHECK_TYPE];
286        }
287        if (CHECK_CUSTOM != -1) {
288            names[CHECK_CUSTOM] = new Name(NF_checkCustomized, outArgs[0]);
289        }
290        names[LINKER_CALL] = new Name(outCallType, outArgs);
291        lform = new LambdaForm(debugName, INARG_LIMIT, names);
292        if (isLinker)
293            lform.compileToBytecode();  // JVM needs a real methodOop
294        if (isCached)
295            lform = mtype.form().setCachedLambdaForm(which, lform);
296        return lform;
297    }
298
299    /*non-public*/ static
300    WrongMethodTypeException newWrongMethodTypeException(MethodType actual, MethodType expected) {
301        // FIXME: merge with JVM logic for throwing WMTE
302        return new WrongMethodTypeException("expected "+expected+" but found "+actual);
303    }
304
305    /** Static definition of MethodHandle.invokeExact checking code. */
306    /*non-public*/ static
307    @ForceInline
308    void checkExactType(Object mhObj, Object expectedObj) {
309        MethodHandle mh = (MethodHandle) mhObj;
310        MethodType expected = (MethodType) expectedObj;
311        MethodType actual = mh.type();
312        if (actual != expected)
313            throw newWrongMethodTypeException(expected, actual);
314    }
315
316    /** Static definition of MethodHandle.invokeGeneric checking code.
317     * Directly returns the type-adjusted MH to invoke, as follows:
318     * {@code (R)MH.invoke(a*) => MH.asType(TYPEOF(a*:R)).invokeBasic(a*)}
319     */
320    /*non-public*/ static
321    @ForceInline
322    Object checkGenericType(Object mhObj, Object expectedObj) {
323        MethodHandle mh = (MethodHandle) mhObj;
324        MethodType expected = (MethodType) expectedObj;
325        return mh.asType(expected);
326        /* Maybe add more paths here.  Possible optimizations:
327         * for (R)MH.invoke(a*),
328         * let MT0 = TYPEOF(a*:R), MT1 = MH.type
329         *
330         * if MT0==MT1 or MT1 can be safely called by MT0
331         *  => MH.invokeBasic(a*)
332         * if MT1 can be safely called by MT0[R := Object]
333         *  => MH.invokeBasic(a*) & checkcast(R)
334         * if MT1 can be safely called by MT0[* := Object]
335         *  => checkcast(A)* & MH.invokeBasic(a*) & checkcast(R)
336         * if a big adapter BA can be pulled out of (MT0,MT1)
337         *  => BA.invokeBasic(MT0,MH,a*)
338         * if a local adapter LA can cached on static CS0 = new GICS(MT0)
339         *  => CS0.LA.invokeBasic(MH,a*)
340         * else
341         *  => MH.asType(MT0).invokeBasic(A*)
342         */
343    }
344
345    static MemberName linkToCallSiteMethod(MethodType mtype) {
346        LambdaForm lform = callSiteForm(mtype, false);
347        return lform.vmentry;
348    }
349
350    static MemberName linkToTargetMethod(MethodType mtype) {
351        LambdaForm lform = callSiteForm(mtype, true);
352        return lform.vmentry;
353    }
354
355    // skipCallSite is true if we are optimizing a ConstantCallSite
356    private static LambdaForm callSiteForm(MethodType mtype, boolean skipCallSite) {
357        mtype = mtype.basicType();  // normalize Z to I, String to Object, etc.
358        final int which = (skipCallSite ? MethodTypeForm.LF_MH_LINKER : MethodTypeForm.LF_CS_LINKER);
359        LambdaForm lform = mtype.form().cachedLambdaForm(which);
360        if (lform != null)  return lform;
361        // exactInvokerForm (Object,Object)Object
362        //   link with java.lang.invoke.MethodHandle.invokeBasic(MethodHandle,Object,Object)Object/invokeSpecial
363        final int ARG_BASE     = 0;
364        final int OUTARG_LIMIT = ARG_BASE + mtype.parameterCount();
365        final int INARG_LIMIT  = OUTARG_LIMIT + 1;
366        int nameCursor = OUTARG_LIMIT;
367        final int APPENDIX_ARG = nameCursor++;  // the last in-argument
368        final int CSITE_ARG    = skipCallSite ? -1 : APPENDIX_ARG;
369        final int CALL_MH      = skipCallSite ? APPENDIX_ARG : nameCursor++;  // result of getTarget
370        final int LINKER_CALL  = nameCursor++;
371        MethodType invokerFormType = mtype.appendParameterTypes(skipCallSite ? MethodHandle.class : CallSite.class);
372        Name[] names = arguments(nameCursor - INARG_LIMIT, invokerFormType);
373        assert(names.length == nameCursor);
374        assert(names[APPENDIX_ARG] != null);
375        if (!skipCallSite)
376            names[CALL_MH] = new Name(NF_getCallSiteTarget, names[CSITE_ARG]);
377        // (site.)invokedynamic(a*):R => mh = site.getTarget(); mh.invokeBasic(a*)
378        final int PREPEND_MH = 0, PREPEND_COUNT = 1;
379        Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, OUTARG_LIMIT + PREPEND_COUNT, Object[].class);
380        // prepend MH argument:
381        System.arraycopy(outArgs, 0, outArgs, PREPEND_COUNT, outArgs.length - PREPEND_COUNT);
382        outArgs[PREPEND_MH] = names[CALL_MH];
383        names[LINKER_CALL] = new Name(mtype, outArgs);
384        lform = new LambdaForm((skipCallSite ? "linkToTargetMethod" : "linkToCallSite"), INARG_LIMIT, names);
385        lform.compileToBytecode();  // JVM needs a real methodOop
386        lform = mtype.form().setCachedLambdaForm(which, lform);
387        return lform;
388    }
389
390    /** Static definition of MethodHandle.invokeGeneric checking code. */
391    /*non-public*/ static
392    @ForceInline
393    Object getCallSiteTarget(Object site) {
394        return ((CallSite)site).getTarget();
395    }
396
397    /*non-public*/ static
398    @ForceInline
399    void checkCustomized(Object o) {
400        MethodHandle mh = (MethodHandle)o;
401        if (MethodHandleImpl.isCompileConstant(mh)) return;
402        if (mh.form.customized == null) {
403            maybeCustomize(mh);
404        }
405    }
406
407    /*non-public*/ static
408    @DontInline
409    void maybeCustomize(MethodHandle mh) {
410        byte count = mh.customizationCount;
411        if (count >= CUSTOMIZE_THRESHOLD) {
412            mh.customize();
413        } else {
414            mh.customizationCount = (byte)(count+1);
415        }
416    }
417
418    // Local constant functions:
419    private static final NamedFunction
420        NF_checkExactType,
421        NF_checkGenericType,
422        NF_getCallSiteTarget,
423        NF_checkCustomized;
424    static {
425        try {
426            NamedFunction nfs[] = {
427                NF_checkExactType = new NamedFunction(Invokers.class
428                        .getDeclaredMethod("checkExactType", Object.class, Object.class)),
429                NF_checkGenericType = new NamedFunction(Invokers.class
430                        .getDeclaredMethod("checkGenericType", Object.class, Object.class)),
431                NF_getCallSiteTarget = new NamedFunction(Invokers.class
432                        .getDeclaredMethod("getCallSiteTarget", Object.class)),
433                NF_checkCustomized = new NamedFunction(Invokers.class
434                        .getDeclaredMethod("checkCustomized", Object.class))
435            };
436            // Each nf must be statically invocable or we get tied up in our bootstraps.
437            assert(InvokerBytecodeGenerator.isStaticallyInvocable(nfs));
438        } catch (ReflectiveOperationException ex) {
439            throw newInternalError(ex);
440        }
441    }
442
443    private static class Lazy {
444        private static final MethodHandle MH_asSpreader;
445
446        static {
447            try {
448                MH_asSpreader = IMPL_LOOKUP.findVirtual(MethodHandle.class, "asSpreader",
449                        MethodType.methodType(MethodHandle.class, Class.class, int.class));
450            } catch (ReflectiveOperationException ex) {
451                throw newInternalError(ex);
452            }
453        }
454    }
455}
456