226 for (int i = 0; i < ARG_TYPE_LIMIT; i++) {
227 assert ARG_TYPES[i].ordinal() == i;
228 assert ARG_TYPES[i] == ALL_TYPES[i];
229 }
230 for (int i = 0; i < TYPE_LIMIT; i++) {
231 assert ALL_TYPES[i].ordinal() == i;
232 }
233 assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE;
234 assert !Arrays.asList(ARG_TYPES).contains(V_TYPE);
235 return true;
236 }
237 }
238
239 LambdaForm(String debugName,
240 int arity, Name[] names, int result) {
241 assert(namesOK(arity, names));
242 this.arity = arity;
243 this.result = fixResult(result, names);
244 this.names = names.clone();
245 this.debugName = fixDebugName(debugName);
246 normalize();
247 }
248
249 LambdaForm(String debugName,
250 int arity, Name[] names) {
251 this(debugName,
252 arity, names, LAST_RESULT);
253 }
254
255 LambdaForm(String debugName,
256 Name[] formals, Name[] temps, Name result) {
257 this(debugName,
258 formals.length, buildNames(formals, temps, result), LAST_RESULT);
259 }
260
261 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
262 int arity = formals.length;
263 int length = arity + temps.length + (result == null ? 0 : 1);
264 Name[] names = Arrays.copyOf(formals, length);
265 System.arraycopy(temps, 0, names, arity, temps.length);
266 if (result != null)
331 if (under < length)
332 buf.append('_').append(debugName, under, length);
333 }
334 return buf.toString();
335 }
336 return debugName;
337 }
338
339 private static boolean namesOK(int arity, Name[] names) {
340 for (int i = 0; i < names.length; i++) {
341 Name n = names[i];
342 assert(n != null) : "n is null";
343 if (i < arity)
344 assert( n.isParam()) : n + " is not param at " + i;
345 else
346 assert(!n.isParam()) : n + " is param at " + i;
347 }
348 return true;
349 }
350
351 /** Renumber and/or replace params so that they are interned and canonically numbered. */
352 private void normalize() {
353 Name[] oldNames = null;
354 int changesStart = 0;
355 for (int i = 0; i < names.length; i++) {
356 Name n = names[i];
357 if (!n.initIndex(i)) {
358 if (oldNames == null) {
359 oldNames = names.clone();
360 changesStart = i;
361 }
362 names[i] = n.cloneWithIndex(i);
363 }
364 }
365 if (oldNames != null) {
366 int startFixing = arity;
367 if (startFixing <= changesStart)
368 startFixing = changesStart+1;
369 for (int i = startFixing; i < names.length; i++) {
370 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i);
371 names[i] = fixed.newIndex(i);
372 }
373 }
374 assert(nameRefsAreLegal());
375 int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
376 boolean needIntern = false;
377 for (int i = 0; i < maxInterned; i++) {
378 Name n = names[i], n2 = internArgument(n);
379 if (n != n2) {
380 names[i] = n2;
381 needIntern = true;
382 }
383 }
384 if (needIntern) {
385 for (int i = arity; i < names.length; i++) {
386 names[i].internArguments();
387 }
388 assert(nameRefsAreLegal());
389 }
390 }
391
392 /**
393 * Check that all embedded Name references are localizable to this lambda,
394 * and are properly ordered after their corresponding definitions.
395 * <p>
396 * Note that a Name can be local to multiple lambdas, as long as
397 * it possesses the same index in each use site.
398 * This allows Name references to be freely reused to construct
399 * fresh lambdas, without confusion.
400 */
401 private boolean nameRefsAreLegal() {
402 assert(arity >= 0 && arity <= names.length);
403 assert(result >= -1 && result < names.length);
404 // Do all names possess an index consistent with their local definition order?
405 for (int i = 0; i < arity; i++) {
406 Name n = names[i];
407 assert(n.index() == i) : Arrays.asList(n.index(), i);
408 assert(n.isParam());
409 }
565 }
566 LambdaForm prep = getPreparedForm(basicTypeSignature());
567 this.vmentry = prep.vmentry;
568 // TO DO: Maybe add invokeGeneric, invokeWithArguments
569 }
570
571 /** Generate optimizable bytecode for this form. */
572 MemberName compileToBytecode() {
573 MethodType invokerType = methodType();
574 assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
575 if (vmentry != null && isCompiled) {
576 return vmentry; // already compiled somehow
577 }
578 try {
579 vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
580 if (TRACE_INTERPRETER)
581 traceInterpreter("compileToBytecode", this);
582 isCompiled = true;
583 return vmentry;
584 } catch (Error | Exception ex) {
585 throw newInternalError("compileToBytecode: " + this, ex);
586 }
587 }
588
589 private static final ConcurrentHashMap<String,LambdaForm> PREPARED_FORMS;
590 static {
591 int capacity = 512; // expect many distinct signatures over time
592 float loadFactor = 0.75f; // normal default
593 int writers = 1;
594 PREPARED_FORMS = new ConcurrentHashMap<>(capacity, loadFactor, writers);
595 }
596
597 private static Map<String,LambdaForm> computeInitialPreparedForms() {
598 // Find all predefined invokers and associate them with canonical empty lambda forms.
599 HashMap<String,LambdaForm> forms = new HashMap<>();
600 for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
601 if (!m.isStatic() || !m.isPackage()) continue;
602 MethodType mt = m.getMethodType();
603 if (mt.parameterCount() > 0 &&
604 mt.parameterType(0) == MethodHandle.class &&
605 m.getName().startsWith("interpret_")) {
692 return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
693 }
694 private static boolean checkInt(Class<?> type, Object x) {
695 assert(x instanceof Integer);
696 if (type == int.class) return true;
697 Wrapper w = Wrapper.forBasicType(type);
698 assert(w.isSubwordOrInt());
699 Object x1 = Wrapper.INT.wrap(w.wrap(x));
700 return x.equals(x1);
701 }
702 private static boolean checkRef(Class<?> type, Object x) {
703 assert(!type.isPrimitive());
704 if (x == null) return true;
705 if (type.isInterface()) return true;
706 return type.isInstance(x);
707 }
708
709 /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
710 private static final int COMPILE_THRESHOLD;
711 static {
712 if (MethodHandleStatics.COMPILE_THRESHOLD != null)
713 COMPILE_THRESHOLD = MethodHandleStatics.COMPILE_THRESHOLD;
714 else
715 COMPILE_THRESHOLD = 30; // default value
716 }
717 private int invocationCounter = 0;
718
719 @Hidden
720 @DontInline
721 /** Interpretively invoke this form on the given arguments. */
722 Object interpretWithArguments(Object... argumentValues) throws Throwable {
723 if (TRACE_INTERPRETER)
724 return interpretWithArgumentsTracing(argumentValues);
725 checkInvocationCounter();
726 assert(arityCheck(argumentValues));
727 Object[] values = Arrays.copyOf(argumentValues, names.length);
728 for (int i = argumentValues.length; i < values.length; i++) {
729 values[i] = interpretName(names[i], values);
730 }
731 return (result < 0) ? null : values[result];
732 }
733
734 @Hidden
735 @DontInline
736 /** Evaluate a single Name within this form, applying its function to its arguments. */
737 Object interpretName(Name name, Object[] values) throws Throwable {
738 if (TRACE_INTERPRETER)
739 traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
740 Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
741 for (int i = 0; i < arguments.length; i++) {
742 Object a = arguments[i];
743 if (a instanceof Name) {
744 int i2 = ((Name)a).index();
745 assert(names[i2] == a);
746 a = values[i2];
747 arguments[i] = a;
748 }
749 }
750 return name.function.invokeWithArguments(arguments);
751 }
802 if (!type.isPrimitive()) return type;
803 if (type == int.class) return type;
804 Wrapper w = Wrapper.forPrimitiveType(type);
805 if (w.isSubwordOrInt()) return int.class;
806 return type;
807 }
808 */
809
810 static void traceInterpreter(String event, Object obj, Object... args) {
811 if (TRACE_INTERPRETER) {
812 System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
813 }
814 }
815 static void traceInterpreter(String event, Object obj) {
816 traceInterpreter(event, obj, (Object[])null);
817 }
818 private boolean arityCheck(Object[] argumentValues) {
819 assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
820 // also check that the leading (receiver) argument is somehow bound to this LF:
821 assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
822 assert(((MethodHandle)argumentValues[0]).internalForm() == this);
823 // note: argument #0 could also be an interface wrapper, in the future
824 return true;
825 }
826
827 private boolean isEmpty() {
828 if (result < 0)
829 return (names.length == arity);
830 else if (result == arity && names.length == arity + 1)
831 return names[arity].isConstantZero();
832 else
833 return false;
834 }
835
836 public String toString() {
837 StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
838 for (int i = 0; i < names.length; i++) {
839 if (i == arity) buf.append(")=>{");
840 Name n = names[i];
841 if (i >= arity) buf.append("\n ");
842 buf.append(n);
843 if (i < arity) {
844 if (i+1 < arity) buf.append(",");
845 continue;
846 }
847 buf.append("=").append(n.exprString());
848 buf.append(";");
849 }
850 buf.append(result < 0 ? "void" : names[result]).append("}");
851 if (TRACE_INTERPRETER) {
852 // Extra verbosity:
853 buf.append(":").append(basicTypeSignature());
854 buf.append("/").append(vmentry);
855 }
856 return buf.toString();
857 }
858
859 /**
860 * Apply immediate binding for a Name in this form indicated by its position relative to the form.
861 * The first parameter to a LambdaForm, a0:L, always represents the form's method handle, so 0 is not
862 * accepted as valid.
863 */
864 LambdaForm bindImmediate(int pos, BasicType basicType, Object value) {
865 // must be an argument, and the types must match
866 assert pos > 0 && pos < arity && names[pos].type == basicType && Name.typesMatch(basicType, value);
867
868 int arity2 = arity - 1;
869 Name[] names2 = new Name[names.length - 1];
870 for (int r = 0, w = 0; r < names.length; ++r, ++w) { // (r)ead from names, (w)rite to names2
871 Name n = names[r];
872 if (n.isParam()) {
873 if (n.index == pos) {
874 // do not copy over the argument that is to be replaced with a literal,
875 // but adjust the write index
876 --w;
877 } else {
878 names2[w] = new Name(w, n.type);
879 }
880 } else {
881 Object[] arguments2 = new Object[n.arguments.length];
882 for (int i = 0; i < n.arguments.length; ++i) {
883 Object arg = n.arguments[i];
884 if (arg instanceof Name) {
885 int ni = ((Name) arg).index;
886 if (ni == pos) {
887 arguments2[i] = value;
888 } else if (ni < pos) {
889 // replacement position not yet passed
890 arguments2[i] = names2[ni];
891 } else {
892 // replacement position passed
893 arguments2[i] = names2[ni - 1];
894 }
895 } else {
896 arguments2[i] = arg;
897 }
898 }
899 names2[w] = new Name(n.function, arguments2);
900 names2[w].initIndex(w);
901 }
902 }
903
904 int result2 = result == -1 ? -1 : result - 1;
905 return new LambdaForm(debugName, arity2, names2, result2);
906 }
907
908 LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) {
909 Name name = names[namePos];
910 BoundMethodHandle.SpeciesData newData = oldData.extendWith(name.type);
911 return bind(name, new Name(newData.getterFunction(oldData.fieldCount()), names[0]), oldData, newData);
912 }
913 LambdaForm bind(Name name, Name binding,
914 BoundMethodHandle.SpeciesData oldData,
915 BoundMethodHandle.SpeciesData newData) {
916 int pos = name.index;
917 assert(name.isParam());
918 assert(!binding.isParam());
919 assert(name.type == binding.type);
920 assert(0 <= pos && pos < arity && names[pos] == name);
921 assert(binding.function.memberDeclaringClassOrNull() == newData.clazz);
922 assert(oldData.getters.length == newData.getters.length-1);
923 if (bindCache != null) {
924 LambdaForm form = bindCache[pos];
925 if (form != null) {
926 assert(form.contains(binding)) : "form << " + form + " >> does not contain binding << " + binding + " >>";
927 return form;
952 Name n2 = new Name(newGetter, n.arguments);
953 names2[i] = n2;
954 }
955 }
956 }
957
958 // Walk over the new list of names once, in forward order.
959 // Replace references to 'name' with 'binding'.
960 // Replace data structure references to the old BMH species with the new.
961 // This might cause a ripple effect, but it will settle in one pass.
962 assert(firstOldRef < 0 || firstOldRef > pos);
963 for (int i = pos+1; i < names2.length; i++) {
964 if (i <= arity2) continue;
965 names2[i] = names2[i].replaceNames(names, names2, pos, i);
966 }
967
968 // (a0, a1, name=a2, a3, a4) => (a0, a1, a3, a4, binding)
969 int insPos = pos;
970 for (; insPos+1 < names2.length; insPos++) {
971 Name n = names2[insPos+1];
972 if (n.isSiblingBindingBefore(binding)) {
973 names2[insPos] = n;
974 } else {
975 break;
976 }
977 }
978 names2[insPos] = binding;
979
980 // Since we moved some stuff, maybe update the result reference:
981 int result2 = result;
982 if (result2 == pos)
983 result2 = insPos;
984 else if (result2 > pos && result2 <= insPos)
985 result2 -= 1;
986
987 return bindCache[pos] = new LambdaForm(debugName, arity2, names2, result2);
988 }
989
990 boolean contains(Name name) {
991 int pos = name.index();
992 if (pos >= 0) {
993 return pos < names.length && name.equals(names[pos]);
994 }
995 for (int i = arity; i < names.length; i++) {
996 if (name.equals(names[i]))
997 return true;
998 }
999 return false;
1000 }
1001
1002 LambdaForm addArguments(int pos, BasicType... types) {
1003 assert(pos <= arity);
1004 int length = names.length;
1005 int inTypes = types.length;
1006 Name[] names2 = Arrays.copyOf(names, length + inTypes);
1007 int arity2 = arity + inTypes;
1008 int result2 = result;
1009 if (result2 >= arity)
1010 result2 += inTypes;
1011 // names array has MH in slot 0; skip it.
1012 int argpos = pos + 1;
1013 // Note: The LF constructor will rename names2[argpos...].
1014 // Make space for new arguments (shift temporaries).
1015 System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
1016 for (int i = 0; i < inTypes; i++) {
1017 names2[argpos + i] = new Name(types[i]);
1018 }
1019 return new LambdaForm(debugName, arity2, names2, result2);
1020 }
1021
1022 LambdaForm addArguments(int pos, List<Class<?>> types) {
1023 return addArguments(pos, basicTypes(types));
1024 }
1025
1026 LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) {
1027 // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg.
1028 // The types are the types of the new (incoming) arguments.
1029 int length = names.length;
1030 int inTypes = types.length;
1031 int outArgs = reorder.length;
1032 assert(skip+outArgs == arity);
1085 static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) {
1086 int inTypes = types.length;
1087 int outArgs = reorder.length;
1088 for (int i = 0; i < outArgs; i++) {
1089 assert(names[skip+i].isParam());
1090 assert(names[skip+i].type == types[reorder[i]]);
1091 }
1092 return true;
1093 }
1094
1095 static class NamedFunction {
1096 final MemberName member;
1097 @Stable MethodHandle resolvedHandle;
1098 @Stable MethodHandle invoker;
1099
1100 NamedFunction(MethodHandle resolvedHandle) {
1101 this(resolvedHandle.internalMemberName(), resolvedHandle);
1102 }
1103 NamedFunction(MemberName member, MethodHandle resolvedHandle) {
1104 this.member = member;
1105 //resolvedHandle = eraseSubwordTypes(resolvedHandle);
1106 this.resolvedHandle = resolvedHandle;
1107 }
1108 NamedFunction(MethodType basicInvokerType) {
1109 assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
1110 if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
1111 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
1112 this.member = resolvedHandle.internalMemberName();
1113 } else {
1114 // necessary to pass BigArityTest
1115 this.member = Invokers.invokeBasicMethod(basicInvokerType);
1116 }
1117 }
1118
1119 // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc.
1120 // Any LambdaForm containing such a member is not interpretable.
1121 // This is OK, since all such LFs are prepared with special primitive vmentry points.
1122 // And even without the resolvedHandle, the name can still be compiled and optimized.
1123 NamedFunction(Method method) {
1124 this(new MemberName(method));
1125 }
1126 NamedFunction(Field field) {
1127 this(new MemberName(field));
1128 }
1129 NamedFunction(MemberName member) {
1130 this.member = member;
1131 this.resolvedHandle = null;
1132 }
1133
1134 MethodHandle resolvedHandle() {
1135 if (resolvedHandle == null) resolve();
1136 return resolvedHandle;
1162 if (!m.isStatic() || !m.isPackage()) continue;
1163 MethodType type = m.getMethodType();
1164 if (type.equals(INVOKER_METHOD_TYPE) &&
1165 m.getName().startsWith("invoke_")) {
1166 String sig = m.getName().substring("invoke_".length());
1167 int arity = LambdaForm.signatureArity(sig);
1168 MethodType srcType = MethodType.genericMethodType(arity);
1169 if (LambdaForm.signatureReturn(sig) == V_TYPE)
1170 srcType = srcType.changeReturnType(void.class);
1171 MethodTypeForm typeForm = srcType.form();
1172 typeForm.namedFunctionInvoker = DirectMethodHandle.make(m);
1173 }
1174 }
1175 }
1176
1177 // The following are predefined NamedFunction invokers. The system must build
1178 // a separate invoker for each distinct signature.
1179 /** void return type invokers. */
1180 @Hidden
1181 static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1182 assert(a.length == 0);
1183 mh.invokeBasic();
1184 return null;
1185 }
1186 @Hidden
1187 static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1188 assert(a.length == 1);
1189 mh.invokeBasic(a[0]);
1190 return null;
1191 }
1192 @Hidden
1193 static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
1194 assert(a.length == 2);
1195 mh.invokeBasic(a[0], a[1]);
1196 return null;
1197 }
1198 @Hidden
1199 static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
1200 assert(a.length == 3);
1201 mh.invokeBasic(a[0], a[1], a[2]);
1202 return null;
1203 }
1204 @Hidden
1205 static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1206 assert(a.length == 4);
1207 mh.invokeBasic(a[0], a[1], a[2], a[3]);
1208 return null;
1209 }
1210 @Hidden
1211 static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1212 assert(a.length == 5);
1213 mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1214 return null;
1215 }
1216 /** Object return type invokers. */
1217 @Hidden
1218 static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
1219 assert(a.length == 0);
1220 return mh.invokeBasic();
1221 }
1222 @Hidden
1223 static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
1224 assert(a.length == 1);
1225 return mh.invokeBasic(a[0]);
1226 }
1227 @Hidden
1228 static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
1229 assert(a.length == 2);
1230 return mh.invokeBasic(a[0], a[1]);
1231 }
1232 @Hidden
1233 static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
1234 assert(a.length == 3);
1235 return mh.invokeBasic(a[0], a[1], a[2]);
1236 }
1237 @Hidden
1238 static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1239 assert(a.length == 4);
1240 return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1241 }
1242 @Hidden
1243 static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1244 assert(a.length == 5);
1245 return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1246 }
1247
1248 static final MethodType INVOKER_METHOD_TYPE =
1249 MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1250
1251 private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1252 MethodHandle mh = typeForm.namedFunctionInvoker;
1253 if (mh != null) return mh;
1254 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while
1255 mh = DirectMethodHandle.make(invoker);
1256 MethodHandle mh2 = typeForm.namedFunctionInvoker;
1257 if (mh2 != null) return mh2; // benign race
1258 if (!mh.type().equals(INVOKER_METHOD_TYPE))
1259 throw newInternalError(mh.debugString());
1260 return typeForm.namedFunctionInvoker = mh;
1261 }
1262
1263 @Hidden
1264 Object invokeWithArguments(Object... arguments) throws Throwable {
1265 // If we have a cached invoker, call it right away.
1266 // NOTE: The invoker always returns a reference value.
1470 return new Name(i, type, function, newArguments);
1471 }
1472 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly
1473 if (oldName == newName) return this;
1474 @SuppressWarnings("LocalVariableHidesMemberVariable")
1475 Object[] arguments = this.arguments;
1476 if (arguments == null) return this;
1477 boolean replaced = false;
1478 for (int j = 0; j < arguments.length; j++) {
1479 if (arguments[j] == oldName) {
1480 if (!replaced) {
1481 replaced = true;
1482 arguments = arguments.clone();
1483 }
1484 arguments[j] = newName;
1485 }
1486 }
1487 if (!replaced) return this;
1488 return new Name(function, arguments);
1489 }
1490 Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
1491 @SuppressWarnings("LocalVariableHidesMemberVariable")
1492 Object[] arguments = this.arguments;
1493 boolean replaced = false;
1494 eachArg:
1495 for (int j = 0; j < arguments.length; j++) {
1496 if (arguments[j] instanceof Name) {
1497 Name n = (Name) arguments[j];
1498 int check = n.index;
1499 // harmless check to see if the thing is already in newNames:
1500 if (check >= 0 && check < newNames.length && n == newNames[check])
1501 continue eachArg;
1502 // n might not have the correct index: n != oldNames[n.index].
1503 for (int i = start; i < end; i++) {
1504 if (n == oldNames[i]) {
1505 if (n == newNames[i])
1506 continue eachArg;
1507 if (!replaced) {
1508 replaced = true;
1509 arguments = arguments.clone();
1510 }
1555 buf.append("(").append(a).append(")");
1556 }
1557 buf.append(")");
1558 return buf.toString();
1559 }
1560
1561 static boolean typesMatch(BasicType parameterType, Object object) {
1562 if (object instanceof Name) {
1563 return ((Name)object).type == parameterType;
1564 }
1565 switch (parameterType) {
1566 case I_TYPE: return object instanceof Integer;
1567 case J_TYPE: return object instanceof Long;
1568 case F_TYPE: return object instanceof Float;
1569 case D_TYPE: return object instanceof Double;
1570 }
1571 assert(parameterType == L_TYPE);
1572 return true;
1573 }
1574
1575 /**
1576 * Does this Name precede the given binding node in some canonical order?
1577 * This predicate is used to order data bindings (via insertion sort)
1578 * with some stability.
1579 */
1580 boolean isSiblingBindingBefore(Name binding) {
1581 assert(!binding.isParam());
1582 if (isParam()) return true;
1583 if (function.equals(binding.function) &&
1584 arguments.length == binding.arguments.length) {
1585 boolean sawInt = false;
1586 for (int i = 0; i < arguments.length; i++) {
1587 Object a1 = arguments[i];
1588 Object a2 = binding.arguments[i];
1589 if (!a1.equals(a2)) {
1590 if (a1 instanceof Integer && a2 instanceof Integer) {
1591 if (sawInt) continue;
1592 sawInt = true;
1593 if ((int)a1 < (int)a2) continue; // still might be true
1594 }
1595 return false;
1596 }
1597 }
1598 return sawInt;
1599 }
1600 return false;
1601 }
1602
1603 /** Return the index of the last occurrence of n in the argument array.
1604 * Return -1 if the name is not used.
1605 */
1606 int lastUseIndex(Name n) {
1607 if (arguments == null) return -1;
1608 for (int i = arguments.length; --i >= 0; ) {
1609 if (arguments[i] == n) return i;
1610 }
1611 return -1;
1612 }
1613
1614 /** Return the number of occurrences of n in the argument array.
1615 * Return 0 if the name is not used.
1616 */
1617 int useCount(Name n) {
1618 if (arguments == null) return 0;
1619 int count = 0;
1620 for (int i = arguments.length; --i >= 0; ) {
1621 if (arguments[i] == n) ++count;
1622 }
1841 private static void zero_V() { return; }
1842
1843 /**
1844 * Internal marker for byte-compiled LambdaForms.
1845 */
1846 /*non-public*/
1847 @Target(ElementType.METHOD)
1848 @Retention(RetentionPolicy.RUNTIME)
1849 @interface Compiled {
1850 }
1851
1852 /**
1853 * Internal marker for LambdaForm interpreter frames.
1854 */
1855 /*non-public*/
1856 @Target(ElementType.METHOD)
1857 @Retention(RetentionPolicy.RUNTIME)
1858 @interface Hidden {
1859 }
1860
1861
1862 /*
1863 // Smoke-test for the invokers used in this file.
1864 static void testMethodHandleLinkers() throws Throwable {
1865 MemberName.Factory lookup = MemberName.getFactory();
1866 MemberName asList_MN = new MemberName(Arrays.class, "asList",
1867 MethodType.methodType(List.class, Object[].class),
1868 REF_invokeStatic);
1869 //MethodHandleNatives.resolve(asList_MN, null);
1870 asList_MN = lookup.resolveOrFail(asList_MN, REF_invokeStatic, null, NoSuchMethodException.class);
1871 System.out.println("about to call "+asList_MN);
1872 Object[] abc = { "a", "bc" };
1873 List<?> lst = (List<?>) MethodHandle.linkToStatic(abc, asList_MN);
1874 System.out.println("lst="+lst);
1875 MemberName toString_MN = new MemberName(Object.class.getMethod("toString"));
1876 String s1 = (String) MethodHandle.linkToVirtual(lst, toString_MN);
1877 toString_MN = new MemberName(Object.class.getMethod("toString"), true);
1878 String s2 = (String) MethodHandle.linkToSpecial(lst, toString_MN);
1879 System.out.println("[s1,s2,lst]="+Arrays.asList(s1, s2, lst.toString()));
1880 MemberName toArray_MN = new MemberName(List.class.getMethod("toArray"));
1881 Object[] arr = (Object[]) MethodHandle.linkToInterface(lst, toArray_MN);
1882 System.out.println("toArray="+Arrays.toString(arr));
1883 }
1884 static { try { testMethodHandleLinkers(); } catch (Throwable ex) { throw new RuntimeException(ex); } }
1885 // Requires these definitions in MethodHandle:
1886 static final native Object linkToStatic(Object x1, MemberName mn) throws Throwable;
1887 static final native Object linkToVirtual(Object x1, MemberName mn) throws Throwable;
1888 static final native Object linkToSpecial(Object x1, MemberName mn) throws Throwable;
1889 static final native Object linkToInterface(Object x1, MemberName mn) throws Throwable;
1890 */
1891
1892 private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1893 static {
1894 if (debugEnabled())
1895 DEBUG_NAME_COUNTERS = new HashMap<>();
1896 else
1897 DEBUG_NAME_COUNTERS = null;
1898 }
1899
1900 // Put this last, so that previous static inits can run before.
1901 static {
1902 createIdentityForms();
1903 if (USE_PREDEFINED_INTERPRET_METHODS)
1904 PREPARED_FORMS.putAll(computeInitialPreparedForms());
1905 NamedFunction.initializeInvokers();
1906 }
1907
1908 // The following hack is necessary in order to suppress TRACE_INTERPRETER
1909 // during execution of the static initializes of this class.
1910 // Turning on TRACE_INTERPRETER too early will cause
1911 // stack overflows and other misbehavior during attempts to trace events
|
226 for (int i = 0; i < ARG_TYPE_LIMIT; i++) {
227 assert ARG_TYPES[i].ordinal() == i;
228 assert ARG_TYPES[i] == ALL_TYPES[i];
229 }
230 for (int i = 0; i < TYPE_LIMIT; i++) {
231 assert ALL_TYPES[i].ordinal() == i;
232 }
233 assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE;
234 assert !Arrays.asList(ARG_TYPES).contains(V_TYPE);
235 return true;
236 }
237 }
238
239 LambdaForm(String debugName,
240 int arity, Name[] names, int result) {
241 assert(namesOK(arity, names));
242 this.arity = arity;
243 this.result = fixResult(result, names);
244 this.names = names.clone();
245 this.debugName = fixDebugName(debugName);
246 int maxOutArity = normalize();
247 if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) {
248 // Cannot use LF interpreter on very high arity expressions.
249 assert(maxOutArity <= MethodType.MAX_JVM_ARITY);
250 compileToBytecode();
251 }
252 }
253
254 LambdaForm(String debugName,
255 int arity, Name[] names) {
256 this(debugName,
257 arity, names, LAST_RESULT);
258 }
259
260 LambdaForm(String debugName,
261 Name[] formals, Name[] temps, Name result) {
262 this(debugName,
263 formals.length, buildNames(formals, temps, result), LAST_RESULT);
264 }
265
266 private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
267 int arity = formals.length;
268 int length = arity + temps.length + (result == null ? 0 : 1);
269 Name[] names = Arrays.copyOf(formals, length);
270 System.arraycopy(temps, 0, names, arity, temps.length);
271 if (result != null)
336 if (under < length)
337 buf.append('_').append(debugName, under, length);
338 }
339 return buf.toString();
340 }
341 return debugName;
342 }
343
344 private static boolean namesOK(int arity, Name[] names) {
345 for (int i = 0; i < names.length; i++) {
346 Name n = names[i];
347 assert(n != null) : "n is null";
348 if (i < arity)
349 assert( n.isParam()) : n + " is not param at " + i;
350 else
351 assert(!n.isParam()) : n + " is param at " + i;
352 }
353 return true;
354 }
355
356 /** Renumber and/or replace params so that they are interned and canonically numbered.
357 * @return maximum argument list length among the names (since we have to pass over them anyway)
358 */
359 private int normalize() {
360 Name[] oldNames = null;
361 int maxOutArity = 0;
362 int changesStart = 0;
363 for (int i = 0; i < names.length; i++) {
364 Name n = names[i];
365 if (!n.initIndex(i)) {
366 if (oldNames == null) {
367 oldNames = names.clone();
368 changesStart = i;
369 }
370 names[i] = n.cloneWithIndex(i);
371 }
372 if (n.arguments != null && maxOutArity < n.arguments.length)
373 maxOutArity = n.arguments.length;
374 }
375 if (oldNames != null) {
376 int startFixing = arity;
377 if (startFixing <= changesStart)
378 startFixing = changesStart+1;
379 for (int i = startFixing; i < names.length; i++) {
380 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i);
381 names[i] = fixed.newIndex(i);
382 }
383 }
384 assert(nameRefsAreLegal());
385 int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
386 boolean needIntern = false;
387 for (int i = 0; i < maxInterned; i++) {
388 Name n = names[i], n2 = internArgument(n);
389 if (n != n2) {
390 names[i] = n2;
391 needIntern = true;
392 }
393 }
394 if (needIntern) {
395 for (int i = arity; i < names.length; i++) {
396 names[i].internArguments();
397 }
398 assert(nameRefsAreLegal());
399 }
400 return maxOutArity;
401 }
402
403 /**
404 * Check that all embedded Name references are localizable to this lambda,
405 * and are properly ordered after their corresponding definitions.
406 * <p>
407 * Note that a Name can be local to multiple lambdas, as long as
408 * it possesses the same index in each use site.
409 * This allows Name references to be freely reused to construct
410 * fresh lambdas, without confusion.
411 */
412 private boolean nameRefsAreLegal() {
413 assert(arity >= 0 && arity <= names.length);
414 assert(result >= -1 && result < names.length);
415 // Do all names possess an index consistent with their local definition order?
416 for (int i = 0; i < arity; i++) {
417 Name n = names[i];
418 assert(n.index() == i) : Arrays.asList(n.index(), i);
419 assert(n.isParam());
420 }
576 }
577 LambdaForm prep = getPreparedForm(basicTypeSignature());
578 this.vmentry = prep.vmentry;
579 // TO DO: Maybe add invokeGeneric, invokeWithArguments
580 }
581
582 /** Generate optimizable bytecode for this form. */
583 MemberName compileToBytecode() {
584 MethodType invokerType = methodType();
585 assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
586 if (vmentry != null && isCompiled) {
587 return vmentry; // already compiled somehow
588 }
589 try {
590 vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
591 if (TRACE_INTERPRETER)
592 traceInterpreter("compileToBytecode", this);
593 isCompiled = true;
594 return vmentry;
595 } catch (Error | Exception ex) {
596 throw newInternalError(this.toString(), ex);
597 }
598 }
599
600 private static final ConcurrentHashMap<String,LambdaForm> PREPARED_FORMS;
601 static {
602 int capacity = 512; // expect many distinct signatures over time
603 float loadFactor = 0.75f; // normal default
604 int writers = 1;
605 PREPARED_FORMS = new ConcurrentHashMap<>(capacity, loadFactor, writers);
606 }
607
608 private static Map<String,LambdaForm> computeInitialPreparedForms() {
609 // Find all predefined invokers and associate them with canonical empty lambda forms.
610 HashMap<String,LambdaForm> forms = new HashMap<>();
611 for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
612 if (!m.isStatic() || !m.isPackage()) continue;
613 MethodType mt = m.getMethodType();
614 if (mt.parameterCount() > 0 &&
615 mt.parameterType(0) == MethodHandle.class &&
616 m.getName().startsWith("interpret_")) {
703 return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
704 }
705 private static boolean checkInt(Class<?> type, Object x) {
706 assert(x instanceof Integer);
707 if (type == int.class) return true;
708 Wrapper w = Wrapper.forBasicType(type);
709 assert(w.isSubwordOrInt());
710 Object x1 = Wrapper.INT.wrap(w.wrap(x));
711 return x.equals(x1);
712 }
713 private static boolean checkRef(Class<?> type, Object x) {
714 assert(!type.isPrimitive());
715 if (x == null) return true;
716 if (type.isInterface()) return true;
717 return type.isInstance(x);
718 }
719
720 /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
721 private static final int COMPILE_THRESHOLD;
722 static {
723 COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD);
724 }
725 private int invocationCounter = 0;
726
727 @Hidden
728 @DontInline
729 /** Interpretively invoke this form on the given arguments. */
730 Object interpretWithArguments(Object... argumentValues) throws Throwable {
731 if (TRACE_INTERPRETER)
732 return interpretWithArgumentsTracing(argumentValues);
733 checkInvocationCounter();
734 assert(arityCheck(argumentValues));
735 Object[] values = Arrays.copyOf(argumentValues, names.length);
736 for (int i = argumentValues.length; i < values.length; i++) {
737 values[i] = interpretName(names[i], values);
738 }
739 Object rv = (result < 0) ? null : values[result];
740 assert(resultCheck(argumentValues, rv));
741 return rv;
742 }
743
744 @Hidden
745 @DontInline
746 /** Evaluate a single Name within this form, applying its function to its arguments. */
747 Object interpretName(Name name, Object[] values) throws Throwable {
748 if (TRACE_INTERPRETER)
749 traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
750 Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
751 for (int i = 0; i < arguments.length; i++) {
752 Object a = arguments[i];
753 if (a instanceof Name) {
754 int i2 = ((Name)a).index();
755 assert(names[i2] == a);
756 a = values[i2];
757 arguments[i] = a;
758 }
759 }
760 return name.function.invokeWithArguments(arguments);
761 }
812 if (!type.isPrimitive()) return type;
813 if (type == int.class) return type;
814 Wrapper w = Wrapper.forPrimitiveType(type);
815 if (w.isSubwordOrInt()) return int.class;
816 return type;
817 }
818 */
819
820 static void traceInterpreter(String event, Object obj, Object... args) {
821 if (TRACE_INTERPRETER) {
822 System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
823 }
824 }
825 static void traceInterpreter(String event, Object obj) {
826 traceInterpreter(event, obj, (Object[])null);
827 }
828 private boolean arityCheck(Object[] argumentValues) {
829 assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
830 // also check that the leading (receiver) argument is somehow bound to this LF:
831 assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
832 MethodHandle mh = (MethodHandle) argumentValues[0];
833 assert(mh.internalForm() == this);
834 // note: argument #0 could also be an interface wrapper, in the future
835 argumentTypesMatch(basicTypeSignature(), argumentValues);
836 return true;
837 }
838 private boolean resultCheck(Object[] argumentValues, Object result) {
839 MethodHandle mh = (MethodHandle) argumentValues[0];
840 MethodType mt = mh.type();
841 assert(valueMatches(returnType(), mt.returnType(), result));
842 return true;
843 }
844
845 private boolean isEmpty() {
846 if (result < 0)
847 return (names.length == arity);
848 else if (result == arity && names.length == arity + 1)
849 return names[arity].isConstantZero();
850 else
851 return false;
852 }
853
854 public String toString() {
855 StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
856 for (int i = 0; i < names.length; i++) {
857 if (i == arity) buf.append(")=>{");
858 Name n = names[i];
859 if (i >= arity) buf.append("\n ");
860 buf.append(n);
861 if (i < arity) {
862 if (i+1 < arity) buf.append(",");
863 continue;
864 }
865 buf.append("=").append(n.exprString());
866 buf.append(";");
867 }
868 if (arity == names.length) buf.append(")=>{");
869 buf.append(result < 0 ? "void" : names[result]).append("}");
870 if (TRACE_INTERPRETER) {
871 // Extra verbosity:
872 buf.append(":").append(basicTypeSignature());
873 buf.append("/").append(vmentry);
874 }
875 return buf.toString();
876 }
877
878 LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) {
879 Name name = names[namePos];
880 BoundMethodHandle.SpeciesData newData = oldData.extendWith(name.type);
881 return bind(name, new Name(newData.getterFunction(oldData.fieldCount()), names[0]), oldData, newData);
882 }
883 LambdaForm bind(Name name, Name binding,
884 BoundMethodHandle.SpeciesData oldData,
885 BoundMethodHandle.SpeciesData newData) {
886 int pos = name.index;
887 assert(name.isParam());
888 assert(!binding.isParam());
889 assert(name.type == binding.type);
890 assert(0 <= pos && pos < arity && names[pos] == name);
891 assert(binding.function.memberDeclaringClassOrNull() == newData.clazz);
892 assert(oldData.getters.length == newData.getters.length-1);
893 if (bindCache != null) {
894 LambdaForm form = bindCache[pos];
895 if (form != null) {
896 assert(form.contains(binding)) : "form << " + form + " >> does not contain binding << " + binding + " >>";
897 return form;
922 Name n2 = new Name(newGetter, n.arguments);
923 names2[i] = n2;
924 }
925 }
926 }
927
928 // Walk over the new list of names once, in forward order.
929 // Replace references to 'name' with 'binding'.
930 // Replace data structure references to the old BMH species with the new.
931 // This might cause a ripple effect, but it will settle in one pass.
932 assert(firstOldRef < 0 || firstOldRef > pos);
933 for (int i = pos+1; i < names2.length; i++) {
934 if (i <= arity2) continue;
935 names2[i] = names2[i].replaceNames(names, names2, pos, i);
936 }
937
938 // (a0, a1, name=a2, a3, a4) => (a0, a1, a3, a4, binding)
939 int insPos = pos;
940 for (; insPos+1 < names2.length; insPos++) {
941 Name n = names2[insPos+1];
942 if (n.isParam()) {
943 names2[insPos] = n;
944 } else {
945 break;
946 }
947 }
948 names2[insPos] = binding;
949
950 // Since we moved some stuff, maybe update the result reference:
951 int result2 = result;
952 if (result2 == pos)
953 result2 = insPos;
954 else if (result2 > pos && result2 <= insPos)
955 result2 -= 1;
956
957 return bindCache[pos] = new LambdaForm(debugName, arity2, names2, result2);
958 }
959
960 boolean contains(Name name) {
961 int pos = name.index();
962 if (pos >= 0) {
963 return pos < names.length && name.equals(names[pos]);
964 }
965 for (int i = arity; i < names.length; i++) {
966 if (name.equals(names[i]))
967 return true;
968 }
969 return false;
970 }
971
972 LambdaForm addArguments(int pos, BasicType... types) {
973 // names array has MH in slot 0; skip it.
974 int argpos = pos + 1;
975 assert(argpos <= arity);
976 int length = names.length;
977 int inTypes = types.length;
978 Name[] names2 = Arrays.copyOf(names, length + inTypes);
979 int arity2 = arity + inTypes;
980 int result2 = result;
981 if (result2 >= argpos)
982 result2 += inTypes;
983 // Note: The LF constructor will rename names2[argpos...].
984 // Make space for new arguments (shift temporaries).
985 System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
986 for (int i = 0; i < inTypes; i++) {
987 names2[argpos + i] = new Name(types[i]);
988 }
989 return new LambdaForm(debugName, arity2, names2, result2);
990 }
991
992 LambdaForm addArguments(int pos, List<Class<?>> types) {
993 return addArguments(pos, basicTypes(types));
994 }
995
996 LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) {
997 // Note: When inArg = reorder[outArg], outArg is fed by a copy of inArg.
998 // The types are the types of the new (incoming) arguments.
999 int length = names.length;
1000 int inTypes = types.length;
1001 int outArgs = reorder.length;
1002 assert(skip+outArgs == arity);
1055 static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) {
1056 int inTypes = types.length;
1057 int outArgs = reorder.length;
1058 for (int i = 0; i < outArgs; i++) {
1059 assert(names[skip+i].isParam());
1060 assert(names[skip+i].type == types[reorder[i]]);
1061 }
1062 return true;
1063 }
1064
1065 static class NamedFunction {
1066 final MemberName member;
1067 @Stable MethodHandle resolvedHandle;
1068 @Stable MethodHandle invoker;
1069
1070 NamedFunction(MethodHandle resolvedHandle) {
1071 this(resolvedHandle.internalMemberName(), resolvedHandle);
1072 }
1073 NamedFunction(MemberName member, MethodHandle resolvedHandle) {
1074 this.member = member;
1075 this.resolvedHandle = resolvedHandle;
1076 // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
1077 //assert(!isInvokeBasic());
1078 }
1079 NamedFunction(MethodType basicInvokerType) {
1080 assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
1081 if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
1082 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
1083 this.member = resolvedHandle.internalMemberName();
1084 } else {
1085 // necessary to pass BigArityTest
1086 this.member = Invokers.invokeBasicMethod(basicInvokerType);
1087 }
1088 assert(isInvokeBasic());
1089 }
1090
1091 private boolean isInvokeBasic() {
1092 return member != null &&
1093 member.isMethodHandleInvoke() &&
1094 "invokeBasic".equals(member.getName());
1095 }
1096
1097 // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc.
1098 // Any LambdaForm containing such a member is not interpretable.
1099 // This is OK, since all such LFs are prepared with special primitive vmentry points.
1100 // And even without the resolvedHandle, the name can still be compiled and optimized.
1101 NamedFunction(Method method) {
1102 this(new MemberName(method));
1103 }
1104 NamedFunction(Field field) {
1105 this(new MemberName(field));
1106 }
1107 NamedFunction(MemberName member) {
1108 this.member = member;
1109 this.resolvedHandle = null;
1110 }
1111
1112 MethodHandle resolvedHandle() {
1113 if (resolvedHandle == null) resolve();
1114 return resolvedHandle;
1140 if (!m.isStatic() || !m.isPackage()) continue;
1141 MethodType type = m.getMethodType();
1142 if (type.equals(INVOKER_METHOD_TYPE) &&
1143 m.getName().startsWith("invoke_")) {
1144 String sig = m.getName().substring("invoke_".length());
1145 int arity = LambdaForm.signatureArity(sig);
1146 MethodType srcType = MethodType.genericMethodType(arity);
1147 if (LambdaForm.signatureReturn(sig) == V_TYPE)
1148 srcType = srcType.changeReturnType(void.class);
1149 MethodTypeForm typeForm = srcType.form();
1150 typeForm.namedFunctionInvoker = DirectMethodHandle.make(m);
1151 }
1152 }
1153 }
1154
1155 // The following are predefined NamedFunction invokers. The system must build
1156 // a separate invoker for each distinct signature.
1157 /** void return type invokers. */
1158 @Hidden
1159 static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1160 assert(arityCheck(0, void.class, mh, a));
1161 mh.invokeBasic();
1162 return null;
1163 }
1164 @Hidden
1165 static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1166 assert(arityCheck(1, void.class, mh, a));
1167 mh.invokeBasic(a[0]);
1168 return null;
1169 }
1170 @Hidden
1171 static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
1172 assert(arityCheck(2, void.class, mh, a));
1173 mh.invokeBasic(a[0], a[1]);
1174 return null;
1175 }
1176 @Hidden
1177 static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
1178 assert(arityCheck(3, void.class, mh, a));
1179 mh.invokeBasic(a[0], a[1], a[2]);
1180 return null;
1181 }
1182 @Hidden
1183 static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1184 assert(arityCheck(4, void.class, mh, a));
1185 mh.invokeBasic(a[0], a[1], a[2], a[3]);
1186 return null;
1187 }
1188 @Hidden
1189 static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1190 assert(arityCheck(5, void.class, mh, a));
1191 mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1192 return null;
1193 }
1194 /** Object return type invokers. */
1195 @Hidden
1196 static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
1197 assert(arityCheck(0, mh, a));
1198 return mh.invokeBasic();
1199 }
1200 @Hidden
1201 static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
1202 assert(arityCheck(1, mh, a));
1203 return mh.invokeBasic(a[0]);
1204 }
1205 @Hidden
1206 static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
1207 assert(arityCheck(2, mh, a));
1208 return mh.invokeBasic(a[0], a[1]);
1209 }
1210 @Hidden
1211 static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
1212 assert(arityCheck(3, mh, a));
1213 return mh.invokeBasic(a[0], a[1], a[2]);
1214 }
1215 @Hidden
1216 static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1217 assert(arityCheck(4, mh, a));
1218 return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1219 }
1220 @Hidden
1221 static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1222 assert(arityCheck(5, mh, a));
1223 return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1224 }
1225 private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
1226 return arityCheck(arity, Object.class, mh, a);
1227 }
1228 private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
1229 assert(a.length == arity)
1230 : Arrays.asList(a.length, arity);
1231 assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
1232 : Arrays.asList(mh, rtype, arity);
1233 MemberName member = mh.internalMemberName();
1234 if (member != null && member.getName().equals("invokeBasic") && member.isMethodHandleInvoke()) {
1235 assert(arity > 0);
1236 assert(a[0] instanceof MethodHandle);
1237 MethodHandle mh2 = (MethodHandle) a[0];
1238 assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
1239 : Arrays.asList(member, mh2, rtype, arity);
1240 }
1241 return true;
1242 }
1243
1244 static final MethodType INVOKER_METHOD_TYPE =
1245 MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1246
1247 private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1248 MethodHandle mh = typeForm.namedFunctionInvoker;
1249 if (mh != null) return mh;
1250 MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm); // this could take a while
1251 mh = DirectMethodHandle.make(invoker);
1252 MethodHandle mh2 = typeForm.namedFunctionInvoker;
1253 if (mh2 != null) return mh2; // benign race
1254 if (!mh.type().equals(INVOKER_METHOD_TYPE))
1255 throw newInternalError(mh.debugString());
1256 return typeForm.namedFunctionInvoker = mh;
1257 }
1258
1259 @Hidden
1260 Object invokeWithArguments(Object... arguments) throws Throwable {
1261 // If we have a cached invoker, call it right away.
1262 // NOTE: The invoker always returns a reference value.
1466 return new Name(i, type, function, newArguments);
1467 }
1468 Name replaceName(Name oldName, Name newName) { // FIXME: use replaceNames uniformly
1469 if (oldName == newName) return this;
1470 @SuppressWarnings("LocalVariableHidesMemberVariable")
1471 Object[] arguments = this.arguments;
1472 if (arguments == null) return this;
1473 boolean replaced = false;
1474 for (int j = 0; j < arguments.length; j++) {
1475 if (arguments[j] == oldName) {
1476 if (!replaced) {
1477 replaced = true;
1478 arguments = arguments.clone();
1479 }
1480 arguments[j] = newName;
1481 }
1482 }
1483 if (!replaced) return this;
1484 return new Name(function, arguments);
1485 }
1486 /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i].
1487 * Limit such replacements to {@code start<=i<end}. Return possibly changed self.
1488 */
1489 Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
1490 if (start >= end) return this;
1491 @SuppressWarnings("LocalVariableHidesMemberVariable")
1492 Object[] arguments = this.arguments;
1493 boolean replaced = false;
1494 eachArg:
1495 for (int j = 0; j < arguments.length; j++) {
1496 if (arguments[j] instanceof Name) {
1497 Name n = (Name) arguments[j];
1498 int check = n.index;
1499 // harmless check to see if the thing is already in newNames:
1500 if (check >= 0 && check < newNames.length && n == newNames[check])
1501 continue eachArg;
1502 // n might not have the correct index: n != oldNames[n.index].
1503 for (int i = start; i < end; i++) {
1504 if (n == oldNames[i]) {
1505 if (n == newNames[i])
1506 continue eachArg;
1507 if (!replaced) {
1508 replaced = true;
1509 arguments = arguments.clone();
1510 }
1555 buf.append("(").append(a).append(")");
1556 }
1557 buf.append(")");
1558 return buf.toString();
1559 }
1560
1561 static boolean typesMatch(BasicType parameterType, Object object) {
1562 if (object instanceof Name) {
1563 return ((Name)object).type == parameterType;
1564 }
1565 switch (parameterType) {
1566 case I_TYPE: return object instanceof Integer;
1567 case J_TYPE: return object instanceof Long;
1568 case F_TYPE: return object instanceof Float;
1569 case D_TYPE: return object instanceof Double;
1570 }
1571 assert(parameterType == L_TYPE);
1572 return true;
1573 }
1574
1575 /** Return the index of the last occurrence of n in the argument array.
1576 * Return -1 if the name is not used.
1577 */
1578 int lastUseIndex(Name n) {
1579 if (arguments == null) return -1;
1580 for (int i = arguments.length; --i >= 0; ) {
1581 if (arguments[i] == n) return i;
1582 }
1583 return -1;
1584 }
1585
1586 /** Return the number of occurrences of n in the argument array.
1587 * Return 0 if the name is not used.
1588 */
1589 int useCount(Name n) {
1590 if (arguments == null) return 0;
1591 int count = 0;
1592 for (int i = arguments.length; --i >= 0; ) {
1593 if (arguments[i] == n) ++count;
1594 }
1813 private static void zero_V() { return; }
1814
1815 /**
1816 * Internal marker for byte-compiled LambdaForms.
1817 */
1818 /*non-public*/
1819 @Target(ElementType.METHOD)
1820 @Retention(RetentionPolicy.RUNTIME)
1821 @interface Compiled {
1822 }
1823
1824 /**
1825 * Internal marker for LambdaForm interpreter frames.
1826 */
1827 /*non-public*/
1828 @Target(ElementType.METHOD)
1829 @Retention(RetentionPolicy.RUNTIME)
1830 @interface Hidden {
1831 }
1832
1833 private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1834 static {
1835 if (debugEnabled())
1836 DEBUG_NAME_COUNTERS = new HashMap<>();
1837 else
1838 DEBUG_NAME_COUNTERS = null;
1839 }
1840
1841 // Put this last, so that previous static inits can run before.
1842 static {
1843 createIdentityForms();
1844 if (USE_PREDEFINED_INTERPRET_METHODS)
1845 PREPARED_FORMS.putAll(computeInitialPreparedForms());
1846 NamedFunction.initializeInvokers();
1847 }
1848
1849 // The following hack is necessary in order to suppress TRACE_INTERPRETER
1850 // during execution of the static initializes of this class.
1851 // Turning on TRACE_INTERPRETER too early will cause
1852 // stack overflows and other misbehavior during attempts to trace events
|