1 /*
  2  * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  */
 23 
 24 /*
 25  * @test
 26  * @modules jdk.incubator.code
 27  * @run junit CoreBinaryOpsTest
 28  * @run junit/othervm -Dbabylon.ssa=cytron CoreBinaryOpsTest
 29  */
 30 
 31 import jdk.incubator.code.Op;
 32 import org.junit.jupiter.api.Named;
 33 import org.junit.jupiter.api.extension.ExtensionContext;
 34 import org.junit.jupiter.api.function.ThrowingSupplier;
 35 import org.junit.jupiter.params.ParameterizedTest;
 36 import org.junit.jupiter.params.provider.Arguments;
 37 import org.junit.jupiter.params.provider.ArgumentsProvider;
 38 import org.junit.jupiter.params.provider.ArgumentsSource;
 39 
 40 import java.lang.annotation.ElementType;
 41 import java.lang.annotation.Retention;
 42 import java.lang.annotation.RetentionPolicy;
 43 import java.lang.annotation.Target;
 44 import java.lang.invoke.MethodHandle;
 45 import java.lang.invoke.MethodHandles;
 46 import java.lang.invoke.MethodType;
 47 import java.lang.reflect.AccessFlag;
 48 import java.lang.reflect.Method;
 49 import java.lang.reflect.Parameter;
 50 import jdk.incubator.code.OpTransformer;
 51 import jdk.incubator.code.TypeElement;
 52 import jdk.incubator.code.analysis.SSA;
 53 import jdk.incubator.code.bytecode.BytecodeGenerator;
 54 import jdk.incubator.code.interpreter.Interpreter;
 55 import jdk.incubator.code.op.CoreOp;
 56 import jdk.incubator.code.type.FunctionType;
 57 import jdk.incubator.code.type.JavaType;
 58 import jdk.incubator.code.CodeReflection;
 59 import java.util.*;
 60 import java.util.stream.Stream;
 61 
 62 import static org.junit.jupiter.api.Assertions.*;
 63 
 64 public class CoreBinaryOpsTest {
 65 
 66     @CodeReflection
 67     @SupportedTypes(TypeList.INTEGRAL_BOOLEAN)
 68     static int and(int left, int right) {
 69         return left & right;
 70     }
 71 
 72     @CodeReflection
 73     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
 74     static int add(int left, int right) {
 75         return left + right;
 76     }
 77 
 78     @CodeReflection
 79     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
 80     static int div(int left, int right) {
 81         return left / right;
 82     }
 83 
 84     @CodeReflection
 85     @SupportedTypes(TypeList.INT_LONG)
 86     static int leftShift(int left, int right) {
 87         return left << right;
 88     }
 89 
 90     @CodeReflection
 91     @Direct
 92     static int leftShiftIL(int left, long right) {
 93         return left << right;
 94     }
 95 
 96     @CodeReflection
 97     @Direct
 98     static long leftShiftLI(long left, int right) {
 99         return left << right;
100     }
101 
102     @CodeReflection
103     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
104     static int mod(int left, int right) {
105         return left % right;
106     }
107 
108     @CodeReflection
109     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
110     static int mul(int left, int right) {
111         return left * right;
112     }
113 
114     @CodeReflection
115     @SupportedTypes(TypeList.INTEGRAL_BOOLEAN)
116     static int or(int left, int right) {
117         return left | right;
118     }
119 
120     @CodeReflection
121     @SupportedTypes(TypeList.INT_LONG)
122     static int signedRightShift(int left, int right) {
123         return left >> right;
124     }
125 
126     @CodeReflection
127     @Direct
128     static int signedRightShiftIL(int left, long right) {
129         return left >> right;
130     }
131 
132     @CodeReflection
133     @Direct
134     static long signedRightShiftLI(long left, int right) {
135         return left >> right;
136     }
137 
138     @CodeReflection
139     @SupportedTypes(TypeList.INTEGRAL_FLOATING_POINT)
140     static int sub(int left, int right) {
141         return left - right;
142     }
143 
144     @CodeReflection
145     @SupportedTypes(TypeList.INT_LONG)
146     static int unsignedRightShift(int left, int right) {
147         return left >>> right;
148     }
149 
150     @CodeReflection
151     @Direct
152     static int unsignedRightShiftIL(int left, long right) {
153         return left >>> right;
154     }
155 
156     @CodeReflection
157     @Direct
158     static long unsignedRightShiftLI(long left, int right) {
159         return left >>> right;
160     }
161 
162     @CodeReflection
163     @SupportedTypes(TypeList.INTEGRAL_BOOLEAN)
164     static int xor(int left, int right) {
165         return left ^ right;
166     }
167 
168     @ParameterizedTest
169     @CodeReflectionExecutionSource
170     void test(CoreOp.FuncOp funcOp, Object left, Object right) {
171         Result interpret = runCatching(() -> interpret(left, right, funcOp));
172         Result bytecode = runCatching(() -> bytecode(left, right, funcOp));
173         assertResults(interpret, bytecode);
174     }
175 
176     @Retention(RetentionPolicy.RUNTIME)
177     @Target(ElementType.METHOD)
178     @interface SupportedTypes {
179         TypeList value();
180     }
181 
182     enum TypeList {
183         INT_LONG(int.class, long.class),
184         INTEGRAL_BOOLEAN(int.class, long.class, byte.class, short.class, char.class, boolean.class),
185         INTEGRAL_FLOATING_POINT(int.class, long.class, byte.class, short.class, char.class, float.class, double.class);
186 
187         private final Class<?>[] types;
188 
189         TypeList(Class<?>... types) {
190             this.types = types;
191         }
192 
193         public Class<?>[] types() {
194             return types;
195         }
196     }
197 
198     // mark as "do not transform"
199     @Retention(RetentionPolicy.RUNTIME)
200     @Target(ElementType.METHOD)
201     @interface Direct {
202     }
203 
204     @Retention(RetentionPolicy.RUNTIME)
205     @Target(ElementType.METHOD)
206     @ArgumentsSource(CodeReflectionSourceProvider.class)
207     @interface CodeReflectionExecutionSource {
208     }
209 
210     static class CodeReflectionSourceProvider implements ArgumentsProvider {
211         private static final Map<JavaType, List<?>> INTERESTING_INPUTS = Map.of(
212                 // explicit type parameters to ensure boxing results in the expected type
213                 JavaType.INT, List.<Integer>of(Integer.MIN_VALUE, Integer.MAX_VALUE, 1, 0, -1),
214                 JavaType.LONG, List.<Long>of(Long.MIN_VALUE, Long.MAX_VALUE, 1L, 0L, -1L),
215                 JavaType.BYTE, List.<Byte>of(Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 1, (byte) 0, (byte) -1),
216                 JavaType.SHORT, List.<Short>of(Short.MIN_VALUE, Short.MAX_VALUE, (short) 1, (short) 0, (short) -1),
217                 JavaType.CHAR, List.<Character>of(Character.MIN_VALUE, Character.MAX_VALUE, (char) 1, (char) 0, (char) -1),
218                 JavaType.DOUBLE, List.<Double>of(Double.MIN_VALUE, Double.MAX_VALUE, Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.MIN_NORMAL, 1d, 0d, -1d),
219                 JavaType.FLOAT, List.<Float>of(Float.MIN_VALUE, Float.MAX_VALUE, Float.NaN, Float.NEGATIVE_INFINITY, Float.POSITIVE_INFINITY, Float.MIN_NORMAL, 1f, 0f, -1f),
220                 JavaType.BOOLEAN, List.<Boolean>of(true, false)
221         );
222 
223         @Override
224         public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) {
225             Method testMethod = extensionContext.getRequiredTestMethod();
226             return codeReflectionMethods(extensionContext.getRequiredTestClass())
227                     .flatMap(method -> {
228                         CoreOp.FuncOp funcOp = Op.ofMethod(method).orElseThrow(
229                                 () -> new IllegalStateException("Expected code model to be present for method " + method)
230                         );
231                         SupportedTypes supportedTypes = method.getAnnotation(SupportedTypes.class);
232                         if (method.isAnnotationPresent(Direct.class)) {
233                             if (supportedTypes != null) {
234                                 throw new IllegalArgumentException("Direct should not be combined with SupportedTypes");
235                             }
236                             return Stream.of(funcOp);
237                         }
238                         if (supportedTypes == null || supportedTypes.value().types().length == 0) {
239                             throw new IllegalArgumentException("Missing supported types");
240                         }
241                         return Arrays.stream(supportedTypes.value().types())
242                                 .map(type -> retype(funcOp, type));
243                     })
244                     .flatMap(transformedFunc -> argumentsForMethod(transformedFunc, testMethod));
245         }
246 
247         private static <T> Stream<List<T>> cartesianProduct(List<List<? extends T>> source) {
248             if (source.isEmpty()) {
249                 return Stream.of(new ArrayList<>());
250             }
251             return source.getFirst().stream()
252                     .flatMap(e -> cartesianProduct(source.subList(1, source.size())).map(l -> {
253                         ArrayList<T> newList = new ArrayList<>(l);
254                         newList.add(e);
255                         return newList;
256                     }));
257         }
258 
259         private static CoreOp.FuncOp retype(CoreOp.FuncOp original, Class<?> newType) {
260             JavaType type = JavaType.type(newType);
261             FunctionType functionType = original.invokableType();
262             if (functionType.parameterTypes().stream().allMatch(t -> t.equals(type))) {
263                 return original; // already expected type
264             }
265             if (functionType.parameterTypes().stream().distinct().count() != 1) {
266                 original.writeTo(System.err);
267                 throw new IllegalArgumentException("Only FuncOps with exactly one distinct parameter type are supported");
268             }
269             // if the return type does not match the input types, we keep it
270             TypeElement retType = functionType.returnType().equals(functionType.parameterTypes().getFirst())
271                     ? type
272                     : functionType.returnType();
273             return CoreOp.func(original.funcName(), FunctionType.functionType(retType, type, type))
274                     .body(builder -> builder.transformBody(original.body(), builder.parameters(), OpTransformer.COPYING_TRANSFORMER)
275                     );
276         }
277 
278         private static Stream<Arguments> argumentsForMethod(CoreOp.FuncOp funcOp, Method testMethod) {
279             Parameter[] testMethodParameters = testMethod.getParameters();
280             List<TypeElement> funcParameters = funcOp.invokableType().parameterTypes();
281             if (testMethodParameters.length - 1 != funcParameters.size()) {
282                 throw new IllegalArgumentException("method " + testMethod + " does not take the correct number of parameters");
283             }
284             if (testMethodParameters[0].getType() != CoreOp.FuncOp.class) {
285                 throw new IllegalArgumentException("method " + testMethod + " does not take a leading FuncOp argument");
286             }
287             Named<CoreOp.FuncOp> opNamed = Named.of(funcOp.funcName() + "{" + funcOp.invokableType() + "}", funcOp);
288             MethodHandles.Lookup lookup = MethodHandles.lookup();
289             for (int i = 1; i < testMethodParameters.length; i++) {
290                 Class<?> resolved = resolveParameter(funcParameters.get(i - 1), lookup);
291                 if (!isCompatible(resolved, testMethodParameters[i].getType())) {
292                     System.out.println(testMethod + " does not accept inputs of type " + resolved + " at index " + i);
293                     return Stream.empty();
294                 }
295             }
296             List<List<?>> allInputs = new ArrayList<>();
297             for (TypeElement parameterType : funcParameters) {
298                 allInputs.add(INTERESTING_INPUTS.get((JavaType) parameterType));
299             }
300             return cartesianProduct(allInputs)
301                     .map(objects -> {
302                         objects.add(opNamed);
303                         return objects.reversed().toArray(); // reverse so FuncOp is at the beginning
304                     })
305                     .map(Arguments::of);
306         }
307 
308         private static Class<?> resolveParameter(TypeElement typeElement, MethodHandles.Lookup lookup) {
309             try {
310                 return (Class<?>)((JavaType) typeElement).erasure().resolve(lookup);
311             } catch (ReflectiveOperationException e) {
312                 throw new RuntimeException(e);
313             }
314         }
315 
316         // check whether elements of type sourceType can be passed to a parameter of parameterType
317         private static boolean isCompatible(Class<?> sourceType, Class<?> parameterType) {
318             return wrapped(parameterType).isAssignableFrom(wrapped(sourceType));
319         }
320 
321         private static Class<?> wrapped(Class<?> target) {
322             return MethodType.methodType(target).wrap().returnType();
323         }
324 
325         private static Stream<Method> codeReflectionMethods(Class<?> testClass) {
326             return Arrays.stream(testClass.getDeclaredMethods())
327                     .filter(method -> method.accessFlags().contains(AccessFlag.STATIC))
328                     .filter(method -> method.isAnnotationPresent(CodeReflection.class));
329         }
330 
331     }
332 
333     private static Object interpret(Object left, Object right, CoreOp.FuncOp op) {
334         return Interpreter.invoke(MethodHandles.lookup(), op, left, right);
335     }
336 
337     private static Object bytecode(Object left, Object right, CoreOp.FuncOp op) throws Throwable {
338         CoreOp.FuncOp func = SSA.transform(op.transform(OpTransformer.LOWERING_TRANSFORMER));
339         MethodHandle handle = BytecodeGenerator.generate(MethodHandles.lookup(), func);
340         return handle.invoke(left, right);
341     }
342 
343     private static void assertResults(Result first, Result second) {
344         System.out.println("first: " + first);
345         System.out.println("second: " + second);
346         // either the same error occurred on both or no error occurred
347         if (first.throwable != null || second.throwable != null) {
348             assertNotNull(first.throwable, () -> "only second threw an exception: " + second.throwable);
349             assertNotNull(second.throwable, () -> "only first threw an exception: " + first.throwable);
350             if (first.throwable.getClass() != second.throwable.getClass()) {
351                 first.throwable.printStackTrace();
352                 second.throwable.printStackTrace();
353                 fail("Different exceptions were thrown");
354             }
355             return;
356         }
357         // otherwise, both results should be non-null and equals
358         assertNotNull(first.onSuccess);
359         assertEquals(first.onSuccess, second.onSuccess);
360     }
361 
362     private static <T> Result runCatching(ThrowingSupplier<T> supplier) {
363         Object value = null;
364         Throwable interpretThrowable = null;
365         try {
366             value = supplier.get();
367         } catch (Throwable t) {
368             interpretThrowable = t;
369         }
370         return new Result(value, interpretThrowable);
371     }
372 
373     record Result(Object onSuccess, Throwable throwable) {
374     }
375 
376 }