File: CastNullCheckDroppingsTest.java

package info (click to toggle)
openjdk-21 21.0.9%2B10-1~deb13u1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 821,840 kB
  • sloc: java: 5,620,360; xml: 1,643,607; cpp: 1,297,809; ansic: 421,231; asm: 404,850; objc: 21,018; sh: 15,299; javascript: 11,217; python: 6,895; makefile: 2,367; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (388 lines) | stat: -rw-r--r-- 15,050 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test NullCheckDroppingsTest
 * @bug 8054492
 * @summary Casting can result in redundant null checks in generated code
 * @requires vm.hasJFR
 * @requires vm.flavor == "server" & !vm.emulatedClient & !vm.graal.enabled
 * @library /test/lib
 * @modules java.base/jdk.internal.misc
 *          java.management
 *
 * @build jdk.test.whitebox.WhiteBox
 * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox
 * @run main/othervm -Xbootclasspath/a:. -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI
 *                   -Xmixed -XX:-BackgroundCompilation -XX:-TieredCompilation -XX:CompileThreshold=1000
 *                   -XX:+UnlockExperimentalVMOptions -XX:PerMethodTrapLimit=100 -XX:-StressReflectiveCode
 *                   -XX:+UncommonNullCast -XX:-StressMethodHandleLinkerInlining -XX:TypeProfileLevel=0
 *                   -XX:-AlwaysIncrementalInline -XX:-StressIncrementalInlining
 *                   -XX:CompileCommand=exclude,compiler.intrinsics.klass.CastNullCheckDroppingsTest::runTest
 *                   compiler.intrinsics.klass.CastNullCheckDroppingsTest
 */

package compiler.intrinsics.klass;

import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.test.lib.Platform;
import jdk.test.lib.jfr.EventNames;
import jdk.test.lib.jfr.Events;
import jdk.test.whitebox.WhiteBox;
import jdk.test.whitebox.code.NMethod;

import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.BiFunction;

public class CastNullCheckDroppingsTest {

    private static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();

    static final BiFunction<Class, Object, Object> fCast = (c, o) -> c.cast(o);

    static final MethodHandle SET_SSINK;
    static final MethodHandle MH_CAST;

    static {
        try {
            SET_SSINK = MethodHandles.lookup().findSetter(CastNullCheckDroppingsTest.class, "ssink", String.class);
            MH_CAST = MethodHandles.lookup().findVirtual(Class.class,
                                                         "cast",
                                                         MethodType.methodType(Object.class, Object.class));
        }
        catch (Exception e) {
            throw new Error(e);
        }
    }

    static volatile String svalue = "A";
    static volatile Object onull = null;
    static volatile Integer iobj = new Integer(0);
    static volatile int[] arr = new int[2];
    static volatile Class objClass = String.class;
    static volatile Class nullClass = null;

    String  ssink;
    Integer isink;
    int[]   asink;

