MethodTypeForm.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.Stable;
29import sun.invoke.util.Wrapper;
30import java.lang.ref.SoftReference;
31import static java.lang.invoke.MethodHandleStatics.*;
32
33/**
34 * Shared information for a group of method types, which differ
35 * only by reference types, and therefore share a common erasure
36 * and wrapping.
37 * <p>
38 * For an empirical discussion of the structure of method types,
39 * see <a href="http://groups.google.com/group/jvm-languages/browse_thread/thread/ac9308ae74da9b7e/">
40 * the thread "Avoiding Boxing" on jvm-languages</a>.
41 * There are approximately 2000 distinct erased method types in the JDK.
42 * There are a little over 10 times that number of unerased types.
43 * No more than half of these are likely to be loaded at once.
44 * @author John Rose
45 */
46final class MethodTypeForm {
47    final int[] argToSlotTable, slotToArgTable;
48    final long argCounts;               // packed slot & value counts
49    final long primCounts;              // packed prim & double counts
50    final MethodType erasedType;        // the canonical erasure
51    final MethodType basicType;         // the canonical erasure, with primitives simplified
52
53    // Cached adapter information:
54    @Stable final SoftReference<MethodHandle>[] methodHandles;
55    // Indexes into methodHandles:
56    static final int
57            MH_BASIC_INV      =  0,  // cached instance of MH.invokeBasic
58            MH_NF_INV         =  1,  // cached helper for LF.NamedFunction
59            MH_UNINIT_CS      =  2,  // uninitialized call site
60            MH_LIMIT          =  3;
61
62    // Cached lambda form information, for basic types only:
63    final @Stable SoftReference<LambdaForm>[] lambdaForms;
64    // Indexes into lambdaForms:
65    static final int
66            LF_INVVIRTUAL              =  0,  // DMH invokeVirtual
67            LF_INVSTATIC               =  1,
68            LF_INVSPECIAL              =  2,
69            LF_NEWINVSPECIAL           =  3,
70            LF_INVINTERFACE            =  4,
71            LF_INVSTATIC_INIT          =  5,  // DMH invokeStatic with <clinit> barrier
72            LF_INTERPRET               =  6,  // LF interpreter
73            LF_REBIND                  =  7,  // BoundMethodHandle
74            LF_DELEGATE                =  8,  // DelegatingMethodHandle
75            LF_DELEGATE_BLOCK_INLINING =  9,  // Counting DelegatingMethodHandle w/ @DontInline
76            LF_EX_LINKER               = 10,  // invokeExact_MT (for invokehandle)
77            LF_EX_INVOKER              = 11,  // MHs.invokeExact
78            LF_GEN_LINKER              = 12,  // generic invoke_MT (for invokehandle)
79            LF_GEN_INVOKER             = 13,  // generic MHs.invoke
80            LF_CS_LINKER               = 14,  // linkToCallSite_CS
81            LF_MH_LINKER               = 15,  // linkToCallSite_MH
82            LF_GWC                     = 16,  // guardWithCatch (catchException)
83            LF_GWT                     = 17,  // guardWithTest
84            LF_LIMIT                   = 18;
85
86    /** Return the type corresponding uniquely (1-1) to this MT-form.
87     *  It might have any primitive returns or arguments, but will have no references except Object.
88     */
89    public MethodType erasedType() {
90        return erasedType;
91    }
92
93    /** Return the basic type derived from the erased type of this MT-form.
94     *  A basic type is erased (all references Object) and also has all primitive
95     *  types (except int, long, float, double, void) normalized to int.
96     *  Such basic types correspond to low-level JVM calling sequences.
97     */
98    public MethodType basicType() {
99        return basicType;
100    }
101
102    private boolean assertIsBasicType() {
103        // primitives must be flattened also
104        assert(erasedType == basicType)
105                : "erasedType: " + erasedType + " != basicType: " + basicType;
106        return true;
107    }
108
109    public MethodHandle cachedMethodHandle(int which) {
110        assert(assertIsBasicType());
111        SoftReference<MethodHandle> entry = methodHandles[which];
112        return (entry != null) ? entry.get() : null;
113    }
114
115    public synchronized MethodHandle setCachedMethodHandle(int which, MethodHandle mh) {
116        // Simulate a CAS, to avoid racy duplication of results.
117        SoftReference<MethodHandle> entry = methodHandles[which];
118        if (entry != null) {
119            MethodHandle prev = entry.get();
120            if (prev != null) {
121                return prev;
122            }
123        }
124        methodHandles[which] = new SoftReference<>(mh);
125        return mh;
126    }
127
128    public LambdaForm cachedLambdaForm(int which) {
129        assert(assertIsBasicType());
130        SoftReference<LambdaForm> entry = lambdaForms[which];
131        return (entry != null) ? entry.get() : null;
132    }
133
134    public synchronized LambdaForm setCachedLambdaForm(int which, LambdaForm form) {
135        // Simulate a CAS, to avoid racy duplication of results.
136        SoftReference<LambdaForm> entry = lambdaForms[which];
137        if (entry != null) {
138            LambdaForm prev = entry.get();
139            if (prev != null) {
140                return prev;
141            }
142        }
143        lambdaForms[which] = new SoftReference<>(form);
144        return form;
145    }
146
147    /**
148     * Build an MTF for a given type, which must have all references erased to Object.
149     * This MTF will stand for that type and all un-erased variations.
150     * Eagerly compute some basic properties of the type, common to all variations.
151     */
152    @SuppressWarnings({"rawtypes", "unchecked"})
153    protected MethodTypeForm(MethodType erasedType) {
154        this.erasedType = erasedType;
155
156        Class<?>[] ptypes = erasedType.ptypes();
157        int ptypeCount = ptypes.length;
158        int pslotCount = ptypeCount;            // temp. estimate
159        int rtypeCount = 1;                     // temp. estimate
160        int rslotCount = 1;                     // temp. estimate
161
162        int[] argToSlotTab = null, slotToArgTab = null;
163
164        // Walk the argument types, looking for primitives.
165        int pac = 0, lac = 0, prc = 0, lrc = 0;
166        Class<?>[] epts = ptypes;
167        Class<?>[] bpts = epts;
168        for (int i = 0; i < epts.length; i++) {
169            Class<?> pt = epts[i];
170            if (pt != Object.class) {
171                ++pac;
172                Wrapper w = Wrapper.forPrimitiveType(pt);
173                if (w.isDoubleWord())  ++lac;
174                if (w.isSubwordOrInt() && pt != int.class) {
175                    if (bpts == epts)
176                        bpts = bpts.clone();
177                    bpts[i] = int.class;
178                }
179            }
180        }
181        pslotCount += lac;                  // #slots = #args + #longs
182        Class<?> rt = erasedType.returnType();
183        Class<?> bt = rt;
184        if (rt != Object.class) {
185            ++prc;          // even void.class counts as a prim here
186            Wrapper w = Wrapper.forPrimitiveType(rt);
187            if (w.isDoubleWord())  ++lrc;
188            if (w.isSubwordOrInt() && rt != int.class)
189                bt = int.class;
190            // adjust #slots, #args
191            if (rt == void.class)
192                rtypeCount = rslotCount = 0;
193            else
194                rslotCount += lrc;
195        }
196        if (epts == bpts && bt == rt) {
197            this.basicType = erasedType;
198        } else {
199            this.basicType = MethodType.makeImpl(bt, bpts, true);
200            // fill in rest of data from the basic type:
201            MethodTypeForm that = this.basicType.form();
202            assert(this != that);
203            this.primCounts = that.primCounts;
204            this.argCounts = that.argCounts;
205            this.argToSlotTable = that.argToSlotTable;
206            this.slotToArgTable = that.slotToArgTable;
207            this.methodHandles = null;
208            this.lambdaForms = null;
209            return;
210        }
211        if (lac != 0) {
212            int slot = ptypeCount + lac;
213            slotToArgTab = new int[slot+1];
214            argToSlotTab = new int[1+ptypeCount];
215            argToSlotTab[0] = slot;  // argument "-1" is past end of slots
216            for (int i = 0; i < epts.length; i++) {
217                Class<?> pt = epts[i];
218                Wrapper w = Wrapper.forBasicType(pt);
219                if (w.isDoubleWord())  --slot;
220                --slot;
221                slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
222                argToSlotTab[1+i]  = slot;
223            }
224            assert(slot == 0);  // filled the table
225        } else if (pac != 0) {
226            // have primitives but no long primitives; share slot counts with generic
227            assert(ptypeCount == pslotCount);
228            MethodTypeForm that = MethodType.genericMethodType(ptypeCount).form();
229            assert(this != that);
230            slotToArgTab = that.slotToArgTable;
231            argToSlotTab = that.argToSlotTable;
232        } else {
233            int slot = ptypeCount; // first arg is deepest in stack
234            slotToArgTab = new int[slot+1];
235            argToSlotTab = new int[1+ptypeCount];
236            argToSlotTab[0] = slot;  // argument "-1" is past end of slots
237            for (int i = 0; i < ptypeCount; i++) {
238                --slot;
239                slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
240                argToSlotTab[1+i]  = slot;
241            }
242        }
243        this.primCounts = pack(lrc, prc, lac, pac);
244        this.argCounts = pack(rslotCount, rtypeCount, pslotCount, ptypeCount);
245        this.argToSlotTable = argToSlotTab;
246        this.slotToArgTable = slotToArgTab;
247
248        if (pslotCount >= 256)  throw newIllegalArgumentException("too many arguments");
249
250        // Initialize caches, but only for basic types
251        assert(basicType == erasedType);
252        this.lambdaForms   = new SoftReference[LF_LIMIT];
253        this.methodHandles = new SoftReference[MH_LIMIT];
254    }
255
256    private static long pack(int a, int b, int c, int d) {
257        assert(((a|b|c|d) & ~0xFFFF) == 0);
258        long hw = ((a << 16) | b), lw = ((c << 16) | d);
259        return (hw << 32) | lw;
260    }
261    private static char unpack(long packed, int word) { // word==0 => return a, ==3 => return d
262        assert(word <= 3);
263        return (char)(packed >> ((3-word) * 16));
264    }
265
266    public int parameterCount() {                      // # outgoing values
267        return unpack(argCounts, 3);
268    }
269    public int parameterSlotCount() {                  // # outgoing interpreter slots
270        return unpack(argCounts, 2);
271    }
272    public int returnCount() {                         // = 0 (V), or 1
273        return unpack(argCounts, 1);
274    }
275    public int returnSlotCount() {                     // = 0 (V), 2 (J/D), or 1
276        return unpack(argCounts, 0);
277    }
278    public int primitiveParameterCount() {
279        return unpack(primCounts, 3);
280    }
281    public int longPrimitiveParameterCount() {
282        return unpack(primCounts, 2);
283    }
284    public int primitiveReturnCount() {                // = 0 (obj), or 1
285        return unpack(primCounts, 1);
286    }
287    public int longPrimitiveReturnCount() {            // = 1 (J/D), or 0
288        return unpack(primCounts, 0);
289    }
290    public boolean hasPrimitives() {
291        return primCounts != 0;
292    }
293    public boolean hasNonVoidPrimitives() {
294        if (primCounts == 0)  return false;
295        if (primitiveParameterCount() != 0)  return true;
296        return (primitiveReturnCount() != 0 && returnCount() != 0);
297    }
298    public boolean hasLongPrimitives() {
299        return (longPrimitiveParameterCount() | longPrimitiveReturnCount()) != 0;
300    }
301    public int parameterToArgSlot(int i) {
302        return argToSlotTable[1+i];
303    }
304    public int argSlotToParameter(int argSlot) {
305        // Note:  Empty slots are represented by zero in this table.
306        // Valid arguments slots contain incremented entries, so as to be non-zero.
307        // We return -1 the caller to mean an empty slot.
308        return slotToArgTable[argSlot] - 1;
309    }
310
311    static MethodTypeForm findForm(MethodType mt) {
312        MethodType erased = canonicalize(mt, ERASE, ERASE);
313        if (erased == null) {
314            // It is already erased.  Make a new MethodTypeForm.
315            return new MethodTypeForm(mt);
316        } else {
317            // Share the MethodTypeForm with the erased version.
318            return erased.form();
319        }
320    }
321
322    /** Codes for {@link #canonicalize(java.lang.Class, int)}.
323     * ERASE means change every reference to {@code Object}.
324     * WRAP means convert primitives (including {@code void} to their
325     * corresponding wrapper types.  UNWRAP means the reverse of WRAP.
326     * INTS means convert all non-void primitive types to int or long,
327     * according to size.  LONGS means convert all non-void primitives
328     * to long, regardless of size.  RAW_RETURN means convert a type
329     * (assumed to be a return type) to int if it is smaller than an int,
330     * or if it is void.
331     */
332    public static final int NO_CHANGE = 0, ERASE = 1, WRAP = 2, UNWRAP = 3, INTS = 4, LONGS = 5, RAW_RETURN = 6;
333
334    /** Canonicalize the types in the given method type.
335     * If any types change, intern the new type, and return it.
336     * Otherwise return null.
337     */
338    public static MethodType canonicalize(MethodType mt, int howRet, int howArgs) {
339        Class<?>[] ptypes = mt.ptypes();
340        Class<?>[] ptc = MethodTypeForm.canonicalizeAll(ptypes, howArgs);
341        Class<?> rtype = mt.returnType();
342        Class<?> rtc = MethodTypeForm.canonicalize(rtype, howRet);
343        if (ptc == null && rtc == null) {
344            // It is already canonical.
345            return null;
346        }
347        // Find the erased version of the method type:
348        if (rtc == null)  rtc = rtype;
349        if (ptc == null)  ptc = ptypes;
350        return MethodType.makeImpl(rtc, ptc, true);
351    }
352
353    /** Canonicalize the given return or param type.
354     *  Return null if the type is already canonicalized.
355     */
356    static Class<?> canonicalize(Class<?> t, int how) {
357        Class<?> ct;
358        if (t == Object.class) {
359            // no change, ever
360        } else if (!t.isPrimitive()) {
361            switch (how) {
362                case UNWRAP:
363                    ct = Wrapper.asPrimitiveType(t);
364                    if (ct != t)  return ct;
365                    break;
366                case RAW_RETURN:
367                case ERASE:
368                    return Object.class;
369            }
370        } else if (t == void.class) {
371            // no change, usually
372            switch (how) {
373                case RAW_RETURN:
374                    return int.class;
375                case WRAP:
376                    return Void.class;
377            }
378        } else {
379            // non-void primitive
380            switch (how) {
381                case WRAP:
382                    return Wrapper.asWrapperType(t);
383                case INTS:
384                    if (t == int.class || t == long.class)
385                        return null;  // no change
386                    if (t == double.class)
387                        return long.class;
388                    return int.class;
389                case LONGS:
390                    if (t == long.class)
391                        return null;  // no change
392                    return long.class;
393                case RAW_RETURN:
394                    if (t == int.class || t == long.class ||
395                        t == float.class || t == double.class)
396                        return null;  // no change
397                    // everything else returns as an int
398                    return int.class;
399            }
400        }
401        // no change; return null to signify
402        return null;
403    }
404
405    /** Canonicalize each param type in the given array.
406     *  Return null if all types are already canonicalized.
407     */
408    static Class<?>[] canonicalizeAll(Class<?>[] ts, int how) {
409        Class<?>[] cs = null;
410        for (int imax = ts.length, i = 0; i < imax; i++) {
411            Class<?> c = canonicalize(ts[i], how);
412            if (c == void.class)
413                c = null;  // a Void parameter was unwrapped to void; ignore
414            if (c != null) {
415                if (cs == null)
416                    cs = ts.clone();
417                cs[i] = c;
418            }
419        }
420        return cs;
421    }
422
423    @Override
424    public String toString() {
425        return "Form"+erasedType;
426    }
427}
428