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 java.lang.annotation.*;
29 import java.lang.reflect.Method;
30 import java.util.Map;
31 import java.util.List;
32 import java.util.Arrays;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.concurrent.ConcurrentHashMap;
36 import sun.invoke.util.Wrapper;
37 import static java.lang.invoke.MethodHandleStatics.*;
38 import static java.lang.invoke.MethodHandleNatives.Constants.*;
39 import java.lang.reflect.Field;
40 import java.util.Objects;
41
42 /**
43 * The symbolic, non-executable form of a method handle's invocation semantics.
44 * It consists of a series of names.
45 * The first N (N=arity) names are parameters,
46 * while any remaining names are temporary values.
47 * Each temporary specifies the application of a function to some arguments.
48 * The functions are method handles, while the arguments are mixes of
49 * constant values and local names.
50 * The result of the lambda is defined as one of the names, often the last one.
51 * <p>
52 * Here is an approximate grammar:
53 * <blockquote><pre>{@code
54 * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}"
55 * ArgName = "a" N ":" T
56 * TempName = "t" N ":" T "=" Function "(" Argument* ");"
57 * Function = ConstantValue
58 * Argument = NameRef | ConstantValue
59 * Result = NameRef | "void"
60 * NameRef = "a" N | "t" N
113 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
114 * t3:L = Class#cast(t2,a1); t3 }
115 * == invoker for identity method handle which performs cast
116 * }</pre></blockquote>
117 * <p>
118 * @author John Rose, JSR 292 EG
119 */
120 class LambdaForm {
121 final int arity;
122 final int result;
123 @Stable final Name[] names;
124 final String debugName;
125 MemberName vmentry; // low-level behavior, or null if not yet prepared
126 private boolean isCompiled;
127
128 // Caches for common structural transforms:
129 LambdaForm[] bindCache;
130
131 public static final int VOID_RESULT = -1, LAST_RESULT = -2;
132
133 LambdaForm(String debugName,
134 int arity, Name[] names, int result) {
135 assert(namesOK(arity, names));
136 this.arity = arity;
137 this.result = fixResult(result, names);
138 this.names = names.clone();
139 this.debugName = debugName;
140 normalize();
141 }
142
143 LambdaForm(String debugName,
144 int arity, Name[] names) {
145 this(debugName,
146 arity, names, LAST_RESULT);
147 }
148
149 LambdaForm(String debugName,
150 Name[] formals, Name[] temps, Name result) {
151 this(debugName,
152 formals.length, buildNames(formals, temps, result), LAST_RESULT);
153 }
154
155 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
156 int arity = formals.length;
157 int length = arity + temps.length + (result == null ? 0 : 1);
158 Name[] names = Arrays.copyOf(formals, length);
159 System.arraycopy(temps, 0, names, arity, temps.length);
160 if (result != null)
161 names[length - 1] = result;
162 return names;
163 }
164
165 private LambdaForm(String sig) {
166 // Make a blank lambda form, which returns a constant zero or null.
167 // It is used as a template for managing the invocation of similar forms that are non-empty.
168 // Called only from getPreparedForm.
169 assert(isValidSignature(sig));
170 this.arity = signatureArity(sig);
171 this.result = (signatureReturn(sig) == 'V' ? -1 : arity);
172 this.names = buildEmptyNames(arity, sig);
173 this.debugName = "LF.zero";
174 assert(nameRefsAreLegal());
175 assert(isEmpty());
176 assert(sig.equals(basicTypeSignature()));
177 }
178
179 private static Name[] buildEmptyNames(int arity, String basicTypeSignature) {
180 assert(isValidSignature(basicTypeSignature));
181 int resultPos = arity + 1; // skip '_'
182 if (arity < 0 || basicTypeSignature.length() != resultPos+1)
183 throw new IllegalArgumentException("bad arity for "+basicTypeSignature);
184 int numRes = (basicTypeSignature.charAt(resultPos) == 'V' ? 0 : 1);
185 Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity));
186 for (int i = 0; i < numRes; i++) {
187 names[arity + i] = constantZero(arity + i, basicTypeSignature.charAt(resultPos + i));
188 }
189 return names;
190 }
191
192 private static int fixResult(int result, Name[] names) {
193 if (result >= 0) {
194 if (names[result].type == 'V')
195 return -1;
196 } else if (result == LAST_RESULT) {
197 return names.length - 1;
198 }
199 return result;
200 }
201
202 private static boolean namesOK(int arity, Name[] names) {
203 for (int i = 0; i < names.length; i++) {
204 Name n = names[i];
205 assert(n != null) : "n is null";
206 if (i < arity)
207 assert( n.isParam()) : n + " is not param at " + i;
208 else
209 assert(!n.isParam()) : n + " is param at " + i;
210 }
211 return true;
212 }
213
214 /** Renumber and/or replace params so that they are interned and canonically numbered. */
215 private void normalize() {
216 Name[] oldNames = null;
217 int changesStart = 0;
218 for (int i = 0; i < names.length; i++) {
219 Name n = names[i];
220 if (!n.initIndex(i)) {
221 if (oldNames == null) {
277 for (Object arg : n.arguments) {
278 if (arg instanceof Name) {
279 Name n2 = (Name) arg;
280 int i2 = n2.index;
281 assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
282 assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
283 assert(i2 < i); // ref must come after def!
284 }
285 }
286 }
287 return true;
288 }
289
290 /** Invoke this form on the given arguments. */
291 // final Object invoke(Object... args) throws Throwable {
292 // // NYI: fit this into the fast path?
293 // return interpretWithArguments(args);
294 // }
295
296 /** Report the return type. */
297 char returnType() {
298 if (result < 0) return 'V';
299 Name n = names[result];
300 return n.type;
301 }
302
303 /** Report the N-th argument type. */
304 char parameterType(int n) {
305 assert(n < arity);
306 return names[n].type;
307 }
308
309 /** Report the arity. */
310 int arity() {
311 return arity;
312 }
313
314 /** Return the method type corresponding to my basic type signature. */
315 MethodType methodType() {
316 return signatureType(basicTypeSignature());
317 }
318 /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
319 final String basicTypeSignature() {
320 StringBuilder buf = new StringBuilder(arity() + 3);
321 for (int i = 0, a = arity(); i < a; i++)
322 buf.append(parameterType(i));
323 return buf.append('_').append(returnType()).toString();
324 }
325 static int signatureArity(String sig) {
326 assert(isValidSignature(sig));
327 return sig.indexOf('_');
328 }
329 static char signatureReturn(String sig) {
330 return sig.charAt(signatureArity(sig)+1);
331 }
332 static boolean isValidSignature(String sig) {
333 int arity = sig.indexOf('_');
334 if (arity < 0) return false; // must be of the form *_*
335 int siglen = sig.length();
336 if (siglen != arity + 2) return false; // *_X
337 for (int i = 0; i < siglen; i++) {
338 if (i == arity) continue; // skip '_'
339 char c = sig.charAt(i);
340 if (c == 'V')
341 return (i == siglen - 1 && arity == siglen - 2);
342 if (ALL_TYPES.indexOf(c) < 0) return false; // must be [LIJFD]
343 }
344 return true; // [LIJFD]*_[LIJFDV]
345 }
346 static Class<?> typeClass(char t) {
347 switch (t) {
348 case 'I': return int.class;
349 case 'J': return long.class;
350 case 'F': return float.class;
351 case 'D': return double.class;
352 case 'L': return Object.class;
353 case 'V': return void.class;
354 default: assert false;
355 }
356 return null;
357 }
358 static MethodType signatureType(String sig) {
359 Class<?>[] ptypes = new Class<?>[signatureArity(sig)];
360 for (int i = 0; i < ptypes.length; i++)
361 ptypes[i] = typeClass(sig.charAt(i));
362 Class<?> rtype = typeClass(signatureReturn(sig));
363 return MethodType.methodType(rtype, ptypes);
364 }
365
366 /*
367 * Code generation issues:
368 *
369 * Compiled LFs should be reusable in general.
370 * The biggest issue is how to decide when to pull a name into
371 * the bytecode, versus loading a reified form from the MH data.
372 *
373 * For example, an asType wrapper may require execution of a cast
374 * after a call to a MH. The target type of the cast can be placed
375 * as a constant in the LF itself. This will force the cast type
376 * to be compiled into the bytecodes and native code for the MH.
377 * Or, the target type of the cast can be erased in the LF, and
378 * loaded from the MH data. (Later on, if the MH as a whole is
379 * inlined, the data will flow into the inlined instance of the LF,
380 * as a constant, and the end result will be an optimal cast.)
381 *
382 * This erasure of cast types can be done with any use of
526 LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET);
527 if (prep != null) return prep;
528 assert(isValidSignature(sig));
529 prep = new LambdaForm(sig);
530 prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig);
531 //LambdaForm prep2 = PREPARED_FORMS.putIfAbsent(sig.intern(), prep);
532 return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep);
533 }
534
535 // The next few routines are called only from assert expressions
536 // They verify that the built-in invokers process the correct raw data types.
537 private static boolean argumentTypesMatch(String sig, Object[] av) {
538 int arity = signatureArity(sig);
539 assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
540 assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0];
541 MethodHandle mh = (MethodHandle) av[0];
542 MethodType mt = mh.type();
543 assert(mt.parameterCount() == arity-1);
544 for (int i = 0; i < av.length; i++) {
545 Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
546 assert(valueMatches(sig.charAt(i), pt, av[i]));
547 }
548 return true;
549 }
550 private static boolean valueMatches(char tc, Class<?> type, Object x) {
551 // The following line is needed because (...)void method handles can use non-void invokers
552 if (type == void.class) tc = 'V'; // can drop any kind of value
553 assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
554 switch (tc) {
555 case 'I': assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break;
556 case 'J': assert x instanceof Long : "instanceof Long: " + x; break;
557 case 'F': assert x instanceof Float : "instanceof Float: " + x; break;
558 case 'D': assert x instanceof Double : "instanceof Double: " + x; break;
559 case 'L': assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break;
560 case 'V': break; // allow anything here; will be dropped
561 default: assert(false);
562 }
563 return true;
564 }
565 private static boolean returnTypesMatch(String sig, Object[] av, Object res) {
566 MethodHandle mh = (MethodHandle) av[0];
567 return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
568 }
569 private static boolean checkInt(Class<?> type, Object x) {
570 assert(x instanceof Integer);
571 if (type == int.class) return true;
572 Wrapper w = Wrapper.forBasicType(type);
573 assert(w.isSubwordOrInt());
574 Object x1 = Wrapper.INT.wrap(w.wrap(x));
575 return x.equals(x1);
576 }
577 private static boolean checkRef(Class<?> type, Object x) {
578 assert(!type.isPrimitive());
579 if (x == null) return true;
580 if (type.isInterface()) return true;
719 if (i+1 < arity) buf.append(",");
720 continue;
721 }
722 buf.append("=").append(n.exprString());
723 buf.append(";");
724 }
725 buf.append(result < 0 ? "void" : names[result]).append("}");
726 if (TRACE_INTERPRETER) {
727 // Extra verbosity:
728 buf.append(":").append(basicTypeSignature());
729 buf.append("/").append(vmentry);
730 }
731 return buf.toString();
732 }
733
734 /**
735 * Apply immediate binding for a Name in this form indicated by its position relative to the form.
736 * The first parameter to a LambdaForm, a0:L, always represents the form's method handle, so 0 is not
737 * accepted as valid.
738 */
739 LambdaForm bindImmediate(int pos, char basicType, Object value) {
740 // must be an argument, and the types must match
741 assert pos > 0 && pos < arity && names[pos].type == basicType && Name.typesMatch(basicType, value);
742
743 int arity2 = arity - 1;
744 Name[] names2 = new Name[names.length - 1];
745 for (int r = 0, w = 0; r < names.length; ++r, ++w) { // (r)ead from names, (w)rite to names2
746 Name n = names[r];
747 if (n.isParam()) {
748 if (n.index == pos) {
749 // do not copy over the argument that is to be replaced with a literal,
750 // but adjust the write index
751 --w;
752 } else {
753 names2[w] = new Name(w, n.type);
754 }
755 } else {
756 Object[] arguments2 = new Object[n.arguments.length];
757 for (int i = 0; i < n.arguments.length; ++i) {
758 Object arg = n.arguments[i];
759 if (arg instanceof Name) {
765 arguments2[i] = names2[ni];
766 } else {
767 // replacement position passed
768 arguments2[i] = names2[ni - 1];
769 }
770 } else {
771 arguments2[i] = arg;
772 }
773 }
774 names2[w] = new Name(n.function, arguments2);
775 names2[w].initIndex(w);
776 }
777 }
778
779 int result2 = result == -1 ? -1 : result - 1;
780 return new LambdaForm(debugName, arity2, names2, result2);
781 }
782
783 LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) {
784 Name name = names[namePos];
785 BoundMethodHandle.SpeciesData newData = oldData.extendWithType(name.type);
786 return bind(name, newData.getterName(names[0], oldData.fieldCount()), oldData, newData);
787 }
788 LambdaForm bind(Name name, Name binding,
789 BoundMethodHandle.SpeciesData oldData,
790 BoundMethodHandle.SpeciesData newData) {
791 int pos = name.index;
792 assert(name.isParam());
793 assert(!binding.isParam());
794 assert(name.type == binding.type);
795 assert(0 <= pos && pos < arity && names[pos] == name);
796 assert(binding.function.memberDeclaringClassOrNull() == newData.clazz);
797 assert(oldData.getters.length == newData.getters.length-1);
798 if (bindCache != null) {
799 LambdaForm form = bindCache[pos];
800 if (form != null) {
801 assert(form.contains(binding)) : "form << " + form + " >> does not contain binding << " + binding + " >>";
802 return form;
803 }
804 } else {
805 bindCache = new LambdaForm[arity];
806 }
857 if (result2 == pos)
858 result2 = insPos;
859 else if (result2 > pos && result2 <= insPos)
860 result2 -= 1;
861
862 return bindCache[pos] = new LambdaForm(debugName, arity2, names2, result2);
863 }
864
865 boolean contains(Name name) {
866 int pos = name.index();
867 if (pos >= 0) {
868 return pos < names.length && name.equals(names[pos]);
869 }
870 for (int i = arity; i < names.length; i++) {
871 if (name.equals(names[i]))
872 return true;
873 }
874 return false;
875 }
876
877 LambdaForm addArguments(int pos, char... types) {
878 assert(pos <= arity);
879 int length = names.length;
880 int inTypes = types.length;
881 Name[] names2 = Arrays.copyOf(names, length + inTypes);
882 int arity2 = arity + inTypes;
883 int result2 = result;
884 if (result2 >= arity)
885 result2 += inTypes;
886 // names array has MH in slot 0; skip it.
887 int argpos = pos + 1;
888 // Note: The LF constructor will rename names2[argpos...].
889 // Make space for new arguments (shift temporaries).
890 System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
891 for (int i = 0; i < inTypes; i++) {
892 names2[argpos + i] = new Name(types[i]);
893 }
894 return new LambdaForm(debugName, arity2, names2, result2);
895 }
896
897 LambdaForm addArguments(int pos, List<Class<?>> types) {
898 char[] basicTypes = new char[types.size()];
899 for (int i = 0; i < basicTypes.length; i++)
900 basicTypes[i] = basicType(types.get(i));
901 return addArguments(pos, basicTypes);
902 }
903
904 LambdaForm permuteArguments(int skip, int[] reorder, char[] types) {
905 // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg.
906 // The types are the types of the new (incoming) arguments.
907 int length = names.length;
908 int inTypes = types.length;
909 int outArgs = reorder.length;
910 assert(skip+outArgs == arity);
911 assert(permutedTypesMatch(reorder, types, names, skip));
912 int pos = 0;
913 // skip trivial first part of reordering:
914 while (pos < outArgs && reorder[pos] == pos) pos += 1;
915 Name[] names2 = new Name[length - outArgs + inTypes];
916 System.arraycopy(names, 0, names2, 0, skip+pos);
917 // copy the body:
918 int bodyLength = length - arity;
919 System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength);
920 int arity2 = names2.length - bodyLength;
921 int result2 = result;
922 if (result2 >= 0) {
923 if (result2 < skip+outArgs) {
924 // return the corresponding inArg
943 }
944 // some names are unused, but must be filled in
945 for (int i = skip+pos; i < arity2; i++) {
946 if (names2[i] == null)
947 names2[i] = argument(i, types[i - skip]);
948 }
949 for (int j = arity; j < names.length; j++) {
950 int i = j - arity + arity2;
951 // replace names2[i] by names[j]
952 Name n = names[j];
953 Name n2 = names2[i];
954 if (n != n2) {
955 for (int k = i+1; k < names2.length; k++) {
956 names2[k] = names2[k].replaceName(n, n2);
957 }
958 }
959 }
960 return new LambdaForm(debugName, arity2, names2, result2);
961 }
962
963 static boolean permutedTypesMatch(int[] reorder, char[] types, Name[] names, int skip) {
964 int inTypes = types.length;
965 int outArgs = reorder.length;
966 for (int i = 0; i < outArgs; i++) {
967 assert(names[skip+i].isParam());
968 assert(names[skip+i].type == types[reorder[i]]);
969 }
970 return true;
971 }
972
973 static class NamedFunction {
974 final MemberName member;
975 @Stable MethodHandle resolvedHandle;
976 @Stable MethodHandle invoker;
977
978 NamedFunction(MethodHandle resolvedHandle) {
979 this(resolvedHandle.internalMemberName(), resolvedHandle);
980 }
981 NamedFunction(MemberName member, MethodHandle resolvedHandle) {
982 this.member = member;
983 //resolvedHandle = eraseSubwordTypes(resolvedHandle);
1027 return this.member != null && this.member.equals(that.member);
1028 }
1029
1030 @Override
1031 public int hashCode() {
1032 if (member != null)
1033 return member.hashCode();
1034 return super.hashCode();
1035 }
1036
1037 // Put the predefined NamedFunction invokers into the table.
1038 static void initializeInvokers() {
1039 for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
1040 if (!m.isStatic() || !m.isPackage()) continue;
1041 MethodType type = m.getMethodType();
1042 if (type.equals(INVOKER_METHOD_TYPE) &&
1043 m.getName().startsWith("invoke_")) {
1044 String sig = m.getName().substring("invoke_".length());
1045 int arity = LambdaForm.signatureArity(sig);
1046 MethodType srcType = MethodType.genericMethodType(arity);
1047 if (LambdaForm.signatureReturn(sig) == 'V')
1048 srcType = srcType.changeReturnType(void.class);
1049 MethodTypeForm typeForm = srcType.form();
1050 typeForm.namedFunctionInvoker = DirectMethodHandle.make(m);
1051 }
1052 }
1053 }
1054
1055 // The following are predefined NamedFunction invokers. The system must build
1056 // a separate invoker for each distinct signature.
1057 /** void return type invokers. */
1058 @Hidden
1059 static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1060 assert(a.length == 0);
1061 mh.invokeBasic();
1062 return null;
1063 }
1064 @Hidden
1065 static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1066 assert(a.length == 1);
1067 mh.invokeBasic(a[0]);
1117 assert(a.length == 4);
1118 return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1119 }
1120 @Hidden
1121 static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1122 assert(a.length == 5);
1123 return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1124 }
1125
1126 static final MethodType INVOKER_METHOD_TYPE =
1127 MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1128
1129 private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1130 MethodHandle mh = typeForm.namedFunctionInvoker;
1131 if (mh != null) return mh;
1132 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while
1133 mh = DirectMethodHandle.make(invoker);
1134 MethodHandle mh2 = typeForm.namedFunctionInvoker;
1135 if (mh2 != null) return mh2; // benign race
1136 if (!mh.type().equals(INVOKER_METHOD_TYPE))
1137 throw new InternalError(mh.debugString());
1138 return typeForm.namedFunctionInvoker = mh;
1139 }
1140
1141 @Hidden
1142 Object invokeWithArguments(Object... arguments) throws Throwable {
1143 // If we have a cached invoker, call it right away.
1144 // NOTE: The invoker always returns a reference value.
1145 if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments);
1146 assert(checkArgumentTypes(arguments, methodType()));
1147 return invoker().invokeBasic(resolvedHandle(), arguments);
1148 }
1149
1150 @Hidden
1151 Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
1152 Object rval;
1153 try {
1154 traceInterpreter("[ call", this, arguments);
1155 if (invoker == null) {
1156 traceInterpreter("| getInvoker", this);
1157 invoker();
1207 }
1208
1209 MemberName member() {
1210 assert(assertMemberIsConsistent());
1211 return member;
1212 }
1213
1214 // Called only from assert.
1215 private boolean assertMemberIsConsistent() {
1216 if (resolvedHandle instanceof DirectMethodHandle) {
1217 MemberName m = resolvedHandle.internalMemberName();
1218 assert(m.equals(member));
1219 }
1220 return true;
1221 }
1222
1223 Class<?> memberDeclaringClassOrNull() {
1224 return (member == null) ? null : member.getDeclaringClass();
1225 }
1226
1227 char returnType() {
1228 return basicType(methodType().returnType());
1229 }
1230
1231 char parameterType(int n) {
1232 return basicType(methodType().parameterType(n));
1233 }
1234
1235 int arity() {
1236 //int siglen = member.getMethodType().parameterCount();
1237 //if (!member.isStatic()) siglen += 1;
1238 //return siglen;
1239 return methodType().parameterCount();
1240 }
1241
1242 public String toString() {
1243 if (member == null) return String.valueOf(resolvedHandle);
1244 return member.getDeclaringClass().getSimpleName()+"."+member.getName();
1245 }
1246 }
1247
1248 void resolve() {
1249 for (Name n : names) n.resolve();
1250 }
1251
1252 public static char basicType(Class<?> type) {
1253 char c = Wrapper.basicTypeChar(type);
1254 if ("ZBSC".indexOf(c) >= 0) c = 'I';
1255 assert("LIJFDV".indexOf(c) >= 0);
1256 return c;
1257 }
1258 public static char[] basicTypes(List<Class<?>> types) {
1259 char[] btypes = new char[types.size()];
1260 for (int i = 0; i < btypes.length; i++) {
1261 btypes[i] = basicType(types.get(i));
1262 }
1263 return btypes;
1264 }
1265 public static String basicTypeSignature(MethodType type) {
1266 char[] sig = new char[type.parameterCount() + 2];
1267 int sigp = 0;
1268 for (Class<?> pt : type.parameterList()) {
1269 sig[sigp++] = basicType(pt);
1270 }
1271 sig[sigp++] = '_';
1272 sig[sigp++] = basicType(type.returnType());
1273 assert(sigp == sig.length);
1274 return String.valueOf(sig);
1275 }
1276
1277 static final class Name {
1278 final char type;
1279 private short index;
1280 final NamedFunction function;
1281 @Stable final Object[] arguments;
1282
1283 private Name(int index, char type, NamedFunction function, Object[] arguments) {
1284 this.index = (short)index;
1285 this.type = type;
1286 this.function = function;
1287 this.arguments = arguments;
1288 assert(this.index == index);
1289 }
1290 Name(MethodHandle function, Object... arguments) {
1291 this(new NamedFunction(function), arguments);
1292 }
1293 Name(MethodType functionType, Object... arguments) {
1294 this(new NamedFunction(functionType), arguments);
1295 assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == 'L');
1296 }
1297 Name(MemberName function, Object... arguments) {
1298 this(new NamedFunction(function), arguments);
1299 }
1300 Name(NamedFunction function, Object... arguments) {
1301 this(-1, function.returnType(), function, arguments = arguments.clone());
1302 assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
1303 for (int i = 0; i < arguments.length; i++)
1304 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
1305 }
1306 Name(int index, char type) {
1307 this(index, type, null, null);
1308 }
1309 Name(char type) {
1310 this(-1, type);
1311 }
1312
1313 char type() { return type; }
1314 int index() { return index; }
1315 boolean initIndex(int i) {
1316 if (index != i) {
1317 if (index != -1) return false;
1318 index = (short)i;
1319 }
1320 return true;
1321 }
1322
1323
1324 void resolve() {
1325 if (function != null)
1326 function.resolve();
1327 }
1328
1329 Name newIndex(int i) {
1330 if (initIndex(i)) return this;
1331 return cloneWithIndex(i);
1332 }
1333 Name cloneWithIndex(int i) {
1334 Object[] newArguments = (arguments == null) ? null : arguments.clone();
1335 return new Name(i, type, function, newArguments);
1336 }
1337 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly
1338 if (oldName == newName) return this;
1339 @SuppressWarnings("LocalVariableHidesMemberVariable")
1340 Object[] arguments = this.arguments;
1341 if (arguments == null) return this;
1342 boolean replaced = false;
1380 }
1381 }
1382 if (!replaced) return this;
1383 return new Name(function, arguments);
1384 }
1385 void internArguments() {
1386 @SuppressWarnings("LocalVariableHidesMemberVariable")
1387 Object[] arguments = this.arguments;
1388 for (int j = 0; j < arguments.length; j++) {
1389 if (arguments[j] instanceof Name) {
1390 Name n = (Name) arguments[j];
1391 if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
1392 arguments[j] = internArgument(n);
1393 }
1394 }
1395 }
1396 boolean isParam() {
1397 return function == null;
1398 }
1399 boolean isConstantZero() {
1400 return !isParam() && arguments.length == 0 && function.equals(constantZero(0, type).function);
1401 }
1402
1403 public String toString() {
1404 return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+type;
1405 }
1406 public String debugString() {
1407 String s = toString();
1408 return (function == null) ? s : s + "=" + exprString();
1409 }
1410 public String exprString() {
1411 if (function == null) return "null";
1412 StringBuilder buf = new StringBuilder(function.toString());
1413 buf.append("(");
1414 String cma = "";
1415 for (Object a : arguments) {
1416 buf.append(cma); cma = ",";
1417 if (a instanceof Name || a instanceof Integer)
1418 buf.append(a);
1419 else
1420 buf.append("(").append(a).append(")");
1421 }
1422 buf.append(")");
1423 return buf.toString();
1424 }
1425
1426 private static boolean typesMatch(char parameterType, Object object) {
1427 if (object instanceof Name) {
1428 return ((Name)object).type == parameterType;
1429 }
1430 switch (parameterType) {
1431 case 'I': return object instanceof Integer;
1432 case 'J': return object instanceof Long;
1433 case 'F': return object instanceof Float;
1434 case 'D': return object instanceof Double;
1435 }
1436 assert(parameterType == 'L');
1437 return true;
1438 }
1439
1440 /**
1441 * Does this Name precede the given binding node in some canonical order?
1442 * This predicate is used to order data bindings (via insertion sort)
1443 * with some stability.
1444 */
1445 boolean isSiblingBindingBefore(Name binding) {
1446 assert(!binding.isParam());
1447 if (isParam()) return true;
1448 if (function.equals(binding.function) &&
1449 arguments.length == binding.arguments.length) {
1450 boolean sawInt = false;
1451 for (int i = 0; i < arguments.length; i++) {
1452 Object a1 = arguments[i];
1453 Object a2 = binding.arguments[i];
1454 if (!a1.equals(a2)) {
1455 if (a1 instanceof Integer && a2 instanceof Integer) {
1456 if (sawInt) continue;
1493 }
1494
1495 public boolean equals(Name that) {
1496 if (this == that) return true;
1497 if (isParam())
1498 // each parameter is a unique atom
1499 return false; // this != that
1500 return
1501 //this.index == that.index &&
1502 this.type == that.type &&
1503 this.function.equals(that.function) &&
1504 Arrays.equals(this.arguments, that.arguments);
1505 }
1506 @Override
1507 public boolean equals(Object x) {
1508 return x instanceof Name && equals((Name)x);
1509 }
1510 @Override
1511 public int hashCode() {
1512 if (isParam())
1513 return index | (type << 8);
1514 return function.hashCode() ^ Arrays.hashCode(arguments);
1515 }
1516 }
1517
1518 /** Return the index of the last name which contains n as an argument.
1519 * Return -1 if the name is not used. Return names.length if it is the return value.
1520 */
1521 int lastUseIndex(Name n) {
1522 int ni = n.index, nmax = names.length;
1523 assert(names[ni] == n);
1524 if (result == ni) return nmax; // live all the way beyond the end
1525 for (int i = nmax; --i > ni; ) {
1526 if (names[i].lastUseIndex(n) >= 0)
1527 return i;
1528 }
1529 return -1;
1530 }
1531
1532 /** Return the number of times n is used as an argument or return value. */
1533 int useCount(Name n) {
1534 int ni = n.index, nmax = names.length;
1535 int end = lastUseIndex(n);
1536 if (end < 0) return 0;
1537 int count = 0;
1538 if (end == nmax) { count++; end--; }
1539 int beg = n.index() + 1;
1540 if (beg < arity) beg = arity;
1541 for (int i = beg; i <= end; i++) {
1542 count += names[i].useCount(n);
1543 }
1544 return count;
1545 }
1546
1547 static Name argument(int which, char type) {
1548 int tn = ALL_TYPES.indexOf(type);
1549 if (tn < 0 || which >= INTERNED_ARGUMENT_LIMIT)
1550 return new Name(which, type);
1551 return INTERNED_ARGUMENTS[tn][which];
1552 }
1553 static Name internArgument(Name n) {
1554 assert(n.isParam()) : "not param: " + n;
1555 assert(n.index < INTERNED_ARGUMENT_LIMIT);
1556 return argument(n.index, n.type);
1557 }
1558 static Name[] arguments(int extra, String types) {
1559 int length = types.length();
1560 Name[] names = new Name[length + extra];
1561 for (int i = 0; i < length; i++)
1562 names[i] = argument(i, types.charAt(i));
1563 return names;
1564 }
1565 static Name[] arguments(int extra, char... types) {
1566 int length = types.length;
1567 Name[] names = new Name[length + extra];
1568 for (int i = 0; i < length; i++)
1569 names[i] = argument(i, types[i]);
1570 return names;
1571 }
1573 int length = types.size();
1574 Name[] names = new Name[length + extra];
1575 for (int i = 0; i < length; i++)
1576 names[i] = argument(i, basicType(types.get(i)));
1577 return names;
1578 }
1579 static Name[] arguments(int extra, Class<?>... types) {
1580 int length = types.length;
1581 Name[] names = new Name[length + extra];
1582 for (int i = 0; i < length; i++)
1583 names[i] = argument(i, basicType(types[i]));
1584 return names;
1585 }
1586 static Name[] arguments(int extra, MethodType types) {
1587 int length = types.parameterCount();
1588 Name[] names = new Name[length + extra];
1589 for (int i = 0; i < length; i++)
1590 names[i] = argument(i, basicType(types.parameterType(i)));
1591 return names;
1592 }
1593 static final String ALL_TYPES = "LIJFD"; // omit V, not an argument type
1594 static final int INTERNED_ARGUMENT_LIMIT = 10;
1595 private static final Name[][] INTERNED_ARGUMENTS
1596 = new Name[ALL_TYPES.length()][INTERNED_ARGUMENT_LIMIT];
1597 static {
1598 for (int tn = 0; tn < ALL_TYPES.length(); tn++) {
1599 for (int i = 0; i < INTERNED_ARGUMENTS[tn].length; i++) {
1600 char type = ALL_TYPES.charAt(tn);
1601 INTERNED_ARGUMENTS[tn][i] = new Name(i, type);
1602 }
1603 }
1604 }
1605
1606 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1607
1608 static Name constantZero(int which, char type) {
1609 return CONSTANT_ZERO[ALL_TYPES.indexOf(type)].newIndex(which);
1610 }
1611 private static final Name[] CONSTANT_ZERO
1612 = new Name[ALL_TYPES.length()];
1613 static {
1614 for (int tn = 0; tn < ALL_TYPES.length(); tn++) {
1615 char bt = ALL_TYPES.charAt(tn);
1616 Wrapper wrap = Wrapper.forBasicType(bt);
1617 MemberName zmem = new MemberName(LambdaForm.class, "zero"+bt, MethodType.methodType(wrap.primitiveType()), REF_invokeStatic);
1618 try {
1619 zmem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zmem, null, NoSuchMethodException.class);
1620 } catch (IllegalAccessException|NoSuchMethodException ex) {
1621 throw newInternalError(ex);
1622 }
1623 NamedFunction zcon = new NamedFunction(zmem);
1624 Name n = new Name(zcon).newIndex(0);
1625 assert(n.type == ALL_TYPES.charAt(tn));
1626 CONSTANT_ZERO[tn] = n;
1627 assert(n.isConstantZero());
1628 }
1629 }
1630
1631 // Avoid appealing to ValueConversions at bootstrap time:
1632 private static int zeroI() { return 0; }
1633 private static long zeroJ() { return 0; }
1634 private static float zeroF() { return 0; }
1635 private static double zeroD() { return 0; }
1636 private static Object zeroL() { return null; }
1637
1638 // Put this last, so that previous static inits can run before.
1639 static {
1640 if (USE_PREDEFINED_INTERPRET_METHODS)
1641 PREPARED_FORMS.putAll(computeInitialPreparedForms());
1642 }
1643
1644 /**
1645 * Internal marker for byte-compiled LambdaForms.
1646 */
1647 /*non-public*/
1648 @Target(ElementType.METHOD)
1649 @Retention(RetentionPolicy.RUNTIME)
1650 @interface Compiled {
1651 }
1652
1653 /**
1654 * Internal marker for LambdaForm interpreter frames.
1655 */
1656 /*non-public*/
1657 @Target(ElementType.METHOD)
1658 @Retention(RetentionPolicy.RUNTIME)
1659 @interface Hidden {
1660 }
1661
1662
1673 Object[] abc = { "a", "bc" };
1674 List<?> lst = (List<?>) MethodHandle.linkToStatic(abc, asList_MN);
1675 System.out.println("lst="+lst);
1676 MemberName toString_MN = new MemberName(Object.class.getMethod("toString"));
1677 String s1 = (String) MethodHandle.linkToVirtual(lst, toString_MN);
1678 toString_MN = new MemberName(Object.class.getMethod("toString"), true);
1679 String s2 = (String) MethodHandle.linkToSpecial(lst, toString_MN);
1680 System.out.println("[s1,s2,lst]="+Arrays.asList(s1, s2, lst.toString()));
1681 MemberName toArray_MN = new MemberName(List.class.getMethod("toArray"));
1682 Object[] arr = (Object[]) MethodHandle.linkToInterface(lst, toArray_MN);
1683 System.out.println("toArray="+Arrays.toString(arr));
1684 }
1685 static { try { testMethodHandleLinkers(); } catch (Throwable ex) { throw new RuntimeException(ex); } }
1686 // Requires these definitions in MethodHandle:
1687 static final native Object linkToStatic(Object x1, MemberName mn) throws Throwable;
1688 static final native Object linkToVirtual(Object x1, MemberName mn) throws Throwable;
1689 static final native Object linkToSpecial(Object x1, MemberName mn) throws Throwable;
1690 static final native Object linkToInterface(Object x1, MemberName mn) throws Throwable;
1691 */
1692
1693 static { NamedFunction.initializeInvokers(); }
1694
1695 // The following hack is necessary in order to suppress TRACE_INTERPRETER
1696 // during execution of the static initializes of this class.
1697 // Turning on TRACE_INTERPRETER too early will cause
1698 // stack overflows and other misbehavior during attempts to trace events
1699 // that occur during LambdaForm.<clinit>.
1700 // Therefore, do not move this line higher in this file, and do not remove.
1701 private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
1702 }
|
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 java.lang.annotation.*;
29 import java.lang.reflect.Method;
30 import java.util.Map;
31 import java.util.List;
32 import java.util.Arrays;
33 import java.util.HashMap;
34 import java.util.concurrent.ConcurrentHashMap;
35 import sun.invoke.util.Wrapper;
36 import java.lang.reflect.Field;
37
38 import static java.lang.invoke.LambdaForm.BasicType.*;
39 import static java.lang.invoke.MethodHandleStatics.*;
40 import static java.lang.invoke.MethodHandleNatives.Constants.*;
41
42 /**
43 * The symbolic, non-executable form of a method handle's invocation semantics.
44 * It consists of a series of names.
45 * The first N (N=arity) names are parameters,
46 * while any remaining names are temporary values.
47 * Each temporary specifies the application of a function to some arguments.
48 * The functions are method handles, while the arguments are mixes of
49 * constant values and local names.
50 * The result of the lambda is defined as one of the names, often the last one.
51 * <p>
52 * Here is an approximate grammar:
53 * <blockquote><pre>{@code
54 * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}"
55 * ArgName = "a" N ":" T
56 * TempName = "t" N ":" T "=" Function "(" Argument* ");"
57 * Function = ConstantValue
58 * Argument = NameRef | ConstantValue
59 * Result = NameRef | "void"
60 * NameRef = "a" N | "t" N
113 * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
114 * t3:L = Class#cast(t2,a1); t3 }
115 * == invoker for identity method handle which performs cast
116 * }</pre></blockquote>
117 * <p>
118 * @author John Rose, JSR 292 EG
119 */
120 class LambdaForm {
121 final int arity;
122 final int result;
123 @Stable final Name[] names;
124 final String debugName;
125 MemberName vmentry; // low-level behavior, or null if not yet prepared
126 private boolean isCompiled;
127
128 // Caches for common structural transforms:
129 LambdaForm[] bindCache;
130
131 public static final int VOID_RESULT = -1, LAST_RESULT = -2;
132
133 enum BasicType {
134 L_TYPE('L', Object.class, Wrapper.OBJECT), // all reference types
135 I_TYPE('I', int.class, Wrapper.INT),
136 J_TYPE('J', long.class, Wrapper.LONG),
137 F_TYPE('F', float.class, Wrapper.FLOAT),
138 D_TYPE('D', double.class, Wrapper.DOUBLE), // all primitive types
139 V_TYPE('V', void.class, Wrapper.VOID); // not valid in all contexts
140
141 static final BasicType[] ALL_TYPES = BasicType.values();
142 static final BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1);
143
144 static final int ARG_TYPE_LIMIT = ARG_TYPES.length;
145 static final int TYPE_LIMIT = ALL_TYPES.length;
146
147 private final char btChar;
148 private final Class<?> btClass;
149 private final Wrapper btWrapper;
150
151 private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) {
152 this.btChar = btChar;
153 this.btClass = btClass;
154 this.btWrapper = wrapper;
155 }
156
157 char basicTypeChar() {
158 return btChar;
159 }
160 Class<?> basicTypeClass() {
161 return btClass;
162 }
163 Wrapper basicTypeWrapper() {
164 return btWrapper;
165 }
166 int basicTypeSlots() {
167 return btWrapper.stackSlots();
168 }
169
170 static BasicType basicType(byte type) {
171 return ALL_TYPES[type];
172 }
173 static BasicType basicType(char type) {
174 switch (type) {
175 case 'L': return L_TYPE;
176 case 'I': return I_TYPE;
177 case 'J': return J_TYPE;
178 case 'F': return F_TYPE;
179 case 'D': return D_TYPE;
180 case 'V': return V_TYPE;
181 // all subword types are represented as ints
182 case 'Z':
183 case 'B':
184 case 'S':
185 case 'C':
186 return I_TYPE;
187 default:
188 throw newInternalError("Unknown type char: '"+type+"'");
189 }
190 }
191 static BasicType basicType(Wrapper type) {
192 char c = type.basicTypeChar();
193 return basicType(c);
194 }
195 static BasicType basicType(Class<?> type) {
196 if (!type.isPrimitive()) return L_TYPE;
197 return basicType(Wrapper.forPrimitiveType(type));
198 }
199
200 static char basicTypeChar(Class<?> type) {
201 return basicType(type).btChar;
202 }
203 static BasicType[] basicTypes(List<Class<?>> types) {
204 BasicType[] btypes = new BasicType[types.size()];
205 for (int i = 0; i < btypes.length; i++) {
206 btypes[i] = basicType(types.get(i));
207 }
208 return btypes;
209 }
210 static BasicType[] basicTypes(String types) {
211 BasicType[] btypes = new BasicType[types.length()];
212 for (int i = 0; i < btypes.length; i++) {
213 btypes[i] = basicType(types.charAt(i));
214 }
215 return btypes;
216 }
217 static boolean isBasicTypeChar(char c) {
218 return "LIJFDV".indexOf(c) >= 0;
219 }
220 static boolean isArgBasicTypeChar(char c) {
221 return "LIJFD".indexOf(c) >= 0;
222 }
223 }
224
225 LambdaForm(String debugName,
226 int arity, Name[] names, int result) {
227 assert(namesOK(arity, names));
228 this.arity = arity;
229 this.result = fixResult(result, names);
230 this.names = names.clone();
231 this.debugName = fixDebugName(debugName);
232 normalize();
233 }
234
235 LambdaForm(String debugName,
236 int arity, Name[] names) {
237 this(debugName,
238 arity, names, LAST_RESULT);
239 }
240
241 LambdaForm(String debugName,
242 Name[] formals, Name[] temps, Name result) {
243 this(debugName,
244 formals.length, buildNames(formals, temps, result), LAST_RESULT);
245 }
246
247 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
248 int arity = formals.length;
249 int length = arity + temps.length + (result == null ? 0 : 1);
250 Name[] names = Arrays.copyOf(formals, length);
251 System.arraycopy(temps, 0, names, arity, temps.length);
252 if (result != null)
253 names[length - 1] = result;
254 return names;
255 }
256
257 private LambdaForm(String sig) {
258 // Make a blank lambda form, which returns a constant zero or null.
259 // It is used as a template for managing the invocation of similar forms that are non-empty.
260 // Called only from getPreparedForm.
261 assert(isValidSignature(sig));
262 this.arity = signatureArity(sig);
263 this.result = (signatureReturn(sig) == V_TYPE ? -1 : arity);
264 this.names = buildEmptyNames(arity, sig);
265 this.debugName = "LF.zero";
266 assert(nameRefsAreLegal());
267 assert(isEmpty());
268 assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature();
269 }
270
271 private static Name[] buildEmptyNames(int arity, String basicTypeSignature) {
272 assert(isValidSignature(basicTypeSignature));
273 int resultPos = arity + 1; // skip '_'
274 if (arity < 0 || basicTypeSignature.length() != resultPos+1)
275 throw new IllegalArgumentException("bad arity for "+basicTypeSignature);
276 int numRes = (basicType(basicTypeSignature.charAt(resultPos)) == V_TYPE ? 0 : 1);
277 Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity));
278 for (int i = 0; i < numRes; i++) {
279 Name zero = new Name(constantZero(basicType(basicTypeSignature.charAt(resultPos + i))));
280 names[arity + i] = zero.newIndex(arity + i);
281 }
282 return names;
283 }
284
285 private static int fixResult(int result, Name[] names) {
286 if (result == LAST_RESULT)
287 result = names.length - 1; // might still be void
288 if (result >= 0 && names[result].type == V_TYPE)
289 result = -1;
290 return result;
291 }
292
293 private static String fixDebugName(String debugName) {
294 if (DEBUG_NAME_COUNTERS != null) {
295 int under = debugName.indexOf('_');
296 int length = debugName.length();
297 if (under < 0) under = length;
298 String debugNameStem = debugName.substring(0, under);
299 Integer ctr;
300 synchronized (DEBUG_NAME_COUNTERS) {
301 ctr = DEBUG_NAME_COUNTERS.get(debugNameStem);
302 if (ctr == null) ctr = 0;
303 DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1);
304 }
305 StringBuilder buf = new StringBuilder(debugNameStem);
306 buf.append('_');
307 int leadingZero = buf.length();
308 buf.append((int) ctr);
309 for (int i = buf.length() - leadingZero; i < 3; i++)
310 buf.insert(leadingZero, '0');
311 if (under < length) {
312 ++under; // skip "_"
313 while (under < length && Character.isDigit(debugName.charAt(under))) {
314 ++under;
315 }
316 if (under < length && debugName.charAt(under) == '_') ++under;
317 if (under < length)
318 buf.append('_').append(debugName, under, length);
319 }
320 return buf.toString();
321 }
322 return debugName;
323 }
324
325 private static boolean namesOK(int arity, Name[] names) {
326 for (int i = 0; i < names.length; i++) {
327 Name n = names[i];
328 assert(n != null) : "n is null";
329 if (i < arity)
330 assert( n.isParam()) : n + " is not param at " + i;
331 else
332 assert(!n.isParam()) : n + " is param at " + i;
333 }
334 return true;
335 }
336
337 /** Renumber and/or replace params so that they are interned and canonically numbered. */
338 private void normalize() {
339 Name[] oldNames = null;
340 int changesStart = 0;
341 for (int i = 0; i < names.length; i++) {
342 Name n = names[i];
343 if (!n.initIndex(i)) {
344 if (oldNames == null) {
400 for (Object arg : n.arguments) {
401 if (arg instanceof Name) {
402 Name n2 = (Name) arg;
403 int i2 = n2.index;
404 assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
405 assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
406 assert(i2 < i); // ref must come after def!
407 }
408 }
409 }
410 return true;
411 }
412
413 /** Invoke this form on the given arguments. */
414 // final Object invoke(Object... args) throws Throwable {
415 // // NYI: fit this into the fast path?
416 // return interpretWithArguments(args);
417 // }
418
419 /** Report the return type. */
420 BasicType returnType() {
421 if (result < 0) return V_TYPE;
422 Name n = names[result];
423 return n.type;
424 }
425
426 /** Report the N-th argument type. */
427 BasicType parameterType(int n) {
428 assert(n < arity);
429 return names[n].type;
430 }
431
432 /** Report the arity. */
433 int arity() {
434 return arity;
435 }
436
437 /** Return the method type corresponding to my basic type signature. */
438 MethodType methodType() {
439 return signatureType(basicTypeSignature());
440 }
441 /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
442 final String basicTypeSignature() {
443 StringBuilder buf = new StringBuilder(arity() + 3);
444 for (int i = 0, a = arity(); i < a; i++)
445 buf.append(parameterType(i).basicTypeChar());
446 return buf.append('_').append(returnType().basicTypeChar()).toString();
447 }
448 static int signatureArity(String sig) {
449 assert(isValidSignature(sig));
450 return sig.indexOf('_');
451 }
452 static BasicType signatureReturn(String sig) {
453 return basicType(sig.charAt(signatureArity(sig)+1));
454 }
455 static boolean isValidSignature(String sig) {
456 int arity = sig.indexOf('_');
457 if (arity < 0) return false; // must be of the form *_*
458 int siglen = sig.length();
459 if (siglen != arity + 2) return false; // *_X
460 for (int i = 0; i < siglen; i++) {
461 if (i == arity) continue; // skip '_'
462 char c = sig.charAt(i);
463 if (c == 'V')
464 return (i == siglen - 1 && arity == siglen - 2);
465 if (!isArgBasicTypeChar(c)) return false; // must be [LIJFD]
466 }
467 return true; // [LIJFD]*_[LIJFDV]
468 }
469 static MethodType signatureType(String sig) {
470 Class<?>[] ptypes = new Class<?>[signatureArity(sig)];
471 for (int i = 0; i < ptypes.length; i++)
472 ptypes[i] = basicType(sig.charAt(i)).btClass;
473 Class<?> rtype = signatureReturn(sig).btClass;
474 return MethodType.methodType(rtype, ptypes);
475 }
476
477 /*
478 * Code generation issues:
479 *
480 * Compiled LFs should be reusable in general.
481 * The biggest issue is how to decide when to pull a name into
482 * the bytecode, versus loading a reified form from the MH data.
483 *
484 * For example, an asType wrapper may require execution of a cast
485 * after a call to a MH. The target type of the cast can be placed
486 * as a constant in the LF itself. This will force the cast type
487 * to be compiled into the bytecodes and native code for the MH.
488 * Or, the target type of the cast can be erased in the LF, and
489 * loaded from the MH data. (Later on, if the MH as a whole is
490 * inlined, the data will flow into the inlined instance of the LF,
491 * as a constant, and the end result will be an optimal cast.)
492 *
493 * This erasure of cast types can be done with any use of
637 LambdaForm prep = mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET);
638 if (prep != null) return prep;
639 assert(isValidSignature(sig));
640 prep = new LambdaForm(sig);
641 prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig);
642 //LambdaForm prep2 = PREPARED_FORMS.putIfAbsent(sig.intern(), prep);
643 return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep);
644 }
645
646 // The next few routines are called only from assert expressions
647 // They verify that the built-in invokers process the correct raw data types.
648 private static boolean argumentTypesMatch(String sig, Object[] av) {
649 int arity = signatureArity(sig);
650 assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
651 assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0];
652 MethodHandle mh = (MethodHandle) av[0];
653 MethodType mt = mh.type();
654 assert(mt.parameterCount() == arity-1);
655 for (int i = 0; i < av.length; i++) {
656 Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
657 assert(valueMatches(basicType(sig.charAt(i)), pt, av[i]));
658 }
659 return true;
660 }
661 private static boolean valueMatches(BasicType tc, Class<?> type, Object x) {
662 // The following line is needed because (...)void method handles can use non-void invokers
663 if (type == void.class) tc = V_TYPE; // can drop any kind of value
664 assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
665 switch (tc) {
666 case I_TYPE: assert checkInt(type, x) : "checkInt(" + type + "," + x +")"; break;
667 case J_TYPE: assert x instanceof Long : "instanceof Long: " + x; break;
668 case F_TYPE: assert x instanceof Float : "instanceof Float: " + x; break;
669 case D_TYPE: assert x instanceof Double : "instanceof Double: " + x; break;
670 case L_TYPE: assert checkRef(type, x) : "checkRef(" + type + "," + x + ")"; break;
671 case V_TYPE: break; // allow anything here; will be dropped
672 default: assert(false);
673 }
674 return true;
675 }
676 private static boolean returnTypesMatch(String sig, Object[] av, Object res) {
677 MethodHandle mh = (MethodHandle) av[0];
678 return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
679 }
680 private static boolean checkInt(Class<?> type, Object x) {
681 assert(x instanceof Integer);
682 if (type == int.class) return true;
683 Wrapper w = Wrapper.forBasicType(type);
684 assert(w.isSubwordOrInt());
685 Object x1 = Wrapper.INT.wrap(w.wrap(x));
686 return x.equals(x1);
687 }
688 private static boolean checkRef(Class<?> type, Object x) {
689 assert(!type.isPrimitive());
690 if (x == null) return true;
691 if (type.isInterface()) return true;
830 if (i+1 < arity) buf.append(",");
831 continue;
832 }
833 buf.append("=").append(n.exprString());
834 buf.append(";");
835 }
836 buf.append(result < 0 ? "void" : names[result]).append("}");
837 if (TRACE_INTERPRETER) {
838 // Extra verbosity:
839 buf.append(":").append(basicTypeSignature());
840 buf.append("/").append(vmentry);
841 }
842 return buf.toString();
843 }
844
845 /**
846 * Apply immediate binding for a Name in this form indicated by its position relative to the form.
847 * The first parameter to a LambdaForm, a0:L, always represents the form's method handle, so 0 is not
848 * accepted as valid.
849 */
850 LambdaForm bindImmediate(int pos, BasicType basicType, Object value) {
851 // must be an argument, and the types must match
852 assert pos > 0 && pos < arity && names[pos].type == basicType && Name.typesMatch(basicType, value);
853
854 int arity2 = arity - 1;
855 Name[] names2 = new Name[names.length - 1];
856 for (int r = 0, w = 0; r < names.length; ++r, ++w) { // (r)ead from names, (w)rite to names2
857 Name n = names[r];
858 if (n.isParam()) {
859 if (n.index == pos) {
860 // do not copy over the argument that is to be replaced with a literal,
861 // but adjust the write index
862 --w;
863 } else {
864 names2[w] = new Name(w, n.type);
865 }
866 } else {
867 Object[] arguments2 = new Object[n.arguments.length];
868 for (int i = 0; i < n.arguments.length; ++i) {
869 Object arg = n.arguments[i];
870 if (arg instanceof Name) {
876 arguments2[i] = names2[ni];
877 } else {
878 // replacement position passed
879 arguments2[i] = names2[ni - 1];
880 }
881 } else {
882 arguments2[i] = arg;
883 }
884 }
885 names2[w] = new Name(n.function, arguments2);
886 names2[w].initIndex(w);
887 }
888 }
889
890 int result2 = result == -1 ? -1 : result - 1;
891 return new LambdaForm(debugName, arity2, names2, result2);
892 }
893
894 LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) {
895 Name name = names[namePos];
896 BoundMethodHandle.SpeciesData newData = oldData.extendWith(name.type);
897 return bind(name, new Name(newData.getterFunction(oldData.fieldCount()), names[0]), oldData, newData);
898 }
899 LambdaForm bind(Name name, Name binding,
900 BoundMethodHandle.SpeciesData oldData,
901 BoundMethodHandle.SpeciesData newData) {
902 int pos = name.index;
903 assert(name.isParam());
904 assert(!binding.isParam());
905 assert(name.type == binding.type);
906 assert(0 <= pos && pos < arity && names[pos] == name);
907 assert(binding.function.memberDeclaringClassOrNull() == newData.clazz);
908 assert(oldData.getters.length == newData.getters.length-1);
909 if (bindCache != null) {
910 LambdaForm form = bindCache[pos];
911 if (form != null) {
912 assert(form.contains(binding)) : "form << " + form + " >> does not contain binding << " + binding + " >>";
913 return form;
914 }
915 } else {
916 bindCache = new LambdaForm[arity];
917 }
968 if (result2 == pos)
969 result2 = insPos;
970 else if (result2 > pos && result2 <= insPos)
971 result2 -= 1;
972
973 return bindCache[pos] = new LambdaForm(debugName, arity2, names2, result2);
974 }
975
976 boolean contains(Name name) {
977 int pos = name.index();
978 if (pos >= 0) {
979 return pos < names.length && name.equals(names[pos]);
980 }
981 for (int i = arity; i < names.length; i++) {
982 if (name.equals(names[i]))
983 return true;
984 }
985 return false;
986 }
987
988 LambdaForm addArguments(int pos, BasicType... types) {
989 assert(pos <= arity);
990 int length = names.length;
991 int inTypes = types.length;
992 Name[] names2 = Arrays.copyOf(names, length + inTypes);
993 int arity2 = arity + inTypes;
994 int result2 = result;
995 if (result2 >= arity)
996 result2 += inTypes;
997 // names array has MH in slot 0; skip it.
998 int argpos = pos + 1;
999 // Note: The LF constructor will rename names2[argpos...].
1000 // Make space for new arguments (shift temporaries).
1001 System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
1002 for (int i = 0; i < inTypes; i++) {
1003 names2[argpos + i] = new Name(types[i]);
1004 }
1005 return new LambdaForm(debugName, arity2, names2, result2);
1006 }
1007
1008 LambdaForm addArguments(int pos, List<Class<?>> types) {
1009 BasicType[] basicTypes = new BasicType[types.size()];
1010 for (int i = 0; i < basicTypes.length; i++)
1011 basicTypes[i] = basicType(types.get(i));
1012 return addArguments(pos, basicTypes);
1013 }
1014
1015 LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) {
1016 // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg.
1017 // The types are the types of the new (incoming) arguments.
1018 int length = names.length;
1019 int inTypes = types.length;
1020 int outArgs = reorder.length;
1021 assert(skip+outArgs == arity);
1022 assert(permutedTypesMatch(reorder, types, names, skip));
1023 int pos = 0;
1024 // skip trivial first part of reordering:
1025 while (pos < outArgs && reorder[pos] == pos) pos += 1;
1026 Name[] names2 = new Name[length - outArgs + inTypes];
1027 System.arraycopy(names, 0, names2, 0, skip+pos);
1028 // copy the body:
1029 int bodyLength = length - arity;
1030 System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength);
1031 int arity2 = names2.length - bodyLength;
1032 int result2 = result;
1033 if (result2 >= 0) {
1034 if (result2 < skip+outArgs) {
1035 // return the corresponding inArg
1054 }
1055 // some names are unused, but must be filled in
1056 for (int i = skip+pos; i < arity2; i++) {
1057 if (names2[i] == null)
1058 names2[i] = argument(i, types[i - skip]);
1059 }
1060 for (int j = arity; j < names.length; j++) {
1061 int i = j - arity + arity2;
1062 // replace names2[i] by names[j]
1063 Name n = names[j];
1064 Name n2 = names2[i];
1065 if (n != n2) {
1066 for (int k = i+1; k < names2.length; k++) {
1067 names2[k] = names2[k].replaceName(n, n2);
1068 }
1069 }
1070 }
1071 return new LambdaForm(debugName, arity2, names2, result2);
1072 }
1073
1074 static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) {
1075 int inTypes = types.length;
1076 int outArgs = reorder.length;
1077 for (int i = 0; i < outArgs; i++) {
1078 assert(names[skip+i].isParam());
1079 assert(names[skip+i].type == types[reorder[i]]);
1080 }
1081 return true;
1082 }
1083
1084 static class NamedFunction {
1085 final MemberName member;
1086 @Stable MethodHandle resolvedHandle;
1087 @Stable MethodHandle invoker;
1088
1089 NamedFunction(MethodHandle resolvedHandle) {
1090 this(resolvedHandle.internalMemberName(), resolvedHandle);
1091 }
1092 NamedFunction(MemberName member, MethodHandle resolvedHandle) {
1093 this.member = member;
1094 //resolvedHandle = eraseSubwordTypes(resolvedHandle);
1138 return this.member != null && this.member.equals(that.member);
1139 }
1140
1141 @Override
1142 public int hashCode() {
1143 if (member != null)
1144 return member.hashCode();
1145 return super.hashCode();
1146 }
1147
1148 // Put the predefined NamedFunction invokers into the table.
1149 static void initializeInvokers() {
1150 for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
1151 if (!m.isStatic() || !m.isPackage()) continue;
1152 MethodType type = m.getMethodType();
1153 if (type.equals(INVOKER_METHOD_TYPE) &&
1154 m.getName().startsWith("invoke_")) {
1155 String sig = m.getName().substring("invoke_".length());
1156 int arity = LambdaForm.signatureArity(sig);
1157 MethodType srcType = MethodType.genericMethodType(arity);
1158 if (LambdaForm.signatureReturn(sig) == V_TYPE)
1159 srcType = srcType.changeReturnType(void.class);
1160 MethodTypeForm typeForm = srcType.form();
1161 typeForm.namedFunctionInvoker = DirectMethodHandle.make(m);
1162 }
1163 }
1164 }
1165
1166 // The following are predefined NamedFunction invokers. The system must build
1167 // a separate invoker for each distinct signature.
1168 /** void return type invokers. */
1169 @Hidden
1170 static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1171 assert(a.length == 0);
1172 mh.invokeBasic();
1173 return null;
1174 }
1175 @Hidden
1176 static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1177 assert(a.length == 1);
1178 mh.invokeBasic(a[0]);
1228 assert(a.length == 4);
1229 return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1230 }
1231 @Hidden
1232 static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1233 assert(a.length == 5);
1234 return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1235 }
1236
1237 static final MethodType INVOKER_METHOD_TYPE =
1238 MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1239
1240 private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1241 MethodHandle mh = typeForm.namedFunctionInvoker;
1242 if (mh != null) return mh;
1243 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while
1244 mh = DirectMethodHandle.make(invoker);
1245 MethodHandle mh2 = typeForm.namedFunctionInvoker;
1246 if (mh2 != null) return mh2; // benign race
1247 if (!mh.type().equals(INVOKER_METHOD_TYPE))
1248 throw newInternalError(mh.debugString());
1249 return typeForm.namedFunctionInvoker = mh;
1250 }
1251
1252 @Hidden
1253 Object invokeWithArguments(Object... arguments) throws Throwable {
1254 // If we have a cached invoker, call it right away.
1255 // NOTE: The invoker always returns a reference value.
1256 if (TRACE_INTERPRETER) return invokeWithArgumentsTracing(arguments);
1257 assert(checkArgumentTypes(arguments, methodType()));
1258 return invoker().invokeBasic(resolvedHandle(), arguments);
1259 }
1260
1261 @Hidden
1262 Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
1263 Object rval;
1264 try {
1265 traceInterpreter("[ call", this, arguments);
1266 if (invoker == null) {
1267 traceInterpreter("| getInvoker", this);
1268 invoker();
1318 }
1319
1320 MemberName member() {
1321 assert(assertMemberIsConsistent());
1322 return member;
1323 }
1324
1325 // Called only from assert.
1326 private boolean assertMemberIsConsistent() {
1327 if (resolvedHandle instanceof DirectMethodHandle) {
1328 MemberName m = resolvedHandle.internalMemberName();
1329 assert(m.equals(member));
1330 }
1331 return true;
1332 }
1333
1334 Class<?> memberDeclaringClassOrNull() {
1335 return (member == null) ? null : member.getDeclaringClass();
1336 }
1337
1338 BasicType returnType() {
1339 return basicType(methodType().returnType());
1340 }
1341
1342 BasicType parameterType(int n) {
1343 return basicType(methodType().parameterType(n));
1344 }
1345
1346 int arity() {
1347 //int siglen = member.getMethodType().parameterCount();
1348 //if (!member.isStatic()) siglen += 1;
1349 //return siglen;
1350 return methodType().parameterCount();
1351 }
1352
1353 public String toString() {
1354 if (member == null) return String.valueOf(resolvedHandle);
1355 return member.getDeclaringClass().getSimpleName()+"."+member.getName();
1356 }
1357
1358 public boolean isIdentity() {
1359 return this.equals(identity(returnType()));
1360 }
1361
1362 public boolean isConstantZero() {
1363 return this.equals(constantZero(returnType()));
1364 }
1365 }
1366
1367 void resolve() {
1368 for (Name n : names) n.resolve();
1369 }
1370
1371 public static String basicTypeSignature(MethodType type) {
1372 char[] sig = new char[type.parameterCount() + 2];
1373 int sigp = 0;
1374 for (Class<?> pt : type.parameterList()) {
1375 sig[sigp++] = basicTypeChar(pt);
1376 }
1377 sig[sigp++] = '_';
1378 sig[sigp++] = basicTypeChar(type.returnType());
1379 assert(sigp == sig.length);
1380 return String.valueOf(sig);
1381 }
1382 public static String shortenSignature(String signature) {
1383 // Hack to make signatures more readable when they show up in method names.
1384 final int NO_CHAR = -1, MIN_RUN = 3;
1385 int c0, c1 = NO_CHAR, c1reps = 0;
1386 StringBuilder buf = null;
1387 int len = signature.length();
1388 if (len < MIN_RUN) return signature;
1389 for (int i = 0; i <= len; i++) {
1390 // shift in the next char:
1391 c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i));
1392 if (c1 == c0) { ++c1reps; continue; }
1393 // shift in the next count:
1394 int c0reps = c1reps; c1reps = 1;
1395 // end of a character run
1396 if (c0reps < MIN_RUN) {
1397 if (buf != null) {
1398 while (--c0reps >= 0)
1399 buf.append((char)c0);
1400 }
1401 continue;
1402 }
1403 // found three or more in a row
1404 if (buf == null)
1405 buf = new StringBuilder().append(signature, 0, i - c0reps);
1406 buf.append((char)c0).append(c0reps);
1407 }
1408 return (buf == null) ? signature : buf.toString();
1409 }
1410
1411 static final class Name {
1412 final BasicType type;
1413 private short index;
1414 final NamedFunction function;
1415 @Stable final Object[] arguments;
1416
1417 private Name(int index, BasicType type, NamedFunction function, Object[] arguments) {
1418 this.index = (short)index;
1419 this.type = type;
1420 this.function = function;
1421 this.arguments = arguments;
1422 assert(this.index == index);
1423 }
1424 Name(MethodHandle function, Object... arguments) {
1425 this(new NamedFunction(function), arguments);
1426 }
1427 Name(MethodType functionType, Object... arguments) {
1428 this(new NamedFunction(functionType), arguments);
1429 assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE);
1430 }
1431 Name(MemberName function, Object... arguments) {
1432 this(new NamedFunction(function), arguments);
1433 }
1434 Name(NamedFunction function, Object... arguments) {
1435 this(-1, function.returnType(), function, arguments = arguments.clone());
1436 assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
1437 for (int i = 0; i < arguments.length; i++)
1438 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
1439 }
1440 /** Create a raw parameter of the given type, with an expected index. */
1441 Name(int index, BasicType type) {
1442 this(index, type, null, null);
1443 }
1444 /** Create a raw parameter of the given type. */
1445 Name(BasicType type) { this(-1, type); }
1446
1447 BasicType type() { return type; }
1448 int index() { return index; }
1449 boolean initIndex(int i) {
1450 if (index != i) {
1451 if (index != -1) return false;
1452 index = (short)i;
1453 }
1454 return true;
1455 }
1456 char typeChar() {
1457 return type.btChar;
1458 }
1459
1460 void resolve() {
1461 if (function != null)
1462 function.resolve();
1463 }
1464
1465 Name newIndex(int i) {
1466 if (initIndex(i)) return this;
1467 return cloneWithIndex(i);
1468 }
1469 Name cloneWithIndex(int i) {
1470 Object[] newArguments = (arguments == null) ? null : arguments.clone();
1471 return new Name(i, type, function, newArguments);
1472 }
1473 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly
1474 if (oldName == newName) return this;
1475 @SuppressWarnings("LocalVariableHidesMemberVariable")
1476 Object[] arguments = this.arguments;
1477 if (arguments == null) return this;
1478 boolean replaced = false;
1516 }
1517 }
1518 if (!replaced) return this;
1519 return new Name(function, arguments);
1520 }
1521 void internArguments() {
1522 @SuppressWarnings("LocalVariableHidesMemberVariable")
1523 Object[] arguments = this.arguments;
1524 for (int j = 0; j < arguments.length; j++) {
1525 if (arguments[j] instanceof Name) {
1526 Name n = (Name) arguments[j];
1527 if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
1528 arguments[j] = internArgument(n);
1529 }
1530 }
1531 }
1532 boolean isParam() {
1533 return function == null;
1534 }
1535 boolean isConstantZero() {
1536 return !isParam() && arguments.length == 0 && function.isConstantZero();
1537 }
1538
1539 public String toString() {
1540 return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar();
1541 }
1542 public String debugString() {
1543 String s = toString();
1544 return (function == null) ? s : s + "=" + exprString();
1545 }
1546 public String exprString() {
1547 if (function == null) return toString();
1548 StringBuilder buf = new StringBuilder(function.toString());
1549 buf.append("(");
1550 String cma = "";
1551 for (Object a : arguments) {
1552 buf.append(cma); cma = ",";
1553 if (a instanceof Name || a instanceof Integer)
1554 buf.append(a);
1555 else
1556 buf.append("(").append(a).append(")");
1557 }
1558 buf.append(")");
1559 return buf.toString();
1560 }
1561
1562 static boolean typesMatch(BasicType parameterType, Object object) {
1563 if (object instanceof Name) {
1564 return ((Name)object).type == parameterType;
1565 }
1566 switch (parameterType) {
1567 case I_TYPE: return object instanceof Integer;
1568 case J_TYPE: return object instanceof Long;
1569 case F_TYPE: return object instanceof Float;
1570 case D_TYPE: return object instanceof Double;
1571 }
1572 assert(parameterType == L_TYPE);
1573 return true;
1574 }
1575
1576 /**
1577 * Does this Name precede the given binding node in some canonical order?
1578 * This predicate is used to order data bindings (via insertion sort)
1579 * with some stability.
1580 */
1581 boolean isSiblingBindingBefore(Name binding) {
1582 assert(!binding.isParam());
1583 if (isParam()) return true;
1584 if (function.equals(binding.function) &&
1585 arguments.length == binding.arguments.length) {
1586 boolean sawInt = false;
1587 for (int i = 0; i < arguments.length; i++) {
1588 Object a1 = arguments[i];
1589 Object a2 = binding.arguments[i];
1590 if (!a1.equals(a2)) {
1591 if (a1 instanceof Integer && a2 instanceof Integer) {
1592 if (sawInt) continue;
1629 }
1630
1631 public boolean equals(Name that) {
1632 if (this == that) return true;
1633 if (isParam())
1634 // each parameter is a unique atom
1635 return false; // this != that
1636 return
1637 //this.index == that.index &&
1638 this.type == that.type &&
1639 this.function.equals(that.function) &&
1640 Arrays.equals(this.arguments, that.arguments);
1641 }
1642 @Override
1643 public boolean equals(Object x) {
1644 return x instanceof Name && equals((Name)x);
1645 }
1646 @Override
1647 public int hashCode() {
1648 if (isParam())
1649 return index | (type.ordinal() << 8);
1650 return function.hashCode() ^ Arrays.hashCode(arguments);
1651 }
1652 }
1653
1654 /** Return the index of the last name which contains n as an argument.
1655 * Return -1 if the name is not used. Return names.length if it is the return value.
1656 */
1657 int lastUseIndex(Name n) {
1658 int ni = n.index, nmax = names.length;
1659 assert(names[ni] == n);
1660 if (result == ni) return nmax; // live all the way beyond the end
1661 for (int i = nmax; --i > ni; ) {
1662 if (names[i].lastUseIndex(n) >= 0)
1663 return i;
1664 }
1665 return -1;
1666 }
1667
1668 /** Return the number of times n is used as an argument or return value. */
1669 int useCount(Name n) {
1670 int ni = n.index, nmax = names.length;
1671 int end = lastUseIndex(n);
1672 if (end < 0) return 0;
1673 int count = 0;
1674 if (end == nmax) { count++; end--; }
1675 int beg = n.index() + 1;
1676 if (beg < arity) beg = arity;
1677 for (int i = beg; i <= end; i++) {
1678 count += names[i].useCount(n);
1679 }
1680 return count;
1681 }
1682
1683 static Name argument(int which, char type) {
1684 return argument(which, basicType(type));
1685 }
1686 static Name argument(int which, BasicType type) {
1687 if (which >= INTERNED_ARGUMENT_LIMIT)
1688 return new Name(which, type);
1689 return INTERNED_ARGUMENTS[type.ordinal()][which];
1690 }
1691 static Name internArgument(Name n) {
1692 assert(n.isParam()) : "not param: " + n;
1693 assert(n.index < INTERNED_ARGUMENT_LIMIT);
1694 return argument(n.index, n.type);
1695 }
1696 static Name[] arguments(int extra, String types) {
1697 int length = types.length();
1698 Name[] names = new Name[length + extra];
1699 for (int i = 0; i < length; i++)
1700 names[i] = argument(i, types.charAt(i));
1701 return names;
1702 }
1703 static Name[] arguments(int extra, char... types) {
1704 int length = types.length;
1705 Name[] names = new Name[length + extra];
1706 for (int i = 0; i < length; i++)
1707 names[i] = argument(i, types[i]);
1708 return names;
1709 }
1711 int length = types.size();
1712 Name[] names = new Name[length + extra];
1713 for (int i = 0; i < length; i++)
1714 names[i] = argument(i, basicType(types.get(i)));
1715 return names;
1716 }
1717 static Name[] arguments(int extra, Class<?>... types) {
1718 int length = types.length;
1719 Name[] names = new Name[length + extra];
1720 for (int i = 0; i < length; i++)
1721 names[i] = argument(i, basicType(types[i]));
1722 return names;
1723 }
1724 static Name[] arguments(int extra, MethodType types) {
1725 int length = types.parameterCount();
1726 Name[] names = new Name[length + extra];
1727 for (int i = 0; i < length; i++)
1728 names[i] = argument(i, basicType(types.parameterType(i)));
1729 return names;
1730 }
1731 static final int INTERNED_ARGUMENT_LIMIT = 10;
1732 private static final Name[][] INTERNED_ARGUMENTS
1733 = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT];
1734 static {
1735 for (BasicType type : BasicType.ARG_TYPES) {
1736 int ord = type.ordinal();
1737 for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) {
1738 INTERNED_ARGUMENTS[ord][i] = new Name(i, type);
1739 }
1740 }
1741 }
1742
1743 private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1744
1745 static LambdaForm identityForm(BasicType type) {
1746 return LF_identityForm[type.ordinal()];
1747 }
1748 static LambdaForm zeroForm(BasicType type) {
1749 return LF_zeroForm[type.ordinal()];
1750 }
1751 static NamedFunction identity(BasicType type) {
1752 return NF_identity[type.ordinal()];
1753 }
1754 static NamedFunction constantZero(BasicType type) {
1755 return NF_zero[type.ordinal()];
1756 }
1757 private static final LambdaForm[] LF_identityForm = new LambdaForm[TYPE_LIMIT];
1758 private static final LambdaForm[] LF_zeroForm = new LambdaForm[TYPE_LIMIT];
1759 private static final NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT];
1760 private static final NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT];
1761 private static void createIdentityForms() {
1762 for (BasicType type : BasicType.ALL_TYPES) {
1763 int ord = type.ordinal();
1764 char btChar = type.basicTypeChar();
1765 boolean isVoid = (type == V_TYPE);
1766 Class<?> btClass = type.btClass;
1767 MethodType zeType = MethodType.methodType(btClass);
1768 MethodType idType = isVoid ? zeType : zeType.appendParameterTypes(btClass);
1769
1770 // Look up some symbolic names. It might not be necessary to have these,
1771 // but if we need to emit direct references to bytecodes, it helps.
1772 // Zero is built from a call to an identity function with a constant zero input.
1773 MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic);
1774 MemberName zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic);
1775 try {
1776 zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class);
1777 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class);
1778 } catch (IllegalAccessException|NoSuchMethodException ex) {
1779 throw newInternalError(ex);
1780 }
1781
1782 NamedFunction idFun = new NamedFunction(idMem);
1783 LambdaForm idForm;
1784 if (isVoid) {
1785 Name[] idNames = new Name[] { argument(0, L_TYPE) };
1786 idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT);
1787 } else {
1788 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
1789 idForm = new LambdaForm(idMem.getName(), 2, idNames, 1);
1790 }
1791 LF_identityForm[ord] = idForm;
1792 NF_identity[ord] = idFun;
1793 //idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm);
1794
1795 NamedFunction zeFun = new NamedFunction(zeMem);
1796 LambdaForm zeForm;
1797 if (isVoid) {
1798 zeForm = idForm;
1799 } else {
1800 Object zeValue = Wrapper.forBasicType(btChar).zero();
1801 Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) };
1802 zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1);
1803 }
1804 LF_zeroForm[ord] = zeForm;
1805 NF_zero[ord] = zeFun;
1806 //zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm);
1807
1808 assert(idFun.isIdentity());
1809 assert(zeFun.isConstantZero());
1810 assert(new Name(zeFun).isConstantZero());
1811 }
1812
1813 // Do this in a separate pass, so that SimpleMethodHandle.make can see the tables.
1814 for (BasicType type : BasicType.ALL_TYPES) {
1815 int ord = type.ordinal();
1816 NamedFunction idFun = NF_identity[ord];
1817 LambdaForm idForm = LF_identityForm[ord];
1818 MemberName idMem = idFun.member;
1819 idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm);
1820
1821 NamedFunction zeFun = NF_zero[ord];
1822 LambdaForm zeForm = LF_zeroForm[ord];
1823 MemberName zeMem = zeFun.member;
1824 zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm);
1825
1826 assert(idFun.isIdentity());
1827 assert(zeFun.isConstantZero());
1828 assert(new Name(zeFun).isConstantZero());
1829 }
1830 }
1831
1832 // Avoid appealing to ValueConversions at bootstrap time:
1833 private static int identity_I(int x) { return x; }
1834 private static long identity_J(long x) { return x; }
1835 private static float identity_F(float x) { return x; }
1836 private static double identity_D(double x) { return x; }
1837 private static Object identity_L(Object x) { return x; }
1838 private static void identity_V() { return; } // same as zeroV, but that's OK
1839 private static int zero_I() { return 0; }
1840 private static long zero_J() { return 0; }
1841 private static float zero_F() { return 0; }
1842 private static double zero_D() { return 0; }
1843 private static Object zero_L() { return null; }
1844 private static void zero_V() { return; }
1845
1846 /**
1847 * Internal marker for byte-compiled LambdaForms.
1848 */
1849 /*non-public*/
1850 @Target(ElementType.METHOD)
1851 @Retention(RetentionPolicy.RUNTIME)
1852 @interface Compiled {
1853 }
1854
1855 /**
1856 * Internal marker for LambdaForm interpreter frames.
1857 */
1858 /*non-public*/
1859 @Target(ElementType.METHOD)
1860 @Retention(RetentionPolicy.RUNTIME)
1861 @interface Hidden {
1862 }
1863
1864
1875 Object[] abc = { "a", "bc" };
1876 List<?> lst = (List<?>) MethodHandle.linkToStatic(abc, asList_MN);
1877 System.out.println("lst="+lst);
1878 MemberName toString_MN = new MemberName(Object.class.getMethod("toString"));
1879 String s1 = (String) MethodHandle.linkToVirtual(lst, toString_MN);
1880 toString_MN = new MemberName(Object.class.getMethod("toString"), true);
1881 String s2 = (String) MethodHandle.linkToSpecial(lst, toString_MN);
1882 System.out.println("[s1,s2,lst]="+Arrays.asList(s1, s2, lst.toString()));
1883 MemberName toArray_MN = new MemberName(List.class.getMethod("toArray"));
1884 Object[] arr = (Object[]) MethodHandle.linkToInterface(lst, toArray_MN);
1885 System.out.println("toArray="+Arrays.toString(arr));
1886 }
1887 static { try { testMethodHandleLinkers(); } catch (Throwable ex) { throw new RuntimeException(ex); } }
1888 // Requires these definitions in MethodHandle:
1889 static final native Object linkToStatic(Object x1, MemberName mn) throws Throwable;
1890 static final native Object linkToVirtual(Object x1, MemberName mn) throws Throwable;
1891 static final native Object linkToSpecial(Object x1, MemberName mn) throws Throwable;
1892 static final native Object linkToInterface(Object x1, MemberName mn) throws Throwable;
1893 */
1894
1895 private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1896 static {
1897 if (debugEnabled())
1898 DEBUG_NAME_COUNTERS = new HashMap<>();
1899 else
1900 DEBUG_NAME_COUNTERS = null;
1901 }
1902
1903 // Put this last, so that previous static inits can run before.
1904 static {
1905 createIdentityForms();
1906 if (USE_PREDEFINED_INTERPRET_METHODS)
1907 PREPARED_FORMS.putAll(computeInitialPreparedForms());
1908 NamedFunction.initializeInvokers();
1909 }
1910
1911 // The following hack is necessary in order to suppress TRACE_INTERPRETER
1912 // during execution of the static initializes of this class.
1913 // Turning on TRACE_INTERPRETER too early will cause
1914 // stack overflows and other misbehavior during attempts to trace events
1915 // that occur during LambdaForm.<clinit>.
1916 // Therefore, do not move this line higher in this file, and do not remove.
1917 private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
1918 }
|