    public static void main(String[] args) throws Exception {
        if (!Platform.isServer() || Platform.isEmulatedClient()) {
            throw new Error("TESTBUG: Not server mode");
        }
        // Make sure background compilation is disabled
        if (WHITE_BOX.getBooleanVMFlag("BackgroundCompilation")) {
            throw new Error("TESTBUG: Background compilation enabled");
        }
        // Make sure Tiered compilation is disabled
        if (WHITE_BOX.getBooleanVMFlag("TieredCompilation")) {
            throw new Error("TESTBUG: Tiered compilation enabled");
        }

        Method methodClassCast = CastNullCheckDroppingsTest.class.getDeclaredMethod("testClassCast", String.class);
        Method methodMHCast    = CastNullCheckDroppingsTest.class.getDeclaredMethod("testMHCast",    String.class);
        Method methodMHSetter  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testMHSetter",  String.class);
        Method methodFunction  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testFunction",  String.class);

        CastNullCheckDroppingsTest t = new CastNullCheckDroppingsTest();
        t.runTest(methodClassCast, false, svalue);
        t.runTest(methodMHCast,    false, svalue);
        t.runTest(methodMHSetter,  false, svalue);
        t.runTest(methodFunction,  false, svalue);

        // Edge cases
        Method methodClassCastNull = CastNullCheckDroppingsTest.class.getDeclaredMethod("testClassCastNull", String.class);
        Method methodNullClassCast = CastNullCheckDroppingsTest.class.getDeclaredMethod("testNullClassCast", String.class);
        Method methodClassCastObj  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testClassCastObj",  Object.class);
        Method methodObjClassCast  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testObjClassCast",  String.class);
        Method methodClassCastInt  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testClassCastInt",  Object.class);
        Method methodIntClassCast  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testIntClassCast",  Object.class);
        Method methodClassCastint  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testClassCastint",  Object.class);
        Method methodintClassCast  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testintClassCast",  Object.class);
        Method methodClassCastPrim = CastNullCheckDroppingsTest.class.getDeclaredMethod("testClassCastPrim", Object.class);
        Method methodPrimClassCast = CastNullCheckDroppingsTest.class.getDeclaredMethod("testPrimClassCast", Object.class);
        Method methodVarClassCast  = CastNullCheckDroppingsTest.class.getDeclaredMethod("testVarClassCast",  Class.class);

        t.runTest(methodClassCastNull, false, svalue);
        t.runTest(methodNullClassCast, false, svalue);
        t.runTest(methodClassCastObj,  false, svalue);
        t.runTest(methodObjClassCast,  false,  svalue);
        t.runTest(methodClassCastInt,  false, svalue);
        t.runTest(methodIntClassCast,  true,  svalue);
        t.runTest(methodClassCastint,  false, svalue);
        t.runTest(methodintClassCast,  false, svalue);
        t.runTest(methodClassCastPrim, false, svalue);
        t.runTest(methodPrimClassCast, true,  svalue);
        t.runTest(methodVarClassCast,  true,  objClass);
    }

