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 
  26 package java.lang.invoke;
  27 
  28 import sun.invoke.util.Wrapper;
  29 import static java.lang.invoke.MethodHandleStatics.*;
  30 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  31  import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  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  */
  46 final 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 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 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         return methodHandles[which];
 112     }
 113 
 114     synchronized public MethodHandle setCachedMethodHandle(int which, MethodHandle mh) {
 115         // Simulate a CAS, to avoid racy duplication of results.
 116         MethodHandle prev = methodHandles[which];
 117         if (prev != null)  return prev;
 118         return methodHandles[which] = mh;
 119     }
 120 
 121     public LambdaForm cachedLambdaForm(int which) {
 122         assert(assertIsBasicType());
 123         return lambdaForms[which];
 124     }
 125 
 126     synchronized public LambdaForm setCachedLambdaForm(int which, LambdaForm form) {
 127         // Simulate a CAS, to avoid racy duplication of results.
 128         LambdaForm prev = lambdaForms[which];
 129         if (prev != null) return prev;
 130         return lambdaForms[which] = form;
 131     }
 132 
 133     /**
 134      * Build an MTF for a given type, which must have all references erased to Object.
 135      * This MTF will stand for that type and all un-erased variations.
 136      * Eagerly compute some basic properties of the type, common to all variations.
 137      */
 138     protected MethodTypeForm(MethodType erasedType) {
 139         this.erasedType = erasedType;
 140 
 141         Class<?>[] ptypes = erasedType.ptypes();
 142         int ptypeCount = ptypes.length;
 143         int pslotCount = ptypeCount;            // temp. estimate
 144         int rtypeCount = 1;                     // temp. estimate
 145         int rslotCount = 1;                     // temp. estimate
 146 
 147         int[] argToSlotTab = null, slotToArgTab = null;
 148 
 149         // Walk the argument types, looking for primitives.
 150         int pac = 0, lac = 0, prc = 0, lrc = 0;
 151         Class<?>[] epts = ptypes;
 152         Class<?>[] bpts = epts;
 153         for (int i = 0; i < epts.length; i++) {
 154             Class<?> pt = epts[i];
 155             if (pt != Object.class) {
 156                 ++pac;
 157                 Wrapper w = Wrapper.forPrimitiveType(pt);
 158                 if (w.isDoubleWord())  ++lac;
 159                 if (w.isSubwordOrInt() && pt != int.class) {
 160                     if (bpts == epts)
 161                         bpts = bpts.clone();
 162                     bpts[i] = int.class;
 163                 }
 164             }
 165         }
 166         pslotCount += lac;                  // #slots = #args + #longs
 167         Class<?> rt = erasedType.returnType();
 168         Class<?> bt = rt;
 169         if (rt != Object.class) {
 170             ++prc;          // even void.class counts as a prim here
 171             Wrapper w = Wrapper.forPrimitiveType(rt);
 172             if (w.isDoubleWord())  ++lrc;
 173             if (w.isSubwordOrInt() && rt != int.class)
 174                 bt = int.class;
 175             // adjust #slots, #args
 176             if (rt == void.class)
 177                 rtypeCount = rslotCount = 0;
 178             else
 179                 rslotCount += lrc;
 180         }
 181         if (epts == bpts && bt == rt) {
 182             this.basicType = erasedType;
 183         } else {
 184             this.basicType = MethodType.makeImpl(bt, bpts, true);
 185             // fill in rest of data from the basic type:
 186             MethodTypeForm that = this.basicType.form();
 187             assert(this != that);
 188             this.primCounts = that.primCounts;
 189             this.argCounts = that.argCounts;
 190             this.argToSlotTable = that.argToSlotTable;
 191             this.slotToArgTable = that.slotToArgTable;
 192             this.methodHandles = null;
 193             this.lambdaForms = null;
 194             return;
 195         }
 196         if (lac != 0) {
 197             int slot = ptypeCount + lac;
 198             slotToArgTab = new int[slot+1];
 199             argToSlotTab = new int[1+ptypeCount];
 200             argToSlotTab[0] = slot;  // argument "-1" is past end of slots
 201             for (int i = 0; i < epts.length; i++) {
 202                 Class<?> pt = epts[i];
 203                 Wrapper w = Wrapper.forBasicType(pt);
 204                 if (w.isDoubleWord())  --slot;
 205                 --slot;
 206                 slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
 207                 argToSlotTab[1+i]  = slot;
 208             }
 209             assert(slot == 0);  // filled the table
 210         } else if (pac != 0) {
 211             // have primitives but no long primitives; share slot counts with generic
 212             assert(ptypeCount == pslotCount);
 213             MethodTypeForm that = MethodType.genericMethodType(ptypeCount).form();
 214             assert(this != that);
 215             slotToArgTab = that.slotToArgTable;
 216             argToSlotTab = that.argToSlotTable;
 217         } else {
 218             int slot = ptypeCount; // first arg is deepest in stack
 219             slotToArgTab = new int[slot+1];
 220             argToSlotTab = new int[1+ptypeCount];
 221             argToSlotTab[0] = slot;  // argument "-1" is past end of slots
 222             for (int i = 0; i < ptypeCount; i++) {
 223                 --slot;
 224                 slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
 225                 argToSlotTab[1+i]  = slot;
 226             }
 227         }
 228         this.primCounts = pack(lrc, prc, lac, pac);
 229         this.argCounts = pack(rslotCount, rtypeCount, pslotCount, ptypeCount);
 230         this.argToSlotTable = argToSlotTab;
 231         this.slotToArgTable = slotToArgTab;
 232 
 233         if (pslotCount >= 256)  throw newIllegalArgumentException("too many arguments");
 234 
 235         // Initialize caches, but only for basic types
 236         assert(basicType == erasedType);
 237         this.lambdaForms = new LambdaForm[LF_LIMIT];
 238         this.methodHandles = new MethodHandle[MH_LIMIT];
 239     }
 240 
 241     private static long pack(int a, int b, int c, int d) {
 242         assert(((a|b|c|d) & ~0xFFFF) == 0);
 243         long hw = ((a << 16) | b), lw = ((c << 16) | d);
 244         return (hw << 32) | lw;
 245     }
 246     private static char unpack(long packed, int word) { // word==0 => return a, ==3 => return d
 247         assert(word <= 3);
 248         return (char)(packed >> ((3-word) * 16));
 249     }
 250 
 251     public int parameterCount() {                      // # outgoing values
 252         return unpack(argCounts, 3);
 253     }
 254     public int parameterSlotCount() {                  // # outgoing interpreter slots
 255         return unpack(argCounts, 2);
 256     }
 257     public int returnCount() {                         // = 0 (V), or 1
 258         return unpack(argCounts, 1);
 259     }
 260     public int returnSlotCount() {                     // = 0 (V), 2 (J/D), or 1
 261         return unpack(argCounts, 0);
 262     }
 263     public int primitiveParameterCount() {
 264         return unpack(primCounts, 3);
 265     }
 266     public int longPrimitiveParameterCount() {
 267         return unpack(primCounts, 2);
 268     }
 269     public int primitiveReturnCount() {                // = 0 (obj), or 1
 270         return unpack(primCounts, 1);
 271     }
 272     public int longPrimitiveReturnCount() {            // = 1 (J/D), or 0
 273         return unpack(primCounts, 0);
 274     }
 275     public boolean hasPrimitives() {
 276         return primCounts != 0;
 277     }
 278     public boolean hasNonVoidPrimitives() {
 279         if (primCounts == 0)  return false;
 280         if (primitiveParameterCount() != 0)  return true;
 281         return (primitiveReturnCount() != 0 && returnCount() != 0);
 282     }
 283     public boolean hasLongPrimitives() {
 284         return (longPrimitiveParameterCount() | longPrimitiveReturnCount()) != 0;
 285     }
 286     public int parameterToArgSlot(int i) {
 287         return argToSlotTable[1+i];
 288     }
 289     public int argSlotToParameter(int argSlot) {
 290         // Note:  Empty slots are represented by zero in this table.
 291         // Valid arguments slots contain incremented entries, so as to be non-zero.
 292         // We return -1 the caller to mean an empty slot.
 293         return slotToArgTable[argSlot] - 1;
 294     }
 295 
 296     static MethodTypeForm findForm(MethodType mt) {
 297         MethodType erased = canonicalize(mt, ERASE, ERASE);
 298         if (erased == null) {
 299             // It is already erased.  Make a new MethodTypeForm.
 300             return new MethodTypeForm(mt);
 301         } else {
 302             // Share the MethodTypeForm with the erased version.
 303             return erased.form();
 304         }
 305     }
 306 
 307     /** Codes for {@link #canonicalize(java.lang.Class, int)}.
 308      * ERASE means change every reference to {@code Object}.
 309      * WRAP means convert primitives (including {@code void} to their
 310      * corresponding wrapper types.  UNWRAP means the reverse of WRAP.
 311      * INTS means convert all non-void primitive types to int or long,
 312      * according to size.  LONGS means convert all non-void primitives
 313      * to long, regardless of size.  RAW_RETURN means convert a type
 314      * (assumed to be a return type) to int if it is smaller than an int,
 315      * or if it is void.
 316      */
 317     public static final int NO_CHANGE = 0, ERASE = 1, WRAP = 2, UNWRAP = 3, INTS = 4, LONGS = 5, RAW_RETURN = 6;
 318 
 319     /** Canonicalize the types in the given method type.
 320      * If any types change, intern the new type, and return it.
 321      * Otherwise return null.
 322      */
 323     public static MethodType canonicalize(MethodType mt, int howRet, int howArgs) {
 324         Class<?>[] ptypes = mt.ptypes();
 325         Class<?>[] ptc = MethodTypeForm.canonicalizeAll(ptypes, howArgs);
 326         Class<?> rtype = mt.returnType();
 327         Class<?> rtc = MethodTypeForm.canonicalize(rtype, howRet);
 328         if (ptc == null && rtc == null) {
 329             // It is already canonical.
 330             return null;
 331         }
 332         // Find the erased version of the method type:
 333         if (rtc == null)  rtc = rtype;
 334         if (ptc == null)  ptc = ptypes;
 335         return MethodType.makeImpl(rtc, ptc, true);
 336     }
 337 
 338     /** Canonicalize the given return or param type.
 339      *  Return null if the type is already canonicalized.
 340      */
 341     static Class<?> canonicalize(Class<?> t, int how) {
 342         Class<?> ct;
 343         if (t == Object.class) {
 344             // no change, ever
 345         } else if (!t.isPrimitive()) {
 346             switch (how) {
 347                 case UNWRAP:
 348                     ct = Wrapper.asPrimitiveType(t);
 349                     if (ct != t)  return ct;
 350                     break;
 351                 case RAW_RETURN:
 352                 case ERASE:
 353                     return Object.class;
 354             }
 355         } else if (t == void.class) {
 356             // no change, usually
 357             switch (how) {
 358                 case RAW_RETURN:
 359                     return int.class;
 360                 case WRAP:
 361                     return Void.class;
 362             }
 363         } else {
 364             // non-void primitive
 365             switch (how) {
 366                 case WRAP:
 367                     return Wrapper.asWrapperType(t);
 368                 case INTS:
 369                     if (t == int.class || t == long.class)
 370                         return null;  // no change
 371                     if (t == double.class)
 372                         return long.class;
 373                     return int.class;
 374                 case LONGS:
 375                     if (t == long.class)
 376                         return null;  // no change
 377                     return long.class;
 378                 case RAW_RETURN:
 379                     if (t == int.class || t == long.class ||
 380                         t == float.class || t == double.class)
 381                         return null;  // no change
 382                     // everything else returns as an int
 383                     return int.class;
 384             }
 385         }
 386         // no change; return null to signify
 387         return null;
 388     }
 389 
 390     /** Canonicalize each param type in the given array.
 391      *  Return null if all types are already canonicalized.
 392      */
 393     static Class<?>[] canonicalizeAll(Class<?>[] ts, int how) {
 394         Class<?>[] cs = null;
 395         for (int imax = ts.length, i = 0; i < imax; i++) {
 396             Class<?> c = canonicalize(ts[i], how);
 397             if (c == void.class)
 398                 c = null;  // a Void parameter was unwrapped to void; ignore
 399             if (c != null) {
 400                 if (cs == null)
 401                     cs = ts.clone();
 402                 cs[i] = c;
 403             }
 404         }
 405         return cs;
 406     }
 407 
 408     @Override
 409     public String toString() {
 410         return "Form"+erasedType;
 411     }
 412 
 413 }