    void testClassCast(String s) {
        try {
            ssink = String.class.cast(s);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testClassCastNull(String s) {
        try {
            ssink = String.class.cast(null);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testNullClassCast(String s) {
        try {
            ssink = (String)nullClass.cast(s);
            throw new AssertionError("NullPointerException is not thrown");
        } catch (NullPointerException t) {
            // Ignore NullPointerException
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testClassCastObj(Object s) {
        try {
            ssink = String.class.cast(s);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testObjClassCast(String s) {
        try {
            ssink = (String)objClass.cast(s);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testVarClassCast(Class cl) {
        try {
            ssink = (String)cl.cast(svalue);
            if (cl == null) {
                throw new AssertionError("NullPointerException is not thrown");
            }
        } catch (NullPointerException t) {
            // Ignore NullPointerException
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testClassCastInt(Object s) {
        try {
            ssink = String.class.cast(iobj);
            throw new AssertionError("ClassCastException is not thrown");
        } catch (ClassCastException t) {
            // Ignore ClassCastException: Cannot cast java.lang.Integer to java.lang.String
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testIntClassCast(Object s) {
        try {
            isink = Integer.class.cast(s);
            if (s != null) {
                throw new AssertionError("ClassCastException is not thrown");
            }
        } catch (ClassCastException t) {
            // Ignore ClassCastException: Cannot cast java.lang.String to java.lang.Integer
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testClassCastint(Object s) {
        try {
            ssink = String.class.cast(45);
            throw new AssertionError("ClassCastException is not thrown");
        } catch (ClassCastException t) {
            // Ignore ClassCastException: Cannot cast java.lang.Integer to java.lang.String
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testintClassCast(Object s) {
        try {
            isink = int.class.cast(s);
            if (s != null) {
                throw new AssertionError("ClassCastException is not thrown");
            }
        } catch (ClassCastException t) {
            // Ignore ClassCastException: Cannot cast java.lang.String to java.lang.Integer
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testClassCastPrim(Object s) {
        try {
            ssink = String.class.cast(arr);
            throw new AssertionError("ClassCastException is not thrown");
        } catch (ClassCastException t) {
            // Ignore ClassCastException: Cannot cast [I to java.lang.String
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testPrimClassCast(Object s) {
        try {
            asink = int[].class.cast(s);
            if (s != null) {
                throw new AssertionError("ClassCastException is not thrown");
            }
        } catch (ClassCastException t) {
            // Ignore ClassCastException: Cannot cast java.lang.String to [I
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testMHCast(String s) {
        try {
            ssink = (String) (Object) MH_CAST.invokeExact(String.class, (Object) s);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testMHSetter(String s) {
        try {
            SET_SSINK.invokeExact(this, s);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void testFunction(String s) {
        try {
            ssink = (String) fCast.apply(String.class, s);
        } catch (Throwable t) {
            throw new Error(t);
        }
    }

    void runTest(Method method, boolean deopt, Object value) {
        if (method == null) {
            throw new AssertionError("method was not found");
        }
        // Ensure method is compiled
        WHITE_BOX.testSetDontInlineMethod(method, true);
        Recording recording = new Recording();
        recording.enable(EventNames.Deoptimization);
        recording.start();

        for (int i = 0; i < 3000; i++) {
            try {
                method.invoke(this, value);
            } catch (Exception e) {
                throw new Error("Unexpected exception: ", e);
            }
        }
        NMethod nm = getNMethod(method);

        // Passing null should cause a de-optimization
        // if method is compiled with a null-check.
        try {
            method.invoke(this, onull);
        } catch (Exception e) {
            throw new Error("Unexpected exception: ", e);
        }
        recording.stop();
        List<RecordedEvent> events;
        try {
            events = Events.fromRecording(recording);
        } catch (IOException e) {
            throw new Error("failed to read jfr events", e);
        }

        checkDeoptimization(events, nm.compile_id, deopt);

        if (!deopt) {
            checkNoRecompilation(method, nm);
        }
    }

    static NMethod getNMethod(Method test) {
        // Because background compilation is disabled, method should now be compiled
        if (!WHITE_BOX.isMethodCompiled(test)) {
            throw new AssertionError(test + " not compiled");
        }

        NMethod nm = NMethod.get(test, false); // not OSR nmethod
        if (nm == null) {
            throw new AssertionError(test + " missing nmethod?");
        }
        if (nm.comp_level != 4) {
            throw new AssertionError(test + " compiled by not C2: " + nm);
        }
        return nm;
    }

    static void checkDeoptimization(List<RecordedEvent> events, int compilerId, boolean mustExist) {
        boolean exist = events.stream()
                .filter(e -> e.getEventType().getName().equals(EventNames.Deoptimization))
                .anyMatch(e -> compilerId == Events.assertField(e, "compileId").<Integer>getValue());

        if (exist != mustExist) {
            System.err.println("events:");
            System.err.println(events);
            throw new AssertionError("compilation must " + (mustExist ? "" : " not ") + " get deoptimized");
        }

        if (mustExist && events.stream()
                  .filter(e -> e.getEventType().getName().equals(EventNames.Deoptimization))
                  .filter(e -> compilerId == Events.assertField(e, "compileId").<Integer>getValue())
                  .noneMatch(e -> "null_check".equals(Events.assertField(e, "reason").getValue()))) {
            System.err.println("events:");
            System.err.println(events);
            throw new AssertionError("no deoptimizations due to null_check found");
        }

    }

    static void checkNoRecompilation(Method method, NMethod nmOrig) {
        NMethod nm = NMethod.get(method, false); // not OSR nmethod
        if (nm == null) {
            throw new AssertionError(method + " missing nmethod?");
        }
        if (nm.comp_level != 4) {
            throw new AssertionError(method + " compiled by not C2: " + nm);
        }
        if (nm.compile_id != nmOrig.compile_id) {
            throw new AssertionError(method + " was recompiled: old nmethod=" + nmOrig + ", new nmethod=" + nm);
        }
    }
}