From a07044e97ddc5da090a7b07385ae821c931aaad3 Mon Sep 17 00:00:00 2001 From: Yudi Zheng Date: Tue, 18 Feb 2025 16:59:02 +0100 Subject: [PATCH] Replace ASM with ClassFile API --- compiler/mx.compiler/suite.py | 49 +-- .../api/test/ExportingClassLoader.java | 42 --- .../compiler/api/test/ModuleSupport.java | 5 +- .../core/amd64/test/AMD64MatchRuleTest.java | 12 +- .../core/test/BytecodeDisassemblerTest.java | 4 +- .../core/test/CheckGraalInvariants.java | 7 +- .../core/test/CompilationWatchDogTest.java | 7 +- .../test/ConditionalEliminationTestBase.java | 7 +- .../core/test/CustomizedBytecodePattern.java | 118 +++++++ .../test/CustomizedBytecodePatternTest.java | 97 ------ .../core/test/DegeneratedLoopsTest.java | 5 +- .../core/test/DontReuseArgumentSpaceTest.java | 3 +- .../compiler/core/test/DumpPathTest.java | 5 +- .../core/test/DynamicConstantTest.java | 101 +++--- .../ExceptionHandlerReachabilityTest.java | 170 ++++------ .../core/test/FinalizableSubclassTest.java | 5 +- .../test/FindUniqueDefaultMethodTest.java | 5 +- .../compiler/core/test/FloatingReadTest.java | 5 +- .../compiler/core/test/GraalCompilerTest.java | 21 +- .../compiler/core/test/GraphDumpingTest.java | 8 +- .../core/test/GraphResetDebugTest.java | 10 +- .../test/GraphUtilOriginalValueTests.java | 70 ++-- .../compiler/core/test/HashCodeTest.java | 3 +- .../core/test/ImplicitNullCheckTest.java | 5 +- .../core/test/InitMemoryVerificationTest.java | 9 +- .../core/test/InterfaceMethodHandleTest.java | 119 ++----- .../core/test/LoopFullUnrollTest.java | 5 +- .../LoopSafepointStateVerificationTest.java | 8 +- .../compiler/core/test/LoopUnswitchTest.java | 5 +- .../core/test/MemoryScheduleTest.java | 5 +- .../core/test/OptionsVerifierTest.java | 188 +++++------ .../core/test/PushNodesThroughPiTest.java | 5 +- .../core/test/ReadAfterCheckCastTest.java | 5 +- .../core/test/ResolveDynamicConstantTest.java | 241 +++++++------- .../core/test/SingleRunSubphaseTest.java | 5 +- .../core/test/StaticInterfaceFieldTest.java | 5 +- .../core/test/SubWordArrayStoreTest.java | 210 ++++++------ .../core/test/SubWordFieldStoreTest.java | 166 +++++----- .../compiler/core/test/SubWordInputTest.java | 85 +++-- .../compiler/core/test/SubWordInputTest2.java | 76 ++--- .../compiler/core/test/SubWordReturnTest.java | 84 ++--- .../compiler/core/test/SubWordTestUtil.java | 79 ----- .../compiler/core/test/SwitchFoldingTest.java | 260 +++++++-------- .../core/test/TwoSlotMarkerClearingTest.java | 71 ++-- .../core/test/UnbalancedLockingTest.java | 266 ++++++--------- .../core/test/UnbalancedMonitorsTest.java | 312 +++++++----------- .../core/test/UnschedulableGraphTest.java | 13 +- .../core/test/VerifyAssertionUsageTest.java | 5 +- .../core/test/VerifyBailoutUsageTest.java | 5 +- .../core/test/VerifyDebugUsageTest.java | 14 +- .../core/test/VerifyVirtualizableTest.java | 5 +- .../core/test/backend/AllocatorTest.java | 13 +- .../core/test/backend/BackendTest.java | 5 +- .../test/deopt/RethrowExceptionLoopTest.java | 3 +- .../compiler/core/test/ea/EATestBase.java | 5 +- .../ea/PartialEscapeAnalysisTreesTest.java | 5 +- .../compiler/core/test/ea/PoorMansEATest.java | 5 +- .../ImpreciseArgumentStampInliningTest.java | 7 +- .../core/test/inlining/InliningTest.java | 10 +- ...NestedLoopEffectsPhaseComplexityTest2.java | 5 +- .../core/test/jfr/TestGetEventWriter.java | 137 ++++---- .../core/test/tutorial/InvokeGraal.java | 5 +- .../core/test/tutorial/StaticAnalysis.java | 5 +- .../test/CompilationAlarmPhaseTimesTest.java | 3 +- .../compiler/debug/test/DebugContextTest.java | 48 +-- .../graal/compiler/debug/test/TTYTest.java | 6 +- .../compiler/debug/test/TimerKeyTest.java | 13 +- .../test/GraphNodeEventListenerTest.java | 8 +- .../compiler/graph/test/NodeUsagesTests.java | 6 +- .../amd64/test/CompressedNullCheckTest.java | 4 +- .../hotspot/test/CheckGraalIntrinsics.java | 3 +- .../hotspot/test/ClassSubstitutionsTests.java | 3 +- .../hotspot/test/CompilationWrapperTest.java | 12 - .../hotspot/test/CompileTheWorld.java | 3 +- .../hotspot/test/CompileTheWorldTest.java | 5 +- .../test/DeferredBarrierAdditionTest.java | 5 +- .../hotspot/test/GraalOSRLockTest.java | 18 +- .../compiler/hotspot/test/GraalOSRTest.java | 4 +- .../test/HotSpotDeoptPostExceptions.java | 3 +- .../HotSpotLoopOverflowSpeculationTest.java | 7 - .../test/HotSpotStackIntrospectionTest.java | 4 +- .../hotspot/test/JVMCIInfopointErrorTest.java | 39 ++- .../hotspot/test/LambdaStableNameTest.java | 5 +- .../test/LibGraalCompilationDriver.java | 11 +- .../hotspot/test/LibGraalCompilerTest.java | 5 +- .../hotspot/test/MemoryUsageBenchmark.java | 9 +- .../hotspot/test/ProfileReplayTest.java | 3 +- .../hotspot/test/SafeConstructionTest.java | 105 +++--- .../test/SharedExceptionHandlerLoopTest.java | 13 +- .../TestDoNotMoveAllocationIntrinsic.java | 13 +- .../hotspot/test/TestIntrinsicCompiles.java | 3 +- .../compiler/jtt/backend/ConstantPhiTest.java | 5 +- .../jtt/backend/LargeConstantSectionTest.java | 119 ++----- .../jtt/bytecode/BC_instanceof01.java | 3 +- .../jtt/except/UntrustedInterfaces.java | 123 +++---- .../compiler/jtt/lang/LambdaEagerTest.java | 3 +- .../test/CompositeValueReplacementTest1.java | 11 +- .../loop/test/LoopPartialUnrollTest.java | 5 +- .../compiler/nodes/test/InliningLogTest.java | 5 +- .../compiler/options/test/TestOptionKey.java | 3 +- .../test/CompiledExceptionHandlerTest.java | 3 +- .../CompiledNullPointerExceptionTest.java | 3 +- .../test/DeoptimizeOnExceptionTest.java | 195 +++++------ .../replacements/test/DerivedOopTest.java | 8 +- .../replacements/test/InstanceOfTest.java | 5 +- .../test/InvokerSignatureMismatchTest.java | 262 ++++++++------- .../test/MethodSubstitutionTest.java | 6 +- .../test/NestedExceptionHandlerTest.java | 8 +- .../replacements/test/PEGraphDecoderTest.java | 6 +- .../test/PointerTrackingTest.java | 5 +- .../test/UnsafeObjectReplacementsTest.java | 71 ++-- .../graal/compiler/test/SubprocessUtil.java | 6 +- .../test/BeginNodeOptimizationTest.java | 4 +- .../test/BytecodeDSLCompilationTest.java | 6 +- ...ecodeInterpreterPartialEvaluationTest.java | 4 +- ...nalWeakReferencePartialEvaluationTest.java | 4 +- .../truffle/test/CompilerAssertsTest.java | 8 +- .../test/ContextLookupCompilationTest.java | 10 +- .../truffle/test/EncodedGraphCacheTest.java | 5 +- .../test/ExecutionListenerCompilerTest.java | 6 +- .../test/FinalBitSetCompilationTest.java | 38 +-- .../truffle/test/FlushEngineQueueTest.java | 3 +- ...nliningBytecodeInterpreterExampleTest.java | 5 +- .../HostInliningBytecodeInterpreterTest.java | 5 +- .../truffle/test/HostInliningTest.java | 5 +- .../truffle/test/IndirectCallSiteTest.java | 3 +- .../test/InstrumentationCompilerTest.java | 4 +- .../test/JFRPartialEvaluationTest.java | 4 +- .../test/LanguageContextFreedTest.java | 13 +- .../test/MultiTierCompilationTest.java | 6 +- .../compiler/truffle/test/NodeLimitTest.java | 3 +- .../truffle/test/OptimizedCallTargetTest.java | 3 +- .../test/OptimizedOSRLoopNodeTest.java | 15 +- .../truffle/test/OverrideOptionsTest.java | 3 +- .../truffle/test/PartialEvaluationTest.java | 7 +- .../truffle/test/PerformanceWarningTest.java | 5 +- ...agateHotnessToLexicalSingleCallerTest.java | 16 +- .../test/ResourceLimitsCompilationTest.java | 10 +- .../test/SimplePartialEvaluationTest.java | 6 +- .../test/StaticObjectCompilationTest.java | 39 +-- .../test/TruffleBoundaryExceptionsTest.java | 3 +- .../truffle/test/TruffleExplicitOOMETest.java | 3 +- .../truffle/test/TruffleHostInliningTest.java | 6 +- ...ffleToTruffleCallExceptionHandlerTest.java | 4 +- substratevm/mx.substratevm/suite.py | 25 +- 145 files changed, 1966 insertions(+), 2751 deletions(-) delete mode 100644 compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ExportingClassLoader.java create mode 100644 compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePattern.java delete mode 100644 compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePatternTest.java delete mode 100644 compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordTestUtil.java diff --git a/compiler/mx.compiler/suite.py b/compiler/mx.compiler/suite.py index d1a7b7789b90..ad2c87035772 100644 --- a/compiler/mx.compiler/suite.py +++ b/compiler/mx.compiler/suite.py @@ -85,41 +85,6 @@ "urls" : ["https://lafo.ssw.uni-linz.ac.at/pub/graal-external-deps/batik-all-1.7.jar"], }, - "ASM_9.7.1" : { - "digest" : "sha512:4767b01603dad5c79cc1e2b5f3722f72b1059d928f184f446ba11badeb1b381b3a3a9a801cc43d25d396df950b09d19597c73173c411b1da890de808b94f1f50", - "sourceDigest" : "sha512:d7c0de5912d04949a3d06cad366ff35a877da2682d9c74579625d62686032ea9349aff6102b17f92e9ec7eb4e9b1cd906b649c6a3ac798bfb9e31e5425de009d", - "maven" : { - "groupId" : "org.ow2.asm", - "artifactId" : "asm", - "version" : "9.7.1", - }, - "license" : "BSD-new", - }, - - "ASM_TREE_9.7.1" : { - "digest" : "sha512:e55008c392fdd35e95d3404766b12dd4b46e13d5c362fcd0ab42a65751a82737eaf0ebc857691d1916190d34407adfde4437615d69c278785416fd911e00978d", - "sourceDigest" : "sha512:3cea80bc7b55679dfa3d2065c6cb6951007cc7817082e9fcf4c5e3cdc073c22eddf7c7899cff60b1092049ec9038e8d3aa9a8828ef731739bda8b5afcec30e86", - "maven" : { - "groupId" : "org.ow2.asm", - "artifactId" : "asm-tree", - "version" : "9.7.1", - }, - "dependencies" : ["ASM_9.7.1"], - "license" : "BSD-new", - }, - - "ASM_UTIL_9.7.1" : { - "digest" : "sha512:522d793d15a2c5ea6504a50222cf0750f1eab7b881cf289675042539b1aba8b3868197b1bebe729de728dd10020eb028ae16252dcd5d84fdcbf7f925832bc269", - "sourceDigest" : "sha512:387aa887bfec24aec287d9aacebfdc0c2e1ab16a4adce933aecac6fc41545ce43a3eea0ed139db52dd0d0af910cfd2162aa4d6330a81b32b64b36f03b49db66a", - "maven" : { - "groupId" : "org.ow2.asm", - "artifactId" : "asm-util", - "version" : "9.7.1", - }, - "dependencies" : ["ASM_9.7.1"], - "license" : "BSD-new", - }, - "HSDIS" : { "urlbase" : "https://lafo.ssw.uni-linz.ac.at/pub/graal-external-deps/hsdis", "packedResource" : True, @@ -248,8 +213,6 @@ "dependencies" : [ "jdk.graal.compiler", "mx:JUNIT", - "ASM_TREE_9.7.1", - "ASM_UTIL_9.7.1", "JAVA_ALLOCATION_INSTRUMENTER", "truffle:TRUFFLE_SL_TEST", "truffle:TRUFFLE_TEST", @@ -295,7 +258,7 @@ "truffle:TRUFFLE_DSL_PROCESSOR" ], "checkstyle" : "jdk.graal.compiler", - "javaCompliance" : "21+", + "javaCompliance" : "23+", "jacoco" : "exclude", "graalCompilerSourceEdition": "ignore", }, @@ -336,8 +299,8 @@ }, "jacoco" : "exclude", "checkstyle": "jdk.graal.compiler", - "javaCompliance" : "21+", - "javaPreviewNeeded": "21+", + "javaCompliance" : "23+", + "javaPreviewNeeded": "23+", "workingSets" : "Graal,HotSpot,Test", "graalCompilerSourceEdition": "ignore", }, @@ -347,7 +310,7 @@ "sourceDirs" : ["src"], "dependencies" : ["mx:JMH_1_21", "jdk.graal.compiler.microbenchmarks"], "checkstyle" : "jdk.graal.compiler", - "javaCompliance" : "21+", + "javaCompliance" : "23+", "annotationProcessors" : ["mx:JMH_1_21"], "spotbugsIgnoresGenerated" : True, "workingSets" : "Graal,Bench", @@ -370,7 +333,7 @@ ], }, "checkstyle" : "jdk.graal.compiler", - "javaCompliance" : "21+", + "javaCompliance" : "23+", "checkPackagePrefix" : "false", "annotationProcessors" : ["mx:JMH_1_21"], "spotbugsIgnoresGenerated" : True, @@ -519,8 +482,6 @@ "truffle:TRUFFLE_COMPILER", "truffle:TRUFFLE_RUNTIME", "regex:TREGEX", - "ASM_TREE_9.7.1", - "ASM_UTIL_9.7.1", ], "exclude" : [ "mx:JUNIT", diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ExportingClassLoader.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ExportingClassLoader.java deleted file mode 100644 index 55bf9997fdd5..000000000000 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ExportingClassLoader.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2016, 2019, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ -package jdk.graal.compiler.api.test; - -/** - * A class loader that exports all packages in the module defining the class loader to all classes - * in the unnamed module associated with the loader. - */ -public class ExportingClassLoader extends ClassLoader { - @SuppressWarnings("this-escape") - public ExportingClassLoader() { - ModuleSupport.exportAllPackagesTo(getClass(), this); - } - - @SuppressWarnings("this-escape") - public ExportingClassLoader(ClassLoader parent) { - super(parent); - ModuleSupport.exportAllPackagesTo(getClass(), this); - } -} diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ModuleSupport.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ModuleSupport.java index d39c739d8b8d..3d190006594b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ModuleSupport.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/api/test/ModuleSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -39,7 +39,6 @@ import java.util.Set; import jdk.graal.compiler.debug.DebugOptions; - import jdk.internal.module.Modules; public class ModuleSupport { @@ -110,7 +109,7 @@ public static List getJRTGraalClassNames() throws IOException { Path top = fs.getPath("/modules/"); Files.find(top, Integer.MAX_VALUE, - (path, attrs) -> attrs.isRegularFile()).forEach(p -> { + (_, attrs) -> attrs.isRegularFile()).forEach(p -> { int nameCount = p.getNameCount(); if (nameCount > 2) { String base = p.getName(nameCount - 1).toString(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/amd64/test/AMD64MatchRuleTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/amd64/test/AMD64MatchRuleTest.java index 332b4f91f488..5ad7b61fa1d2 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/amd64/test/AMD64MatchRuleTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/amd64/test/AMD64MatchRuleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -26,6 +26,9 @@ import static org.junit.Assume.assumeTrue; +import org.junit.Before; +import org.junit.Test; + import jdk.graal.compiler.core.common.cfg.BasicBlock; import jdk.graal.compiler.core.test.MatchRuleTest; import jdk.graal.compiler.lir.LIR; @@ -37,9 +40,6 @@ import jdk.graal.compiler.lir.amd64.AMD64ControlFlow.CmpConstBranchOp; import jdk.graal.compiler.lir.amd64.AMD64ControlFlow.CmpDataBranchOp; import jdk.graal.compiler.lir.amd64.AMD64Unary; -import org.junit.Before; -import org.junit.Test; - import jdk.vm.ci.amd64.AMD64; import jdk.vm.ci.amd64.AMD64Kind; @@ -103,7 +103,7 @@ public void testVolatileExtension() { boolean found = false; for (LIRInstruction ins : lir.getLIRforBlock(lir.getControlFlowGraph().getBlocks()[lir.codeEmittingOrder()[0]])) { if (ins instanceof AMD64Unary.MemoryOp) { - ins.visitEachOutput((value, mode, flags) -> assertTrue(value.getPlatformKind().toString(), value.getPlatformKind().equals(AMD64Kind.QWORD))); + ins.visitEachOutput((value, _, _) -> assertTrue(value.getPlatformKind().toString(), value.getPlatformKind().equals(AMD64Kind.QWORD))); assertFalse("MemoryOp expected only once in first block", found); found = true; } @@ -209,7 +209,7 @@ public void testVolatileExtensionDifferentBlocks() { boolean found = false; for (LIRInstruction ins : lir.getLIRforBlock(lir.getControlFlowGraph().getBlocks()[lir.codeEmittingOrder()[0]])) { if (ins instanceof AMD64Unary.MemoryOp) { - ins.visitEachOutput((value, mode, flags) -> assertTrue(value.getPlatformKind().toString(), value.getPlatformKind().equals(AMD64Kind.QWORD))); + ins.visitEachOutput((value, _, _) -> assertTrue(value.getPlatformKind().toString(), value.getPlatformKind().equals(AMD64Kind.QWORD))); assertFalse("MemoryOp expected only once in first block", found); found = true; } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/BytecodeDisassemblerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/BytecodeDisassemblerTest.java index b99faf3e0015..f8432dfc3b24 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/BytecodeDisassemblerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/BytecodeDisassemblerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -58,7 +58,7 @@ private static List> gatherClasses() throws IOException { FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), Collections.emptyMap()); Path top = fs.getPath("/modules/"); Files.find(top, Integer.MAX_VALUE, - (path, attrs) -> attrs.isRegularFile()).forEach(p -> { + (_, attrs) -> attrs.isRegularFile()).forEach(p -> { int nameCount = p.getNameCount(); if (nameCount > 2) { String base = p.getName(nameCount - 1).toString(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CheckGraalInvariants.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CheckGraalInvariants.java index 88fe9a092e6f..f45113fabbcd 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CheckGraalInvariants.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CheckGraalInvariants.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -238,7 +238,6 @@ public void test() { runTest(new InvariantsTool()); } - @SuppressWarnings("try") public static void runTest(InvariantsTool tool) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); @@ -383,7 +382,7 @@ public static void runTest(InvariantsTool tool) { ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m); try (DebugContext debug = new Builder(options).build()) { StructuredGraph graph = new StructuredGraph.Builder(options, debug, AllowAssumptions.YES).method(method).build(); - try (DebugCloseable s = debug.disableIntercept(); DebugContext.Scope ds = debug.scope("CheckingGraph", graph, method)) { + try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("CheckingGraph", graph, method)) { graphBuilderSuite.apply(graph, context); // update phi stamps graph.getNodes().filter(PhiNode.class).forEach(PhiNode::inferStamp); @@ -437,7 +436,7 @@ public static void runTest(InvariantsTool tool) { try (DebugContext debug = new Builder(options).build()) { boolean isSubstitution = method.getAnnotation(Snippet.class) != null; StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).setIsSubstitution(isSubstitution).build(); - try (DebugCloseable s = debug.disableIntercept(); DebugContext.Scope ds = debug.scope("CheckingGraph", graph, method)) { + try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("CheckingGraph", graph, method)) { checkMethod(method); graphBuilderSuite.apply(graph, context); // update phi stamps diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CompilationWatchDogTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CompilationWatchDogTest.java index 0b71b4fd77f2..b70d1b397e62 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CompilationWatchDogTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CompilationWatchDogTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -104,7 +104,6 @@ protected InstalledCode getCode(ResolvedJavaMethod installedCodeOwner, Structure } } - @SuppressWarnings("try") private InstalledCode getCodeHelper(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile, boolean installAsDefault, OptionValues options) { CompilationIdentifier compilation = new CompilationIdentifier() { @Override @@ -138,9 +137,9 @@ public void onStuckCompilation(CompilationWatchDog watchDog, Thread watched, Com }; CompilationWatchDog watch = CompilationWatchDog.watch(compilation, options, false, longCompilationHandler, null); - try (CompilationWatchDog watchScope = watch) { + try (CompilationWatchDog _ = watch) { event("start compiling"); - try (TTY.Filter f = new TTY.Filter()) { + try (TTY.Filter _ = new TTY.Filter()) { return super.getCode(installedCodeOwner, graph, forceCompile, installAsDefault, options); } } finally { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ConditionalEliminationTestBase.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ConditionalEliminationTestBase.java index 92332c43e6f1..ba293c0871e2 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ConditionalEliminationTestBase.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ConditionalEliminationTestBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -61,7 +61,6 @@ protected void testConditionalElimination(String snippet, String referenceSnippe testConditionalElimination(snippet, referenceSnippet, false, false); } - @SuppressWarnings("try") protected void testConditionalElimination(String snippet, String referenceSnippet, boolean applyConditionalEliminationOnReference, boolean applyLowering) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES); DebugContext debug = graph.getDebug(); @@ -69,7 +68,7 @@ protected void testConditionalElimination(String snippet, String referenceSnippe CoreProviders context = getProviders(); CanonicalizerPhase canonicalizer1 = createCanonicalizerPhase(); CanonicalizerPhase canonicalizer = createCanonicalizerPhase(); - try (DebugContext.Scope scope = debug.scope("ConditionalEliminationTest", graph)) { + try (DebugContext.Scope _ = debug.scope("ConditionalEliminationTest", graph)) { prepareGraph(graph, canonicalizer1, context, applyLowering); new IterativeConditionalEliminationPhase(canonicalizer, true).apply(graph, context); canonicalizer.apply(graph, context); @@ -78,7 +77,7 @@ protected void testConditionalElimination(String snippet, String referenceSnippe debug.handle(t); } StructuredGraph referenceGraph = parseEager(referenceSnippet, AllowAssumptions.YES); - try (DebugContext.Scope scope = debug.scope("ConditionalEliminationTest.ReferenceGraph", referenceGraph)) { + try (DebugContext.Scope _ = debug.scope("ConditionalEliminationTest.ReferenceGraph", referenceGraph)) { prepareGraph(referenceGraph, canonicalizer, context, applyLowering); if (applyConditionalEliminationOnReference) { new ConditionalEliminationPhase(canonicalizer, true).apply(referenceGraph, context); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePattern.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePattern.java new file mode 100644 index 000000000000..797800d9044b --- /dev/null +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePattern.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2018, 2025, 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. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * 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. + */ +package jdk.graal.compiler.core.test; + +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.classfile.ClassFile.ACC_STATIC; + +import java.io.File; +import java.io.IOException; +import java.lang.constant.ClassDesc; +import java.lang.invoke.MethodHandles; +import java.nio.file.Files; +import java.util.function.Function; + +public interface CustomizedBytecodePattern { + + class DumpSupport { + static final File GENERATED_CLASS_FILE_OUTPUT_DIRECTORY; + + static { + String prop = System.getProperty("save.generated.classfile.dir"); + File file = null; + if (prop != null) { + file = new File(prop); + ensureDirectoryExists(file); + assert file.exists() : file; + } + GENERATED_CLASS_FILE_OUTPUT_DIRECTORY = file; + } + + private static File ensureDirectoryExists(File file) { + if (!file.exists()) { + file.mkdirs(); + } + return file; + } + + static void dump(String className, byte[] classfileBytes) { + if (GENERATED_CLASS_FILE_OUTPUT_DIRECTORY != null) { + try { + File classfile = new File(GENERATED_CLASS_FILE_OUTPUT_DIRECTORY, className.replace('.', File.separatorChar) + ".class"); + ensureDirectoryExists(classfile.getParentFile()); + Files.write(classfile.toPath(), classfileBytes); + System.out.println("Wrote: " + classfile.getAbsolutePath()); + } catch (IOException e) { + throw new AssertionError(e); + } + } + } + } + + class CachedLoader extends ClassLoader { + + final String className; + Class loaded; + final Function classfileSupplier; + + public CachedLoader(ClassLoader parent, String className, Function classfileSupplier) { + super(parent); + this.className = className; + this.classfileSupplier = classfileSupplier; + } + + @Override + public Class findClass(String name) throws ClassNotFoundException { + if (name.equals(className)) { + if (loaded == null) { + byte[] classfileBytes = classfileSupplier.apply(name); + DumpSupport.dump(name, classfileBytes); + loaded = defineClass(name, classfileBytes, 0, classfileBytes.length); + } + return loaded; + } else { + return super.findClass(name); + } + } + } + + default Class getClass(String className) throws ClassNotFoundException { + return new CachedLoader(CustomizedBytecodePattern.class.getClassLoader(), className, this::generateClass).findClass(className); + } + + default Class lookupClass(MethodHandles.Lookup lookup, String className) throws IllegalAccessException { + byte[] classfileBytes = generateClass(className); + DumpSupport.dump(className, classfileBytes); + return lookup.defineClass(classfileBytes); + } + + int ACC_PUBLIC_STATIC = ACC_PUBLIC | ACC_STATIC; + + default ClassDesc cd(Class klass) { + return klass.describeConstable().orElseThrow(); + } + + byte[] generateClass(String className); +} diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePatternTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePatternTest.java deleted file mode 100644 index 705b27b9b11b..000000000000 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/CustomizedBytecodePatternTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2018, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ -package jdk.graal.compiler.core.test; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.function.Function; - -import org.objectweb.asm.Opcodes; - -public abstract class CustomizedBytecodePatternTest extends GraalCompilerTest implements Opcodes { - - protected Class getClass(String className) throws ClassNotFoundException { - return new CachedLoader(CustomizedBytecodePatternTest.class.getClassLoader(), className, this::generateClass).findClass(className); - } - - private static final File GENERATED_CLASS_FILE_OUTPUT_DIRECTORY; - static { - String prop = System.getProperty("save.generated.classfile.dir"); - File file = null; - if (prop != null) { - file = new File(prop); - ensureDirectoryExists(file); - assert file.exists() : file; - } - GENERATED_CLASS_FILE_OUTPUT_DIRECTORY = file; - } - - private static File ensureDirectoryExists(File file) { - if (!file.exists()) { - file.mkdirs(); - } - return file; - } - - public static class CachedLoader extends ClassLoader { - - final String className; - Class loaded; - final Function classfileSupplier; - - public CachedLoader(ClassLoader parent, String className, Function classfileSupplier) { - super(parent); - this.className = className; - this.classfileSupplier = classfileSupplier; - } - - @Override - public Class findClass(String name) throws ClassNotFoundException { - if (name.equals(className)) { - if (loaded == null) { - byte[] classfileBytes = classfileSupplier.apply(name.replace('.', '/')); - if (GENERATED_CLASS_FILE_OUTPUT_DIRECTORY != null) { - try { - File classfile = new File(GENERATED_CLASS_FILE_OUTPUT_DIRECTORY, name.replace('.', File.separatorChar) + ".class"); - ensureDirectoryExists(classfile.getParentFile()); - Files.write(classfile.toPath(), classfileBytes); - System.out.println("Wrote: " + classfile.getAbsolutePath()); - } catch (IOException e) { - throw new AssertionError(e); - } - } - loaded = defineClass(name, classfileBytes, 0, classfileBytes.length); - } - return loaded; - } else { - return super.findClass(name); - } - } - - } - - protected abstract byte[] generateClass(String internalClassName); -} diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DegeneratedLoopsTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DegeneratedLoopsTest.java index 85dac4c9af79..baed1427d51a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DegeneratedLoopsTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DegeneratedLoopsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -77,10 +77,9 @@ private static void test() { } - @SuppressWarnings("try") private void test(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("DegeneratedLoopsTest", new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope("DegeneratedLoopsTest", new DebugDumpScope(snippet))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES); HighTierContext context = getDefaultHighTierContext(); createInliningPhase().apply(graph, context); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DontReuseArgumentSpaceTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DontReuseArgumentSpaceTest.java index a3a6c23df6a6..3ca8a626dc1f 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DontReuseArgumentSpaceTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DontReuseArgumentSpaceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -41,7 +41,6 @@ public final class DontReuseArgumentSpaceTest extends GraalCompilerTest { @Override - @SuppressWarnings("try") protected Suites createSuites(OptionValues options) { return super.createSuites(new OptionValues(options, HighTier.Options.Inline, false)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DumpPathTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DumpPathTest.java index 3c0cc5e36669..ce0a29b2cfb1 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DumpPathTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DumpPathTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -51,7 +51,6 @@ public static Object snippet() { return new String("snippet"); } - @SuppressWarnings("try") @Test public void testDump() throws Exception { assumeManagementLibraryIsLoadable(); @@ -67,7 +66,7 @@ public void testDump() throws Exception { overrides.put(GraalCompilerOptions.DumpHeapAfter, ":Schedule"); overrides.put(DebugOptions.MethodFilter, null); - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { // Generate dump files. test(new OptionValues(getInitialOptions(), overrides), "snippet"); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DynamicConstantTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DynamicConstantTest.java index a893b5382d52..8f60245f2d96 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DynamicConstantTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/DynamicConstantTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -24,6 +24,15 @@ */ package jdk.graal.compiler.core.test; +import java.lang.classfile.ClassFile; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.TypeKind; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; +import java.lang.constant.DirectMethodHandleDesc.Kind; +import java.lang.constant.DynamicConstantDesc; +import java.lang.constant.MethodHandleDesc; +import java.lang.constant.MethodTypeDesc; import java.lang.invoke.MethodHandles; import java.util.Arrays; import java.util.LinkedHashMap; @@ -32,11 +41,6 @@ import org.junit.Assume; import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.ConstantDynamic; -import org.objectweb.asm.Handle; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; import jdk.vm.ci.meta.ConstantPool; import jdk.vm.ci.meta.ResolvedJavaMethod; @@ -47,20 +51,14 @@ * @see "https://openjdk.java.net/jeps/309" * @see "https://bugs.openjdk.java.net/browse/JDK-8177279" */ -public class DynamicConstantTest extends CustomizedBytecodePatternTest { - - private static final int PUBLIC_STATIC = ACC_PUBLIC | ACC_STATIC; - - static final String testClassInternalName = DynamicConstantTest.class.getName().replace('.', '/'); - static final String constantBootstrapsClassInternalName = "java/lang/invoke/ConstantBootstraps"; - +public class DynamicConstantTest extends GraalCompilerTest { /** * Map of test class generators keyed by internal class name. */ private final Map generators = new LinkedHashMap<>(); private void add(TestGenerator gen) { - generators.put(gen.className.replace('.', '/'), gen); + generators.put(gen.taregtClassName.replace('.', '/'), gen); } enum CondyType { @@ -88,11 +86,11 @@ enum CondyType { * Generates a class with a static {@code run} method that returns a value loaded from * CONSTANT_Dynamic constant pool entry. */ - static class TestGenerator { + static class TestGenerator implements CustomizedBytecodePattern { /** * Type of value returned by the generated {@code run} method. */ - final Type type; + final ClassDesc type; /** * Type of condy used to produce the returned value. @@ -108,63 +106,50 @@ static class TestGenerator { /** * Name of the generated class. */ - final String className; + final String taregtClassName; TestGenerator(Class type, CondyType condyType) { String typeName = type.getSimpleName(); - this.type = Type.getType(type); + this.type = cd(type); this.condyType = condyType; this.getter = "get" + typeName.substring(0, 1).toUpperCase() + typeName.substring(1); - this.className = DynamicConstantTest.class.getName() + "$" + typeName + '_' + condyType; + this.taregtClassName = DynamicConstantTest.class.getName() + "$" + typeName + '_' + condyType; } - void generate(ClassWriter cw) { + @Override + public byte[] generateClass(String className) { // @formatter:off - // Object ConstantBootstraps.invoke(MethodHandles.Lookup lookup, String name, Class type, MethodHandle handle, Object... args) + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethodBody("run", MethodTypeDesc.of(type), ACC_PUBLIC_STATIC, this::generate)); // @formatter:on - String invokeSig = "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/invoke/MethodHandle;[Ljava/lang/Object;)Ljava/lang/Object;"; - Handle invokeHandle = new Handle(H_INVOKESTATIC, constantBootstrapsClassInternalName, "invoke", invokeSig, false); + } + + private void generate(CodeBuilder b) { + // @formatter:off + // Object ConstantBootstraps.invoke(MethodHandles.Lookup lookup, String name, Class type, MethodHandle handle, Object... args) + ClassDesc outerClass = cd(DynamicConstantTest.class); + String desc = type.descriptorString(); - String desc = type.getDescriptor(); if (condyType == CondyType.CALL_DIRECT_BSM) { // Example: int DynamicConstantTest.getIntBSM(MethodHandles.Lookup l, String name, // Class type) String sig = "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)" + desc; - Handle handle = new Handle(H_INVOKESTATIC, testClassInternalName, getter + "BSM", sig, false); - - ConstantDynamic condy = new ConstantDynamic("const", desc, handle); - MethodVisitor run = cw.visitMethod(PUBLIC_STATIC, "run", "()" + desc, null, null); - run.visitLdcInsn(condy); - run.visitInsn(type.getOpcode(IRETURN)); - run.visitMaxs(0, 0); - run.visitEnd(); + var condy = DynamicConstantDesc.ofNamed(MethodHandleDesc.of(Kind.STATIC, outerClass, getter + "BSM", sig), "const", type); + b.ldc(condy).return_(TypeKind.from(type)); } else if (condyType == CondyType.CALL_INDIRECT_BSM) { // Example: int DynamicConstantTest.getInt() - Handle handle = new Handle(H_INVOKESTATIC, testClassInternalName, getter, "()" + desc, false); - - ConstantDynamic condy = new ConstantDynamic("const", desc, invokeHandle, handle); - MethodVisitor run = cw.visitMethod(PUBLIC_STATIC, "run", "()" + desc, null, null); - run.visitLdcInsn(condy); - run.visitInsn(type.getOpcode(IRETURN)); - run.visitMaxs(0, 0); - run.visitEnd(); + var condy = DynamicConstantDesc.ofNamed(ConstantDescs.BSM_INVOKE, "const", type, MethodHandleDesc.of(Kind.STATIC, outerClass, getter, "()" + desc)); + b.ldc(condy).return_(TypeKind.from(type)); } else { assert condyType == CondyType.CALL_INDIRECT_WITH_ARGS_BSM; // Example: int DynamicConstantTest.getInt() - Handle handle1 = new Handle(H_INVOKESTATIC, testClassInternalName, getter, "()" + desc, false); - + var condy1 = DynamicConstantDesc.ofNamed(ConstantDescs.BSM_INVOKE, "const1", type, MethodHandleDesc.of(Kind.STATIC, outerClass, getter, "()" + desc)); // Example: int DynamicConstantTest.getInt(int v1, int v2) - Handle handle2 = new Handle(H_INVOKESTATIC, testClassInternalName, getter, "(" + desc + desc + ")" + desc, false); - - ConstantDynamic condy1 = new ConstantDynamic("const1", desc, invokeHandle, handle1); - ConstantDynamic condy2 = new ConstantDynamic("const2", desc, invokeHandle, handle2, condy1, condy1); - - MethodVisitor run = cw.visitMethod(PUBLIC_STATIC, "run", "()" + desc, null, null); - run.visitLdcInsn(condy2); - run.visitInsn(type.getOpcode(IRETURN)); - run.visitMaxs(0, 0); - run.visitEnd(); + var condy2 = DynamicConstantDesc.ofNamed(ConstantDescs.BSM_INVOKE, "const2", type, MethodHandleDesc.of(Kind.STATIC, outerClass, getter, "(" + desc + desc + ")" + desc), condy1, + condy1); + b.ldc(condy2).return_(TypeKind.from(type)); } + // @formatter:on } } @@ -226,21 +211,11 @@ public DynamicConstantTest() { private static final boolean VERBOSE = Boolean.getBoolean(DynamicConstantTest.class.getSimpleName() + ".verbose"); - @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(55, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - generators.get(internalClassName).generate(cw); - cw.visitEnd(); - return cw.toByteArray(); - } - - @SuppressWarnings("try") @Test public void test() throws Throwable { boolean jvmciCompatibilityChecked = false; for (TestGenerator e : generators.values()) { - Class testClass = getClass(e.className); + Class testClass = e.getClass(e.taregtClassName); ResolvedJavaMethod run = getResolvedJavaMethod(testClass, "run"); if (!jvmciCompatibilityChecked) { checkJVMCICompatibility(run); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ExceptionHandlerReachabilityTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ExceptionHandlerReachabilityTest.java index bde63885ae1d..3779379af616 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ExceptionHandlerReachabilityTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ExceptionHandlerReachabilityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -24,20 +24,19 @@ */ package jdk.graal.compiler.core.test; -import java.io.IOException; +import static java.lang.constant.ConstantDescs.CD_int; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.Label; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import org.junit.Assert; import org.junit.Test; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; import jdk.graal.compiler.core.common.PermanentBailoutException; import jdk.graal.compiler.debug.GraalError; -import jdk.graal.compiler.nodes.StructuredGraph; +import jdk.graal.compiler.nodes.StructuredGraph.AllowAssumptions; import jdk.vm.ci.meta.ResolvedJavaMethod; /** @@ -74,20 +73,16 @@ * * */ -public class ExceptionHandlerReachabilityTest extends CustomizedBytecodePatternTest { +public class ExceptionHandlerReachabilityTest extends GraalCompilerTest implements CustomizedBytecodePattern { @Test public void test() { - testParseAndRun(SharedExceptionHandlerClass.class.getName(), "sharedExceptionHandlerMethod", new Class[]{int.class}); - } - - public void testParseAndRun(String clazzName, String methodName, Class[] args) { try { - Class testClass = getClass(clazzName); - ResolvedJavaMethod method = asResolvedJavaMethod(testClass.getMethod(methodName, args)); + Class testClass = getClass(SharedExceptionHandlerClass.class.getName() + "$Test"); + ResolvedJavaMethod method = asResolvedJavaMethod(testClass.getMethod("sharedExceptionHandlerMethod", int.class)); // test successful parsing - parseEager(method, StructuredGraph.AllowAssumptions.YES, getInitialOptions()); + parseEager(method, AllowAssumptions.YES, getInitialOptions()); // test successful compilation + execution int actual = (int) test(method, null, 11).returnValue; @@ -98,109 +93,58 @@ public void testParseAndRun(String clazzName, String methodName, Class[] args } catch (ClassNotFoundException | NoSuchMethodException e) { throw GraalError.shouldNotReachHere(e); } - } @Override - protected byte[] generateClass(String className) { - try { - ClassReader classReader = new ClassReader(className); - final ClassWriter cw = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - classReader.accept(new ClassVisitor(Opcodes.ASM9, cw) { - - @Override - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); - if (name.equals("sharedExceptionHandlerMethod")) { - return new SharedExceptionHandlerReplacer(mv, className.replace('.', '/')); - } - return mv; - } - - }, ClassReader.EXPAND_FRAMES); - - return cw.toByteArray(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private static class SharedExceptionHandlerReplacer extends MethodVisitor { - private final MethodVisitor mv; - private final String clazzName; - - SharedExceptionHandlerReplacer(MethodVisitor methodVisitor, String clazzName) { - super(ASM9, null); - this.mv = methodVisitor; - this.clazzName = clazzName; - } - - @Override - public void visitCode() { - mv.visitCode(); - Label label0 = new Label(); - Label label1 = new Label(); - - Label startEx1 = new Label(); - Label endEx1 = new Label(); - Label handlerEx1 = new Label(); - Label startEx2 = new Label(); - Label endEx2 = new Label(); - Label handlerEx2 = new Label(); - mv.visitVarInsn(ILOAD, 0); - mv.visitVarInsn(ISTORE, 1); - mv.visitTryCatchBlock(startEx1, endEx1, handlerEx1, "java/lang/IllegalArgumentException"); - mv.visitLabel(startEx1); - mv.visitVarInsn(ILOAD, 1); - mv.visitMethodInsn(INVOKESTATIC, clazzName, "foo", "(I)I", false); - mv.visitVarInsn(ISTORE, 1); - mv.visitLabel(endEx1); - mv.visitJumpInsn(GOTO, label0); - mv.visitLabel(handlerEx1); - // --- REMOVE storing exception to make stack frames compatible: - // mv.visitVarInsn(ASTORE, 2); - mv.visitVarInsn(ILOAD, 1); - mv.visitMethodInsn(INVOKESTATIC, clazzName, "baz", "(I)I", false); - mv.visitVarInsn(ISTORE, 1); - mv.visitVarInsn(ILOAD, 1); - mv.visitInsn(IRETURN); - mv.visitLabel(label0); - mv.visitTryCatchBlock(startEx2, endEx2, handlerEx2, "java/lang/NumberFormatException"); - mv.visitLabel(startEx2); - mv.visitVarInsn(ILOAD, 1); - mv.visitMethodInsn(INVOKESTATIC, clazzName, "bar", "(I)I", false); - mv.visitVarInsn(ISTORE, 1); - mv.visitLabel(endEx2); - mv.visitJumpInsn(GOTO, label1); - mv.visitLabel(handlerEx2); - // --- REMOVE storing exception to make stack frames compatible: - // mv.visitVarInsn(ASTORE, 2); - mv.visitVarInsn(ILOAD, 1); - mv.visitMethodInsn(INVOKESTATIC, clazzName, "doSomething", "(I)I", false); - mv.visitVarInsn(ISTORE, 1); - // --- ADD jump to first exception handler from within second exception handler: - mv.visitJumpInsn(GOTO, handlerEx1); - // --- REMOVE duplicate code from first handler: - // mv.visitVarInsn(ILOAD, 1); - // mv.visitMethodInsn(INVOKESTATIC, clazzName, "baz", "(I)I", false); - // mv.visitVarInsn(ISTORE, 1); - // mv.visitVarInsn(ILOAD, 1); - // mv.visitInsn(IRETURN); - mv.visitLabel(label1); - mv.visitVarInsn(ILOAD, 1); - mv.visitInsn(IRETURN); - mv.visitMaxs(1, 3); - mv.visitEnd(); - } + public byte[] generateClass(String className) { + ClassDesc classSharedExceptionHandlerClass = cd(SharedExceptionHandlerClass.class); + MethodTypeDesc mtdII = MethodTypeDesc.of(CD_int, CD_int); + + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethodBody("sharedExceptionHandlerMethod", mtdII, ACC_PUBLIC_STATIC, b -> { + Label handlerEx1 = b.newLabel(); + b + .iload(0) + .istore(1) + .trying(tryBlock -> { + tryBlock + .iload(1) + .invokestatic(classSharedExceptionHandlerClass, "foo", mtdII) + .istore(1); + }, catchBuilder -> catchBuilder.catching(cd(IllegalArgumentException.class), catchBlock -> { + catchBlock + .labelBinding(handlerEx1) + .iload(1) + .invokestatic(classSharedExceptionHandlerClass, "baz", mtdII) + .istore(1) + .iload(1) + .ireturn(); + })) + .trying(tryBlock -> { + tryBlock + .iload(1) + .invokestatic(classSharedExceptionHandlerClass, "bar", mtdII) + .istore(1); + }, catchBuilder -> catchBuilder.catching(cd(NumberFormatException.class), catchBlock -> { + catchBlock + .iload(1) + .invokestatic(classSharedExceptionHandlerClass, "doSomething", mtdII) + .istore(1) + .goto_(handlerEx1); + })) + .iload(1) + .ireturn(); + })); + // @formatter:on } public class SharedExceptionHandlerClass { - /** - * The bytecode of this method will be modified by {@link SharedExceptionHandlerReplacer}. - * The modified bytecode contains a {@code goto} from within the second exception handler to - * the first exception handler. This reduces the overall bytecode size due to code sharing. - * The pattern is produced by code obfuscation tools, see [GR-47376]. + * The bytecode of this method will be modified and placed in an inner class. The modified + * bytecode contains a {@code goto} from within the second exception handler to the first + * exception handler. This reduces the overall bytecode size due to code sharing. The + * pattern is produced by code obfuscation tools, see [GR-47376]. */ public static int sharedExceptionHandlerMethod(int i) { int x = i; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FinalizableSubclassTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FinalizableSubclassTest.java index 4f1e10460f99..db4b31328444 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FinalizableSubclassTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FinalizableSubclassTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -70,7 +70,6 @@ protected void finalize() throws Throwable { } } - @SuppressWarnings("try") private StructuredGraph parseAndProcess(Class cl, AllowAssumptions allowAssumptions) { Constructor[] constructors = cl.getConstructors(); Assert.assertTrue(constructors.length == 1); @@ -78,7 +77,7 @@ private StructuredGraph parseAndProcess(Class cl, AllowAssumptions allowAssum OptionValues options = getInitialOptions(); DebugContext debug = getDebugContext(options, null, javaMethod); StructuredGraph graph = new StructuredGraph.Builder(options, debug, allowAssumptions).method(javaMethod).build(); - try (DebugContext.Scope s = debug.scope("FinalizableSubclassTest", graph)) { + try (DebugContext.Scope _ = debug.scope("FinalizableSubclassTest", graph)) { GraphBuilderConfiguration conf = GraphBuilderConfiguration.getSnippetDefault(getDefaultGraphBuilderPlugins()); new TestGraphBuilderPhase.Instance(getProviders(), conf, OptimisticOptimizations.ALL, null).apply(graph); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FindUniqueDefaultMethodTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FindUniqueDefaultMethodTest.java index 2df6921b4e3b..31785a8d0161 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FindUniqueDefaultMethodTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FindUniqueDefaultMethodTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -137,10 +137,9 @@ private void testConstantReturn(String name, Object value) { assertDeepEquals(value, ret.result().asJavaConstant().asBoxedPrimitive()); } - @SuppressWarnings("try") protected StructuredGraph buildGraph(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("InstanceOfTest", getMetaAccess().lookupJavaMethod(getMethod(snippet)))) { + try (DebugContext.Scope _ = debug.scope("InstanceOfTest", getMetaAccess().lookupJavaMethod(getMethod(snippet)))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES, debug); compile(graph.method(), graph); debug.dump(DebugContext.BASIC_LEVEL, graph, snippet); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FloatingReadTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FloatingReadTest.java index d543f92d1c5b..5387afca29c7 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FloatingReadTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/FloatingReadTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -60,10 +60,9 @@ public void test1() { test("test1Snippet"); } - @SuppressWarnings("try") private void test(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("FloatingReadTest", new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope("FloatingReadTest", new DebugDumpScope(snippet))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES); CoreProviders context = getProviders(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/GraalCompilerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/GraalCompilerTest.java index 892b460c976e..05819dce1947 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/GraalCompilerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/GraalCompilerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -525,7 +525,6 @@ protected void assertEquals(StructuredGraph expected, StructuredGraph actual, bo * {@code actual} in its context so that these graphs are dumped when the comparison * fails and {@code DumpOnError=true} */ - @SuppressWarnings("try") protected void assertEquals(StructuredGraph expected, StructuredGraph actual, boolean excludeVirtual, @@ -539,7 +538,7 @@ protected void assertEquals(StructuredGraph expected, String mismatchString = compareGraphStrings(expected, expectedString, actual, actualString); // Open a scope so that `expected` and `actual` are dumped if DumpOnError=true - try (DebugContext.Scope scope = addGraphsToDebugContext ? debug.scope("GraphEqualsTest", expected, actual) : null) { + try (DebugContext.Scope _ = addGraphsToDebugContext ? debug.scope("GraphEqualsTest", expected, actual) : null) { if (!excludeVirtual && getNodeCountExcludingUnusedConstants(expected) != getNodeCountExcludingUnusedConstants(actual)) { debug.dump(DebugContext.BASIC_LEVEL, expected, "Node count not matching - expected"); debug.dump(DebugContext.BASIC_LEVEL, actual, "Node count not matching - actual"); @@ -1132,7 +1131,6 @@ protected final InstalledCode getCode(final ResolvedJavaMethod installedCodeOwne * @param installAsDefault specifies whether to install as the default implementation * @param options the options that will be used in {@link #parseForCompile(ResolvedJavaMethod)} */ - @SuppressWarnings("try") protected InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile, boolean installAsDefault, OptionValues options) { boolean useCache = !forceCompile && getArgumentToBind() == null; if (useCache && graph == null) { @@ -1157,12 +1155,12 @@ protected InstalledCode getCode(final ResolvedJavaMethod installedCodeOwner, Str StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner, id, options) : graph; DebugContext debug = graphToCompile.getDebug(); - try (AllocSpy spy = AllocSpy.open(installedCodeOwner); DebugContext.Scope ds = debug.scope("Compiling", graph)) { + try (AllocSpy _ = AllocSpy.open(installedCodeOwner); DebugContext.Scope _ = debug.scope("Compiling", graph)) { CompilationPrinter printer = CompilationPrinter.begin(options, id, installedCodeOwner, INVOCATION_ENTRY_BCI); CompilationResult compResult = compile(installedCodeOwner, graphToCompile, new CompilationResult(graphToCompile.compilationId()), id, options); - try (DebugContext.Scope s = debug.scope("CodeInstall", getCodeCache(), installedCodeOwner, compResult); - DebugContext.Activation a = debug.activate()) { + try (DebugContext.Scope _ = debug.scope("CodeInstall", getCodeCache(), installedCodeOwner, compResult); + DebugContext.Activation _ = debug.activate()) { try { if (installAsDefault) { installedCode = addDefaultMethod(debug, installedCodeOwner, compResult); @@ -1301,12 +1299,11 @@ protected final CompilationResult compile(ResolvedJavaMethod installedCodeOwner, * {@link #parseForCompile(ResolvedJavaMethod)}. * @param compilationId */ - @SuppressWarnings("try") protected CompilationResult compile(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, CompilationResult compilationResult, CompilationIdentifier compilationId, OptionValues options) { StructuredGraph graphToCompile = graph == null ? parseForCompile(installedCodeOwner, compilationId, options) : graph; lastCompiledGraph = graphToCompile; DebugContext debug = graphToCompile.getDebug(); - try (DebugContext.Scope s = debug.scope("Compile", graphToCompile)) { + try (DebugContext.Scope _ = debug.scope("Compile", graphToCompile)) { assert options != null; Suites suites = createSuites(options); @@ -1340,10 +1337,9 @@ protected StructuredGraph getFinalGraph(ResolvedJavaMethod method, OptionValues return graph; } - @SuppressWarnings("try") protected void applyFrontEnd(StructuredGraph graph) { DebugContext debug = graph.getDebug(); - try (DebugContext.Scope s = debug.scope("FrontEnd", graph)) { + try (DebugContext.Scope _ = debug.scope("FrontEnd", graph)) { GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), getOptimisticOptimizations(), graph.getProfilingInfo(), createSuites(graph.getOptions())); } catch (Throwable e) { throw debug.handle(e); @@ -1586,7 +1582,6 @@ public ProfilingInfo getProfilingInfo(ResolvedJavaMethod method, boolean include }; - @SuppressWarnings("try") protected StructuredGraph parse(StructuredGraph.Builder builder, PhaseSuite graphBuilderSuite) { ResolvedJavaMethod javaMethod = builder.getMethod(); builder.speculationLog(getSpeculationLog()); @@ -1604,7 +1599,7 @@ protected StructuredGraph parse(StructuredGraph.Builder builder, PhaseSuite classBuilder + .withMethodBody("unbalancedMonitors", MethodTypeDesc.of(CD_void, CD_Object), ACC_PUBLIC_STATIC, b -> { + Label loopHead = b.newLabel(); + Label end = b.newLabel(); + b + .aload(0) + .monitorenter() + .labelBinding(loopHead) + .aload(0) + .monitorexit() + .aload(0) + .invokevirtual(CD_Object, "toString", MethodTypeDesc.of(CD_String)) + .aload(0) + .if_acmpeq(end) + .aload(0) + .invokevirtual(CD_Object, "toString", MethodTypeDesc.of(CD_String)) + .astore(0) + .goto_(loopHead) + .labelBinding(end) + .return_(); + })); // @formatter:on - - m.visitVarInsn(ALOAD, 0); - m.visitInsn(MONITORENTER); - m.visitLabel(loopHead); - m.visitVarInsn(ALOAD, 0); - m.visitInsn(MONITOREXIT); - m.visitVarInsn(ALOAD, 0); - m.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false); - m.visitVarInsn(ALOAD, 0); - m.visitJumpInsn(IF_ACMPEQ, end); - m.visitVarInsn(ALOAD, 0); - m.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "toString", "()Ljava/lang/String;", false); - m.visitVarInsn(ASTORE, 0); - m.visitJumpInsn(GOTO, loopHead); - m.visitLabel(end); - m.visitInsn(RETURN); - m.visitMaxs(2, 2); - m.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); } /** diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/HashCodeTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/HashCodeTest.java index fe55951e4176..417563d47166 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/HashCodeTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/HashCodeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -116,7 +116,6 @@ public void test06() { Assert.assertEquals(0, g.getNodes().filter(InvokeNode.class).count()); } - @SuppressWarnings("try") private StructuredGraph buildGraphAfterMidTier(String name) { StructuredGraph g = parseForCompile(getResolvedJavaMethod(name)); OptionValues options = getInitialOptions(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ImplicitNullCheckTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ImplicitNullCheckTest.java index aeb94dd42df6..d947d8d75980 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ImplicitNullCheckTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ImplicitNullCheckTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -65,10 +65,9 @@ public void test1() { test("test1Snippet"); } - @SuppressWarnings("try") private void test(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("FloatingReadTest", new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope("FloatingReadTest", new DebugDumpScope(snippet))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES, debug); CoreProviders context = getProviders(); CanonicalizerPhase canonicalizer = createCanonicalizerPhase(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InitMemoryVerificationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InitMemoryVerificationTest.java index ea43f94481e5..f3e8539ac712 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InitMemoryVerificationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InitMemoryVerificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -61,7 +61,6 @@ public static Object allocate(int val) { return new TestClass(val + 2); } - @SuppressWarnings("try") private StructuredGraph getMidTierGraph(String snippet, Suites suites) { StructuredGraph g = parseEager(snippet, AllowAssumptions.NO, getInitialOptions()); suites.getHighTier().apply(g, getDefaultHighTierContext()); @@ -77,7 +76,6 @@ public void testVerificationPasses() { } @Test - @SuppressWarnings("try") public void testVerificationFailsWithoutPublish() { Suites s = createSuites(getInitialOptions()); s.getMidTier().appendPhase(new BasePhase<>() { @@ -98,7 +96,7 @@ protected void run(StructuredGraph graph, MidTierContext context) { StructuredGraph g = getMidTierGraph("allocate", s); assertNotInGraph(g, PublishWritesNode.class); - try (DebugContext.Scope scope = getDebugContext().disable()) { + try (DebugContext.Scope _ = getDebugContext().disable()) { new InitMemoryVerificationPhase().apply(g, getDefaultLowTierContext()); throw new GraalError("Should fail init memory verification"); } catch (VerifyPhase.VerificationError e) { @@ -107,7 +105,6 @@ protected void run(StructuredGraph graph, MidTierContext context) { } @Test - @SuppressWarnings("try") public void testVerificationFailsWithoutMembar() { Suites s = createSuites(getInitialOptions()); s.getMidTier().appendPhase(new BasePhase<>() { @@ -126,7 +123,7 @@ protected void run(StructuredGraph graph, MidTierContext context) { StructuredGraph g = getMidTierGraph("allocate", s); assertNotInGraph(g, GraphUtil.class); - try (DebugContext.Scope scope = getDebugContext().disable()) { + try (DebugContext.Scope _ = getDebugContext().disable()) { new InitMemoryVerificationPhase().apply(g, getDefaultLowTierContext()); throw new GraalError("Should fail init memory verification"); } catch (VerifyPhase.VerificationError e) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InterfaceMethodHandleTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InterfaceMethodHandleTest.java index d0ad3635a418..0f728d2b9861 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InterfaceMethodHandleTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/InterfaceMethodHandleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -24,23 +24,28 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.classfile.ClassFile.ACC_PRIVATE; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.ClassFile; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; -import jdk.graal.compiler.api.test.ExportingClassLoader; -import jdk.graal.compiler.code.CompilationResult; -import jdk.graal.compiler.debug.DebugContext; import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; +import jdk.graal.compiler.code.CompilationResult; +import jdk.graal.compiler.debug.DebugContext; import jdk.vm.ci.code.InstalledCode; import jdk.vm.ci.meta.ResolvedJavaMethod; -public final class InterfaceMethodHandleTest extends GraalCompilerTest { +public final class InterfaceMethodHandleTest extends GraalCompilerTest implements CustomizedBytecodePattern { private static final MethodHandle INTERFACE_HANDLE_M; private static final MethodHandle INTERFACE_HANDLE_M2; @@ -99,7 +104,7 @@ public void testInvokeInterface01() { @Test public void testInvokeInterface02() throws Exception { - test("invokeInterfaceHandle", loader.findClass(NAME).getDeclaredConstructor().newInstance()); + test("invokeInterfaceHandle", getClass(NAME).getDeclaredConstructor().newInstance()); } public static Object invokeInterfaceHandle2(I o, int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) throws Throwable { @@ -138,84 +143,22 @@ public void testInvokeInterface03() throws Throwable { private static final String BASENAME = InterfaceMethodHandleTest.class.getName(); private static final String NAME = BASENAME + "_B"; - private final AsmLoader loader; - - public InterfaceMethodHandleTest() { - loader = new AsmLoader(UnbalancedMonitorsTest.class.getClassLoader()); - } - - static class Gen implements Opcodes { - /** - * Construct a type which claims to implement {@link I} but with incorrect access on - * {@link I#m} so that an exception must be thrown. - */ - public static byte[] bytesForB() { - - ClassWriter cw = new ClassWriter(0); - MethodVisitor mv; - String jvmName = NAME.replace('.', '/'); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, jvmName, null, "java/lang/Object", new String[]{BASENAME.replace('.', '/') + "$I"}); - - mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); - mv.visitInsn(RETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - mv = cw.visitMethod(ACC_PRIVATE, "m", "()I", null, null); - mv.visitCode(); - l0 = new Label(); - mv.visitLabel(l0); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - l1 = new Label(); - mv.visitLabel(l1); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - cw.visitEnd(); - - mv = cw.visitMethod(ACC_PRIVATE, "m2", "(IIIIIIIIII)I", null, null); - mv.visitCode(); - l0 = new Label(); - mv.visitLabel(l0); - mv.visitInsn(ICONST_0); - mv.visitInsn(IRETURN); - l1 = new Label(); - mv.visitLabel(l1); - mv.visitMaxs(1, 11); - mv.visitEnd(); - - cw.visitEnd(); - - return cw.toByteArray(); - } - } - - public static class AsmLoader extends ExportingClassLoader { - Class loaded; - public AsmLoader(ClassLoader parent) { - super(parent); - } - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - if (name.equals(NAME)) { - if (loaded != null) { - return loaded; - } - byte[] bytes = Gen.bytesForB(); - return (loaded = defineClass(name, bytes, 0, bytes.length)); - } else { - return super.findClass(name); - } - } + @Override + public byte[] generateClass(String className) { + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withInterfaceSymbols(cd(I.class)) + .withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .return_()) + .withMethodBody("m", MethodTypeDesc.of(CD_int), ACC_PRIVATE, b -> b + .iconst_0() + .ireturn()) + .withMethodBody("m2", MethodTypeDesc.of(CD_int, CD_int, CD_int, CD_int, CD_int, CD_int, CD_int, CD_int, CD_int, CD_int, CD_int), ACC_PRIVATE, b -> b + .iconst_0() + .ireturn())); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopFullUnrollTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopFullUnrollTest.java index bc318d32b703..f3a1c7e518e0 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopFullUnrollTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopFullUnrollTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -84,10 +84,9 @@ public void runNegativeTripCount() throws Throwable { test("testNegativeTripCount", 0); } - @SuppressWarnings("try") private void test(String snippet, int loopCount) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope(getClass().getSimpleName(), new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope(getClass().getSimpleName(), new DebugDumpScope(snippet))) { final StructuredGraph graph = parseEager(snippet, AllowAssumptions.NO, debug); new DisableOverflownCountedLoopsPhase().apply(graph); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopSafepointStateVerificationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopSafepointStateVerificationTest.java index e4daf7b9984d..7e119361976a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopSafepointStateVerificationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopSafepointStateVerificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -39,11 +39,11 @@ import jdk.graal.compiler.nodes.FixedWithNextNode; import jdk.graal.compiler.nodes.GraphState; import jdk.graal.compiler.nodes.LoopBeginNode; +import jdk.graal.compiler.nodes.LoopBeginNode.SafepointState; import jdk.graal.compiler.nodes.LoopEndNode; import jdk.graal.compiler.nodes.LoopExitNode; import jdk.graal.compiler.nodes.PhiNode; import jdk.graal.compiler.nodes.StructuredGraph; -import jdk.graal.compiler.nodes.LoopBeginNode.SafepointState; import jdk.graal.compiler.nodes.StructuredGraph.AllowAssumptions; import jdk.graal.compiler.nodes.loop.Loop; import jdk.graal.compiler.nodes.util.GraphUtil; @@ -72,9 +72,8 @@ OptionValues testOptions() { } @Test - @SuppressWarnings("try") public void test01() { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { // Do not capture graphs for expected compilation failures. OptionValues opt = new OptionValues(testOptions(), GraalOptions.FullUnroll, false, DebugOptions.DumpOnError, false); test(opt, "snippet01"); @@ -197,7 +196,6 @@ public static void snippet02() { } @Test - @SuppressWarnings("try") public void testLoopDataStructure() { StructuredGraph g = parseEager(getResolvedJavaMethod("snippet02"), AllowAssumptions.NO); assert g.verify(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopUnswitchTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopUnswitchTest.java index 9fba3d037d6b..6dc76677870a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopUnswitchTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/LoopUnswitchTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -371,7 +371,6 @@ private void test(String snippet, String referenceSnippet) { test(snippet, referenceSnippet, new DefaultLoopPolicies()); } - @SuppressWarnings("try") private void test(String snippet, String referenceSnippet, LoopPolicies policies) { DebugContext debug = getDebugContext(); final StructuredGraph graph = parseEager(snippet, AllowAssumptions.NO); @@ -389,7 +388,7 @@ private void test(String snippet, String referenceSnippet, LoopPolicies policies canonicalizer.apply(graph, getProviders()); canonicalizer.apply(referenceGraph, getProviders()); - try (DebugContext.Scope s = debug.scope("Test", new DebugDumpScope("Test:" + snippet))) { + try (DebugContext.Scope _ = debug.scope("Test", new DebugDumpScope("Test:" + snippet))) { assertEquals(referenceGraph, graph); } catch (Throwable e) { throw debug.handle(e); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/MemoryScheduleTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/MemoryScheduleTest.java index 13b4dcc323e6..627053e5e734 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/MemoryScheduleTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/MemoryScheduleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -688,12 +688,11 @@ private ScheduleResult getFinalSchedule(final String snippet, final TestMode mod return getFinalSchedule(snippet, mode, SchedulingStrategy.LATEST_OUT_OF_LOOPS); } - @SuppressWarnings("try") private ScheduleResult getFinalSchedule(final String snippet, final TestMode mode, final SchedulingStrategy schedulingStrategy) { OptionValues options = new OptionValues(getInitialOptions(), OptScheduleOutOfLoops, schedulingStrategy == SchedulingStrategy.LATEST_OUT_OF_LOOPS, OptImplicitNullChecks, false); final StructuredGraph graph = parseEager(snippet, AllowAssumptions.NO, options); DebugContext debug = graph.getDebug(); - try (DebugContext.Scope d = debug.scope("FloatingReadTest", graph)) { + try (DebugContext.Scope _ = debug.scope("FloatingReadTest", graph)) { HighTierContext context = getDefaultHighTierContext(); CanonicalizerPhase canonicalizer = createCanonicalizerPhase(); canonicalizer.apply(graph, context); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/OptionsVerifierTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/OptionsVerifierTest.java index abae403b7992..04b625279806 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/OptionsVerifierTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/OptionsVerifierTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -25,28 +25,42 @@ package jdk.graal.compiler.core.test; import static java.lang.String.format; +import static java.lang.constant.ConstantDescs.CD_Boolean; +import static java.lang.constant.ConstantDescs.CD_Byte; +import static java.lang.constant.ConstantDescs.CD_Character; +import static java.lang.constant.ConstantDescs.CD_Double; +import static java.lang.constant.ConstantDescs.CD_Float; +import static java.lang.constant.ConstantDescs.CD_Integer; +import static java.lang.constant.ConstantDescs.CD_Long; +import static java.lang.constant.ConstantDescs.CD_Short; +import static java.lang.constant.ConstantDescs.CLASS_INIT_NAME; import java.io.IOException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Executable; -import java.lang.reflect.Method; -import java.util.Arrays; +import java.lang.classfile.Attributes; +import java.lang.classfile.ClassFile; +import java.lang.classfile.ClassModel; +import java.lang.classfile.CodeElement; +import java.lang.classfile.CodeModel; +import java.lang.classfile.MethodModel; +import java.lang.classfile.Opcode; +import java.lang.classfile.constantpool.MemberRefEntry; +import java.lang.classfile.instruction.FieldInstruction; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.classfile.instruction.LineNumber; +import java.lang.constant.ClassDesc; +import java.lang.constant.ConstantDescs; import java.util.HashSet; +import java.util.List; import java.util.Set; import java.util.TreeSet; +import org.junit.Test; + import jdk.graal.compiler.options.OptionDescriptor; import jdk.graal.compiler.options.OptionDescriptors; import jdk.graal.compiler.options.OptionKey; import jdk.graal.compiler.options.OptionsParser; import jdk.graal.compiler.serviceprovider.GraalServices; -import org.junit.Test; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; /** * Verifies a class declaring one or more {@linkplain OptionKey options} has a class initializer @@ -55,11 +69,11 @@ */ public class OptionsVerifierTest { - private static Set ALLOWLIST = new TreeSet<>(Arrays.asList(// + private static final Set ALLOWLIST = new TreeSet<>(List.of(// "jdk.graal.compiler.truffle.TruffleCompilerOptions")); @Test - public void verifyOptions() throws IOException { + public void verifyOptions() throws IOException, ReflectiveOperationException { HashSet> checked = new HashSet<>(); for (OptionDescriptors opts : OptionsParser.getOptionsLoader()) { for (OptionDescriptor desc : opts) { @@ -71,9 +85,9 @@ public void verifyOptions() throws IOException { } } - static final class OptionsVerifier extends ClassVisitor { + static final class OptionsVerifier { - public static void checkClass(Class cls, OptionDescriptor option, Set> checked) throws IOException { + public static void checkClass(Class cls, OptionDescriptor option, Set> checked) throws IOException, ReflectiveOperationException { if (!checked.contains(cls)) { checked.add(cls); Class superclass = cls.getSuperclass(); @@ -81,11 +95,7 @@ public static void checkClass(Class cls, OptionDescriptor option, Set cls, OptionDescriptor option, Set} method is being verified. @@ -103,32 +115,17 @@ public static void checkClass(Class cls, OptionDescriptor option, Set[] boxingTypes = {Boolean.class, Byte.class, Short.class, Character.class, Integer.class, Float.class, Long.class, Double.class}; - - private static Class resolve(String name) { - try { - return Class.forName(name.replace('/', '.')); - } catch (ClassNotFoundException e) { - throw new InternalError(e); - } - } - OptionsVerifier(Class cls, OptionDescriptor desc) { - super(Opcodes.ASM7); this.cls = cls; this.option = desc; - } - - @Override - public void visitSource(String source, String debug) { - this.sourceFile = source; + this.optionClassDesc = option.getDeclaringClass().describeConstable().orElseThrow(); } void verify(boolean condition, String message) { @@ -138,83 +135,68 @@ void verify(boolean condition, String message) { } void error(String message) { - String errorMessage = format( - "%s:%d: Illegal code in %s. which may be executed when %s.%s is initialized:%n%n %s%n%n" + "The recommended solution is to move " + option.getName() + - " into a separate class (e.g., %s.Options).%n", - sourceFile, lineNo, cls.getSimpleName(), option.getDeclaringClass().getSimpleName(), option.getName(), - message, option.getDeclaringClass().getSimpleName()); + String errorMessage = format(""" + %s:%d: Illegal code in %s. which may be executed when %s.%s is initialized: + %s + The recommended solution is to move %s into a separate class (e.g., %s.Options). + """, sourceFile, lineNo, cls.getSimpleName(), option.getDeclaringClass().getSimpleName(), option.getName(), + message, option.getName(), option.getDeclaringClass().getSimpleName()); throw new InternalError(errorMessage); - } - @Override - public MethodVisitor visitMethod(int access, String name, String d, String signature, String[] exceptions) { - if (name.equals("")) { - return new MethodVisitor(Opcodes.ASM5) { + private static Class resolve(String name) { + try { + return Class.forName(name.replace('/', '.')); + } catch (ClassNotFoundException e) { + throw new InternalError(e); + } + } - @Override - public void visitLineNumber(int line, Label start) { - lineNo = line; - } + private static final List boxingTypes = List.of(CD_Boolean, CD_Byte, CD_Short, CD_Character, CD_Integer, CD_Float, CD_Long, CD_Double); - @Override - public void visitFieldInsn(int opcode, String owner, String fieldName, String fieldDesc) { - if (opcode == Opcodes.PUTFIELD || opcode == Opcodes.PUTSTATIC) { - verify(resolve(owner).equals(option.getDeclaringClass()), format("store to field %s.%s", resolve(owner).getSimpleName(), fieldName)); - verify(opcode != Opcodes.PUTFIELD, format("store to non-static field %s.%s", resolve(owner).getSimpleName(), fieldName)); - } - } + /** + * Checks whether a given method is allowed to be called. + */ + private static boolean checkInvokeTarget(MemberRefEntry method) { + ClassDesc owner = method.owner().asSymbol(); + String methodName = method.name().stringValue(); + + if ("".equals(methodName)) { + return OptionKey.class.isAssignableFrom(resolve(method.owner().asInternalName())); + } else if ("valueOf".equals(methodName)) { + return boxingTypes.contains(owner); + } else if ("desiredAssertionStatus".equals(methodName)) { + return ConstantDescs.CD_Class.equals(owner); + } + return false; + } - private Executable resolveMethod(String owner, String methodName, String methodDesc) { - Class declaringClass = resolve(owner); - if (methodName.equals("")) { - for (Constructor c : declaringClass.getDeclaredConstructors()) { - if (methodDesc.equals(Type.getConstructorDescriptor(c))) { - return c; - } - } - } else { - Type[] argumentTypes = Type.getArgumentTypes(methodDesc); - for (Method m : declaringClass.getDeclaredMethods()) { - if (m.getName().equals(methodName)) { - if (Arrays.equals(argumentTypes, Type.getArgumentTypes(m))) { - if (Type.getReturnType(methodDesc).equals(Type.getReturnType(m))) { - return m; - } - } + public void apply() throws IOException { + ClassModel cm = ClassFile.of().parse(GraalServices.getClassfileAsStream(cls).readAllBytes()); + cm.findAttribute(Attributes.sourceFile()).ifPresent(attr -> sourceFile = attr.sourceFile().stringValue()); + + // @formatter:off + for (MethodModel methodModel : cm.methods()) { + if (CLASS_INIT_NAME.equals(methodModel.methodName().stringValue())) { + CodeModel code = methodModel.code().orElseThrow(); + for (CodeElement instruction : code) { + switch (instruction) { + case LineNumber line -> lineNo = line.line(); + case FieldInstruction fi -> { + if (fi.opcode() == Opcode.PUTFIELD) { + error(format("store to non-static field %s.%s", fi.owner().asInternalName(), fi.name().stringValue())); + } else if (fi.opcode() == Opcode.PUTSTATIC) { + verify(fi.owner().asSymbol().equals(optionClassDesc), format("store to static field %s.%s", fi.owner().asInternalName(), fi.name().stringValue())); } } - } - throw new NoSuchMethodError(declaringClass + "." + methodName + methodDesc); - } - - /** - * Checks whether a given method is allowed to be called. - */ - private boolean checkInvokeTarget(Executable method) { - Class holder = method.getDeclaringClass(); - if (method instanceof Constructor) { - if (OptionKey.class.isAssignableFrom(holder)) { - return true; + case InvokeInstruction invoke -> verify(checkInvokeTarget(invoke.method()), "invocation of " + invoke.method()); + default -> { } - } else if (Arrays.asList(boxingTypes).contains(holder)) { - return method.getName().equals("valueOf"); - } else if (method.getDeclaringClass().equals(Class.class)) { - return method.getName().equals("desiredAssertionStatus"); } - return false; - } - - @Override - public void visitMethodInsn(int opcode, String owner, String methodName, String methodDesc, boolean itf) { - Executable callee = resolveMethod(owner, methodName, methodDesc); - verify(checkInvokeTarget(callee), "invocation of " + callee); } - }; - } else { - return null; + } } + // @formatter:on } } - } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/PushNodesThroughPiTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/PushNodesThroughPiTest.java index 5cc0ce85e2cf..5b61dd8fa62a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/PushNodesThroughPiTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/PushNodesThroughPiTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -73,11 +73,10 @@ public static long test1Snippet(A a) { @Ignore @Test - @SuppressWarnings("try") public void test1() { final String snippet = "test1Snippet"; DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("PushThroughPi", new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope("PushThroughPi", new DebugDumpScope(snippet))) { StructuredGraph graph = compileTestSnippet(snippet); for (ReadNode rn : graph.getNodes().filter(ReadNode.class)) { OffsetAddressNode address = (OffsetAddressNode) rn.getAddress(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ReadAfterCheckCastTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ReadAfterCheckCastTest.java index fc4865f0a6cf..7a408720d6c8 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ReadAfterCheckCastTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ReadAfterCheckCastTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -81,10 +81,9 @@ public void test1() { test("test1Snippet"); } - @SuppressWarnings("try") private void test(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("ReadAfterCheckCastTest", new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope("ReadAfterCheckCastTest", new DebugDumpScope(snippet))) { // check shape of graph, with lots of assumptions. will probably fail if graph // structure changes significantly StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ResolveDynamicConstantTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ResolveDynamicConstantTest.java index ff1231a39fff..8c488fce6de8 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ResolveDynamicConstantTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ResolveDynamicConstantTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -24,28 +24,43 @@ */ package jdk.graal.compiler.core.test; -import java.lang.reflect.Method; +import static java.lang.classfile.ClassFile.ACC_VARARGS; +import static java.lang.constant.ConstantDescs.CD_MethodHandles_Lookup; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_String; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_double; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.CD_void; + +import java.io.PrintStream; +import java.lang.classfile.ClassFile; +import java.lang.classfile.Label; +import java.lang.classfile.constantpool.ConstantPoolBuilder; +import java.lang.classfile.constantpool.FieldRefEntry; +import java.lang.constant.ClassDesc; +import java.lang.constant.DirectMethodHandleDesc.Kind; +import java.lang.constant.DynamicConstantDesc; +import java.lang.constant.MethodHandleDesc; +import java.lang.constant.MethodTypeDesc; import java.time.Clock; import java.time.Instant; import org.junit.Assert; import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.ConstantDynamic; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.Handle; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; import jdk.vm.ci.meta.ResolvedJavaMethod; -public class ResolveDynamicConstantTest extends CustomizedBytecodePatternTest { - - private static final int PUBLIC_STATIC = ACC_PUBLIC | ACC_STATIC; +public class ResolveDynamicConstantTest extends GraalCompilerTest { @Test public void test00601m001() throws Throwable { - runTest("test.resolveDynamicConstant00601m001"); + runTest(new ResolveDynamicConstant00601m001Gen().getClass("test.resolveDynamicConstant00601m001")); + } + + @Test + public void test00602m008() throws Throwable { + runTest(new ResolveDynamicConstant00602m008Gen().getClass("test.resolveDynamicConstant00602m008")); } public static void main(String[] args) { @@ -59,125 +74,99 @@ public static void main(String[] args) { } } - @Test - public void test00602m008() throws Throwable { - runTest("test.resolveDynamicConstant00602m008"); - } - - static void resolveDynamicConstant00601m001Gen(String internalClassName, ClassWriter cw) { - FieldVisitor fv = cw.visitField(PUBLIC_STATIC, "bsmInvocationCount", "I", null, null); - fv.visitEnd(); - - String sig; - Handle handle; - - sig = "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)I"; - handle = new Handle(H_INVOKESTATIC, internalClassName, "getConstant", sig, false); - ConstantDynamic iconst = new ConstantDynamic("constantdynamic", "I", handle); - - MethodVisitor run = cw.visitMethod(PUBLIC_STATIC, "run", "()Z", null, null); - run.visitFieldInsn(GETSTATIC, internalClassName, "bsmInvocationCount", "I"); - Label labelFalse = new Label(); - run.visitJumpInsn(IFNE, labelFalse); - run.visitLdcInsn(iconst); - run.visitInsn(POP); - run.visitFieldInsn(GETSTATIC, internalClassName, "bsmInvocationCount", "I"); - run.visitJumpInsn(IFEQ, labelFalse); - run.visitInsn(ICONST_1); - run.visitInsn(IRETURN); - run.visitLabel(labelFalse); - run.visitInsn(ICONST_0); - run.visitInsn(IRETURN); - run.visitMaxs(0, 0); - run.visitEnd(); - - MethodVisitor getConstant = cw.visitMethod(PUBLIC_STATIC | ACC_VARARGS, "getConstant", "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)I", null, null); - getConstant.visitFieldInsn(GETSTATIC, internalClassName, "bsmInvocationCount", "I"); - getConstant.visitInsn(ICONST_1); - getConstant.visitInsn(IADD); - getConstant.visitFieldInsn(PUTSTATIC, internalClassName, "bsmInvocationCount", "I"); - getConstant.visitInsn(ICONST_1); - getConstant.visitInsn(IRETURN); - getConstant.visitMaxs(0, 0); - getConstant.visitEnd(); - } - - static void resolveDynamicConstant00602m008Gen(String internalClassName, ClassWriter cw) { - FieldVisitor fv = cw.visitField(PUBLIC_STATIC, "staticBSMInvocationCount", "I", null, null); - fv.visitEnd(); - - String sig; - Handle handle; - - sig = "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)D"; - handle = new Handle(H_INVOKESTATIC, internalClassName, "getStaticConstant", sig, false); - ConstantDynamic dconst = new ConstantDynamic("constantdynamic", "D", handle); - - sig = "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)I"; - handle = new Handle(H_INVOKESTATIC, internalClassName, "getConstant", sig, false); - ConstantDynamic iconst = new ConstantDynamic("constantdynamic", "I", handle, dconst); - - MethodVisitor run = cw.visitMethod(PUBLIC_STATIC, "run", "()Z", null, null); - run.visitFieldInsn(GETSTATIC, internalClassName, "staticBSMInvocationCount", "I"); - Label labelFalse = new Label(); - run.visitJumpInsn(IFNE, labelFalse); - run.visitLdcInsn(iconst); - run.visitInsn(POP); - run.visitFieldInsn(GETSTATIC, internalClassName, "staticBSMInvocationCount", "I"); - run.visitLdcInsn(Integer.valueOf(1)); - run.visitJumpInsn(IF_ICMPNE, labelFalse); - run.visitInsn(ICONST_1); - run.visitInsn(IRETURN); - run.visitLabel(labelFalse); - run.visitInsn(ICONST_0); - run.visitInsn(IRETURN); - run.visitMaxs(0, 0); - run.visitEnd(); - - MethodVisitor getConstant = cw.visitMethod(PUBLIC_STATIC | ACC_VARARGS, "getConstant", "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)I", null, null); - getConstant.visitInsn(ICONST_1); - getConstant.visitInsn(IRETURN); - getConstant.visitMaxs(0, 0); - getConstant.visitEnd(); - - MethodVisitor getStaticConstant = cw.visitMethod(PUBLIC_STATIC | ACC_VARARGS, "getStaticConstant", "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)D", null, null); - getStaticConstant.visitFieldInsn(GETSTATIC, internalClassName, "staticBSMInvocationCount", "I"); - getStaticConstant.visitInsn(ICONST_1); - getStaticConstant.visitInsn(IADD); - getStaticConstant.visitFieldInsn(PUTSTATIC, internalClassName, "staticBSMInvocationCount", "I"); - getStaticConstant.visitInsn(DCONST_1); - getStaticConstant.visitInsn(DRETURN); - getStaticConstant.visitMaxs(0, 0); - getStaticConstant.visitEnd(); + static class ResolveDynamicConstant00601m001Gen implements CustomizedBytecodePattern { + @Override + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + FieldRefEntry field = ConstantPoolBuilder.of().fieldRefEntry(thisClass, "bsmInvocationCount", CD_int); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField("bsmInvocationCount", CD_int, ACC_PUBLIC_STATIC) + .withMethodBody("run", MethodTypeDesc.of(CD_boolean), ACC_PUBLIC_STATIC, b -> { + Label labelFalse = b.newLabel(); + var iconst = DynamicConstantDesc.ofNamed(MethodHandleDesc.of(Kind.STATIC, thisClass, "getConstant", + "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)I"), "constantdynamic", CD_int); + + b + .getstatic(field) + .ifne(labelFalse) + .ldc(iconst) + .pop() + .getstatic(field) + .ifeq(labelFalse) + .iconst_1() + .ireturn() + .labelBinding(labelFalse) + .iconst_0() + .ireturn(); + }) + .withMethodBody("getConstant", MethodTypeDesc.of(CD_int, CD_MethodHandles_Lookup, CD_Object.arrayType()), ACC_PUBLIC_STATIC | ACC_VARARGS, b -> b + .getstatic(field) + .iconst_1() + .iadd() + .putstatic(field) + .iconst_1() + .ireturn()) + .withMethodBody("main", MethodTypeDesc.of(CD_void, CD_String.arrayType()), ACC_PUBLIC_STATIC, b -> b + .getstatic(cd(System.class), "out", cd(PrintStream.class)) + .invokestatic(thisClass, "run", MethodTypeDesc.of(CD_boolean)) + .invokevirtual(cd(PrintStream.class), "println", MethodTypeDesc.of(CD_void, CD_boolean)) + .return_())); + // @formatter:on + } } - @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(55, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - - try { - String simpleName = internalClassName.substring("test/".length()); - Method method = getClass().getDeclaredMethod(simpleName + "Gen", String.class, ClassWriter.class); - method.invoke(this, internalClassName, cw); - } catch (Exception e) { - throw new AssertionError(e); + static class ResolveDynamicConstant00602m008Gen implements CustomizedBytecodePattern { + @Override + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + FieldRefEntry field = ConstantPoolBuilder.of().fieldRefEntry(thisClass, "staticBSMInvocationCount", CD_int); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField("staticBSMInvocationCount", CD_int, ACC_PUBLIC_STATIC) + .withMethodBody("run", MethodTypeDesc.of(CD_boolean), ACC_PUBLIC_STATIC, b -> { + Label labelFalse = b.newLabel(); + var dconst = DynamicConstantDesc.ofNamed(MethodHandleDesc.of(Kind.STATIC, thisClass, "getStaticConstant", + "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)D"), "constantdynamic", CD_double); + var iconst = DynamicConstantDesc.ofNamed(MethodHandleDesc.of(Kind.STATIC, thisClass, "getConstant", + "(Ljava/lang/invoke/MethodHandles$Lookup;[Ljava/lang/Object;)I"), "constantdynamic", CD_int, dconst); + + b + .getstatic(field) + .ifne(labelFalse) + .ldc(iconst) + .pop() + .getstatic(field) + .ldc(1) + .if_icmpne(labelFalse) + .iconst_1() + .ireturn() + .labelBinding(labelFalse) + .iconst_0() + .ireturn(); + }) + .withMethodBody("getConstant", MethodTypeDesc.of(CD_int, CD_MethodHandles_Lookup, CD_Object.arrayType()), ACC_PUBLIC_STATIC | ACC_VARARGS, b -> b + .iconst_1() + .ireturn()) + .withMethodBody("getStaticConstant", MethodTypeDesc.of(CD_double, CD_MethodHandles_Lookup, CD_Object.arrayType()), ACC_PUBLIC_STATIC | ACC_VARARGS, b -> b + .getstatic(field) + .iconst_1() + .iadd() + .putstatic(field) + .dconst_1() + .dreturn()) + .withMethodBody("main", MethodTypeDesc.of(CD_void, CD_String.arrayType()), ACC_PUBLIC_STATIC, b -> b + .getstatic(cd(System.class), "out", cd(PrintStream.class)) + .invokestatic(thisClass, "run", MethodTypeDesc.of(CD_boolean)) + .invokevirtual(cd(PrintStream.class), "println", MethodTypeDesc.of(CD_void, CD_boolean)) + .return_())); + // @formatter:on } - - MethodVisitor main = cw.visitMethod(PUBLIC_STATIC, "main", "([Ljava/lang/String;)V", null, null); - main.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); - main.visitMethodInsn(INVOKESTATIC, internalClassName, "run", "()Z", false); - main.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Z)V", false); - main.visitInsn(RETURN); - main.visitMaxs(0, 0); - main.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); } - private void runTest(String internalClassName) throws Throwable { - Class testClass = getClass(internalClassName); + private void runTest(Class testClass) throws Throwable { ResolvedJavaMethod run = getResolvedJavaMethod(testClass, "run"); Result actual = executeActual(run, null); if (actual.exception != null) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SingleRunSubphaseTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SingleRunSubphaseTest.java index 76274dfb176a..9a6d38f89ec5 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SingleRunSubphaseTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SingleRunSubphaseTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -69,10 +69,9 @@ public void testSingleRun() { phase.apply(graph, getProviders()); } - @SuppressWarnings("try") @Test public void testMultipleRuns() { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { OptionValues noDumpOnError = new OptionValues(getInitialOptions(), DumpOnError, false); StructuredGraph graph = parseForCompile(getResolvedJavaMethod("testSnippet"), noDumpOnError); EmptyPhase phase = new EmptyPhase(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/StaticInterfaceFieldTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/StaticInterfaceFieldTest.java index 2c5e51974830..acaf2138b545 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/StaticInterfaceFieldTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/StaticInterfaceFieldTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -73,7 +73,6 @@ public void test() { } - @SuppressWarnings("try") private void eagerlyParseMethod(Class clazz, String methodName) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); @@ -92,7 +91,7 @@ private void eagerlyParseMethod(Class clazz, String methodName) { OptionValues options = GraalCompilerTest.getInitialOptions(); DebugContext debug = new Builder(options).build(); StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).build(); - try (DebugCloseable s = debug.disableIntercept(); DebugContext.Scope ds = debug.scope("GraphBuilding", graph, method)) { + try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("GraphBuilding", graph, method)) { graphBuilderSuite.apply(graph, context); } catch (Throwable e) { throw debug.handle(e); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordArrayStoreTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordArrayStoreTest.java index e1e9d8f0b370..4f7365db650a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordArrayStoreTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordArrayStoreTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -24,21 +24,35 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.classfile.ClassFile.ACC_STATIC; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_long; +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.MTD_void; +import static jdk.graal.compiler.core.test.SubWordFieldStoreTest.getUnsafePutMethodName; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.Opcode; +import java.lang.classfile.TypeKind; +import java.lang.classfile.constantpool.ConstantPoolBuilder; +import java.lang.classfile.constantpool.FieldRefEntry; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.util.ArrayList; import java.util.List; -import jdk.graal.compiler.debug.GraalError; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; -import jdk.vm.ci.meta.JavaKind; +import jdk.graal.compiler.debug.GraalError; +import jdk.graal.compiler.test.GraalTest; +import jdk.internal.misc.Unsafe; @RunWith(Parameterized.class) -public class SubWordArrayStoreTest extends CustomizedBytecodePatternTest { +public class SubWordArrayStoreTest extends GraalCompilerTest implements CustomizedBytecodePattern { @Parameterized.Parameters(name = "{0}, {1}, {2}, {3}") public static List data() { @@ -46,10 +60,10 @@ public static List data() { for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF, 0x01020304}) { for (boolean unsafeStore : new boolean[]{false, true}) { for (boolean unsafeLoad : new boolean[]{false, true}) { - ret.add(new Object[]{JavaKind.Boolean, i, unsafeStore, unsafeLoad}); - ret.add(new Object[]{JavaKind.Byte, i, unsafeStore, unsafeLoad}); - ret.add(new Object[]{JavaKind.Short, i, unsafeStore, unsafeLoad}); - ret.add(new Object[]{JavaKind.Char, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.BOOLEAN, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.BYTE, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.SHORT, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.CHAR, i, unsafeStore, unsafeLoad}); } } } @@ -57,13 +71,14 @@ public static List data() { } private static final String SNIPPET = "snippet"; + private static final String FIELD = "array"; - private final JavaKind kind; + private final TypeKind kind; private final int value; private final boolean unsafeStore; private final boolean unsafeLoad; - public SubWordArrayStoreTest(JavaKind kind, int value, boolean unsafeStore, boolean unsafeLoad) { + public SubWordArrayStoreTest(TypeKind kind, int value, boolean unsafeStore, boolean unsafeLoad) { this.kind = kind; this.value = value; this.unsafeStore = unsafeStore; @@ -72,123 +87,92 @@ public SubWordArrayStoreTest(JavaKind kind, int value, boolean unsafeStore, bool @Test public void testArrayStore() throws ClassNotFoundException { - Class testClass = getClass(SubWordArrayStoreTest.class.getName() + "$" + kind.toString() + "Getter"); + Class testClass = getClass(SubWordArrayStoreTest.class.getName() + "$" + kind.toString().toLowerCase() + "Getter"); test(getResolvedJavaMethod(testClass, SNIPPET), null); } - private static long arrayBaseOffset(JavaKind kind) { - switch (kind) { - case Boolean: - return UNSAFE.arrayBaseOffset(boolean[].class); - case Byte: - return UNSAFE.arrayBaseOffset(byte[].class); - case Short: - return UNSAFE.arrayBaseOffset(short[].class); - case Char: - return UNSAFE.arrayBaseOffset(char[].class); - default: - throw GraalError.shouldNotReachHereUnexpectedValue(kind); // ExcludeFromJacocoGeneratedReport - } - } - - static int toASMType(JavaKind kind) { - switch (kind) { - case Boolean: - return T_BOOLEAN; - case Byte: - return T_BYTE; - case Short: - return T_SHORT; - case Char: - return T_CHAR; - default: - throw GraalError.shouldNotReachHereUnexpectedValue(kind); // ExcludeFromJacocoGeneratedReport - } - } - - private static int toArrayStoreOpcode(JavaKind kind) { - switch (kind) { - case Boolean: - case Byte: - return BASTORE; - case Short: - return SASTORE; - case Char: - return CASTORE; - default: - throw GraalError.shouldNotReachHereUnexpectedValue(kind); // ExcludeFromJacocoGeneratedReport - } + @Override + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc targetType = kind.upperBound(); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField(FIELD, targetType.arrayType(), ACC_PUBLIC_STATIC) + .withMethodBody("", MTD_void, ACC_STATIC, b -> b + .bipush(16) + .newarray(kind) + .putstatic(thisClass, FIELD, targetType.arrayType()) + .return_()) + .withMethodBody(SNIPPET, MethodTypeDesc.of(CD_boolean), ACC_PUBLIC_STATIC, b -> generateSnippet(b, thisClass))); + // @formatter:on } - private static int toArrayLoadOpcode(JavaKind kind) { - switch (kind) { - case Boolean: - case Byte: - return BALOAD; - case Short: - return SALOAD; - case Char: - return CALOAD; - default: - throw GraalError.shouldNotReachHereUnexpectedValue(kind); // ExcludeFromJacocoGeneratedReport - } + private static long arrayBaseOffset(TypeKind kind) { + return switch (kind) { + case BOOLEAN -> UNSAFE.arrayBaseOffset(boolean[].class); + case BYTE -> UNSAFE.arrayBaseOffset(byte[].class); + case SHORT -> UNSAFE.arrayBaseOffset(short[].class); + case CHAR -> UNSAFE.arrayBaseOffset(char[].class); + default -> throw GraalError.shouldNotReachHereUnexpectedValue(kind); + }; } - @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - - final String fieldName = "array"; - final String fieldDescriptor = "[" + kind.getTypeChar(); - - FieldVisitor field = cw.visitField(ACC_PUBLIC | ACC_STATIC, fieldName, fieldDescriptor, null, null); - field.visitEnd(); + private void generateSnippet(CodeBuilder b, ClassDesc thisClass) { + // @formatter:off + ClassDesc targetType = kind.upperBound(); - MethodVisitor clinit = cw.visitMethod(ACC_STATIC, "", "()V", null, null); - clinit.visitCode(); - clinit.visitIntInsn(BIPUSH, 16); - clinit.visitIntInsn(NEWARRAY, toASMType(kind)); - clinit.visitFieldInsn(PUTSTATIC, internalClassName, fieldName, fieldDescriptor); - clinit.visitInsn(RETURN); - clinit.visitMaxs(1, 0); - clinit.visitEnd(); + ClassDesc classGraalTest = cd(GraalTest.class); + ClassDesc classUnsafe = cd(Unsafe.class); - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, SNIPPET, "()Z", null, null); - snippet.visitCode(); + ConstantPoolBuilder cpb = ConstantPoolBuilder.of(); + FieldRefEntry unsafeField = cpb.fieldRefEntry(classGraalTest, "UNSAFE", classUnsafe); + FieldRefEntry arrayField = cpb.fieldRefEntry(thisClass, FIELD, targetType.arrayType()); if (unsafeStore) { - SubWordTestUtil.getUnsafe(snippet); - snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor); - snippet.visitLdcInsn(arrayBaseOffset(kind)); - snippet.visitLdcInsn(value); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "put" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J" + kind.getTypeChar() + ")V", false); + b + .getstatic(unsafeField) + .getstatic(arrayField) + .ldc(arrayBaseOffset(kind)) + .ldc(value) + .invokevirtual(classUnsafe, "put" + getUnsafePutMethodName(kind), MethodTypeDesc.of(CD_void, CD_Object, CD_long, targetType)); } else { - snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor); - snippet.visitInsn(ICONST_0); - snippet.visitLdcInsn(value); - snippet.visitInsn(toArrayStoreOpcode(kind)); + b + .getstatic(arrayField) + .iconst_0() + .ldc(value); + + switch (kind) { + case BOOLEAN, BYTE -> b.bastore(); + case SHORT -> b.sastore(); + case CHAR -> b.castore(); + } } if (unsafeLoad) { - SubWordTestUtil.getUnsafe(snippet); - snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor); - snippet.visitLdcInsn(arrayBaseOffset(kind)); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "get" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J)" + kind.getTypeChar(), false); + b + .getstatic(unsafeField) + .getstatic(arrayField) + .ldc(arrayBaseOffset(kind)) + .invokevirtual(classUnsafe, "get" + getUnsafePutMethodName(kind), MethodTypeDesc.of(targetType, CD_Object, CD_long)); } else { - snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor); - snippet.visitInsn(ICONST_0); - snippet.visitInsn(toArrayLoadOpcode(kind)); + b + .getstatic(arrayField) + .iconst_0(); + + switch (kind) { + case BOOLEAN, BYTE -> b.baload(); + case SHORT -> b.saload(); + case CHAR -> b.caload(); + } } - snippet.visitLdcInsn(value); - SubWordTestUtil.convertToKind(snippet, kind); - SubWordTestUtil.testEqual(snippet); - - snippet.visitMaxs(5, 0); - snippet.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); + b + .ldc(value) + .conversion(TypeKind.INT, kind) + .ifThenElse(Opcode.IF_ICMPEQ, + thenBlock -> thenBlock.iconst_1().ireturn(), + elseBlock -> elseBlock.iconst_0().ireturn()); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordFieldStoreTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordFieldStoreTest.java index 194748442d36..bef0a1e09e36 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordFieldStoreTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordFieldStoreTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -24,21 +24,36 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.constant.ConstantDescs.CD_Class; +import static java.lang.constant.ConstantDescs.CD_Exception; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_String; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_long; +import static java.lang.constant.ConstantDescs.CD_void; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.Opcode; +import java.lang.classfile.TypeKind; +import java.lang.classfile.attribute.ExceptionsAttribute; +import java.lang.classfile.constantpool.ConstantPoolBuilder; +import java.lang.classfile.constantpool.FieldRefEntry; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; -import jdk.vm.ci.meta.JavaKind; +import jdk.graal.compiler.test.GraalTest; +import jdk.internal.misc.Unsafe; @RunWith(Parameterized.class) -public class SubWordFieldStoreTest extends CustomizedBytecodePatternTest { +public class SubWordFieldStoreTest extends GraalCompilerTest implements CustomizedBytecodePattern { @Parameterized.Parameters(name = "{0}, {1}, {2}, {3}") public static List data() { @@ -46,10 +61,10 @@ public static List data() { for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF, 0x01020304}) { for (boolean unsafeStore : new boolean[]{false, true}) { for (boolean unsafeLoad : new boolean[]{false, true}) { - ret.add(new Object[]{JavaKind.Boolean, i, unsafeStore, unsafeLoad}); - ret.add(new Object[]{JavaKind.Byte, i, unsafeStore, unsafeLoad}); - ret.add(new Object[]{JavaKind.Short, i, unsafeStore, unsafeLoad}); - ret.add(new Object[]{JavaKind.Char, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.BOOLEAN, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.BYTE, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.SHORT, i, unsafeStore, unsafeLoad}); + ret.add(new Object[]{TypeKind.CHAR, i, unsafeStore, unsafeLoad}); } } } @@ -57,13 +72,14 @@ public static List data() { } private static final String SNIPPET = "snippet"; + private static final String FIELD = "field"; - private final JavaKind kind; + private final TypeKind kind; private final int value; private final boolean unsafeStore; private final boolean unsafeLoad; - public SubWordFieldStoreTest(JavaKind kind, int value, boolean unsafeStore, boolean unsafeLoad) { + public SubWordFieldStoreTest(TypeKind kind, int value, boolean unsafeStore, boolean unsafeLoad) { this.kind = kind; this.value = value; this.unsafeStore = unsafeStore; @@ -72,83 +88,79 @@ public SubWordFieldStoreTest(JavaKind kind, int value, boolean unsafeStore, bool @Test public void testFieldStore() throws ClassNotFoundException { - Class testClass = getClass(SubWordFieldStoreTest.class.getName() + "$" + kind.toString() + "Getter"); + Class testClass = getClass(SubWordFieldStoreTest.class.getName() + "$" + kind.toString().toLowerCase() + "Getter"); test(getResolvedJavaMethod(testClass, SNIPPET), null); } @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - - final String fieldName = "field"; - final String fieldDescriptor = Character.toString(kind.getTypeChar()); + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc targetType = kind.upperBound(); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField(FIELD, targetType, ACC_PUBLIC_STATIC) + .withMethod(SNIPPET, MethodTypeDesc.of(CD_boolean), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .with(ExceptionsAttribute.ofSymbols(CD_Exception)) + .withCode(b -> generateSnippet(b, thisClass)))); + // @formatter:on + } - FieldVisitor field = cw.visitField(ACC_PUBLIC | ACC_STATIC, fieldName, fieldDescriptor, null, value); - field.visitEnd(); + static String getUnsafePutMethodName(TypeKind kind) { + String name = kind.name(); + return name.charAt(0) + name.substring(1).toLowerCase(); + } - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, SNIPPET, "()Z", null, new String[]{"java/lang/NoSuchFieldException"}); - snippet.visitCode(); + private void generateSnippet(CodeBuilder b, ClassDesc thisClass) { + ClassDesc targetType = kind.upperBound(); + + ClassDesc classField = cd(Field.class); + ClassDesc classGraalTest = cd(GraalTest.class); + ClassDesc classUnsafe = cd(Unsafe.class); + + FieldRefEntry unsafeField = ConstantPoolBuilder.of().fieldRefEntry(classGraalTest, "UNSAFE", classUnsafe); + + // @formatter:off + if (unsafeStore | unsafeLoad) { + b + .ldc(thisClass) + .ldc(FIELD) + .invokevirtual(CD_Class, "getField", MethodTypeDesc.of(classField, CD_String)) + .astore(0) + .getstatic(unsafeField) + .aload(0) + .invokevirtual(classUnsafe, "staticFieldBase", MethodTypeDesc.of(CD_Object, classField)) + .astore(1) + .getstatic(unsafeField) + .aload(0) + .invokevirtual(classUnsafe, "staticFieldOffset", MethodTypeDesc.of(CD_long, classField)) + .lstore(2); + } if (unsafeStore) { - snippet.visitLdcInsn(Type.getObjectType(internalClassName)); - snippet.visitLdcInsn(fieldName); - snippet.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", false); - snippet.visitVarInsn(ASTORE, 0); - - SubWordTestUtil.getUnsafe(snippet); - snippet.visitVarInsn(ALOAD, 0); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "staticFieldBase", "(Ljava/lang/reflect/Field;)Ljava/lang/Object;", false); - snippet.visitVarInsn(ASTORE, 1); - - SubWordTestUtil.getUnsafe(snippet); - snippet.visitVarInsn(ALOAD, 0); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "staticFieldOffset", "(Ljava/lang/reflect/Field;)J", false); - snippet.visitVarInsn(LSTORE, 2); - - SubWordTestUtil.getUnsafe(snippet); - snippet.visitVarInsn(ALOAD, 1); - snippet.visitVarInsn(LLOAD, 2); - snippet.visitLdcInsn(value); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "put" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J" + kind.getTypeChar() + ")V", false); + b.getstatic(unsafeField) + .aload(1) + .lload(2) + .ldc(value) + .invokevirtual(classUnsafe, "put" + getUnsafePutMethodName(kind), MethodTypeDesc.of(CD_void, CD_Object, CD_long, targetType)); } else { - snippet.visitLdcInsn(value); - snippet.visitFieldInsn(PUTSTATIC, internalClassName, fieldName, fieldDescriptor); + b.ldc(value) + .putstatic(thisClass, FIELD, targetType); } - if (unsafeLoad) { - if (!unsafeStore) { - snippet.visitLdcInsn(Type.getObjectType(internalClassName)); - snippet.visitLdcInsn(fieldName); - snippet.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getField", "(Ljava/lang/String;)Ljava/lang/reflect/Field;", false); - snippet.visitVarInsn(ASTORE, 0); - - SubWordTestUtil.getUnsafe(snippet); - snippet.visitVarInsn(ALOAD, 0); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "staticFieldBase", "(Ljava/lang/reflect/Field;)Ljava/lang/Object;", false); - snippet.visitVarInsn(ASTORE, 1); - - SubWordTestUtil.getUnsafe(snippet); - snippet.visitVarInsn(ALOAD, 0); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "staticFieldOffset", "(Ljava/lang/reflect/Field;)J", false); - snippet.visitVarInsn(LSTORE, 2); - } - SubWordTestUtil.getUnsafe(snippet); - snippet.visitVarInsn(ALOAD, 1); - snippet.visitVarInsn(LLOAD, 2); - snippet.visitMethodInsn(INVOKEVIRTUAL, "jdk/internal/misc/Unsafe", "get" + SubWordTestUtil.getUnsafePutMethodName(kind), "(Ljava/lang/Object;J)" + kind.getTypeChar(), false); + b.getstatic(unsafeField) + .aload(1) + .lload(2) + .invokevirtual(classUnsafe, "get" + getUnsafePutMethodName(kind), MethodTypeDesc.of(targetType, CD_Object, CD_long)); } else { - snippet.visitFieldInsn(GETSTATIC, internalClassName, fieldName, fieldDescriptor); + b.getstatic(thisClass, FIELD, targetType); } - snippet.visitLdcInsn(value); - SubWordTestUtil.convertToKind(snippet, kind); - SubWordTestUtil.testEqual(snippet); - - snippet.visitMaxs(5, 4); - snippet.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); + b.ldc(value) + .conversion(TypeKind.INT, kind) + .ifThenElse(Opcode.IF_ICMPEQ, + thenBlock -> thenBlock.iconst_1().ireturn(), + elseBlock -> elseBlock.iconst_0().ireturn()); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest.java index ba1b31f357d7..c2866623c904 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -24,6 +24,14 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_int; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.Opcode; +import java.lang.classfile.TypeKind; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -31,24 +39,21 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; +import org.junit.runners.Parameterized.Parameters; -import jdk.vm.ci.meta.DeoptimizationReason; -import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.ResolvedJavaMethod; @RunWith(Parameterized.class) -public class SubWordInputTest extends CustomizedBytecodePatternTest { +public class SubWordInputTest extends GraalCompilerTest implements CustomizedBytecodePattern { - @Parameterized.Parameters(name = "{0}, {1}") + @Parameters(name = "{0}, {1}") public static List data() { ArrayList ret = new ArrayList<>(); for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF}) { - ret.add(new Object[]{JavaKind.Boolean, i}); - ret.add(new Object[]{JavaKind.Byte, i}); - ret.add(new Object[]{JavaKind.Short, i}); - ret.add(new Object[]{JavaKind.Char, i}); + ret.add(new Object[]{TypeKind.BOOLEAN, i}); + ret.add(new Object[]{TypeKind.BYTE, i}); + ret.add(new Object[]{TypeKind.SHORT, i}); + ret.add(new Object[]{TypeKind.CHAR, i}); } return ret; } @@ -56,57 +61,45 @@ public static List data() { private static final String GET = "get"; private static final String WRAPPER = "wrapper"; - private final JavaKind kind; + private final TypeKind kind; private final int value; - public SubWordInputTest(JavaKind kind, int value) { + public SubWordInputTest(TypeKind kind, int value) { this.kind = kind; this.value = value; } @Test public void testSubWordInput() throws ClassNotFoundException { - Class testClass = getClass(SubWordInputTest.class.getName() + "$" + kind.toString() + "Getter"); + Class testClass = getClass(SubWordInputTest.class.getName() + "$" + kind.toString().toLowerCase() + "Getter"); ResolvedJavaMethod wrapper = getResolvedJavaMethod(testClass, WRAPPER); Result expected = executeExpected(wrapper, null, value); // test standalone callee getCode(getResolvedJavaMethod(testClass, GET), null, false, true, getInitialOptions()); assertEquals(executeExpected(wrapper, null, value), expected); // test with inlining - testAgainstExpected(wrapper, expected, Collections. emptySet(), null, value); + testAgainstExpected(wrapper, expected, Collections.emptySet(), null, value); } @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - - final char typeChar = kind.getTypeChar(); - - // Generates a method that returns the input subword immediately. - String getDescriptor = "(" + typeChar + ")" + typeChar; - MethodVisitor get = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, GET, getDescriptor, null, null); - get.visitCode(); - get.visitVarInsn(ILOAD, 0); - get.visitInsn(IRETURN); - get.visitMaxs(1, 1); - get.visitEnd(); - - // Genearates a method that compares the return value of the preceding method by passing the - // input value, and a manual masking of the input value. - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, WRAPPER, "(I)Z", null, null); - snippet.visitCode(); - snippet.visitVarInsn(ILOAD, 0); - snippet.visitMethodInsn(INVOKESTATIC, internalClassName, GET, getDescriptor, false); - - snippet.visitVarInsn(ILOAD, 0); - SubWordTestUtil.convertToKind(snippet, kind); - SubWordTestUtil.testEqual(snippet); - - snippet.visitMaxs(2, 1); - snippet.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc targetType = kind.upperBound(); + MethodTypeDesc getMethodTypeDesc = MethodTypeDesc.of(targetType, targetType); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withMethodBody(GET, getMethodTypeDesc, ACC_PUBLIC_STATIC, b -> b + .iload(0) + .ireturn()) + .withMethodBody(WRAPPER, MethodTypeDesc.of(CD_boolean, CD_int), ACC_PUBLIC_STATIC, b -> b + .iload(0) + .invokestatic(thisClass, GET, getMethodTypeDesc) + .iload(0) + .conversion(TypeKind.INT, kind) + .ifThenElse(Opcode.IF_ICMPEQ, + thenBlock -> thenBlock.iconst_1().ireturn(), + elseBlock -> elseBlock.iconst_0().ireturn()))); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest2.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest2.java index 76b6a15c3916..5256b17ef227 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest2.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordInputTest2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -24,6 +24,14 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_int; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.Opcode; +import java.lang.classfile.TypeKind; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -31,24 +39,19 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import jdk.vm.ci.meta.DeoptimizationReason; -import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.ResolvedJavaMethod; @RunWith(Parameterized.class) -public class SubWordInputTest2 extends CustomizedBytecodePatternTest { +public class SubWordInputTest2 extends GraalCompilerTest implements CustomizedBytecodePattern { @Parameterized.Parameters(name = "{0}, {1}") public static List data() { ArrayList ret = new ArrayList<>(); for (int i : new int[]{0xFFFF0000, 0xFFFF0001, 0x0000FFFF}) { - ret.add(new Object[]{JavaKind.Byte, i}); - ret.add(new Object[]{JavaKind.Short, i}); - ret.add(new Object[]{JavaKind.Char, i}); + ret.add(new Object[]{TypeKind.BYTE, i}); + ret.add(new Object[]{TypeKind.SHORT, i}); + ret.add(new Object[]{TypeKind.CHAR, i}); } return ret; } @@ -56,55 +59,42 @@ public static List data() { private static final String GET = "get"; private static final String WRAPPER = "wrapper"; - private final JavaKind kind; + private final TypeKind kind; private final int value; - public SubWordInputTest2(JavaKind kind, int value) { + public SubWordInputTest2(TypeKind kind, int value) { this.kind = kind; this.value = value; } @Test public void testSubWordInput() throws ClassNotFoundException { - Class testClass = getClass(SubWordInputTest2.class.getName() + "$" + kind.toString() + "Getter"); + Class testClass = getClass(SubWordInputTest2.class.getName() + "$" + kind.toString().toLowerCase() + "Getter"); ResolvedJavaMethod wrapper = getResolvedJavaMethod(testClass, WRAPPER); Result expected = executeExpected(wrapper, null, value); // test standalone callee getCode(getResolvedJavaMethod(testClass, GET), null, false, true, getInitialOptions()); assertEquals(executeExpected(wrapper, null, value), expected); // test with inlining - testAgainstExpected(wrapper, expected, Collections. emptySet(), null, value); + testAgainstExpected(wrapper, expected, Collections.emptySet(), null, value); } @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - - final char typeChar = kind.getTypeChar(); - String getDescriptor = "(" + typeChar + ")" + "Z"; - MethodVisitor get = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, GET, getDescriptor, null, null); - get.visitCode(); - get.visitVarInsn(ILOAD, 0); - Label label = new Label(); - get.visitJumpInsn(IFGE, label); - get.visitInsn(ICONST_0); - get.visitInsn(IRETURN); - get.visitLabel(label); - get.visitInsn(ICONST_1); - get.visitInsn(IRETURN); - get.visitMaxs(1, 1); - get.visitEnd(); - - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, WRAPPER, "(I)Z", null, null); - snippet.visitCode(); - snippet.visitVarInsn(ILOAD, 0); - snippet.visitMethodInsn(INVOKESTATIC, internalClassName, GET, getDescriptor, false); - snippet.visitInsn(IRETURN); - snippet.visitMaxs(1, 1); - snippet.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc targetType = kind.upperBound(); + MethodTypeDesc getMethodTypeDesc = MethodTypeDesc.of(CD_boolean, targetType); + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withMethodBody(GET, getMethodTypeDesc, ACC_PUBLIC_STATIC, b -> b + .iload(0) + .ifThenElse(Opcode.IFLT, + thenBlock -> thenBlock.iconst_0().ireturn(), + elseBlock -> elseBlock.iconst_1().ireturn())) + .withMethodBody(WRAPPER, MethodTypeDesc.of(CD_boolean, CD_int), ACC_PUBLIC_STATIC, b -> b + .iload(0) + .invokestatic(thisClass, GET, getMethodTypeDesc) + .ireturn())); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordReturnTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordReturnTest.java index 9b56bddecefa..00cd5b844bf5 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordReturnTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordReturnTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -24,6 +24,15 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.classfile.ClassFile.ACC_PRIVATE; +import static java.lang.classfile.ClassFile.ACC_STATIC; +import static java.lang.constant.ConstantDescs.CD_int; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.TypeKind; +import java.lang.classfile.attribute.ConstantValueAttribute; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.util.ArrayList; import java.util.List; @@ -31,40 +40,40 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; -import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.ResolvedJavaMethod; @RunWith(Parameterized.class) -public class SubWordReturnTest extends CustomizedBytecodePatternTest { - - private final JavaKind kind; - private final int value; +public class SubWordReturnTest extends GraalCompilerTest implements CustomizedBytecodePattern { @Parameters(name = "{0}, {1}") public static List data() { ArrayList ret = new ArrayList<>(); for (int i : new int[]{1000000, 1000001, -1000000, -1}) { - ret.add(new Object[]{JavaKind.Boolean, i}); - ret.add(new Object[]{JavaKind.Byte, i}); - ret.add(new Object[]{JavaKind.Short, i}); - ret.add(new Object[]{JavaKind.Char, i}); + ret.add(new Object[]{TypeKind.BOOLEAN, i}); + ret.add(new Object[]{TypeKind.BYTE, i}); + ret.add(new Object[]{TypeKind.SHORT, i}); + ret.add(new Object[]{TypeKind.CHAR, i}); } return ret; } - public SubWordReturnTest(JavaKind kind, int value) { + private static final String GET = "get"; + private static final String WRAPPER = "wrapper"; + private static final String FIELD = "intField"; + + private final TypeKind kind; + private final int value; + + public SubWordReturnTest(TypeKind kind, int value) { this.kind = kind; this.value = value; } @Test public void testSubWordReturn() throws ClassNotFoundException { - Class testClass = getClass(SubWordReturnTest.class.getName() + "$" + kind.toString() + "Getter"); - ResolvedJavaMethod method = getResolvedJavaMethod(testClass, "testSnippet"); + Class testClass = getClass(SubWordReturnTest.class.getName() + "$" + kind.toString().toLowerCase() + "Getter"); + ResolvedJavaMethod method = getResolvedJavaMethod(testClass, WRAPPER); test(method, null); } @@ -82,35 +91,28 @@ private static byte get() { return 0; } - public static int testByteSnippet() { + public static int wrapper() { return get(); } } @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(0); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - - FieldVisitor intField = cw.visitField(ACC_PRIVATE | ACC_STATIC, "intField", "I", null, value); - intField.visitEnd(); - - MethodVisitor get = cw.visitMethod(ACC_PRIVATE | ACC_STATIC, "get", "()" + kind.getTypeChar(), null, null); - get.visitCode(); - get.visitFieldInsn(GETSTATIC, internalClassName, "intField", "I"); - get.visitInsn(IRETURN); - get.visitMaxs(1, 0); - get.visitEnd(); - - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "testSnippet", "()I", null, null); - snippet.visitCode(); - snippet.visitMethodInsn(INVOKESTATIC, internalClassName, "get", "()" + kind.getTypeChar(), false); - snippet.visitInsn(IRETURN); - snippet.visitMaxs(1, 0); - snippet.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc targetType = kind.upperBound(); + MethodTypeDesc getMethodTypeDesc = MethodTypeDesc.of(targetType); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField(FIELD, CD_int, fieldBuilder -> fieldBuilder + .withFlags(ACC_PRIVATE | ACC_STATIC) + .with(ConstantValueAttribute.of(value))) + .withMethodBody(GET, getMethodTypeDesc, ACC_PUBLIC_STATIC, b -> b + .getstatic(thisClass, FIELD, CD_int) + .ireturn()) + .withMethodBody(WRAPPER, MethodTypeDesc.of(CD_int), ACC_PUBLIC_STATIC, b -> b + .invokestatic(thisClass, GET, getMethodTypeDesc) + .ireturn())); + // @formatter:on } - } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordTestUtil.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordTestUtil.java deleted file mode 100644 index d1766808325c..000000000000 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SubWordTestUtil.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2018, 2024, 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. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * 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. - */ -package jdk.graal.compiler.core.test; - -import jdk.graal.compiler.debug.GraalError; -import jdk.graal.compiler.test.GraalTest; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - -import jdk.vm.ci.meta.JavaKind; - -public final class SubWordTestUtil implements Opcodes { - - private SubWordTestUtil() { - } - - static void convertToKind(MethodVisitor snippet, JavaKind kind) { - switch (kind) { - case Boolean: - snippet.visitInsn(ICONST_1); - snippet.visitInsn(IAND); - break; - case Byte: - snippet.visitInsn(I2B); - break; - case Short: - snippet.visitInsn(I2S); - break; - case Char: - snippet.visitInsn(I2C); - break; - default: - throw GraalError.shouldNotReachHereUnexpectedValue(kind); // ExcludeFromJacocoGeneratedReport - } - } - - static void testEqual(MethodVisitor snippet) { - Label label = new Label(); - snippet.visitJumpInsn(IF_ICMPNE, label); - snippet.visitInsn(ICONST_1); - snippet.visitInsn(IRETURN); - snippet.visitLabel(label); - snippet.visitInsn(ICONST_0); - snippet.visitInsn(IRETURN); - } - - static void getUnsafe(MethodVisitor snippet) { - snippet.visitFieldInsn(GETSTATIC, GraalTest.class.getName().replace('.', '/'), "UNSAFE", "Ljdk/internal/misc/Unsafe;"); - } - - static String getUnsafePutMethodName(JavaKind kind) { - String name = kind.getJavaName(); - return name.substring(0, 1).toUpperCase() + name.substring(1); - } - -} diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SwitchFoldingTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SwitchFoldingTest.java index 61a4bbaee2a7..22a53c28521a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SwitchFoldingTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/SwitchFoldingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -25,21 +25,24 @@ package jdk.graal.compiler.core.test; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_STATIC; -import static org.objectweb.asm.Opcodes.ACC_SUPER; -import static org.objectweb.asm.Opcodes.GOTO; -import static org.objectweb.asm.Opcodes.ICONST_0; -import static org.objectweb.asm.Opcodes.ICONST_1; -import static org.objectweb.asm.Opcodes.ICONST_5; -import static org.objectweb.asm.Opcodes.ICONST_M1; -import static org.objectweb.asm.Opcodes.IFLT; -import static org.objectweb.asm.Opcodes.ILOAD; -import static org.objectweb.asm.Opcodes.INVOKESTATIC; -import static org.objectweb.asm.Opcodes.IRETURN; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.classfile.ClassFile.ACC_STATIC; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.Label; +import java.lang.classfile.instruction.SwitchCase; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; import jdk.graal.compiler.api.directives.GraalDirectives; -import jdk.graal.compiler.api.test.ExportingClassLoader; import jdk.graal.compiler.debug.DebugContext; import jdk.graal.compiler.graph.iterators.NodeIterable; import jdk.graal.compiler.loop.phases.ConvertDeoptimizeToGuardPhase; @@ -50,16 +53,10 @@ import jdk.graal.compiler.nodes.ReturnNode; import jdk.graal.compiler.nodes.StructuredGraph; import jdk.graal.compiler.nodes.extended.IntegerSwitchNode; -import org.junit.Assert; -import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; - import jdk.vm.ci.meta.JavaConstant; import jdk.vm.ci.meta.ResolvedJavaMethod; -public class SwitchFoldingTest extends GraalCompilerTest { +public class SwitchFoldingTest extends GraalCompilerTest implements CustomizedBytecodePattern { private static final String REFERENCE_SNIPPET = "referenceSnippet"; private static final String REFERENCE_SNIPPET_2 = "reference2Snippet"; @@ -558,130 +555,100 @@ private static boolean compareGraphs(StructuredGraph g1, StructuredGraph g2) { return true; } - private static final String NAME = "D"; - private static final byte[] clazz = makeClass(); - - public static class MyClassLoader extends ExportingClassLoader { - @Override - protected Class findClass(String className) throws ClassNotFoundException { - return defineClass(NAME.replace('/', '.'), clazz, 0, clazz.length); - } - } - - private static byte[] makeClass() { - ClassWriter cw = new ClassWriter(0); - MethodVisitor mv; - String jvmName = NAME.replace('.', '/'); - cw.visit(49, ACC_SUPER | ACC_PUBLIC, jvmName, null, "java/lang/Object", new String[]{}); - - // Checkstyle: stop AvoidNestedBlocks - { - /*- - * public static int m(boolean, int) { - * ILOAD_0 - * IFLT L1 - * ILOAD_1 - * LOOKUPSWITCH - * [1, 2] -> - * return some int - * [5, 7] -> - * GOTO L1 - * [3, 6, 9] -> - * GOTO L2 (Different blocks) - * [0, 4, 8] -> - * GOTO L2 (Same block) - * L1: - * deopt - * return 0 - * L2: - * return 5 - * } - * - * Optimization should coalesce branches [5, 7] and [3, 6, 9] - */ - Label outMerge = new Label(); - Label inMerge = new Label(); - Label commonTarget = new Label(); - Label def = new Label(); - - int[] keys = new int[10]; - Label[] labels = new Label[10]; - - Label[] inMerges = new Label[3]; - Label[] outMerges = new Label[2]; - Label[] simple = new Label[2]; - - for (int i = 0; i < inMerges.length; i++) { - inMerges[i] = new Label(); - } - for (int i = 0; i < simple.length; i++) { - simple[i] = new Label(); - } - for (int i = 0; i < outMerges.length; i++) { - outMerges[i] = new Label(); - } - for (int i = 0; i < keys.length; i++) { - keys[i] = i; - } - int in = 0; - int out = 0; - int s = 0; - labels[0] = commonTarget; - labels[1] = simple[s++]; - labels[2] = simple[s++]; - labels[3] = inMerges[in++]; - labels[4] = commonTarget; - labels[5] = outMerges[out++]; - labels[6] = inMerges[in++]; - labels[7] = outMerges[out++]; - labels[8] = commonTarget; - labels[9] = inMerges[in++]; - - mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "m", "(ZI)I", null, null); - mv.visitCode(); - mv.visitIntInsn(ILOAD, 0); - mv.visitJumpInsn(IFLT, outMerge); - - mv.visitIntInsn(ILOAD, 1); - mv.visitLookupSwitchInsn(def, keys, labels); - - for (int i = 0; i < inMerges.length; i++) { - mv.visitLabel(inMerges[i]); - mv.visitJumpInsn(GOTO, inMerge); - } - for (int i = 0; i < outMerges.length; i++) { - mv.visitLabel(outMerges[i]); - mv.visitJumpInsn(GOTO, outMerge); - } - for (int i = 0; i < simple.length; i++) { - mv.visitLabel(simple[i]); - mv.visitInsn(ICONST_0 + i); - mv.visitInsn(IRETURN); - } - - mv.visitLabel(def); - mv.visitInsn(ICONST_1); - mv.visitInsn(IRETURN); - - mv.visitLabel(inMerge); - mv.visitInsn(ICONST_5); - mv.visitInsn(IRETURN); - - mv.visitLabel(commonTarget); - mv.visitJumpInsn(GOTO, inMerge); - - mv.visitLabel(outMerge); - mv.visitMethodInsn(INVOKESTATIC, GraalDirectives.class.getName().replace('.', '/'), "deoptimize", "()V", false); - mv.visitInsn(ICONST_M1); - mv.visitInsn(IRETURN); - - mv.visitMaxs(3, 2); - mv.visitEnd(); - } - // Checkstyle: resume AvoidNestedBlocks - - cw.visitEnd(); - return cw.toByteArray(); + @Override + public byte[] generateClass(String className) { + /*- + * public static int m(boolean, int) { + * ILOAD_0 + * IFLT L1 + * ILOAD_1 + * LOOKUPSWITCH + * [1, 2] -> + * return some int + * [5, 7] -> + * GOTO L1 + * [3, 6, 9] -> + * GOTO L2 (Different blocks) + * [0, 4, 8] -> + * GOTO L2 (Same block) + * L1: + * deopt + * return 0 + * L2: + * return 5 + * } + * + * Optimization should coalesce branches [5, 7] and [3, 6, 9] + */ + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethodBody("m", MethodTypeDesc.of(CD_int, CD_boolean, CD_int), ACC_STATIC | ACC_PUBLIC, b -> { + Label outMerge = b.newLabel(); + Label inMerge = b.newLabel(); + Label commonTarget = b.newLabel(); + Label def = b.newLabel(); + + Label[] inMerges = new Label[3]; + Label[] outMerges = new Label[2]; + Label[] simple = new Label[2]; + + for (int i = 0; i < inMerges.length; i++) { + inMerges[i] = b.newLabel(); + } + for (int i = 0; i < simple.length; i++) { + simple[i] = b.newLabel(); + } + for (int i = 0; i < outMerges.length; i++) { + outMerges[i] = b.newLabel(); + } + + int in = 0; + int out = 0; + int s = 0; + + List cases = new ArrayList<>(); + cases.add(SwitchCase.of(0, commonTarget)); + cases.add(SwitchCase.of(1, simple[s++])); + cases.add(SwitchCase.of(2, simple[s++])); + cases.add(SwitchCase.of(3, inMerges[in++])); + cases.add(SwitchCase.of(4, commonTarget)); + cases.add(SwitchCase.of(5, outMerges[out++])); + cases.add(SwitchCase.of(6, inMerges[in++])); + cases.add(SwitchCase.of(7, outMerges[out++])); + cases.add(SwitchCase.of(8, commonTarget)); + cases.add(SwitchCase.of(9, inMerges[in++])); + + b + .iload(0) + .iflt(outMerge) + .iload(1) + .lookupswitch(def, cases); + + for (int i = 0; i < inMerges.length; i++) { + b.labelBinding(inMerges[i]).goto_(inMerge); + } + + for (int i = 0; i < outMerges.length; i++) { + b.labelBinding(outMerges[i]).goto_(outMerge); + } + for (int i = 0; i < simple.length; i++) { + b.labelBinding(simple[i]).loadConstant(i).ireturn(); + } + + b.labelBinding(def) + .iconst_1() + .ireturn() + .labelBinding(inMerge) + .iconst_5() + .ireturn() + .labelBinding(commonTarget) + .goto_(inMerge) + .labelBinding(outMerge) + .invokestatic(cd(GraalDirectives.class), "deoptimize", MTD_void) + .iconst_m1() + .ireturn(); + })); + // @formatter:on } /** @@ -691,8 +658,7 @@ private static byte[] makeClass() { @Test public void compileTest() { try { - MyClassLoader loader = new MyClassLoader(); - Class c = loader.findClass(NAME); + Class c = getClass("D"); ResolvedJavaMethod method = getResolvedJavaMethod(c, "m"); StructuredGraph graph = parse(builder(method, StructuredGraph.AllowAssumptions.NO), getEagerGraphBuilderSuite()); graph.getDebug().dump(DebugContext.BASIC_LEVEL, graph, "Graph"); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/TwoSlotMarkerClearingTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/TwoSlotMarkerClearingTest.java index b21aa2c8613b..b150a1a6df2c 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/TwoSlotMarkerClearingTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/TwoSlotMarkerClearingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -25,14 +25,19 @@ package jdk.graal.compiler.core.test; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.CD_long; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.Opcode; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; + import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Label; import jdk.vm.ci.meta.ResolvedJavaMethod; -public class TwoSlotMarkerClearingTest extends CustomizedBytecodePatternTest { +public class TwoSlotMarkerClearingTest extends GraalCompilerTest implements CustomizedBytecodePattern { @Test public void testTwoSlotMarkerClearing() throws ClassNotFoundException { @@ -44,43 +49,23 @@ public void testTwoSlotMarkerClearing() throws ClassNotFoundException { } @Override - protected byte[] generateClass(String className) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, className, null, "java/lang/Object", null); - - String getDescriptor = "(" + "JII" + ")" + "I"; - MethodVisitor t1 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "t1", getDescriptor, null, null); - t1.visitCode(); - t1.visitVarInsn(ILOAD, 2); - t1.visitVarInsn(ISTORE, 0); - t1.visitVarInsn(ILOAD, 0); - Label label = new Label(); - t1.visitJumpInsn(IFGE, label); - t1.visitVarInsn(ILOAD, 0); - t1.visitInsn(IRETURN); - t1.visitLabel(label); - t1.visitVarInsn(ILOAD, 3); - t1.visitInsn(IRETURN); - t1.visitMaxs(4, 1); - t1.visitEnd(); - - getDescriptor = "(" + "IJIJ" + ")" + "J"; - MethodVisitor t2 = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "t2", getDescriptor, null, null); - t2.visitCode(); - t2.visitVarInsn(LLOAD, 1); - t2.visitVarInsn(LSTORE, 0); - t2.visitVarInsn(ILOAD, 3); - Label label1 = new Label(); - t2.visitJumpInsn(IFGE, label1); - t2.visitVarInsn(LLOAD, 0); - t2.visitInsn(LRETURN); - t2.visitLabel(label1); - t2.visitVarInsn(LLOAD, 4); - t2.visitInsn(LRETURN); - t2.visitMaxs(6, 2); - t2.visitEnd(); - - cw.visitEnd(); - return cw.toByteArray(); + public byte[] generateClass(String className) { + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethodBody("t1", MethodTypeDesc.of(CD_int, CD_long, CD_int, CD_int), ACC_PUBLIC_STATIC, b -> b + .iload(2) + .istore(0) + .iload(0) + .ifThenElse(Opcode.IFLT, + thenBlock -> thenBlock.iload(0).ireturn(), + elseBlock -> elseBlock.iload(3).ireturn())) + .withMethodBody("t2", MethodTypeDesc.of(CD_long, CD_int, CD_long, CD_int, CD_long), ACC_PUBLIC_STATIC, b -> b + .lload(1) + .lstore(0) + .iload(3) + .ifThenElse(Opcode.IFLT, + thenBlock -> thenBlock.lload(0).lreturn(), + elseBlock -> elseBlock.lload(4).lreturn()))); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedLockingTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedLockingTest.java index 45639c00fa81..ccaf1054d9d2 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedLockingTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedLockingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2025, 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 @@ -24,24 +24,32 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.Label; +import java.lang.classfile.Opcode; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.lang.reflect.InvocationTargetException; +import org.junit.Ignore; +import org.junit.Test; + import jdk.graal.compiler.core.common.GraalOptions; import jdk.graal.compiler.java.BciBlockMapping; import jdk.graal.compiler.java.BytecodeParserOptions; import jdk.graal.compiler.options.OptionValues; -import org.junit.Ignore; -import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; /** * Test class exercising irreducible loop duplication logic in {@link BciBlockMapping} in * conjunction with locking and exception handlers. */ -public class UnbalancedLockingTest extends CustomizedBytecodePatternTest { +public class UnbalancedLockingTest extends GraalCompilerTest implements CustomizedBytecodePattern { /** * Run many calls to a test method to force a c1/c2 compile, check with -XX:+PrintCompilation. @@ -77,15 +85,15 @@ public void testIrreducibleLoop() throws ClassNotFoundException { * {@linkp BciBlockMapping.Options#DuplicateIrreducibleLoops}. */ @Override - protected byte[] generateClass(String internalClassName) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, internalClassName, null, "java/lang/Object", null); - createTestMethod(cw); - createIllegalLockingMethod(cw); - createIrreducibleMethod(cw); - cw.visitEnd(); - // Checkstyle: resume - return cw.toByteArray(); + public byte[] generateClass(String internalClassName) { + ClassDesc thisClass = ClassDesc.of(internalClassName); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withMethodBody("test", MTD_void, ACC_PUBLIC_STATIC, UnbalancedLockingTest::createTestMethod) + .withMethodBody("snippet", MethodTypeDesc.of(CD_void, CD_int, CD_Object, CD_Object), ACC_PUBLIC_STATIC, UnbalancedLockingTest::createIllegalLockingMethod) + .withMethodBody("bar", MethodTypeDesc.of(CD_void, CD_int, CD_int, CD_Object, CD_Object), ACC_PUBLIC_STATIC, b -> createIrreducibleMethod(thisClass, b))); + // @formatter:on } /** @@ -122,110 +130,55 @@ protected byte[] generateClass(String internalClassName) { * } * */ - private static void createIrreducibleMethod(ClassWriter cw) { - // Checkstyle: stop - { - - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "bar", "(IILjava/lang/Object;Ljava/lang/Object;)V", null, null); - Label assignmentEnd = new Label(); - Label assignmentElse = new Label(); - - snippet.visitVarInsn(ILOAD, 0); - snippet.visitIntInsn(BIPUSH, 12); - snippet.visitJumpInsn(IF_ICMPLE, assignmentElse); - { - snippet.visitVarInsn(ALOAD, 2); - snippet.visitVarInsn(ASTORE, 6); - snippet.visitJumpInsn(GOTO, assignmentEnd); - } - snippet.visitLabel(assignmentElse); - { - - snippet.visitVarInsn(ALOAD, 3); - snippet.visitVarInsn(ASTORE, 6); - } - - snippet.visitLabel(assignmentEnd); - - Label exceptionHandler = new Label(); - Label irreducible = new Label(); - Label loopHeader1 = new Label(); - Label end1 = new Label(); - Label loopHeader2 = new Label(); - Label end2 = new Label(); - - snippet.visitCode(); - - snippet.visitInsn(ICONST_0); - snippet.visitVarInsn(ISTORE, 3); - snippet.visitVarInsn(ILOAD, 0); - snippet.visitVarInsn(ILOAD, 1); - Label elseBranch = new Label(); - snippet.visitJumpInsn(IF_ICMPNE, elseBranch); - { - snippet.visitLabel(loopHeader1); - { - snippet.visitVarInsn(ILOAD, 3); - snippet.visitVarInsn(ILOAD, 0); - snippet.visitJumpInsn(IF_ICMPGE, end1); - snippet.visitIincInsn(3, 1); - - Label exceptionStart = new Label(); - Label exceptionEnd = new Label(); - - snippet.visitTryCatchBlock(exceptionStart, exceptionEnd, exceptionHandler, null); - - snippet.visitLabel(exceptionStart); - - snippet.visitVarInsn(ALOAD, 6); - snippet.visitInsn(MONITORENTER); - - snippet.visitMethodInsn(INVOKESTATIC, Type.getInternalName(UnbalancedLockingTest.class) + "$ABC", "test", "()V", false); - - snippet.visitVarInsn(ALOAD, 6); - snippet.visitInsn(MONITOREXIT); - snippet.visitLabel(irreducible); - - snippet.visitLabel(exceptionEnd); - - snippet.visitJumpInsn(GOTO, loopHeader1); - } - snippet.visitLabel(end1); - snippet.visitInsn(RETURN); - } - snippet.visitLabel(elseBranch); - { - Label secondEnd = new Label(); - snippet.visitLabel(loopHeader2); - { - snippet.visitVarInsn(ILOAD, 3); - snippet.visitVarInsn(ILOAD, 0); - snippet.visitJumpInsn(IF_ICMPGE, end2); - snippet.visitIincInsn(3, 1); - snippet.visitJumpInsn(GOTO, loopHeader2); - } - snippet.visitLabel(end2); - snippet.visitVarInsn(ALOAD, 2); - snippet.visitJumpInsn(IFNULL, secondEnd); - { - // irreducible jump into other loops body - snippet.visitJumpInsn(GOTO, irreducible); - } - snippet.visitLabel(secondEnd); - snippet.visitInsn(RETURN); - } - - snippet.visitLabel(exceptionHandler); - { - snippet.visitVarInsn(ALOAD, 6); - snippet.visitInsn(MONITOREXIT); - snippet.visitInsn(ATHROW); - } - - snippet.visitMaxs(1, 4); - snippet.visitEnd(); - } - // Checkstyle: resume + private static void createIrreducibleMethod(ClassDesc thisClass, CodeBuilder b) { + Label irreducible = b.newLabel(); + Label loopHeader1 = b.newLabel(); + Label loopHeader2 = b.newLabel(); + + // @formatter:off + b + .iload(0) + .bipush(12) + .ifThenElse(Opcode.IF_ICMPGT, + thenBlock -> thenBlock.aload(2).astore(6), + elseBlock -> elseBlock.aload(3).astore(6)) + .iconst_0() + .istore(3) + .iload(0) + .iload(1) + .ifThenElse(Opcode.IF_ICMPEQ, + thenBlock -> thenBlock + .labelBinding(loopHeader1) + .iload(3) + .iload(0) + .ifThen(Opcode.IF_ICMPLT, thenBlock1 -> thenBlock1 + .iinc(3, 1) + .trying(tryBlock -> { + tryBlock + .aload(6) + .monitorenter() + .invokestatic(thisClass, "test", MTD_void) + .aload(6) + .monitorexit(); + }, catchBuilder -> catchBuilder.catchingAll(catchBlock -> { + catchBlock + .aload(6) + .monitorexit() + .athrow(); + })) + .labelBinding(irreducible) + .goto_(loopHeader1)), + elseBlock -> elseBlock + .labelBinding(loopHeader2) + .iload(3) + .iload(0) + .ifThen(Opcode.IF_ICMPLT, thenBlock1 -> thenBlock1 + .iinc(3, 1) + .goto_(loopHeader2)) + .aload(2) + .ifnonnull(irreducible)) + .return_(); + // @formatter:on } /** @@ -246,44 +199,26 @@ private static void createIrreducibleMethod(ClassWriter cw) { * } * */ - private static void createIllegalLockingMethod(ClassWriter cw) { - // Checkstyle: stop - { - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "snippet", "(ILjava/lang/Object;Ljava/lang/Object;)V", null, null); - snippet.visitCode(); - snippet.visitVarInsn(ILOAD, 0); - - Label falseBranch = new Label(); - Label merge = new Label(); - - snippet.visitJumpInsn(IFNE, falseBranch); - {// true branch - snippet.visitVarInsn(ALOAD, 1); - snippet.visitVarInsn(ASTORE, 3); - - snippet.visitVarInsn(ALOAD, 1); - snippet.visitInsn(MONITORENTER); - - snippet.visitJumpInsn(GOTO, merge); - } - {// false branch - snippet.visitLabel(falseBranch); - snippet.visitVarInsn(ALOAD, 2); - snippet.visitVarInsn(ASTORE, 3); - - snippet.visitVarInsn(ALOAD, 2); - snippet.visitInsn(MONITORENTER); - } - snippet.visitLabel(merge); - - snippet.visitVarInsn(ALOAD, 3); - snippet.visitInsn(MONITOREXIT); - - snippet.visitInsn(RETURN); - snippet.visitMaxs(1, 4); - snippet.visitEnd(); - } - // Checkstyle: resume + private static void createIllegalLockingMethod(CodeBuilder b) { + // @formatter:off + b + .iload(0) + .ifThenElse( + Opcode.IFEQ, + thenBlock -> thenBlock + .aload(1) + .astore(3) + .aload(1) + .monitorenter(), + elseBlock -> elseBlock + .aload(2) + .astore(3) + .aload(2) + .monitorenter()) + .aload(3) + .monitorexit() + .return_(); + // @formatter:on } /** @@ -294,16 +229,7 @@ private static void createIllegalLockingMethod(ClassWriter cw) { * } * */ - private static void createTestMethod(ClassWriter cw) { - // Checkstyle: stop - { - MethodVisitor snippet = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "test", "()V", null, null); - snippet.visitCode(); - snippet.visitInsn(RETURN); - snippet.visitMaxs(1, 4); - snippet.visitEnd(); - } - // Checkstyle: resume + private static void createTestMethod(CodeBuilder b) { + b.return_(); } - } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedMonitorsTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedMonitorsTest.java index e969929ebc8d..2edb5622b471 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedMonitorsTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnbalancedMonitorsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -24,11 +24,19 @@ */ package jdk.graal.compiler.core.test; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_boolean; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.CodeBuilder; +import java.lang.classfile.Label; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; + import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; import jdk.graal.compiler.java.GraphBuilderPhase; import jdk.graal.compiler.nodes.StructuredGraph; @@ -52,17 +60,13 @@ * Since [GR-51446], Graal defers some checks to run time, e.g., if it cannot be proven statically * that an unlocked object matches the object on top of the monitor stack. */ -public class UnbalancedMonitorsTest extends GraalCompilerTest { +public class UnbalancedMonitorsTest extends GraalCompilerTest implements CustomizedBytecodePattern { private static final String CLASS_NAME = UnbalancedMonitorsTest.class.getName(); private static final String INNER_CLASS_NAME = CLASS_NAME + "$UnbalancedMonitors"; - private static final String CLASS_NAME_INTERNAL = CLASS_NAME.replace('.', '/'); - private static final String INNER_CLASS_NAME_INTERNAL = INNER_CLASS_NAME.replace('.', '/'); - - private static AsmLoader LOADER = new AsmLoader(UnbalancedMonitorsTest.class.getClassLoader()); @Test public void runWrongOrder() throws Exception { - Class clazz = LOADER.findClass(INNER_CLASS_NAME); + Class clazz = getClass(INNER_CLASS_NAME); ResolvedJavaMethod method = getResolvedJavaMethod(clazz, "wrongOrder"); Object instance = clazz.getName(); InstalledCode code = getCode(method); @@ -91,7 +95,7 @@ public void runTooManyExitsExceptional() throws Exception { } private void checkForBailout(String name) throws ClassNotFoundException { - ResolvedJavaMethod method = getResolvedJavaMethod(LOADER.findClass(INNER_CLASS_NAME), name); + ResolvedJavaMethod method = getResolvedJavaMethod(getClass(INNER_CLASS_NAME), name); try { OptionValues options = getInitialOptions(); StructuredGraph graph = new StructuredGraph.Builder(options, getDebugContext(options, null, method)).method(method).build(); @@ -112,8 +116,6 @@ private void checkForBailout(String name) throws ClassNotFoundException { assertTrue("should have bailed out", false); } - static class Gen implements Opcodes { - // @formatter:off // Template class used with Bytecode Outline to generate ASM code // public static class UnbalancedMonitors { @@ -146,188 +148,126 @@ static class Gen implements Opcodes { // } // } // @formatter:on + @Override + public byte[] generateClass(String className) { + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .return_()) + .withMethodBody("wrongOrder", MethodTypeDesc.of(CD_Object, CD_Object, CD_Object), ACC_PUBLIC, UnbalancedMonitorsTest::visitWrongOrder) + .withMethodBody("tooFewExits", MethodTypeDesc.of(CD_boolean, CD_Object, CD_Object), ACC_PUBLIC, b -> visitBlockStructured(b, true, false)) + .withMethodBody("tooManyExits", MethodTypeDesc.of(CD_boolean, CD_Object, CD_Object), ACC_PUBLIC, b -> visitBlockStructured(b, true, true)) + .withMethodBody("tooFewExitsExceptional", MethodTypeDesc.of(CD_boolean, CD_Object, CD_Object), ACC_PUBLIC, b -> visitBlockStructured(b, false, false)) + .withMethodBody("tooManyExitsExceptional", MethodTypeDesc.of(CD_boolean, CD_Object, CD_Object), ACC_PUBLIC, b -> visitBlockStructured(b, false, true))); + // @formatter:on + } - public static byte[] generateClass() { - - ClassWriter cw = new ClassWriter(0); - - cw.visit(52, ACC_SUPER | ACC_PUBLIC, INNER_CLASS_NAME_INTERNAL, null, "java/lang/Object", null); - - cw.visitSource("UnbalancedMonitorsTest.java", null); - - cw.visitInnerClass(INNER_CLASS_NAME_INTERNAL, CLASS_NAME_INTERNAL, "UnbalancedMonitors", ACC_STATIC); + private static void visitBlockStructured(CodeBuilder b, boolean normalReturnError, boolean tooMany) { + // Generate too many or too few exits down either the normal or exceptional return paths + int exceptionalExitCount = normalReturnError ? 1 : (tooMany ? 2 : 0); + int normalExitCount = normalReturnError ? (tooMany ? 2 : 0) : 1; - visitConstructor(cw); - visitWrongOrder(cw); - visitBlockStructured(cw, true, false); - visitBlockStructured(cw, true, true); - visitBlockStructured(cw, false, false); - visitBlockStructured(cw, false, true); - cw.visitEnd(); + Label l0 = b.newLabel(); + Label l1 = b.newLabel(); + Label l2 = b.newLabel(); + Label l3 = b.newLabel(); + Label l4 = b.newLabel(); + Label l5 = b.newLabel(); + Label l6 = b.newLabel(); + Label l7 = b.newLabel(); + Label l8 = b.newLabel(); - return cw.toByteArray(); + // @formatter:off + b.labelBinding(l8) + .aload(1) + .dup() + .astore(3) + .monitorenter() + .labelBinding(l4) + .aload(2) + .dup() + .astore(4) + .monitorenter() + .labelBinding(l0) + .aload(2) + .aload(1) + .invokevirtual(CD_Object, "equals", MethodTypeDesc.of(CD_boolean, CD_Object)) + .aload(4) + .monitorexit() + .labelBinding(l1); + for (int i = 0; i < normalExitCount; i++) { + b.aload(3).monitorexit(); } - private static void visitBlockStructured(ClassWriter cw, boolean normalReturnError, boolean tooMany) { - String name = (tooMany ? "tooMany" : "tooFew") + "Exits" + (normalReturnError ? "" : "Exceptional"); - // Generate too many or too few exits down the either the normal or exceptional return - // paths - int exceptionalExitCount = normalReturnError ? 1 : (tooMany ? 2 : 0); - int normalExitCount = normalReturnError ? (tooMany ? 2 : 0) : 1; - MethodVisitor mv; - mv = cw.visitMethod(ACC_PUBLIC, name, "(Ljava/lang/Object;Ljava/lang/Object;)Z", null, null); - mv.visitCode(); - Label l0 = new Label(); - Label l1 = new Label(); - Label l2 = new Label(); - mv.visitTryCatchBlock(l0, l1, l2, null); - Label l3 = new Label(); - mv.visitTryCatchBlock(l2, l3, l2, null); - Label l4 = new Label(); - Label l5 = new Label(); - Label l6 = new Label(); - mv.visitTryCatchBlock(l4, l5, l6, null); - Label l7 = new Label(); - mv.visitTryCatchBlock(l2, l7, l6, null); - Label l8 = new Label(); - mv.visitLabel(l8); - mv.visitVarInsn(ALOAD, 1); - mv.visitInsn(DUP); - mv.visitVarInsn(ASTORE, 3); - mv.visitInsn(MONITORENTER); - mv.visitLabel(l4); - mv.visitVarInsn(ALOAD, 2); - mv.visitInsn(DUP); - mv.visitVarInsn(ASTORE, 4); - mv.visitInsn(MONITORENTER); - mv.visitLabel(l0); - mv.visitVarInsn(ALOAD, 2); - mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "equals", "(Ljava/lang/Object;)Z", false); - mv.visitVarInsn(ALOAD, 4); - mv.visitInsn(MONITOREXIT); - mv.visitLabel(l1); - for (int i = 0; i < normalExitCount; i++) { - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(MONITOREXIT); - } - mv.visitLabel(l5); - mv.visitInsn(IRETURN); - mv.visitLabel(l2); - mv.visitFrame(Opcodes.F_FULL, 5, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object", - "java/lang/Object"}, 1, new Object[]{"java/lang/Throwable"}); - mv.visitVarInsn(ALOAD, 4); - mv.visitInsn(MONITOREXIT); - mv.visitLabel(l3); - mv.visitInsn(ATHROW); - mv.visitLabel(l6); - mv.visitFrame(Opcodes.F_FULL, 4, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object"}, 1, - new Object[]{"java/lang/Throwable"}); - for (int i = 0; i < exceptionalExitCount; i++) { - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(MONITOREXIT); - } - mv.visitLabel(l7); - mv.visitInsn(ATHROW); - Label l9 = new Label(); - mv.visitLabel(l9); - mv.visitMaxs(2, 5); - mv.visitEnd(); - } + b.labelBinding(l5) + .ireturn() + .labelBinding(l2) + .aload(4) + .monitorexit() + .labelBinding(l3) + .athrow() + .labelBinding(l6); - private static void visitWrongOrder(ClassWriter cw) { - MethodVisitor mv; - mv = cw.visitMethod(ACC_PUBLIC, "wrongOrder", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", null, null); - mv.visitCode(); - Label l0 = new Label(); - Label l1 = new Label(); - Label l2 = new Label(); - mv.visitTryCatchBlock(l0, l1, l2, null); - Label l3 = new Label(); - mv.visitTryCatchBlock(l2, l3, l2, null); - Label l4 = new Label(); - Label l5 = new Label(); - Label l6 = new Label(); - mv.visitTryCatchBlock(l4, l5, l6, null); - Label l7 = new Label(); - mv.visitTryCatchBlock(l2, l7, l6, null); - Label l8 = new Label(); - mv.visitLabel(l8); - mv.visitVarInsn(ALOAD, 1); - mv.visitInsn(DUP); - mv.visitVarInsn(ASTORE, 3); - mv.visitInsn(MONITORENTER); - mv.visitLabel(l4); - mv.visitVarInsn(ALOAD, 2); - mv.visitInsn(DUP); - mv.visitVarInsn(ASTORE, 4); - mv.visitInsn(MONITORENTER); - mv.visitLabel(l0); - mv.visitVarInsn(ALOAD, 2); - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(MONITOREXIT); - mv.visitLabel(l1); - // Swapped exit order with exit above - mv.visitVarInsn(ALOAD, 4); - mv.visitInsn(MONITOREXIT); - mv.visitLabel(l5); - mv.visitInsn(ARETURN); - mv.visitLabel(l2); - mv.visitFrame(Opcodes.F_FULL, 5, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object", - "java/lang/Object"}, 1, new Object[]{"java/lang/Throwable"}); - mv.visitVarInsn(ALOAD, 4); - mv.visitInsn(MONITOREXIT); - mv.visitLabel(l3); - mv.visitInsn(ATHROW); - mv.visitLabel(l6); - mv.visitFrame(Opcodes.F_FULL, 4, new Object[]{INNER_CLASS_NAME_INTERNAL, "java/lang/Object", "java/lang/Object", "java/lang/Object"}, 1, - new Object[]{"java/lang/Throwable"}); - mv.visitVarInsn(ALOAD, 3); - mv.visitInsn(MONITOREXIT); - mv.visitLabel(l7); - mv.visitInsn(ATHROW); - Label l9 = new Label(); - mv.visitLabel(l9); - mv.visitMaxs(2, 5); - mv.visitEnd(); + for (int i = 0; i < exceptionalExitCount; i++) { + b.aload(3).monitorexit(); } - private static void visitConstructor(ClassWriter cw) { - MethodVisitor mv; - mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitInsn(RETURN); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitMaxs(1, 1); - mv.visitEnd(); - } + b.labelBinding(l7) + .athrow() + .exceptionCatchAll(l0, l1, l2) + .exceptionCatchAll(l2, l3, l2) + .exceptionCatchAll(l4, l5, l6) + .exceptionCatchAll(l2, l7, l6); + // @formatter:on } - public static class AsmLoader extends ClassLoader { - Class loaded; + private static void visitWrongOrder(CodeBuilder b) { + Label l0 = b.newLabel(); + Label l1 = b.newLabel(); + Label l2 = b.newLabel(); + Label l3 = b.newLabel(); + Label l4 = b.newLabel(); + Label l5 = b.newLabel(); + Label l6 = b.newLabel(); + Label l7 = b.newLabel(); + Label l8 = b.newLabel(); - public AsmLoader(ClassLoader parent) { - super(parent); - } - - @Override - protected Class findClass(String name) throws ClassNotFoundException { - if (name.equals(INNER_CLASS_NAME)) { - if (loaded != null) { - return loaded; - } - byte[] bytes = Gen.generateClass(); - return (loaded = defineClass(name, bytes, 0, bytes.length)); - } else { - return super.findClass(name); - } - } + // @formatter:off + b.labelBinding(l8) + .aload(1) + .dup() + .astore(3) + .monitorenter() + .labelBinding(l4) + .aload(2) + .dup() + .astore(4) + .monitorenter() + .labelBinding(l0) + .aload(2) + .aload(3) + .monitorexit() + .labelBinding(l1) + .aload(4) + .monitorexit() + .labelBinding(l5) + .areturn() + .labelBinding(l2) + .aload(4) + .monitorexit() + .labelBinding(l3) + .athrow() + .labelBinding(l6) + .aload(3) + .monitorexit() + .labelBinding(l7) + .athrow() + .exceptionCatchAll(l0, l1, l2) + .exceptionCatchAll(l2, l3, l2) + .exceptionCatchAll(l4, l5, l6) + .exceptionCatchAll(l2, l7, l6); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnschedulableGraphTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnschedulableGraphTest.java index 38296f6e5c15..f78ab3db313f 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnschedulableGraphTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/UnschedulableGraphTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -28,6 +28,9 @@ import java.util.List; +import org.junit.Assert; +import org.junit.Test; + import jdk.graal.compiler.api.directives.GraalDirectives; import jdk.graal.compiler.core.common.cfg.BlockMap; import jdk.graal.compiler.debug.DebugCloseable; @@ -42,9 +45,6 @@ import jdk.graal.compiler.nodes.extended.OpaqueNode; import jdk.graal.compiler.options.OptionValues; import jdk.graal.compiler.phases.OptimisticOptimizations; -import org.junit.Assert; -import org.junit.Test; - import jdk.vm.ci.meta.ResolvedJavaMethod; /** @@ -110,12 +110,11 @@ protected OptimisticOptimizations getOptimisticOptimizations() { } @Test - @SuppressWarnings("try") public void test01() { ResolvedJavaMethod method = getResolvedJavaMethod("snippet01"); - try (AutoCloseable c = new TTY.Filter(); + try (AutoCloseable _ = new TTY.Filter(); DebugContext debug = getDebugContext(method); - DebugCloseable s = debug.disableIntercept()) { + DebugCloseable _ = debug.disableIntercept()) { test(debug.getOptions(), "snippet01", 0, 1, 2); Assert.fail("Compilation should not reach this point, must throw an exception before"); } catch (Throwable t) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyAssertionUsageTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyAssertionUsageTest.java index e1bd5c39d6ab..eddec1d4df23 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyAssertionUsageTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyAssertionUsageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -421,7 +421,6 @@ public void testAssertInvalidCallGraph5() { testDebugUsageClass(InvalidCallGraphUsage5.class); } - @SuppressWarnings("try") private static void testDebugUsageClass(Class c) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); @@ -439,7 +438,7 @@ private static void testDebugUsageClass(Class c) { ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m); StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).build(); graphBuilderSuite.apply(graph, context); - try (DebugCloseable s = debug.disableIntercept()) { + try (DebugCloseable _ = debug.disableIntercept()) { vaU.apply(graph, context); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyBailoutUsageTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyBailoutUsageTest.java index fe4a62b987de..691f35f06d9e 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyBailoutUsageTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyBailoutUsageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -113,7 +113,6 @@ public void testValidRetryableBailout() { testBailoutUsage(ValidRetryableBailoutUsage.class); } - @SuppressWarnings("try") private static void testBailoutUsage(Class c) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); @@ -130,7 +129,7 @@ private static void testBailoutUsage(Class c) { ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m); StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).build(); graphBuilderSuite.apply(graph, context); - try (DebugCloseable s = debug.disableIntercept()) { + try (DebugCloseable _ = debug.disableIntercept()) { new VerifyBailoutUsage().apply(graph, context); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyDebugUsageTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyDebugUsageTest.java index e3982f327814..4b389ae50125 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyDebugUsageTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyDebugUsageTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -67,10 +67,9 @@ protected void run(StructuredGraph graph) { private static final class InvalidLogAndIndentUsagePhase extends TestPhase { @Override - @SuppressWarnings("try") protected void run(StructuredGraph graph) { DebugContext debug = graph.getDebug(); - try (Indent i = debug.logAndIndent("%s", graph.toString())) { + try (Indent _ = debug.logAndIndent("%s", graph.toString())) { for (Node n : graph.getNodes()) { debug.log("%s", n); } @@ -129,10 +128,9 @@ protected void run(StructuredGraph graph) { private static final class InvalidConcatLogAndIndentUsagePhase extends TestPhase { @Override - @SuppressWarnings("try") protected void run(StructuredGraph graph) { DebugContext debug = graph.getDebug(); - try (Indent i = debug.logAndIndent("error " + graph)) { + try (Indent _ = debug.logAndIndent("error " + graph)) { for (Node n : graph.getNodes()) { debug.log("%s", n); } @@ -172,10 +170,9 @@ protected void run(StructuredGraph graph) { static class ValidLogAndIndentUsagePhase extends TestPhase { @Override - @SuppressWarnings("try") protected void run(StructuredGraph graph) { DebugContext debug = graph.getDebug(); - try (Indent i = debug.logAndIndent("%s", graph)) { + try (Indent _ = debug.logAndIndent("%s", graph)) { for (Node n : graph.getNodes()) { debug.log("%s", n); } @@ -322,7 +319,6 @@ public void testGraalCtorValid() { testDebugUsageClass(ValidGraalErrorCtorPhase.class); } - @SuppressWarnings("try") private static void testDebugUsageClass(Class c) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); @@ -339,7 +335,7 @@ private static void testDebugUsageClass(Class c) { ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m); StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).build(); graphBuilderSuite.apply(graph, context); - try (DebugCloseable s = debug.disableIntercept()) { + try (DebugCloseable _ = debug.disableIntercept()) { new VerifyDebugUsage().apply(graph, context); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyVirtualizableTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyVirtualizableTest.java index 6e70749237f3..24fc6cff87d8 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyVirtualizableTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/VerifyVirtualizableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -261,7 +261,6 @@ public void testValidAddOrUniqueWithInputs() { testVirtualizableEffects(ValidEffectNodeAddOrUniqueWithInputs.class); } - @SuppressWarnings("try") private static void testVirtualizableEffects(Class c) { RuntimeProvider rt = Graal.getRequiredCapability(RuntimeProvider.class); Providers providers = rt.getHostBackend().getProviders(); @@ -278,7 +277,7 @@ private static void testVirtualizableEffects(Class c) { ResolvedJavaMethod method = metaAccess.lookupJavaMethod(m); StructuredGraph graph = new StructuredGraph.Builder(options, debug).method(method).build(); graphBuilderSuite.apply(graph, context); - try (DebugCloseable s = debug.disableIntercept()) { + try (DebugCloseable _ = debug.disableIntercept()) { new VerifyVirtualizableUsage().apply(graph, context); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/AllocatorTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/AllocatorTest.java index b9c5520d9972..0a1d93119b95 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/AllocatorTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/AllocatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -28,6 +28,8 @@ import java.util.HashSet; +import org.junit.Assert; + import jdk.graal.compiler.core.common.cfg.BasicBlock; import jdk.graal.compiler.debug.DebugContext; import jdk.graal.compiler.lir.LIR; @@ -37,21 +39,18 @@ import jdk.graal.compiler.lir.ValueProcedure; import jdk.graal.compiler.nodes.StructuredGraph; import jdk.graal.compiler.nodes.StructuredGraph.AllowAssumptions; -import org.junit.Assert; - import jdk.vm.ci.code.Register; import jdk.vm.ci.code.ValueUtil; import jdk.vm.ci.meta.Value; public class AllocatorTest extends BackendTest { - @SuppressWarnings("try") protected void testAllocation(String snippet, final int expectedRegisters, final int expectedRegRegMoves, final int expectedSpillMoves) { final StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES); DebugContext debug = graph.getDebug(); - try (DebugContext.Scope s = debug.scope("AllocatorTest", graph, graph.method(), getCodeCache())) { + try (DebugContext.Scope _ = debug.scope("AllocatorTest", graph, graph.method(), getCodeCache())) { final RegisterStats stats = new RegisterStats(getLIRGenerationResult(graph).getLIR()); - try (DebugContext.Scope s2 = debug.scope("Assertions", stats.lir)) { + try (DebugContext.Scope _ = debug.scope("Assertions", stats.lir)) { Assert.assertEquals("register count", expectedRegisters, stats.registers.size()); Assert.assertEquals("reg-reg moves", expectedRegRegMoves, stats.regRegMoves); Assert.assertEquals("spill moves", expectedSpillMoves, stats.spillMoves); @@ -84,7 +83,7 @@ private class RegisterStats { } } - private ValueProcedure collectStatsProc = (value, mode, flags) -> { + private ValueProcedure collectStatsProc = (value, _, _) -> { if (ValueUtil.isRegister(value)) { final Register reg = ValueUtil.asRegister(value); registers.add(reg); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/BackendTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/BackendTest.java index 078ebfe07c9f..2f7f9b8aacad 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/BackendTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/backend/BackendTest.java @@ -43,16 +43,15 @@ public BackendTest(Class arch) { super(arch); } - @SuppressWarnings("try") protected LIRGenerationResult getLIRGenerationResult(final StructuredGraph graph, OptimisticOptimizations optimizations) { DebugContext debug = graph.getDebug(); - try (DebugContext.Scope s = debug.scope("FrontEnd")) { + try (DebugContext.Scope _ = debug.scope("FrontEnd")) { GraalCompiler.emitFrontEnd(getProviders(), getBackend(), graph, getDefaultGraphBuilderSuite(), optimizations, graph.getProfilingInfo(), createSuites(graph.getOptions())); } catch (Throwable e) { throw debug.handle(e); } - try (DebugContext.Scope s = debug.scope("BackEnd", graph, graph.getLastSchedule())) { + try (DebugContext.Scope _ = debug.scope("BackEnd", graph, graph.getLastSchedule())) { return LIRCompilerBackend.emitLIR(getBackend(), graph, null, null, createLIRSuites(graph.getOptions()), null); } catch (Throwable e) { throw debug.handle(e); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/deopt/RethrowExceptionLoopTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/deopt/RethrowExceptionLoopTest.java index df9637e2a48f..120b9a219004 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/deopt/RethrowExceptionLoopTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/deopt/RethrowExceptionLoopTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -66,7 +66,6 @@ public static Object catchInLoop(Object object) { } @Override - @SuppressWarnings("try") protected Suites createSuites(OptionValues options) { return super.createSuites(new OptionValues(options, HighTier.Options.Inline, false)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/EATestBase.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/EATestBase.java index b84eb6a64b06..c301dc505623 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/EATestBase.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/EATestBase.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -207,11 +207,10 @@ protected int getAllocationCount() { return graph.getNodes().filter(isA(NewInstanceNode.class).or(NewArrayNode.class).or(AllocatedObjectNode.class)).count(); } - @SuppressWarnings("try") protected void prepareGraph(String snippet, boolean removeIdentity) { ResolvedJavaMethod method = getResolvedJavaMethod(snippet); DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope(getClass(), method, getCodeCache())) { + try (DebugContext.Scope _ = debug.scope(getClass(), method, getCodeCache())) { graph = parseEager(method, AllowAssumptions.YES, debug); context = getDefaultHighTierContext(); createInliningPhase().apply(graph, context); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PartialEscapeAnalysisTreesTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PartialEscapeAnalysisTreesTest.java index 89850830509f..d4a9999a17ff 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PartialEscapeAnalysisTreesTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PartialEscapeAnalysisTreesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -107,12 +107,11 @@ public void testBuildTree() { * Prepare a graph that includes some blackholes and then remove the blackholes and compile * normally to create an unusual situation for PEA. */ - @SuppressWarnings("try") public void testGraph(String name) { ResolvedJavaMethod method = getResolvedJavaMethod(name); prepareGraph(name, true); - try (DebugContext.Scope s = graph.getDebug().scope(getClass(), method, getCodeCache(), graph)) { + try (DebugContext.Scope _ = graph.getDebug().scope(getClass(), method, getCodeCache(), graph)) { for (BlackholeNode node : graph.getNodes().filter(BlackholeNode.class)) { graph.removeFixed(node); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PoorMansEATest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PoorMansEATest.java index 4dcfa457f441..b5f1d9b5d563 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PoorMansEATest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/ea/PoorMansEATest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -53,10 +53,9 @@ public void test1() { test("test1Snippet"); } - @SuppressWarnings("try") private void test(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("PoorMansEATest", new DebugDumpScope(snippet))) { + try (DebugContext.Scope _ = debug.scope("PoorMansEATest", new DebugDumpScope(snippet))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.NO); HighTierContext highTierContext = getDefaultHighTierContext(); createInliningPhase().apply(graph, highTierContext); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/ImpreciseArgumentStampInliningTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/ImpreciseArgumentStampInliningTest.java index fa30902e6923..99898b1554f8 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/ImpreciseArgumentStampInliningTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/ImpreciseArgumentStampInliningTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -145,11 +145,10 @@ private static ManualClassLoader getClassLoader(Set initialLoadedClasses return loader; } - @SuppressWarnings("try") private StructuredGraph getGraph(final String snippet, Set initialLoadedClasses) { DebugContext debug = getDebugContext(new OptionValues(getInitialOptions(), BytecodeParserOptions.InlineDuringParsing, false)); try (ManualClassLoader loader = getClassLoader(initialLoadedClasses); - DebugContext.Scope s = debug.scope("InliningTest", new DebugDumpScope(snippet, true))) { + DebugContext.Scope _ = debug.scope("InliningTest", new DebugDumpScope(snippet, true))) { Class holderClass = loader.loadClass(InlineMethodHolder.class.getName()); ResolvedJavaMethod method = getResolvedJavaMethod(holderClass, snippet); Builder builder = builder(method, AllowAssumptions.YES, debug); @@ -158,7 +157,7 @@ private StructuredGraph getGraph(final String snippet, Set initialLoaded * At this point, the return stamp of doNotInlineMe is a plain Object stamp, since * UnresolveableClass is unresolved. */ - try (DebugContext.Scope s2 = debug.scope("Inlining", graph)) { + try (DebugContext.Scope _ = debug.scope("Inlining", graph)) { debug.dump(DebugContext.BASIC_LEVEL, graph, "Graph"); createCanonicalizerPhase().apply(graph, getDefaultHighTierContext()); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/InliningTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/InliningTest.java index ebf549a502bf..b2af9863a798 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/InliningTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/InliningTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -216,11 +216,10 @@ private static double callNonTrivial() { } @Test - @SuppressWarnings("try") public void testTracing() { OptionValues options = new OptionValues(getInitialOptions(), GraalOptions.TraceInlining, true); StructuredGraph graph; - try (TTY.Filter f = new TTY.Filter()) { + try (TTY.Filter _ = new TTY.Filter()) { graph = getGraph("traceInliningTest", options, false); } String inliningTree = graph.getInliningLog().formatAsTree(false); @@ -272,14 +271,13 @@ private StructuredGraph getGraph(final String snippet, final boolean eagerInfopo return getGraph(snippet, null, eagerInfopointMode); } - @SuppressWarnings("try") private StructuredGraph getGraph(final String snippet, OptionValues options, final boolean eagerInfopointMode) { DebugContext debug = options == null ? getDebugContext() : getDebugContext(options, null, null); - try (DebugContext.Scope s = debug.scope("InliningTest", new DebugDumpScope(snippet, true))) { + try (DebugContext.Scope _ = debug.scope("InliningTest", new DebugDumpScope(snippet, true))) { ResolvedJavaMethod method = getResolvedJavaMethod(snippet); Builder builder = builder(method, AllowAssumptions.YES, debug); StructuredGraph graph = eagerInfopointMode ? parse(builder, getDebugGraphBuilderSuite()) : parse(builder, getEagerGraphBuilderSuite()); - try (DebugContext.Scope s2 = debug.scope("Inlining", graph)) { + try (DebugContext.Scope _ = debug.scope("Inlining", graph)) { PhaseSuite graphBuilderSuite = eagerInfopointMode ? getCustomGraphBuilderSuite(GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withFullInfopoints(true)) : getDefaultGraphBuilderSuite(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/NestedLoopEffectsPhaseComplexityTest2.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/NestedLoopEffectsPhaseComplexityTest2.java index 804d9fb128cc..cb28a07a61de 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/NestedLoopEffectsPhaseComplexityTest2.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/inlining/NestedLoopEffectsPhaseComplexityTest2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -348,9 +348,8 @@ public static int recursiveMethod2(int a, A o) { } @Test - @SuppressWarnings("try") public void testIterative2() { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { OptionValues options = new OptionValues(getInitialOptions(), DumpOnError, false, GraalOptions.EscapeAnalysisLoopCutoff, 2); prepareGraph("recursiveMethod1", 30, true, options); } catch (Throwable t) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/jfr/TestGetEventWriter.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/jfr/TestGetEventWriter.java index 3c2f2c19593c..3b9b4b8b5ee0 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/jfr/TestGetEventWriter.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/jfr/TestGetEventWriter.java @@ -24,18 +24,24 @@ */ package jdk.graal.compiler.core.test.jfr; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + import java.io.IOException; -import java.lang.reflect.Constructor; +import java.lang.classfile.Annotation; +import java.lang.classfile.AnnotationElement; +import java.lang.classfile.ClassFile; +import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.lang.reflect.InvocationTargetException; import org.junit.Assert; import org.junit.Test; -import org.objectweb.asm.AnnotationVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; import jdk.graal.compiler.core.common.PermanentBailoutException; +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; import jdk.graal.compiler.core.test.SubprocessTest; import jdk.graal.compiler.test.AddExports; import jdk.jfr.Event; @@ -120,14 +126,14 @@ public void testInitializationEvent() { // attempts to resolve and link against EventWriterFactory. This user implementation // is not blessed for linkage. public void testNonEvent() throws Throwable { - testEvent("Non", "java/lang/Object", null, "commit", false); + testEvent("Non", "java.lang.Object", null, "commit", false); } // The user has defined a class which overrides and implements the "commit()V" // method declared final in jdk.jfr.Event. // This user implementation is not blessed for linkage. public void testRegisteredTrueEvent() throws Throwable { - testEvent("Registered", "jdk/jfr/Event", true, "commit", false); + testEvent("Registered", "jdk.jfr.Event", true, "commit", false); } // The user has defined a class which overrides and implements the "commit()V" @@ -139,14 +145,14 @@ public void testRegisteredTrueEvent() throws Throwable { // such a class throws an IllegalArgumentException. The user-defined // "commit()V" method is still not blessed for linkage, even after registration. public void testRegisteredFalseEvent() throws Throwable { - testEvent("Registered", "jdk/jfr/Event", false, "commit", false); + testEvent("Registered", "jdk.jfr.Event", false, "commit", false); } // The user has implemented another method, "myCommit()V", not an override nor // overload. that attempts to resolve and link EventWriterFactory. This will fail, // because "myCommit()V" is not blessed for linkage. public void testMyCommitRegisteredTrue() throws Throwable { - testEvent("MyCommit", "jdk/jfr/Event", true, "myCommit", false); + testEvent("MyCommit", "jdk.jfr.Event", true, "myCommit", false); } // The user has implemented another method, "myCommit()V", not an override, @@ -155,14 +161,14 @@ public void testMyCommitRegisteredTrue() throws Throwable { // the class is not excluded wholesale from the JFR system. // Invoking the real "commit()V", installed by the framework, is OK. public void testMyCommitRegisteredFalse() throws Throwable { - testEvent("MyCommit", "jdk/jfr/Event", false, "myCommit", false); + testEvent("MyCommit", "jdk.jfr.Event", false, "myCommit", false); } // Events located in the boot class loader can create a static // commit-method to emit events. It must not be used by code // outside of the boot class loader. public void testStaticCommit() throws Throwable { - testEvent("StaticCommit", "jdk/jfr/Event", null, "commit", true); + testEvent("StaticCommit", "jdk.jfr.Event", null, "commit", true); } private void testEvent(String name, String superClass, Boolean isRegistered, String commitName, boolean isStatic) throws Throwable { @@ -202,78 +208,59 @@ private void testEvent(String name, String superClass, Boolean isRegistered, Str * } */ // @formatter:on - Runnable newEventObject(String superClass, Boolean isRegistered, String commitName, boolean isStatic, String className) + Runnable newEventObject(String superClassName, Boolean isRegistered, String commitName, boolean isStatic, String className) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); - String[] interfaces = {"java/lang/Runnable"}; - cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, className.replace('.', '/'), null, superClass, interfaces); + return (Runnable) new CustomizedClass(superClassName, isRegistered, commitName, isStatic).getClass(className).getConstructor().newInstance(); + } - if (isRegistered != null) { - AnnotationVisitor registered = cw.visitAnnotation("Ljdk/jfr/Registered;", true); - registered.visit("value", isRegistered); - registered.visitEnd(); - } + static class CustomizedClass implements CustomizedBytecodePattern { - // constructor - MethodVisitor constructor = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); - constructor.visitCode(); - constructor.visitVarInsn(Opcodes.ALOAD, 0); - constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, superClass, "", "()V", false); - constructor.visitInsn(Opcodes.RETURN); - constructor.visitMaxs(0, 0); - constructor.visitEnd(); + private String superClassName; + private Boolean isRegistered; + private String commitName; + private boolean isStatic; - int commitAccess = Opcodes.ACC_PUBLIC; - if (isStatic) { - commitAccess |= Opcodes.ACC_STATIC; + CustomizedClass(String superClassName, Boolean isRegistered, String commitName, boolean isStatic) { + this.superClassName = superClassName; + this.isRegistered = isRegistered; + this.commitName = commitName; + this.isStatic = isStatic; } - MethodVisitor commit = cw.visitMethod(commitAccess, commitName, "()V", null, null); - commit.visitCode(); - commit.visitMethodInsn(Opcodes.INVOKESTATIC, "jdk/jfr/internal/event/EventWriter", "getEventWriter", "()Ljdk/jfr/internal/event/EventWriter;", false); - commit.visitInsn(Opcodes.POP); - commit.visitInsn(Opcodes.RETURN); - commit.visitMaxs(0, 0); - commit.visitEnd(); - - MethodVisitor run = cw.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null); - run.visitCode(); - if (isStatic) { - run.visitMethodInsn(Opcodes.INVOKESTATIC, className.replace('.', '/'), commitName, "()V", false); - } else { - run.visitVarInsn(Opcodes.ALOAD, 0); - run.visitMethodInsn(Opcodes.INVOKEVIRTUAL, className.replace('.', '/'), commitName, "()V", false); - } - run.visitInsn(Opcodes.RETURN); - run.visitMaxs(0, 0); - run.visitEnd(); - - cw.visitEnd(); - byte[] bytes = cw.toByteArray(); - BytesClassLoader bc = new BytesClassLoader(bytes, className); - Class clazz = bc.loadClass(className); - Constructor cons = clazz.getConstructor(); - - Runnable event = (Runnable) cons.newInstance(); - return event; - } + @Override + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc superClass = ClassDesc.of(superClassName); - private static class BytesClassLoader extends ClassLoader { - private final byte[] bytes; - private final String className; + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> { + if (isRegistered != null) { + classBuilder.with(RuntimeVisibleAnnotationsAttribute.of(Annotation.of(ClassDesc.of("jdk.jfr.Registered"), + AnnotationElement.ofBoolean("value", isRegistered)))); + } - BytesClassLoader(byte[] bytes, String name) { - this.bytes = bytes; - this.className = name; - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (name.equals(className)) { - return defineClass(name, bytes, 0, bytes.length); - } else { - return super.loadClass(name); - } + classBuilder + .withSuperclass(superClass) + .withInterfaceSymbols(cd(Runnable.class)) + .withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .invokespecial(superClass, INIT_NAME, MTD_void) + .return_()) + .withMethodBody(commitName, MTD_void, isStatic ? ACC_PUBLIC_STATIC : ACC_PUBLIC, b -> b + .invokestatic(ClassDesc.of("jdk.jfr.internal.event.EventWriter"), "getEventWriter", + MethodTypeDesc.of(ClassDesc.of("jdk.jfr.internal.event.EventWriter"))) + .pop() + .return_()) + .withMethodBody("run", MTD_void, ACC_PUBLIC, b -> { + if (isStatic) { + b.invokestatic(thisClass, commitName, MTD_void); + } else { + b.aload(0).invokevirtual(thisClass, commitName, MTD_void); + } + b.return_(); + }); + }); + // @formatter:on } } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/InvokeGraal.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/InvokeGraal.java index 0a3540f80b08..a17fa2ad1acf 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/InvokeGraal.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/InvokeGraal.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -83,13 +83,12 @@ public InvokeGraal() { /** * The simplest way to compile a method, using the default behavior for everything. */ - @SuppressWarnings("try") protected InstalledCode compileAndInstallMethod(ResolvedJavaMethod method) { /* Create a unique compilation identifier, visible in IGV. */ CompilationIdentifier compilationId = backend.getCompilationIdentifier(method); OptionValues options = getInitialOptions(); DebugContext debug = new Builder(options).build(); - try (DebugContext.Scope s = debug.scope("compileAndInstallMethod", new DebugDumpScope(String.valueOf(compilationId), true))) { + try (DebugContext.Scope _ = debug.scope("compileAndInstallMethod", new DebugDumpScope(String.valueOf(compilationId), true))) { /* * The graph that is compiled. We leave it empty (no nodes added yet). This means that diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/StaticAnalysis.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/StaticAnalysis.java index c43edd11b766..609b0aa964c7 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/StaticAnalysis.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/core/test/tutorial/StaticAnalysis.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -235,7 +235,6 @@ public TypeFlow getFormalReturn() { } @Override - @SuppressWarnings("try") protected void process() { if (!processed) { /* We want to process a method only once. */ @@ -252,7 +251,7 @@ protected void process() { * Support for graph dumping, IGV uses this information to show the method name of a * graph. */ - try (DebugContext.Scope scope = debug.scope("graph building", graph)) { + try (DebugContext.Scope _ = debug.scope("graph building", graph)) { /* * We want all types to be resolved by the graph builder, i.e., we want classes * referenced by the bytecodes to be loaded and initialized. Since we do not run diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/CompilationAlarmPhaseTimesTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/CompilationAlarmPhaseTimesTest.java index 53cb11b9123f..9d2145e91bc8 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/CompilationAlarmPhaseTimesTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/CompilationAlarmPhaseTimesTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -262,7 +262,6 @@ public void testExplicitly() { } - @SuppressWarnings("try") private static StringBuilder runAndTrack(Runnable r) { // set the timeout very high, we just want to verify toString methods OptionValues opt = new OptionValues(getInitialOptions(), CompilationAlarm.Options.CompilationExpirationPeriod, Double.MAX_VALUE); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/DebugContextTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/DebugContextTest.java index 0d4fa3e2c01d..a878ccfc8a03 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/DebugContextTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/DebugContextTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -38,6 +38,10 @@ import java.util.stream.Collectors; import org.graalvm.collections.EconomicMap; +import org.junit.Assert; +import org.junit.Assume; +import org.junit.Test; + import jdk.graal.compiler.debug.Assertions; import jdk.graal.compiler.debug.CounterKey; import jdk.graal.compiler.debug.DebugCloseable; @@ -53,11 +57,7 @@ import jdk.graal.compiler.options.OptionKey; import jdk.graal.compiler.options.OptionValues; import jdk.graal.compiler.serviceprovider.GraalServices; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.Test; -@SuppressWarnings("try") public class DebugContextTest { static class DebugContextSetup { @@ -92,7 +92,7 @@ public void testDisabledScopes() { OptionValues options = new OptionValues(EconomicMap.create()); DebugContextSetup setup = new DebugContextSetup(); try (DebugContext debug = setup.openDebugContext(options); - DebugContext.Scope d = debug.scope("TestDisabledScoping")) { + DebugContext.Scope _ = debug.scope("TestDisabledScoping")) { for (int level = DebugContext.BASIC_LEVEL; level <= DebugContext.VERY_DETAILED_LEVEL; level++) { debug.dump(level, "an object", "at level %d", level); debug.verify("an object", "at level %d", level); @@ -114,12 +114,12 @@ public void testDumping() { options = new OptionValues(options, DebugOptions.Dump, "Scope" + level + ":" + level); DebugContextSetup setup = new DebugContextSetup(); try (DebugContext debug = setup.openDebugContext(options); - DebugContext.Scope s0 = debug.scope("TestDumping")) { - try (DebugContext.Scope s1 = debug.scope("Scope1")) { - try (DebugContext.Scope s2 = debug.scope("Scope2")) { - try (DebugContext.Scope s3 = debug.scope("Scope3")) { - try (DebugContext.Scope s4 = debug.scope("Scope4")) { - try (DebugContext.Scope s5 = debug.scope("Scope5")) { + DebugContext.Scope _ = debug.scope("TestDumping")) { + try (DebugContext.Scope _ = debug.scope("Scope1")) { + try (DebugContext.Scope _ = debug.scope("Scope2")) { + try (DebugContext.Scope _ = debug.scope("Scope3")) { + try (DebugContext.Scope _ = debug.scope("Scope4")) { + try (DebugContext.Scope _ = debug.scope("Scope5")) { debug.dump(level, "an object", "at level %d", level); } } @@ -142,17 +142,17 @@ public void testLogging() throws IOException { DebugContextSetup setup = new DebugContextSetup(); try (DebugContext debug = setup.openDebugContext(options)) { for (int level = DebugContext.BASIC_LEVEL; level <= DebugContext.VERY_DETAILED_LEVEL; level++) { - try (DebugContext.Scope s0 = debug.scope("TestLogging")) { + try (DebugContext.Scope _ = debug.scope("TestLogging")) { debug.log(level, "log statement at level %d", level); - try (DebugContext.Scope s1 = debug.scope("Level1")) { + try (DebugContext.Scope _ = debug.scope("Level1")) { debug.log(level, "log statement at level %d", level); - try (DebugContext.Scope s2 = debug.scope("Level2")) { + try (DebugContext.Scope _ = debug.scope("Level2")) { debug.log(level, "log statement at level %d", level); - try (DebugContext.Scope s3 = debug.scope("Level3")) { + try (DebugContext.Scope _ = debug.scope("Level3")) { debug.log(level, "log statement at level %d", level); - try (DebugContext.Scope s4 = debug.scope("Level4")) { + try (DebugContext.Scope _ = debug.scope("Level4")) { debug.log(level, "log statement at level %d", level); - try (DebugContext.Scope s5 = debug.scope("Level5")) { + try (DebugContext.Scope _ = debug.scope("Level5")) { debug.log(level, "log statement at level %d", level); } } @@ -177,15 +177,15 @@ public void testContextScope() { options = new OptionValues(options, DebugOptions.Log, ":5"); DebugContextSetup setup = new DebugContextSetup(); try (DebugContext debug = setup.openDebugContext(options)) { - try (DebugContext.Scope s0 = debug.scope("TestLogging")) { - try (DebugContext.Scope s1 = debug.withContext("A")) { + try (DebugContext.Scope _ = debug.scope("TestLogging")) { + try (DebugContext.Scope _ = debug.withContext("A")) { for (Object o : debug.context()) { Assert.assertEquals(o, "A"); } } catch (Throwable t) { throw debug.handle(t); } - try (DebugContext.Scope s1 = debug.withContext("B")) { + try (DebugContext.Scope _ = debug.withContext("B")) { for (Object o : debug.context()) { Assert.assertEquals(o, "B"); } @@ -239,7 +239,7 @@ public void testDisabledSandbox() { Exception e = new Exception("testDisabledSandbox"); try { // Test a disabled sandbox scope - try (DebugContext.Scope d = debug.sandbox("TestExceptionHandling", null)) { + try (DebugContext.Scope _ = debug.sandbox("TestExceptionHandling", null)) { throw e; } catch (Throwable t) { assert e == t; @@ -296,8 +296,8 @@ public void testDisableIntercept() { DebugContext debug = new Builder(options).globalMetrics(NO_GLOBAL_METRIC_VALUES).description(NO_DESCRIPTION).logStream(new PrintStream(baos)).build(); Exception e = new Exception(); try { - try (DebugCloseable disabled = debug.disableIntercept(); Scope s1 = debug.scope("ScopeWithDisabledIntercept")) { - try (Scope s2 = debug.scope("InnerScopeInheritsDisabledIntercept")) { + try (DebugCloseable _ = debug.disableIntercept(); Scope _ = debug.scope("ScopeWithDisabledIntercept")) { + try (Scope _ = debug.scope("InnerScopeInheritsDisabledIntercept")) { throw e; } } catch (Throwable t) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TTYTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TTYTest.java index cbb9dd2c3a25..587f867310b2 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TTYTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TTYTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -30,15 +30,13 @@ public class TTYTest { @Test - @SuppressWarnings("try") public void testTTYFiltered() throws Exception { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { printAll(); } } @Test - @SuppressWarnings("try") public void testTTYNoFilter() { // This test exists to get coverage of the non-filter paths in TTY // so its console output cannot be suppressed. As such, the source diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TimerKeyTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TimerKeyTest.java index 4c126a7deaaa..b9d7e80913fe 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TimerKeyTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/debug/test/TimerKeyTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -41,7 +41,6 @@ import org.junit.Before; import org.junit.Test; -@SuppressWarnings("try") public class TimerKeyTest { @Before @@ -89,15 +88,15 @@ public void test2() { DebugContext debug = new Builder(options, NO_CONFIG_CUSTOMIZERS).build(); TimerKey timerC = DebugContext.timer("TimerC"); - try (DebugCloseable c1 = timerC.start(debug)) { + try (DebugCloseable _ = timerC.start(debug)) { spin(50); - try (DebugCloseable c2 = timerC.start(debug)) { + try (DebugCloseable _ = timerC.start(debug)) { spin(50); - try (DebugCloseable c3 = timerC.start(debug)) { + try (DebugCloseable _ = timerC.start(debug)) { spin(50); - try (DebugCloseable c4 = timerC.start(debug)) { + try (DebugCloseable _ = timerC.start(debug)) { spin(50); - try (DebugCloseable c5 = timerC.start(debug)) { + try (DebugCloseable _ = timerC.start(debug)) { spin(50); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/GraphNodeEventListenerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/GraphNodeEventListenerTest.java index 642e161b90a4..5e44e9e970f7 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/GraphNodeEventListenerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/GraphNodeEventListenerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -63,14 +63,13 @@ private static void resetListenersCalled() { } @Test - @SuppressWarnings("try") public void testAddRemove() { OptionValues options = getOptions(); Graph graph = new Graph(options, getDebug(options)); resetListenersCalled(); - try (NodeEventScope nes0 = graph.trackNodeEvents(new Listener0())) { + try (NodeEventScope _ = graph.trackNodeEvents(new Listener0())) { graph.addWithoutUnique(ConstantNode.forInt(0)); } assert listener0Called; @@ -82,7 +81,6 @@ public void testAddRemove() { } @Test - @SuppressWarnings("try") public void testAddRemoveUnstructured() { OptionValues options = getOptions(); Graph graph = new Graph(options, getDebug(options)); @@ -90,7 +88,7 @@ public void testAddRemoveUnstructured() { resetListenersCalled(); NodeEventScope nes1 = null; - try (NodeEventScope nes0 = graph.trackNodeEvents(new Listener0())) { + try (NodeEventScope _ = graph.trackNodeEvents(new Listener0())) { nes1 = graph.trackNodeEvents(new Listener1()); graph.addWithoutUnique(ConstantNode.forInt(0)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/NodeUsagesTests.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/NodeUsagesTests.java index 292bc81c1229..47a35dcbc72c 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/NodeUsagesTests.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/graph/test/NodeUsagesTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -120,7 +120,7 @@ public void testReplaceAtUsagesWithPredicateAll() { assertThat(def0.usages(), NodeIterableIsEmpty.isNotEmpty()); assertThat(def1.usages(), NodeIterableIsEmpty.isEmpty()); - def0.replaceAtMatchingUsages(def1, u -> true); + def0.replaceAtMatchingUsages(def1, _ -> true); assertThat(def0.usages(), NodeIterableIsEmpty.isEmpty()); @@ -150,7 +150,7 @@ public void testReplaceAtUsagesWithPredicateNone() { assertThat(def0.usages(), NodeIterableIsEmpty.isNotEmpty()); assertThat(def1.usages(), NodeIterableIsEmpty.isEmpty()); - def0.replaceAtMatchingUsages(def1, u -> false); + def0.replaceAtMatchingUsages(def1, _ -> false); assertThat(def1.usages(), NodeIterableIsEmpty.isEmpty()); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/amd64/test/CompressedNullCheckTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/amd64/test/CompressedNullCheckTest.java index 4ab718b3bcb5..cc3a1a44357b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/amd64/test/CompressedNullCheckTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/amd64/test/CompressedNullCheckTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -46,7 +46,6 @@ public static void testSnippet(Container c) { c.i.intValue(); } - @SuppressWarnings("try") private void testImplicit(Integer i) { Assume.assumeTrue(runtime().getVMConfig().useCompressedOops); @@ -64,7 +63,6 @@ private void testImplicit(Integer i) { assertEquals(expect, actual); } - @SuppressWarnings("try") private void testExplicit(Integer i) { Assume.assumeTrue(runtime().getVMConfig().useCompressedOops); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CheckGraalIntrinsics.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CheckGraalIntrinsics.java index 89d5f1670f4c..13bdf327b361 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CheckGraalIntrinsics.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CheckGraalIntrinsics.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -145,7 +145,6 @@ public interface Refiner { public final UnimplementedGraalIntrinsics unimplementedGraalIntrinsics = new UnimplementedGraalIntrinsics(rt.getTarget().arch); @Test - @SuppressWarnings("try") public void test() throws ClassNotFoundException, NoSuchFieldException { HotSpotProviders providers = rt.getHostBackend().getProviders(); Plugins graphBuilderPlugins = providers.getGraphBuilderPlugins(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ClassSubstitutionsTests.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ClassSubstitutionsTests.java index cd4aec58b954..84dc6095a209 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ClassSubstitutionsTests.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ClassSubstitutionsTests.java @@ -58,10 +58,9 @@ public class ClassSubstitutionsTests extends GraalCompilerTest { public String[] stringArrayField; - @SuppressWarnings("try") protected StructuredGraph test(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("ClassSubstitutionsTest", getMetaAccess().lookupJavaMethod(getMethod(snippet)))) { + try (DebugContext.Scope _ = debug.scope("ClassSubstitutionsTest", getMetaAccess().lookupJavaMethod(getMethod(snippet)))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES, debug); compile(graph.method(), graph); assertNotInGraph(graph, Invoke.class); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompilationWrapperTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompilationWrapperTest.java index 180d06642a9e..4e87e34b450a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompilationWrapperTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompilationWrapperTest.java @@ -44,7 +44,6 @@ import java.util.zip.ZipFile; import org.junit.Assert; -import org.junit.Assume; import org.junit.Test; import jdk.graal.compiler.core.GraalCompilerOptions; @@ -63,7 +62,6 @@ public class CompilationWrapperTest extends GraalCompilerTest { */ @Test public void testVMCompilation1() throws IOException, InterruptedException { - assumeNotImpactedByJDK8316453(); assumeManagementLibraryIsLoadable(); testHelper(Collections.emptyList(), Arrays.asList("-XX:-TieredCompilation", "-XX:+UseJVMCICompiler", @@ -76,15 +74,6 @@ public void testVMCompilation1() throws IOException, InterruptedException { TestProgram.class.getName())); } - /** - * Assumes the current JDK does not contain the bug resolved by JDK-8316453. - */ - private static void assumeNotImpactedByJDK8316453() { - Runtime.Version version = Runtime.version(); - Runtime.Version jdk8316453 = Runtime.Version.parse("22+17"); - Assume.assumeTrue("-Xcomp broken", version.feature() < 22 || version.compareTo(jdk8316453) >= 0); - } - public static class Probe { final String substring; final int minOccurrences; @@ -162,7 +151,6 @@ public String test() { */ @Test public void testVMCompilation3() throws IOException, InterruptedException { - assumeNotImpactedByJDK8316453(); assumeManagementLibraryIsLoadable(); final int maxProblems = 2; Probe failurePatternProbe = new Probe("[[[Graal compilation failure]]]", 1, maxProblems); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorld.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorld.java index aa1396a27193..587f36aed784 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorld.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorld.java @@ -534,7 +534,7 @@ public List getClassNames() throws IOException { FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), Collections.emptyMap()); Path top = fs.getPath("/modules/"); Files.find(top, Integer.MAX_VALUE, - (path, attrs) -> attrs.isRegularFile()).forEach(p -> { + (_, attrs) -> attrs.isRegularFile()).forEach(p -> { int nameCount = p.getNameCount(); if (nameCount > 2) { String base = p.getName(nameCount - 1).toString(); @@ -971,7 +971,6 @@ protected void handleFailure(HotSpotCompilationRequestResult result) { * Prepares a compilation of the methods in the classes in {@link #inputClassPath}. If * {@link #inputClassPath} equals {@link #SUN_BOOT_CLASS_PATH} the boot classes are used. */ - @SuppressWarnings("try") public List prepare() throws IOException { String classPath = SUN_BOOT_CLASS_PATH.equals(inputClassPath) ? JRT_CLASS_PATH_ENTRY : inputClassPath; final String[] entries = getEntries(classPath); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorldTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorldTest.java index 3a92f22b66a3..9e19c78909af 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorldTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/CompileTheWorldTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -43,7 +43,6 @@ */ public class CompileTheWorldTest extends GraalCompilerTest { - @SuppressWarnings("try") @Test public void testJDK() throws Throwable { boolean originalBailoutAction = CompilationBailoutAsFailure.getValue(getInitialOptions()); @@ -60,7 +59,7 @@ public void testJDK() throws Throwable { String excludeMethodFilters = null; String scratchDir = ""; boolean verbose = false; - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { CompileTheWorld ctw = new CompileTheWorld(runtime, (HotSpotGraalCompiler) runtime.getCompiler(), CompileTheWorld.SUN_BOOT_CLASS_PATH, diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/DeferredBarrierAdditionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/DeferredBarrierAdditionTest.java index aa3465d0d477..485ec39853f5 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/DeferredBarrierAdditionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/DeferredBarrierAdditionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -83,11 +83,10 @@ public void testGroupAllocation() throws Exception { testHelper("testCrossReferences", 1, getInitialOptions()); } - @SuppressWarnings("try") protected void testHelper(final String snippetName, final int expectedBarriers, OptionValues options) { ResolvedJavaMethod snippet = getResolvedJavaMethod(snippetName); DebugContext debug = getDebugContext(options, null, snippet); - try (DebugContext.Scope s = debug.scope("WriteBarrierAdditionTest", snippet)) { + try (DebugContext.Scope _ = debug.scope("WriteBarrierAdditionTest", snippet)) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.NO, debug); HighTierContext highContext = getDefaultHighTierContext(); MidTierContext midContext = new MidTierContext(getProviders(), getTargetProvider(), OptimisticOptimizations.ALL, graph.getProfilingInfo()); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRLockTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRLockTest.java index df3cf139613c..6669a82ffcff 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRLockTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRLockTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -176,7 +176,6 @@ private static void afterOSRLockTest() { } // @Test - @SuppressWarnings("try") public void testLockOSROuterImmediateDeoptAfter() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockDeopt()); @@ -210,7 +209,6 @@ public synchronized ReturnValue synchronizedSnippet() { } @Test - @SuppressWarnings("try") public void testSynchronizedSnippet() { GraalOSRLockTest instance = new GraalOSRLockTest(); // enough entries to trigger OSR @@ -222,7 +220,6 @@ public void testSynchronizedSnippet() { } @Test - @SuppressWarnings("try") public void testOSRTrivialLoop() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockDeopt()); @@ -235,7 +232,6 @@ public void testOSRTrivialLoop() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerImmediateDeoptAfter() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockDeopt()); @@ -244,7 +240,6 @@ public void testLockOSROuterInnerImmediateDeoptAfter() { } @Test - @SuppressWarnings("try") public void testLockOSROuterCompileRestOfMethod() { run(() -> { EconomicMap, Object> overrides = osrLockNoDeopt(); @@ -255,7 +250,6 @@ public void testLockOSROuterCompileRestOfMethod() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerCompileRestOfMethod() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockNoDeopt()); @@ -264,7 +258,6 @@ public void testLockOSROuterInnerCompileRestOfMethod() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerLockDepthCompileRestOfMethod() { run(() -> { EconomicMap, Object> overrides = osrLockNoDeopt(); @@ -275,7 +268,6 @@ public void testLockOSROuterInnerLockDepthCompileRestOfMethod() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerLockDepthDeopt() { run(() -> { EconomicMap, Object> overrides = osrLockNoDeopt(); @@ -286,7 +278,6 @@ public void testLockOSROuterInnerLockDepthDeopt() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerLockDepthRecursiveCompileRestOfMethod0() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockNoDeopt()); @@ -295,7 +286,6 @@ public void testLockOSROuterInnerLockDepthRecursiveCompileRestOfMethod0() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerLockDepthRecursiveCompileRestOfMethod1() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockNoDeopt()); @@ -304,7 +294,6 @@ public void testLockOSROuterInnerLockDepthRecursiveCompileRestOfMethod1() { } @Test - @SuppressWarnings("try") public void testLockOSROuterCompileRestOfMethodSubsequentLock() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockNoDeopt()); @@ -313,7 +302,6 @@ public void testLockOSROuterCompileRestOfMethodSubsequentLock() { } @Test - @SuppressWarnings("try") public void testLockOSROuterInnerSameLockCompileRestOfMethod() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockNoDeopt()); @@ -322,7 +310,6 @@ public void testLockOSROuterInnerSameLockCompileRestOfMethod() { } @Test - @SuppressWarnings("try") public void testOuterLockDeoptDoesNotFloatAboveMonitor() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockNoDeopt()); @@ -331,7 +318,6 @@ public void testOuterLockDeoptDoesNotFloatAboveMonitor() { } @Test - @SuppressWarnings("try") public void testLockOSRRecursive() { run(() -> { // call it @@ -350,7 +336,6 @@ public void testLockOSRRecursive() { } @Test - @SuppressWarnings("try") public void testLockOSRRecursiveLeafOSR() { run(() -> { testRecursiveRootNoOSR(); @@ -731,7 +716,6 @@ public static ReturnValue testOuterLockOptimizeToDeopt() { } @Test - @SuppressWarnings("try") public void testLocksAtOSREntry() { run(() -> { OptionValues options = new OptionValues(getInitialOptions(), osrLockDeopt()); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRTest.java index 85aa4a63b657..588086124e98 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/GraalOSRTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -264,7 +264,7 @@ public Object visitFrame(InspectedFrame frame) { */ private static String normalizedDisassembly(String dis) { Pattern cpRef = Pattern.compile("#\\d+"); - return Stream.of(dis.split("\n")).map(line -> cpRef.matcher(line.trim()).replaceAll(mr -> "#__")).collect(Collectors.joining(System.lineSeparator())); + return Stream.of(dis.split("\n")).map(line -> cpRef.matcher(line.trim()).replaceAll(_ -> "#__")).collect(Collectors.joining(System.lineSeparator())); } private static final int ArrayLength = 10000; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotDeoptPostExceptions.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotDeoptPostExceptions.java index 13b22c56fd22..a7d4cbc71d36 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotDeoptPostExceptions.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotDeoptPostExceptions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -45,7 +45,6 @@ public class HotSpotDeoptPostExceptions extends GraalCompilerTest { @Override - @SuppressWarnings("try") protected Suites createSuites(OptionValues options) { return super.createSuites(new OptionValues(options, HighTier.Options.Inline, false)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotLoopOverflowSpeculationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotLoopOverflowSpeculationTest.java index 29d4c8e991ae..53190c3ef084 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotLoopOverflowSpeculationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotLoopOverflowSpeculationTest.java @@ -28,8 +28,6 @@ import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assume; -import org.junit.Before; import org.junit.Test; import jdk.graal.compiler.api.directives.GraalDirectives; @@ -56,11 +54,6 @@ */ public class HotSpotLoopOverflowSpeculationTest extends GraalCompilerTest { - @Before - public void checkJDKVersion() { - Assume.assumeTrue("inconsistent speculation log fixed in 23+5", Runtime.version().compareToIgnoreOptional(Runtime.Version.parse("23+5")) >= 0); - } - public static final boolean LOG_STDOUT = false; // Snippet with a loop that can easily overflow diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotStackIntrospectionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotStackIntrospectionTest.java index 6991779750e5..49f42ac5e9d7 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotStackIntrospectionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/HotSpotStackIntrospectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -88,7 +88,7 @@ public void runSynchronized() throws InvalidInstalledCodeException { private void test(String name) throws InvalidInstalledCodeException { ResolvedJavaMethod method = getMetaAccess().lookupJavaMethod(getMethod(name)); - Function f = o -> { + Function f = _ -> { stackIntrospection.iterateFrames(null, null, 0, frame -> { if (frame.getMethod().equals(method)) { frame.materializeVirtualObjects(true); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/JVMCIInfopointErrorTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/JVMCIInfopointErrorTest.java index 4f5d3d63909f..5976d66f24a2 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/JVMCIInfopointErrorTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/JVMCIInfopointErrorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -32,10 +32,12 @@ import java.util.function.Consumer; +import org.junit.Test; + import jdk.graal.compiler.code.CompilationResult; -import jdk.graal.compiler.core.test.GraalCompilerTest; import jdk.graal.compiler.core.common.LIRKind; import jdk.graal.compiler.core.common.type.StampFactory; +import jdk.graal.compiler.core.test.GraalCompilerTest; import jdk.graal.compiler.debug.DebugContext; import jdk.graal.compiler.debug.DebugContext.Builder; import jdk.graal.compiler.debug.DebugContext.Scope; @@ -54,8 +56,6 @@ import jdk.graal.compiler.nodes.spi.LIRLowerable; import jdk.graal.compiler.nodes.spi.NodeLIRBuilderTool; import jdk.graal.compiler.options.OptionValues; -import org.junit.Test; - import jdk.vm.ci.code.BytecodeFrame; import jdk.vm.ci.code.CodeCacheProvider; import jdk.vm.ci.code.VirtualObject; @@ -203,7 +203,7 @@ private static LIRFrameState modifyTopFrame(LIRFrameState state, VirtualObject[] @Test(expected = JVMCIError.class) public void testUnexpectedScopeValuesLength() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{JavaConstant.FALSE}, new JavaKind[0], 0, 0, 0); safepoint.accept(newState); }); @@ -211,7 +211,7 @@ public void testUnexpectedScopeValuesLength() { @Test(expected = JVMCIError.class) public void testUnexpectedScopeSlotKindsLength() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[0], new JavaKind[]{JavaKind.Boolean}, 0, 0, 0); safepoint.accept(newState); }); @@ -219,7 +219,7 @@ public void testUnexpectedScopeSlotKindsLength() { @Test(expected = JVMCIError.class) public void testWrongMonitorType() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{JavaConstant.INT_0}, new JavaKind[]{}, 0, 0, 1); safepoint.accept(newState); }); @@ -227,7 +227,7 @@ public void testWrongMonitorType() { @Test(expected = JVMCIError.class) public void testUnexpectedIllegalValue() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{Value.ILLEGAL}, new JavaKind[]{JavaKind.Int}, 1, 0, 0); safepoint.accept(newState); }); @@ -245,7 +245,7 @@ public void testUnexpectedTypeInRegister() { @Test(expected = JVMCIError.class) public void testWrongConstantType() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{JavaConstant.INT_0}, new JavaKind[]{JavaKind.Object}, 1, 0, 0); safepoint.accept(newState); }); @@ -253,7 +253,7 @@ public void testWrongConstantType() { @Test(expected = JVMCIError.class) public void testUnsupportedConstantType() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{JavaConstant.forShort((short) 0)}, new JavaKind[]{JavaKind.Short}, 1, 0, 0); safepoint.accept(newState); }); @@ -261,7 +261,7 @@ public void testUnsupportedConstantType() { @Test(expected = JVMCIError.class) public void testUnexpectedNull() { - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{JavaConstant.NULL_POINTER}, new JavaKind[]{JavaKind.Int}, 1, 0, 0); safepoint.accept(newState); }); @@ -270,7 +270,7 @@ public void testUnexpectedNull() { @Test(expected = JVMCIError.class) public void testUnexpectedObject() { JavaValue wrapped = getSnippetReflection().forObject(this); - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{wrapped}, new JavaKind[]{JavaKind.Int}, 1, 0, 0); safepoint.accept(newState); }); @@ -279,16 +279,15 @@ public void testUnexpectedObject() { private static final class UnknownJavaValue implements JavaValue { } - @SuppressWarnings("try") @Test(expected = Error.class) public void testUnknownJavaValue() { DebugContext debug = new Builder(getInitialOptions()).build(); - try (Scope s = debug.disable()) { + try (Scope _ = debug.disable()) { /* * Expected: either AssertionError or GraalError, depending on whether the unit test run * is with assertions enabled or disabled. */ - test(debug, (tool, state, safepoint) -> { + test(debug, (_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{new UnknownJavaValue()}, new JavaKind[]{JavaKind.Int}, 1, 0, 0); safepoint.accept(newState); }); @@ -301,7 +300,7 @@ public void testMissingIllegalAfterDouble() { * Expected: either AssertionError or GraalError, depending on whether the unit test run is * with assertions enabled or disabled. */ - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { LIRFrameState newState = modifyTopFrame(state, new JavaValue[]{JavaConstant.DOUBLE_0, JavaConstant.INT_0}, new JavaKind[]{JavaKind.Double, JavaKind.Int}, 2, 0, 0); safepoint.accept(newState); }); @@ -310,7 +309,7 @@ public void testMissingIllegalAfterDouble() { @Test(expected = JVMCIError.class) public void testInvalidVirtualObjectId() { ResolvedJavaType obj = getMetaAccess().lookupJavaType(Object.class); - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { VirtualObject o = VirtualObject.get(obj, 5); o.setValues(new JavaValue[0], new JavaKind[0]); @@ -321,7 +320,7 @@ public void testInvalidVirtualObjectId() { @Test(expected = JVMCIError.class) public void testDuplicateVirtualObject() { ResolvedJavaType obj = getMetaAccess().lookupJavaType(Object.class); - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { VirtualObject o1 = VirtualObject.get(obj, 0); o1.setValues(new JavaValue[0], new JavaKind[0]); @@ -335,7 +334,7 @@ public void testDuplicateVirtualObject() { @Test(expected = JVMCIError.class) public void testUnexpectedVirtualObject() { ResolvedJavaType obj = getMetaAccess().lookupJavaType(Object.class); - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { VirtualObject o = VirtualObject.get(obj, 0); o.setValues(new JavaValue[0], new JavaKind[0]); @@ -347,7 +346,7 @@ public void testUnexpectedVirtualObject() { @Test(expected = JVMCIError.class) public void testUndefinedVirtualObject() { ResolvedJavaType obj = getMetaAccess().lookupJavaType(Object.class); - test((tool, state, safepoint) -> { + test((_, state, safepoint) -> { VirtualObject o0 = VirtualObject.get(obj, 0); o0.setValues(new JavaValue[0], new JavaKind[0]); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LambdaStableNameTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LambdaStableNameTest.java index 827493c0f366..5dc2c684d315 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LambdaStableNameTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LambdaStableNameTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -33,7 +33,6 @@ import java.math.BigInteger; import org.junit.Test; -import org.objectweb.asm.Type; import jdk.graal.compiler.java.LambdaUtils; import jdk.vm.ci.meta.ResolvedJavaType; @@ -54,7 +53,7 @@ public void checkStableLamdaNameForRunnableAndAutoCloseable() { String acName = LambdaUtils.findStableLambdaName(acType); assertEquals("Both stable lambda names are the same as they reference the same method", name, acName); - String myName = Type.getInternalName(getClass()); + String myName = getClass().getName().replace('.', '/'); assertEquals("The name known in 24.0 version is computed", "L" + myName + "$$Lambda.0x605511206480068bfd9e0bafd4f79e22;", name); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java index 3d36bbb9deb5..a232a3b70ae2 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilationDriver.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -655,7 +655,6 @@ protected CompilationResult compileWithJarGraal(Compilation compilation, OptionV /** * Compiles all the given methods, using libgraal if available. */ - @SuppressWarnings("try") public void compileAll(List compilations, OptionValues options) { try (LibGraalParams libgraal = LibGraal.isAvailable() ? new LibGraalParams(options) : null) { compileAll(libgraal, compilations, options); @@ -738,7 +737,6 @@ private void compileAndRecord(Compilation task, LibGraalParams libgraal, OptionV /** * Compiles all methods in {@code compilations} sequentially on one thread. */ - @SuppressWarnings("try") private Map compileAllSingleThreaded( LibGraalParams libgraal, List compilations, OptionValues options, AtomicLong compileTime, AtomicLong memoryUsed, AtomicLong codeSize) { @@ -747,7 +745,7 @@ private Map compileAllSingleThreaded( long intervalStart = System.currentTimeMillis(); long lastCompletedTaskCount = 0; long completedTaskCount = 0; - try (LibGraalScope scope = libgraal == null ? null : new LibGraalScope()) { + try (LibGraalScope _ = libgraal == null ? null : new LibGraalScope()) { for (Compilation task : compilations) { compileAndRecord(task, libgraal, options, compileTime, memoryUsed, codeSize, results); completedTaskCount++; @@ -775,11 +773,10 @@ static final class GraalCompileThread extends Thread { setDaemon(true); } - @SuppressWarnings("try") @Override public void run() { setContextClassLoader(getClass().getClassLoader()); - try (LibGraalScope scope = libgraal == null ? null : new LibGraalScope()) { + try (LibGraalScope _ = libgraal == null ? null : new LibGraalScope()) { super.run(); } } @@ -851,7 +848,7 @@ private void armPrintMetrics() { */ private boolean shouldPrintMetrics(LibGraalIsolate isolate) { synchronized (printMetrics) { - return printMetrics.computeIfAbsent(isolate.getId(), id -> new AtomicBoolean()).getAndSet(false); + return printMetrics.computeIfAbsent(isolate.getId(), _ -> new AtomicBoolean()).getAndSet(false); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java index 89d7aa53fe26..edbd2fb089e0 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/LibGraalCompilerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -78,13 +78,12 @@ public static native long hashConstantOopFields(long isolateThreadAddress, int oopsPerIteration, boolean verbose); - @SuppressWarnings("try") @Test public void testHashConstantFields() throws ClassNotFoundException { Assume.assumeTrue(LibGraal.isAvailable()); Class cls = CLASS_NAME != null ? Class.forName(CLASS_NAME) : getClass(); ResolvedJavaType type = getMetaAccess().lookupJavaType(cls); - try (LibGraalScope scope = new LibGraalScope()) { + try (LibGraalScope _ = new LibGraalScope()) { long isolateThread = LibGraalScope.getIsolateThread(); for (boolean useScope : new boolean[]{true, false}) { long hash = hashConstantOopFields(isolateThread, diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/MemoryUsageBenchmark.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/MemoryUsageBenchmark.java index 16b427a43b67..a90a528bf92b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/MemoryUsageBenchmark.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/MemoryUsageBenchmark.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -33,7 +33,6 @@ import jdk.graal.compiler.hotspot.HotSpotGraalCompiler; import jdk.graal.compiler.nodes.StructuredGraph.AllowAssumptions; import jdk.graal.compiler.options.OptionValues; - import jdk.vm.ci.hotspot.HotSpotCompilationRequest; import jdk.vm.ci.hotspot.HotSpotJVMCIRuntime; import jdk.vm.ci.hotspot.HotSpotResolvedJavaMethod; @@ -125,7 +124,6 @@ public static void main(String[] args) { new MemoryUsageBenchmark().run(); } - @SuppressWarnings("try") private void doCompilation(String methodName, String label) { HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) getResolvedJavaMethod(methodName); @@ -134,7 +132,7 @@ private void doCompilation(String methodName, String label) { long jvmciEnv = 0L; - try (MemoryUsageCloseable c = label == null ? null : new MemoryUsageCloseable(label)) { + try (MemoryUsageCloseable _ = label == null ? null : new MemoryUsageCloseable(label)) { HotSpotJVMCIRuntime runtime = HotSpotJVMCIRuntime.runtime(); int entryBCI = JVMCICompiler.INVOCATION_ENTRY_BCI; HotSpotCompilationRequest request = new HotSpotCompilationRequest(method, entryBCI, jvmciEnv); @@ -143,7 +141,6 @@ private void doCompilation(String methodName, String label) { } } - @SuppressWarnings("try") private void allocSpyCompilation(String methodName) { if (AllocSpy.isEnabled()) { HotSpotResolvedJavaMethod method = (HotSpotResolvedJavaMethod) getResolvedJavaMethod(methodName); @@ -152,7 +149,7 @@ private void allocSpyCompilation(String methodName) { method.reprofile(); long jvmciEnv = 0L; - try (AllocSpy as = AllocSpy.open(methodName)) { + try (AllocSpy _ = AllocSpy.open(methodName)) { HotSpotJVMCIRuntime runtime = HotSpotJVMCIRuntime.runtime(); HotSpotCompilationRequest request = new HotSpotCompilationRequest(method, JVMCICompiler.INVOCATION_ENTRY_BCI, jvmciEnv); HotSpotGraalCompiler compiler = (HotSpotGraalCompiler) runtime.getCompiler(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ProfileReplayTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ProfileReplayTest.java index f5a67b89a5d6..d2d8d8c85b9b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ProfileReplayTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/ProfileReplayTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -92,7 +92,6 @@ static int foo(int bar, int baz, A a) { } } - @SuppressWarnings("try") @Test public void testProfileReplay() throws IOException { HotSpotJVMCIRuntime jvmciRuntime = HotSpotJVMCIRuntime.runtime(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SafeConstructionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SafeConstructionTest.java index 8991482e8b5d..cc7a8846691c 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SafeConstructionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SafeConstructionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -24,20 +24,28 @@ */ package jdk.graal.compiler.hotspot.test; +import static java.lang.classfile.ClassFile.ACC_PRIVATE; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.CD_short; +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + import java.io.IOException; +import java.lang.classfile.Annotation; +import java.lang.classfile.ClassFile; +import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.lang.invoke.MethodHandles; -import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.util.List; import org.junit.Assert; import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; - -import com.oracle.truffle.api.impl.asm.Opcodes; +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; import jdk.graal.compiler.core.test.SubprocessTest; import jdk.graal.compiler.nodes.StructuredGraph; import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration; @@ -53,7 +61,7 @@ * -XX:+AlwaysSafeConstructors is specified. */ @AddExports("java.base/jdk.internal.vm.annotation") -public class SafeConstructionTest extends SubprocessTest { +public class SafeConstructionTest extends SubprocessTest implements CustomizedBytecodePattern { static class TestClass { int a; @@ -96,7 +104,7 @@ public void runCheckStableWriteConstructors() throws IOException, InterruptedExc private void checkStableWriteConstructors() { try { - Class clazz = generatePrivilegedTestClass(); + Class clazz = lookupClass(MethodHandles.privateLookupIn(String.class, MethodHandles.lookup()), "java.lang.TestClass"); List> constructors = List.of(clazz.getConstructor(), clazz.getConstructor(int.class), clazz.getConstructor(short.class)); List> constructorsWithStableWrite = List.of(clazz.getConstructor(int.class), clazz.getConstructor(short.class)); @@ -110,56 +118,33 @@ private void checkStableWriteConstructors() { } } - /** - * This generates TestClass but in privileged location, allowing @Stable to be effective. - */ - private static Class generatePrivilegedTestClass() throws IllegalAccessException { - String clazzInternalName = "java/lang/TestClass"; - String init = ""; - String aName = "a"; - String bName = "b"; - String intTypeDesc = int.class.descriptorString(); - - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); - cw.visit(Opcodes.V21, Opcodes.ACC_PUBLIC, clazzInternalName, null, "java/lang/Object", null); - MethodVisitor mv; - cw.visitField(Opcodes.ACC_PRIVATE, aName, intTypeDesc, null, null); - FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE, bName, intTypeDesc, null, null); - fv.visitAnnotation(Stable.class.descriptorString(), true); - - mv = cw.visitMethod(Opcodes.ACC_PUBLIC, init, MethodType.methodType(void.class).descriptorString(), null, null); - mv.visitCode(); - mv.visitIntInsn(Opcodes.ALOAD, 0); - mv.visitInsn(Opcodes.ICONST_4); - mv.visitFieldInsn(Opcodes.PUTFIELD, clazzInternalName, aName, intTypeDesc); - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - - mv = cw.visitMethod(Opcodes.ACC_PUBLIC, init, MethodType.methodType(void.class, int.class).descriptorString(), null, null); - mv.visitCode(); - mv.visitIntInsn(Opcodes.ALOAD, 0); - mv.visitIntInsn(Opcodes.ILOAD, 1); - mv.visitFieldInsn(Opcodes.PUTFIELD, clazzInternalName, bName, intTypeDesc); - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - - mv = cw.visitMethod(Opcodes.ACC_PUBLIC, init, MethodType.methodType(void.class, short.class).descriptorString(), null, null); - mv.visitCode(); - mv.visitIntInsn(Opcodes.ALOAD, 0); - mv.visitInsn(Opcodes.DUP); - mv.visitInsn(Opcodes.ICONST_0); - mv.visitFieldInsn(Opcodes.PUTFIELD, clazzInternalName, bName, intTypeDesc); - mv.visitIntInsn(Opcodes.ILOAD, 1); - mv.visitFieldInsn(Opcodes.PUTFIELD, clazzInternalName, aName, intTypeDesc); - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(0, 0); - mv.visitEnd(); - - cw.visitEnd(); - - MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(String.class, MethodHandles.lookup()); - return lookup.defineClass(cw.toByteArray()); + @Override + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField("a", CD_int, ACC_PRIVATE) + .withField("b", CD_int, fieldBuilder -> fieldBuilder + .withFlags(ACC_PRIVATE) + .with(RuntimeVisibleAnnotationsAttribute.of(Annotation.of(ClassDesc.of("jdk.internal.vm.annotation.Stable"))))) + .withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .iconst_4() + .putfield(thisClass, "a", CD_int) + .return_()) + .withMethodBody(INIT_NAME, MethodTypeDesc.of(CD_void, CD_int), ACC_PUBLIC, b -> b + .aload(0) + .iload(1) + .putfield(thisClass, "b", CD_int) + .return_()) + .withMethodBody(INIT_NAME, MethodTypeDesc.of(CD_void, CD_short), ACC_PUBLIC, b -> b + .aload(0) + .dup() + .iconst_0() + .putfield(thisClass, "b", CD_int) + .iload(1) + .putfield(thisClass, "a", CD_int) + .return_())); + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SharedExceptionHandlerLoopTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SharedExceptionHandlerLoopTest.java index b9d3d0255d2f..e62340a0be7f 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SharedExceptionHandlerLoopTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/SharedExceptionHandlerLoopTest.java @@ -32,7 +32,8 @@ import org.junit.Test; -import jdk.graal.compiler.core.test.CustomizedBytecodePatternTest; +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; +import jdk.graal.compiler.core.test.GraalCompilerTest; import jdk.vm.ci.meta.ResolvedJavaMethod; /** @@ -41,7 +42,7 @@ * Java code, but the Kotlin compiler can produce such patterns when compiling coroutines. See * {@link #generateClass} for the Java source code from which the modified bytecode is derived. */ -public class SharedExceptionHandlerLoopTest extends CustomizedBytecodePatternTest { +public class SharedExceptionHandlerLoopTest extends GraalCompilerTest implements CustomizedBytecodePattern { @Test public void test() throws ClassNotFoundException { @@ -114,13 +115,13 @@ public String toString() { * */ @Override - protected byte[] generateClass(String internalClassName) { + public byte[] generateClass(String internalClassName) { MethodTypeDesc getMethodTypeDesc = MethodTypeDesc.of(ConstantDescs.CD_Object, ConstantDescs.CD_Object, ConstantDescs.CD_Object); ClassDesc thisClass = ClassDesc.of(internalClassName.replace('/', '.')); return ClassFile.of().build(thisClass, classBuilder -> classBuilder // @formatter:off - .withMethod("testMethod", getMethodTypeDesc, ACC_PUBLIC | ACC_STATIC, methodBuilder -> methodBuilder.withCode(codeBuilder -> { + .withMethod("testMethod", getMethodTypeDesc, ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder.withCode(codeBuilder -> { Label start = codeBuilder.newLabel(); Label loopExcEnd = codeBuilder.newLabel(); Label loopNPEHandler = codeBuilder.newLabel(); @@ -160,8 +161,4 @@ protected byte[] generateClass(String internalClassName) { }))); // @formatter:on } - - public static ClassDesc cd(Class klass) { - return klass.describeConstable().orElseThrow(); - } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestDoNotMoveAllocationIntrinsic.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestDoNotMoveAllocationIntrinsic.java index 9087448ccf0a..990ea09b053b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestDoNotMoveAllocationIntrinsic.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestDoNotMoveAllocationIntrinsic.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -73,9 +73,8 @@ protected CompilationResult compile(ResolvedJavaMethod installedCodeOwner, Struc } @Test - @SuppressWarnings("try") public void test02Local() throws Exception { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { try { compile("snippet02Local"); Assert.fail("Compilation should fail because the parameter is not a freshly allocated object"); @@ -93,9 +92,8 @@ public static void snippet03() { } @Test - @SuppressWarnings("try") public void test03() throws Exception { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { try { compile("snippet03"); Assert.fail("Compilation should fail because there is code between the allocation and the actual usage of ensureAllocatedHere"); @@ -110,9 +108,8 @@ public static void snippet04(Object o) { } @Test - @SuppressWarnings("try") public void test04() throws Exception { - try (AutoCloseable c = new TTY.Filter()) { + try (AutoCloseable _ = new TTY.Filter()) { try { compile("snippet04"); Assert.fail("Compilation should fail because ensureAllocatedHere is used with an input that is not an allocation."); @@ -127,7 +124,6 @@ public static void snippet05() { } @Test - @SuppressWarnings("try") public void test05() throws Exception { compile("snippet05"); } @@ -141,7 +137,6 @@ public static void snippet06() { } @Test - @SuppressWarnings("try") public void test06() throws Exception { compile("snippet06"); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestIntrinsicCompiles.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestIntrinsicCompiles.java index c4b9cf79b85e..daaa85f5d5fb 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestIntrinsicCompiles.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/hotspot/test/TestIntrinsicCompiles.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -55,7 +55,6 @@ public class TestIntrinsicCompiles extends HotSpotGraalCompilerTest { @Test - @SuppressWarnings("try") public void test() throws ClassNotFoundException { HotSpotGraalRuntimeProvider rt = (HotSpotGraalRuntimeProvider) Graal.getRequiredCapability(RuntimeProvider.class); HotSpotProviders providers = rt.getHostBackend().getProviders(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/ConstantPhiTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/ConstantPhiTest.java index 677bf7e4c75d..4a32a0c89e2f 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/ConstantPhiTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/ConstantPhiTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -57,19 +57,16 @@ public static void destroyCallerSavedValues0() { } @Test - @SuppressWarnings("try") public void run0() { runTest(new OptionValues(getInitialOptions(), MaximumInliningSize, -1), "test", 0, 0xDEADDEAD); } @Test - @SuppressWarnings("try") public void run1() { runTest(new OptionValues(getInitialOptions(), MaximumInliningSize, -1), "test", -1, 0xDEADDEAD); } @Test - @SuppressWarnings("try") public void run2() { runTest(new OptionValues(getInitialOptions(), MaximumInliningSize, -1), "test", 1, 0xDEADDEAD); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/LargeConstantSectionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/LargeConstantSectionTest.java index 5077c4c7783f..53b78619f6f1 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/LargeConstantSectionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/backend/LargeConstantSectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -24,34 +24,26 @@ */ package jdk.graal.compiler.jtt.backend; -import static org.objectweb.asm.Opcodes.ACC_FINAL; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_STATIC; -import static org.objectweb.asm.Opcodes.ACC_SUPER; -import static org.objectweb.asm.Opcodes.ILOAD; -import static org.objectweb.asm.Opcodes.LRETURN; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.CD_long; -import java.lang.reflect.Method; +import java.lang.classfile.ClassFile; +import java.lang.classfile.Label; +import java.lang.classfile.instruction.SwitchCase; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import jdk.graal.compiler.debug.GraalError; -import jdk.graal.compiler.jtt.JTTTest; -import jdk.graal.compiler.api.test.ExportingClassLoader; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import jdk.vm.ci.meta.ResolvedJavaMethod; -import junit.framework.AssertionFailedError; +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; +import jdk.graal.compiler.jtt.JTTTest; /** * This test let the compiler deal with a large amount of constant data in a method. This data is @@ -79,10 +71,9 @@ * */ @RunWith(Parameterized.class) -public class LargeConstantSectionTest extends JTTTest { +public class LargeConstantSectionTest extends JTTTest implements CustomizedBytecodePattern { private static final String NAME = "LargeConstantSection"; private static final long LARGE_CONSTANT = 0xF0F0F0F0F0L; - private static LargeConstantClassLoader LOADER; @Parameter(value = 0) public int numberBlocks; @Parameters(name = "{0}") @@ -94,76 +85,36 @@ public static Collection data() { return parameters; } - @Before - public void before() { - LOADER = new LargeConstantClassLoader(LargeConstantSectionTest.class.getClassLoader()); - } + @Override + public byte[] generateClass(String className) { + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethodBody("run", MethodTypeDesc.of(CD_long, CD_int), ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC | ClassFile.ACC_FINAL, b -> { + Label defaultLabel = b.newLabel(); + List cases = new ArrayList<>(numberBlocks); - public class LargeConstantClassLoader extends ExportingClassLoader { - public LargeConstantClassLoader(ClassLoader parent) { - super(parent); - } + for (int i = 0; i < numberBlocks; i++) { + cases.add(SwitchCase.of(i, b.newLabel())); + } - @Override - protected Class findClass(String name) throws ClassNotFoundException { - if (name.equals(NAME)) { - ClassWriter cw = new ClassWriter(0); - MethodVisitor mv; - cw.visit(52, ACC_PUBLIC + ACC_SUPER, NAME, null, "java/lang/Object", null); + b.iload(0).lookupswitch(defaultLabel, cases); - mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL + ACC_STATIC, "run", "(I)J", null, null); - mv.visitCode(); - Label begin = new Label(); - mv.visitLabel(begin); - mv.visitVarInsn(ILOAD, 0); - Label[] labels = new Label[numberBlocks]; - int[] keys = new int[numberBlocks]; - for (int i = 0; i < labels.length; i++) { - labels[i] = new Label(); - keys[i] = i; - } - Label defaultLabel = new Label(); - mv.visitLookupSwitchInsn(defaultLabel, keys, labels); - for (int i = 0; i < labels.length; i++) { - mv.visitLabel(labels[i]); - mv.visitFrame(Opcodes.F_NEW, 1, new Object[]{Opcodes.INTEGER}, 0, new Object[]{}); - mv.visitLdcInsn(Long.valueOf(LARGE_CONSTANT + i)); - mv.visitInsn(LRETURN); - } - mv.visitLabel(defaultLabel); - mv.visitFrame(Opcodes.F_NEW, 1, new Object[]{Opcodes.INTEGER}, 0, new Object[]{}); - mv.visitLdcInsn(Long.valueOf(3L)); - mv.visitInsn(LRETURN); - Label end = new Label(); - mv.visitLabel(end); - mv.visitLocalVariable("a", "I", null, begin, end, 0); - mv.visitMaxs(2, 1); - mv.visitEnd(); - byte[] bytes = cw.toByteArray(); - return defineClass(name, bytes, 0, bytes.length); - } else { - return super.findClass(name); - } - } + for (int i = 0; i < cases.size(); i++) { + b.labelBinding(cases.get(i).target()) + .ldc(Long.valueOf(LARGE_CONSTANT + i)) + .lreturn(); + } + + b.labelBinding(defaultLabel) + .ldc(Long.valueOf(3L)) + .lreturn(); + })); + // @formatter:on } @Test - @SuppressWarnings("try") public void run0() throws Exception { - test("run", numberBlocks - 3); - } - - @Override - protected ResolvedJavaMethod getResolvedJavaMethod(String methodName) { - try { - for (Method method : LOADER.findClass(NAME).getDeclaredMethods()) { - if (method.getName().equals(methodName)) { - return asResolvedJavaMethod(method); - } - } - } catch (ClassNotFoundException e) { - throw new AssertionFailedError("Cannot find class " + NAME); - } - throw GraalError.shouldNotReachHereUnexpectedValue(methodName); // ExcludeFromJacocoGeneratedReport + Class testClass = getClass(LargeConstantSectionTest.class.getName() + "$" + NAME); + test(getResolvedJavaMethod(testClass, "run"), null, numberBlocks - 3); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/bytecode/BC_instanceof01.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/bytecode/BC_instanceof01.java index 70d63f496866..739d5796dc1b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/bytecode/BC_instanceof01.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/bytecode/BC_instanceof01.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -89,7 +89,6 @@ public void run0() throws Throwable { } @Override - @SuppressWarnings("try") protected Suites createSuites(OptionValues options) { return super.createSuites(new OptionValues(options, HighTier.Options.Inline, false)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/except/UntrustedInterfaces.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/except/UntrustedInterfaces.java index fe388c7809f0..ecdebb6d72a3 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/except/UntrustedInterfaces.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/except/UntrustedInterfaces.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -24,14 +24,21 @@ */ package jdk.graal.compiler.jtt.except; -import jdk.graal.compiler.jtt.JTTTest; -import jdk.graal.compiler.api.test.ExportingClassLoader; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.ClassFile; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; + import org.junit.BeforeClass; import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; + +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; +import jdk.graal.compiler.jtt.JTTTest; public class UntrustedInterfaces extends JTTTest { @@ -152,7 +159,7 @@ public TestInterface returnCheckcast(Pill pill) { // Checkstyle: stop @BeforeClass public static void setUp() throws Exception { - poisonPill = (Pill) new PoisonLoader().findClass(PoisonLoader.POISON_IMPL_NAME).getDeclaredConstructor().newInstance(); + poisonPill = (Pill) new PoisonLoader().getClass(PoisonLoader.POISON_IMPL_NAME).getDeclaredConstructor().newInstance(); } // Checkstyle: resume @@ -217,71 +224,47 @@ public void testReturn2() { runTest("returnCheckcast", poisonPill); } - private static final class PoisonLoader extends ExportingClassLoader { + private static final class PoisonLoader implements CustomizedBytecodePattern { + public static final String POISON_IMPL_NAME = "jdk.graal.compiler.jtt.except.PoisonPill"; @Override - protected Class findClass(String name) throws ClassNotFoundException { - if (name.equals(POISON_IMPL_NAME)) { - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); - - cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, POISON_IMPL_NAME.replace('.', '/'), null, Type.getInternalName(Pill.class), null); - // constructor - MethodVisitor constructor = cw.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, null); - constructor.visitCode(); - constructor.visitVarInsn(Opcodes.ALOAD, 0); - constructor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Pill.class), "", "()V", false); - constructor.visitInsn(Opcodes.RETURN); - constructor.visitMaxs(0, 0); - constructor.visitEnd(); - - MethodVisitor setList = cw.visitMethod(Opcodes.ACC_PUBLIC, "setField", "()V", null, null); - setList.visitCode(); - setList.visitVarInsn(Opcodes.ALOAD, 0); - setList.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Object.class)); - setList.visitInsn(Opcodes.DUP); - setList.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "", "()V", false); - setList.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(Pill.class), "field", Type.getDescriptor(TestInterface.class)); - setList.visitInsn(Opcodes.RETURN); - setList.visitMaxs(0, 0); - setList.visitEnd(); - - MethodVisitor setStaticList = cw.visitMethod(Opcodes.ACC_PUBLIC, "setStaticField", "()V", null, null); - setStaticList.visitCode(); - setStaticList.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Object.class)); - setStaticList.visitInsn(Opcodes.DUP); - setStaticList.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "", "()V", false); - setStaticList.visitFieldInsn(Opcodes.PUTSTATIC, Type.getInternalName(Pill.class), "staticField", Type.getDescriptor(TestInterface.class)); - setStaticList.visitInsn(Opcodes.RETURN); - setStaticList.visitMaxs(0, 0); - setStaticList.visitEnd(); - - MethodVisitor callMe = cw.visitMethod(Opcodes.ACC_PUBLIC, "callMe", Type.getMethodDescriptor(Type.INT_TYPE, Type.getType(CallBack.class)), null, null); - callMe.visitCode(); - callMe.visitVarInsn(Opcodes.ALOAD, 1); - callMe.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Object.class)); - callMe.visitInsn(Opcodes.DUP); - callMe.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "", "()V", false); - callMe.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(CallBack.class), "callBack", Type.getMethodDescriptor(Type.INT_TYPE, Type.getType(TestInterface.class)), true); - callMe.visitInsn(Opcodes.IRETURN); - callMe.visitMaxs(0, 0); - callMe.visitEnd(); - - MethodVisitor getList = cw.visitMethod(Opcodes.ACC_PUBLIC, "get", Type.getMethodDescriptor(Type.getType(TestInterface.class)), null, null); - getList.visitCode(); - getList.visitTypeInsn(Opcodes.NEW, Type.getInternalName(Object.class)); - getList.visitInsn(Opcodes.DUP); - getList.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "", "()V", false); - getList.visitInsn(Opcodes.ARETURN); - getList.visitMaxs(0, 0); - getList.visitEnd(); - - cw.visitEnd(); - - byte[] bytes = cw.toByteArray(); - return defineClass(name, bytes, 0, bytes.length); - } - return super.findClass(name); + public byte[] generateClass(String className) { + ClassDesc classPill = cd(Pill.class); + ClassDesc classTestInterface = cd(TestInterface.class); + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withSuperclass(classPill) + .withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .invokespecial(classPill, INIT_NAME, MTD_void) + .return_()) + .withMethodBody("setField", MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .new_(CD_Object) + .dup() + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .putfield(classPill, "field", classTestInterface) + .return_()) + .withMethodBody("setStaticField", MTD_void, ACC_PUBLIC, b -> b + .new_(CD_Object) + .dup() + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .putstatic(classPill, "staticField", classTestInterface) + .return_()) + .withMethodBody("callMe", MethodTypeDesc.of(CD_int, cd(CallBack.class)), ACC_PUBLIC, b -> b + .aload(1) + .new_(CD_Object) + .dup() + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .invokeinterface(cd(CallBack.class), "callBack", MethodTypeDesc.of(CD_int, classTestInterface)) + .ireturn()) + .withMethodBody("get", MethodTypeDesc.of(classTestInterface), ACC_PUBLIC, b -> b + .new_(CD_Object) + .dup() + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .areturn())); + // @formatter:on } } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/lang/LambdaEagerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/lang/LambdaEagerTest.java index 4038ee7ba251..8fda9b6f40c5 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/lang/LambdaEagerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/jtt/lang/LambdaEagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -81,7 +81,6 @@ public void testEagerResolveCapturing() { } @Override - @SuppressWarnings("try") protected InstalledCode getCode(ResolvedJavaMethod installedCodeOwner, StructuredGraph graph, boolean forceCompile, boolean installAsDefault, OptionValues options) { assert graph == null; return super.getCode(installedCodeOwner, graph, forceCompile, installAsDefault, new OptionValues(options, InlineEverything, true)); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/lir/test/CompositeValueReplacementTest1.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/lir/test/CompositeValueReplacementTest1.java index 9daaaf9eeebd..8412ff98e929 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/lir/test/CompositeValueReplacementTest1.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/lir/test/CompositeValueReplacementTest1.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2025, 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 @@ -42,7 +42,6 @@ import jdk.graal.compiler.lir.LIRInstruction.OperandMode; import jdk.graal.compiler.lir.LIRInstructionClass; import jdk.graal.compiler.lir.asm.CompilationResultBuilder; - import jdk.vm.ci.meta.Value; /** @@ -151,17 +150,17 @@ public void replaceCompValueTest0() { LIRInstruction op1 = new TestOp(compValue1); LIRInstruction op2 = new TestOp(compValue1); - op1.forEachInput((instruction, value, mode, flags) -> { + op1.forEachInput((_, value, _, _) -> { assertEquals(dummyValue1, value); return dummyValue2; }); - op2.forEachInput((instruction, value, mode, flags) -> { + op2.forEachInput((_, value, _, _) -> { assertEquals(dummyValue1, value); return dummyValue3; }); - op1.visitEachInput((instruction, value, mode, flags) -> assertEquals(dummyValue2, value)); - op2.visitEachInput((instruction, value, mode, flags) -> assertEquals(dummyValue3, value)); + op1.visitEachInput((_, value, _, _) -> assertEquals(dummyValue2, value)); + op2.visitEachInput((_, value, _, _) -> assertEquals(dummyValue3, value)); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/loop/test/LoopPartialUnrollTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/loop/test/LoopPartialUnrollTest.java index 6cd3d2c6483f..f003195304ae 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/loop/test/LoopPartialUnrollTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/loop/test/LoopPartialUnrollTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -322,7 +322,6 @@ public void testGraph(String reference, String test) { assertEquals(referenceGraph, testGraph, false, false); } - @SuppressWarnings("try") public StructuredGraph buildGraph(String name, boolean partialUnroll) { CompilationIdentifier id = new CompilationIdentifier() { @Override @@ -333,7 +332,7 @@ public String toString(Verbosity verbosity) { ResolvedJavaMethod method = getResolvedJavaMethod(name); OptionValues options = new OptionValues(getInitialOptions(), DefaultLoopPolicies.Options.UnrollMaxIterations, 2); StructuredGraph graph = parse(builder(method, StructuredGraph.AllowAssumptions.YES, id, options), getEagerGraphBuilderSuite()); - try (DebugContext.Scope buildScope = graph.getDebug().scope(name, method, graph)) { + try (DebugContext.Scope _ = graph.getDebug().scope(name, method, graph)) { MidTierContext context = new MidTierContext(getProviders(), getTargetProvider(), OptimisticOptimizations.ALL, null); CanonicalizerPhase canonicalizer = this.createCanonicalizerPhase(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/nodes/test/InliningLogTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/nodes/test/InliningLogTest.java index 04ebb963ac0a..b2cc7c9a25af 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/nodes/test/InliningLogTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/nodes/test/InliningLogTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -56,13 +56,12 @@ private static void snippetB(Foo foo) { * Verifies that the invokes created by peeling the loop in {@link #snippetB(Foo)} are siblings * of the original call-tree node. */ - @SuppressWarnings("try") @Test public void duplicatedInvokesAttachedCorrectly() { OptionValues optionValues = new OptionValues(getInitialOptions(), GraalOptions.TraceInlining, true, LoopPolicies.Options.PeelALot, true); ResolvedJavaMethod method = getResolvedJavaMethod("snippetA"); StructuredGraph graph = parseEager(method, StructuredGraph.AllowAssumptions.YES, getCompilationId(method), optionValues); - try (TTY.Filter suppress = new TTY.Filter()) { + try (TTY.Filter _ = new TTY.Filter()) { compile(method, graph); } InliningLog inliningLog = graph.getInliningLog(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/options/test/TestOptionKey.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/options/test/TestOptionKey.java index 137c926da38e..f3682edf1a9a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/options/test/TestOptionKey.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/options/test/TestOptionKey.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -69,7 +69,6 @@ import jdk.graal.compiler.options.OptionValues; import jdk.graal.compiler.options.OptionsParser; -@SuppressWarnings("try") public class TestOptionKey { public enum TestEnum { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledExceptionHandlerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledExceptionHandlerTest.java index 0eca4f5aefdd..3f8dc7e05630 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledExceptionHandlerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledExceptionHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -47,7 +47,6 @@ public class CompiledExceptionHandlerTest extends GraalCompilerTest { @Override - @SuppressWarnings("try") protected Suites createSuites(OptionValues options) { return super.createSuites(new OptionValues(options, HighTier.Options.Inline, false)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledNullPointerExceptionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledNullPointerExceptionTest.java index ca88c912ad4e..e891e8c9dbb7 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledNullPointerExceptionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/CompiledNullPointerExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -50,7 +50,6 @@ public class CompiledNullPointerExceptionTest extends GraalCompilerTest { @Override - @SuppressWarnings("try") protected Suites createSuites(OptionValues options) { return super.createSuites(new OptionValues(options, HighTier.Options.Inline, false)); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DeoptimizeOnExceptionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DeoptimizeOnExceptionTest.java index bc8e07f03c02..3344e1e823de 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DeoptimizeOnExceptionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DeoptimizeOnExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -24,24 +24,34 @@ */ package jdk.graal.compiler.replacements.test; +import static java.lang.classfile.ClassFile.ACC_PUBLIC; +import static java.lang.classfile.ClassFile.JAVA_5_VERSION; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_long; +import static java.lang.constant.ConstantDescs.INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.ClassFile; +import java.lang.classfile.Label; +import java.lang.classfile.Opcode; +import java.lang.classfile.instruction.DiscontinuedInstruction.JsrInstruction; +import java.lang.classfile.instruction.DiscontinuedInstruction.RetInstruction; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; import java.util.Random; +import org.junit.Assert; +import org.junit.Test; + import jdk.graal.compiler.api.directives.GraalDirectives; -import jdk.graal.compiler.api.test.ExportingClassLoader; import jdk.graal.compiler.core.phases.HighTier; +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; import jdk.graal.compiler.core.test.GraalCompilerTest; import jdk.graal.compiler.nodes.ValueNode; import jdk.graal.compiler.nodes.graphbuilderconf.GraphBuilderContext; import jdk.graal.compiler.nodes.graphbuilderconf.InlineInvokePlugin; import jdk.graal.compiler.options.OptionValues; import jdk.graal.compiler.phases.common.AbstractInliningPhase; -import org.junit.Assert; -import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.Label; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; - import jdk.vm.ci.code.InstalledCode; import jdk.vm.ci.meta.DeoptimizationReason; import jdk.vm.ci.meta.ResolvedJavaMethod; @@ -49,7 +59,7 @@ /** * Tests that deoptimization upon exception handling works. */ -public class DeoptimizeOnExceptionTest extends GraalCompilerTest { +public class DeoptimizeOnExceptionTest extends GraalCompilerTest implements CustomizedBytecodePattern { @SuppressWarnings("this-escape") public DeoptimizeOnExceptionTest() { @@ -73,32 +83,88 @@ public static String test1Snippet(String m1, String m2, String m3, String m4, St return m1 + m2 + m3 + m4 + m5; } + @SuppressWarnings("unchecked") @Test public void test2() { - test("test2Snippet"); - } - - public String test2Snippet() throws Exception { try { - ClassLoader testCl = new MyClassLoader(); - @SuppressWarnings("unchecked") - Class c = (Class) testCl.loadClass(name); - Runnable r = c.getDeclaredConstructor().newInstance(); + Class testClass = (Class) getClass(DeoptimizeOnExceptionTest.class.getName() + "$" + "TestJSR"); + Runnable r = testClass.getDeclaredConstructor().newInstance(); ct = Long.MAX_VALUE; // warmup for (int i = 0; i < 100; i++) { r.run(); } - // compile - ResolvedJavaMethod method = getResolvedJavaMethod(c, "run"); - getCode(method); ct = 0; - r.run(); + InstalledCode compiledMethod = getCode(getResolvedJavaMethod(testClass, "run")); + compiledMethod.executeVarargs(r); } catch (Throwable e) { e.printStackTrace(System.out); Assert.fail(); } - return "SUCCESS"; + } + + public static void methodB() { + // Application code to be compiled. No need to use + // GraalCompilerTest.getRandomInstance() + Random r = new Random(System.currentTimeMillis()); + while (r.nextFloat() > .03f) { + // Empty + } + + return; + } + + public static void methodA() { + // Application code to be compiled. No need to use + // GraalCompilerTest.getRandomInstance() + Random r = new Random(System.currentTimeMillis()); + while (r.nextDouble() > .05) { + // Empty + } + return; + } + + private static Object m = new Object(); + static long ct = Long.MAX_VALUE; + + public static Object getM() { + if (ct-- > 0) { + return m; + } else { + return null; + } + } + + @Override + public byte[] generateClass(String className) { + ClassDesc outerClass = cd(DeoptimizeOnExceptionTest.class); + + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withVersion(JAVA_5_VERSION, 0) + .withInterfaceSymbols(cd(Runnable.class)) + .withMethodBody(INIT_NAME, MTD_void, ACC_PUBLIC, b -> b + .aload(0) + .invokespecial(CD_Object, INIT_NAME, MTD_void) + .return_()) + .withMethodBody("run", MTD_void, ACC_PUBLIC, b -> { + Label l1 = b.newLabel(); + b + .invokestatic(outerClass, "getM", MethodTypeDesc.of(CD_Object)) + .with(JsrInstruction.of(l1)) + .return_() + .labelBinding(l1) + .astore(1) + .invokestatic(cd(System.class), "currentTimeMillis", MethodTypeDesc.of(CD_long)) + .pop2() + .invokestatic(outerClass, "getM", MethodTypeDesc.of(CD_Object)) + .dup() + .ifThenElse(Opcode.IFNONNULL, + thenBlock -> thenBlock.invokestatic(outerClass, "methodA", MTD_void), + elseBlock -> elseBlock.invokestatic(outerClass, "methodB", MTD_void)) + .with(RetInstruction.of(1)); + })); + // @formatter:on } @Test @@ -154,87 +220,4 @@ public static boolean test3Snippet(boolean rethrowException) throws Exception { return GraalDirectives.inCompiledCode(); } - - public static class MyClassLoader extends ExportingClassLoader { - @Override - protected Class findClass(String className) throws ClassNotFoundException { - return defineClass(name.replace('/', '.'), clazz, 0, clazz.length); - } - } - - public static void methodB() { - Random r = new Random(System.currentTimeMillis()); - while (r.nextFloat() > .03f) { - // Empty - } - - return; - } - - public static void methodA() { - Random r = new Random(System.currentTimeMillis()); - while (r.nextDouble() > .05) { - // Empty - } - return; - } - - private static Object m = new Object(); - static long ct = Long.MAX_VALUE; - - public static Object getM() { - if (ct-- > 0) { - return m; - } else { - return null; - } - } - - private static String name = "t/TestJSR"; - - private static final byte[] clazz = makeClazz(); - - private static byte[] makeClazz() { - // Code generated the class below using asm. - String clazzName = DeoptimizeOnExceptionTest.class.getName().replace('.', '/'); - final ClassWriter w = new ClassWriter(0); - w.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, - "t/TestJSR", null, "java/lang/Object", - new String[]{"java/lang/Runnable"}); - MethodVisitor mv = w.visitMethod(Opcodes.ACC_PUBLIC, "", "()V", null, new String[]{}); - mv.visitCode(); - mv.visitVarInsn(Opcodes.ALOAD, 0); - mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "", "()V", false); - mv.visitInsn(Opcodes.RETURN); - mv.visitMaxs(10, 10); - mv.visitEnd(); - - mv = w.visitMethod(Opcodes.ACC_PUBLIC, "run", "()V", null, null); - mv.visitCode(); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "getM", "()Ljava/lang/Object;", false); - Label l1 = new Label(); - mv.visitJumpInsn(Opcodes.JSR, l1); - mv.visitInsn(Opcodes.RETURN); - - mv.visitLabel(l1); - mv.visitVarInsn(Opcodes.ASTORE, 1); - - Label lElse = new Label(); - Label lEnd = new Label(); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/System", "currentTimeMillis", "()J", false); - mv.visitInsn(Opcodes.POP2); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "getM", "()Ljava/lang/Object;", false); - mv.visitInsn(Opcodes.DUP); - mv.visitJumpInsn(Opcodes.IFNULL, lElse); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "methodA", "()V", false); - mv.visitJumpInsn(Opcodes.GOTO, lEnd); - mv.visitLabel(lElse); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, clazzName, "methodB", "()V", false); - mv.visitLabel(lEnd); - - mv.visitVarInsn(Opcodes.RET, 1); - mv.visitMaxs(10, 10); - mv.visitEnd(); - return w.toByteArray(); - } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DerivedOopTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DerivedOopTest.java index 89c79decf7f2..03ad840fa254 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DerivedOopTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/DerivedOopTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -144,11 +144,10 @@ public static Result fieldOffsetSnippet(Result obj, long offset) { private static final String UNKNOWN_REFERENCE_AT_SAFEPOINT_MSG = "should not reach here: unknown reference alive across safepoint"; @Test - @SuppressWarnings("try") public void testFieldOffsetMergeNonLiveBasePointer() { GraalError error = Assert.assertThrows(GraalError.class, () -> { DebugContext debug = getDebugContext(); - try (Scope s = debug.disable()) { + try (Scope _ = debug.disable()) { // Run a couple times to encourage objects to move for (int i = 0; i < 4; i++) { Result r = new Result(); @@ -170,11 +169,10 @@ public void testFieldOffsetMergeNonLiveBasePointerNotAccrossSafepoint() { } @Test - @SuppressWarnings("try") public void testFieldOffsetMergeLiveBasePointer() { GraalError error = Assert.assertThrows(GraalError.class, () -> { DebugContext debug = getDebugContext(); - try (Scope s = debug.disable()) { + try (Scope _ = debug.disable()) { // Run a couple times to encourage objects to move for (int i = 0; i < 4; i++) { Result r = new Result(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InstanceOfTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InstanceOfTest.java index f0af9a5d431b..4fb739a45ba5 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InstanceOfTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InstanceOfTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2025, 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 @@ -489,10 +489,9 @@ private void testConstantReturn(String name, Object value) { assertDeepEquals(value, ret.result().asJavaConstant().asBoxedPrimitive()); } - @SuppressWarnings("try") protected StructuredGraph buildGraph(final String snippet) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("InstanceOfTest", getMetaAccess().lookupJavaMethod(getMethod(snippet)))) { + try (DebugContext.Scope _ = debug.scope("InstanceOfTest", getMetaAccess().lookupJavaMethod(getMethod(snippet)))) { StructuredGraph graph = parseEager(snippet, AllowAssumptions.YES, debug); compile(graph.method(), graph); debug.dump(DebugContext.BASIC_LEVEL, graph, snippet); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InvokerSignatureMismatchTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InvokerSignatureMismatchTest.java index ce2cbeac46b1..80a1efa94982 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InvokerSignatureMismatchTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/InvokerSignatureMismatchTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -24,147 +24,143 @@ */ package jdk.graal.compiler.replacements.test; -import static jdk.graal.compiler.test.SubprocessUtil.getVMCommandLine; -import static jdk.graal.compiler.test.SubprocessUtil.withoutDebuggerArguments; +import static java.lang.classfile.ClassFile.ACC_FINAL; +import static java.lang.classfile.ClassFile.ACC_STATIC; +import static java.lang.constant.ConstantDescs.CD_Class; +import static java.lang.constant.ConstantDescs.CD_Exception; +import static java.lang.constant.ConstantDescs.CD_Integer; +import static java.lang.constant.ConstantDescs.CD_MethodHandle; +import static java.lang.constant.ConstantDescs.CD_MethodHandles; +import static java.lang.constant.ConstantDescs.CD_MethodHandles_Lookup; +import static java.lang.constant.ConstantDescs.CD_MethodType; +import static java.lang.constant.ConstantDescs.CD_Object; +import static java.lang.constant.ConstantDescs.CD_String; +import static java.lang.constant.ConstantDescs.CD_float; +import static java.lang.constant.ConstantDescs.CD_int; +import static java.lang.constant.ConstantDescs.CD_void; +import static java.lang.constant.ConstantDescs.CLASS_INIT_NAME; +import static java.lang.constant.ConstantDescs.MTD_void; + +import java.lang.classfile.Annotation; +import java.lang.classfile.ClassFile; +import java.lang.classfile.attribute.ExceptionsAttribute; +import java.lang.classfile.attribute.RuntimeVisibleAnnotationsAttribute; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodHandles.Lookup; +import java.lang.reflect.Field; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; - -import jdk.graal.compiler.core.test.CustomizedBytecodePatternTest; -import jdk.graal.compiler.test.SubprocessUtil; -import jdk.graal.compiler.test.SubprocessUtil.Subprocess; import org.junit.Test; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Type; -public class InvokerSignatureMismatchTest extends CustomizedBytecodePatternTest { +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; +import jdk.graal.compiler.core.test.GraalCompilerTest; +import jdk.graal.compiler.test.AddExports; - @SuppressWarnings("try") - @Test - public void test() throws Throwable { - List args = withoutDebuggerArguments(getVMCommandLine()); - try (TemporaryDirectory temp = new TemporaryDirectory(getClass().getSimpleName())) { - args.add("--class-path=" + temp); - args.add("--patch-module=java.base=" + temp); - args.add("-XX:-TieredCompilation"); - args.add("-XX:+UnlockExperimentalVMOptions"); - args.add("-XX:+EnableJVMCI"); - args.add("-XX:+UseJVMCICompiler"); +@AddExports({"java.base/java.lang", "java.base/java.lang.invoke"}) +public class InvokerSignatureMismatchTest extends GraalCompilerTest { - Path invokeDir = Files.createDirectories(temp.path.resolve(Paths.get("java", "lang", "invoke"))); - Files.write(temp.path.resolve("ISMTest.class"), generateClass("ISMTest")); - Files.write(invokeDir.resolve("MethodHandleHelper.class"), generateClass("java/lang/invoke/MethodHandleHelper")); + static String helperClassName = "java.lang.invoke.MethodHandleHelper"; - args.add("ISMTest"); - Subprocess proc = SubprocessUtil.java(args); - if (proc.exitCode != 0) { - throw new AssertionError(proc.toString()); - } - } + @Test + public void testInvokeSignatureMismatch() throws Exception { + Field trustedLookupField = Lookup.class.getDeclaredField("IMPL_LOOKUP"); + trustedLookupField.setAccessible(true); + Lookup trustedLookup = (Lookup) trustedLookupField.get(null); + + new MethodHandleHelperGen().lookupClass(trustedLookup.in(MethodHandles.class), helperClassName); + Class testClass = new ISMTestGen().getClass(InvokerSignatureMismatchTest.class.getName() + "$" + "ISMTest"); + test(getResolvedJavaMethod(testClass, "main"), null, new Object[]{new String[0]}); } - @Override - protected byte[] generateClass(String className) { - String[] exceptions = new String[]{"java/lang/Throwable"}; - ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); - cw.visit(52, ACC_SUPER | ACC_PUBLIC, className, null, "java/lang/Object", null); - - if (className.equals("java/lang/invoke/MethodHandleHelper")) { - MethodVisitor internalMemberName = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "internalMemberName", "(Ljava/lang/invoke/MethodHandle;)Ljava/lang/Object;", null, exceptions); - internalMemberName.visitCode(); - internalMemberName.visitVarInsn(ALOAD, 0); - internalMemberName.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "internalMemberName", "()Ljava/lang/invoke/MemberName;", false); - internalMemberName.visitInsn(ARETURN); - internalMemberName.visitMaxs(1, 1); - internalMemberName.visitEnd(); - - MethodVisitor linkToStatic = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "linkToStatic", "(FLjava/lang/Object;)I", null, exceptions); - linkToStatic.visitCode(); - linkToStatic.visitVarInsn(FLOAD, 0); - linkToStatic.visitVarInsn(ALOAD, 1); - linkToStatic.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodHandle", "linkToStatic", "(FLjava/lang/Object;)I", false); - linkToStatic.visitInsn(IRETURN); - linkToStatic.visitMaxs(1, 1); - linkToStatic.visitEnd(); - - MethodVisitor invokeBasicI = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "invokeBasicI", "(Ljava/lang/invoke/MethodHandle;F)I", null, exceptions); - invokeBasicI.visitCode(); - invokeBasicI.visitVarInsn(ALOAD, 0); - invokeBasicI.visitVarInsn(FLOAD, 1); - invokeBasicI.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandle", "invokeBasic", "(F)I", false); - invokeBasicI.visitInsn(IRETURN); - invokeBasicI.visitMaxs(1, 1); - invokeBasicI.visitEnd(); - - } else { - assert className.equals("ISMTest") : className; - cw.visitField(ACC_FINAL | ACC_STATIC, "INT_MH", "Ljava/lang/invoke/MethodHandle;", null, null).visitAnnotation("Ljava/lang/invoke/Stable.class;", true).visitEnd(); - MethodVisitor clinit = cw.visitMethod(ACC_STATIC, "", "()V", null, exceptions); - clinit.visitCode(); - clinit.visitInsn(ACONST_NULL); - clinit.visitVarInsn(ASTORE, 0); - clinit.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodHandles", "lookup", "()Ljava/lang/invoke/MethodHandles$Lookup;", false); - clinit.visitLdcInsn(Type.getObjectType(className)); - clinit.visitLdcInsn("bodyI"); - clinit.visitFieldInsn(GETSTATIC, "java/lang/Integer", "TYPE", "Ljava/lang/Class;"); - clinit.visitFieldInsn(GETSTATIC, "java/lang/Integer", "TYPE", "Ljava/lang/Class;"); - clinit.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodType", "methodType", "(Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/invoke/MethodType;", false); - clinit.visitMethodInsn(INVOKEVIRTUAL, "java/lang/invoke/MethodHandles$Lookup", "findStatic", - "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/MethodHandle;", false); - clinit.visitFieldInsn(PUTSTATIC, className, "INT_MH", "Ljava/lang/invoke/MethodHandle;"); - clinit.visitInsn(RETURN); - clinit.visitMaxs(1, 1); - clinit.visitEnd(); - - MethodVisitor mainLink = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "mainLink", "(I)I", null, exceptions); - mainLink.visitCode(); - mainLink.visitFieldInsn(GETSTATIC, className, "INT_MH", "Ljava/lang/invoke/MethodHandle;"); - mainLink.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodHandleHelper", "internalMemberName", "(Ljava/lang/invoke/MethodHandle;)Ljava/lang/Object;", false); - mainLink.visitVarInsn(ASTORE, 1); - mainLink.visitVarInsn(ILOAD, 0); - mainLink.visitInsn(I2F); - mainLink.visitVarInsn(ALOAD, 1); - mainLink.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodHandleHelper", "linkToStatic", "(FLjava/lang/Object;)I", false); - mainLink.visitInsn(IRETURN); - mainLink.visitMaxs(1, 1); - mainLink.visitEnd(); - - MethodVisitor mainInvoke = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "mainInvoke", "(I)I", null, exceptions); - mainInvoke.visitCode(); - mainInvoke.visitFieldInsn(GETSTATIC, className, "INT_MH", "Ljava/lang/invoke/MethodHandle;"); - mainInvoke.visitVarInsn(ILOAD, 0); - mainInvoke.visitInsn(I2F); - mainInvoke.visitMethodInsn(INVOKESTATIC, "java/lang/invoke/MethodHandleHelper", "invokeBasicI", "(Ljava/lang/invoke/MethodHandle;F)I", false); - mainInvoke.visitInsn(IRETURN); - mainInvoke.visitMaxs(1, 1); - mainInvoke.visitEnd(); - - MethodVisitor bodyI = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "bodyI", "(I)I", null, null); - bodyI.visitCode(); - bodyI.visitVarInsn(ILOAD, 0); - bodyI.visitIntInsn(SIPUSH, 1023); - bodyI.visitInsn(IAND); - bodyI.visitInsn(IRETURN); - bodyI.visitMaxs(1, 1); - bodyI.visitEnd(); - - MethodVisitor main = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "main", "([Ljava/lang/String;)V", null, exceptions); - main.visitCode(); - main.visitIntInsn(SIPUSH, 100); - main.visitMethodInsn(INVOKESTATIC, "ISMTest", "mainLink", "(I)I", false); - main.visitInsn(POP); - main.visitIntInsn(SIPUSH, 100); - main.visitMethodInsn(INVOKESTATIC, "ISMTest", "mainInvoke", "(I)I", false); - main.visitInsn(POP); - main.visitInsn(RETURN); - main.visitMaxs(1, 1); - main.visitEnd(); + static class MethodHandleHelperGen implements CustomizedBytecodePattern { + @Override + public byte[] generateClass(String className) { + // @formatter:off + return ClassFile.of().build(ClassDesc.of(className), classBuilder -> classBuilder + .withMethod("internalMemberName", MethodTypeDesc.of(CD_Object, CD_MethodHandle), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .with(ExceptionsAttribute.ofSymbols(CD_Exception)) + .withCode(b -> b + .aload(0) + .invokevirtual(CD_MethodHandle, "internalMemberName", MethodTypeDesc.of(ClassDesc.of("java.lang.invoke.MemberName"))) + .areturn())) + .withMethod("linkToStatic", MethodTypeDesc.of(CD_int, CD_float, CD_Object), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .with(ExceptionsAttribute.ofSymbols(CD_Exception)) + .withCode(b -> b + .fload(0) + .aload(1) + .invokestatic(CD_MethodHandle, "linkToStatic", MethodTypeDesc.of(CD_int, CD_float, CD_Object)) + .ireturn())) + .withMethod("invokeBasicI", MethodTypeDesc.of(CD_int, CD_MethodHandle, CD_float), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .with(ExceptionsAttribute.ofSymbols(CD_Exception)) + .withCode(b -> b + .aload(0) + .fload(1) + .invokevirtual(CD_MethodHandle, "invokeBasic", MethodTypeDesc.of(CD_int, CD_float)) + .ireturn()))); + // @formatter:on + } + } + static class ISMTestGen implements CustomizedBytecodePattern { + @Override + public byte[] generateClass(String className) { + ClassDesc thisClass = ClassDesc.of(className); + ClassDesc methodHandleHelper = ClassDesc.of(helperClassName); + + // @formatter:off + return ClassFile.of().build(thisClass, classBuilder -> classBuilder + .withField("INT_MH", CD_MethodHandle, fieldBuilder -> fieldBuilder + .withFlags(ACC_FINAL | ACC_STATIC) + .with(RuntimeVisibleAnnotationsAttribute.of(Annotation.of(ClassDesc.of("jdk.internal.vm.annotation.Stable"))))) + .withMethod(CLASS_INIT_NAME, MTD_void, ACC_STATIC, methodBuilder -> methodBuilder + .withCode(b -> b + .aconst_null() + .astore(0) + .invokestatic(CD_MethodHandles, "lookup", MethodTypeDesc.of(CD_MethodHandles_Lookup)) + .ldc(thisClass) + .ldc("bodyI") + .getstatic(CD_Integer, "TYPE", CD_Class) + .getstatic(CD_Integer, "TYPE", CD_Class) + .invokestatic(CD_MethodType, "methodType", MethodTypeDesc.of(CD_MethodType, CD_Class, CD_Class)) + .invokevirtual(CD_MethodHandles_Lookup, "findStatic", MethodTypeDesc.of(CD_MethodHandle, CD_Class, CD_String, CD_MethodType)) + .putstatic(thisClass, "INT_MH", CD_MethodHandle) + .return_())) + .withMethod("mainLink", MethodTypeDesc.of(CD_int, CD_int), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .with(ExceptionsAttribute.ofSymbols(CD_Exception)) + .withCode(b -> b + .getstatic(thisClass, "INT_MH", CD_MethodHandle) + .invokestatic(methodHandleHelper, "internalMemberName", MethodTypeDesc.of(CD_Object, CD_MethodHandle)) + .astore(1) + .iload(0) + .i2f() + .aload(1) + .invokestatic(methodHandleHelper, "linkToStatic", MethodTypeDesc.of(CD_int, CD_float, CD_Object)) + .ireturn())) + .withMethod("mainInvoke", MethodTypeDesc.of(CD_int, CD_int), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .with(ExceptionsAttribute.ofSymbols(CD_Exception)) + .withCode(b -> b + .getstatic(thisClass, "INT_MH", CD_MethodHandle) + .iload(0) + .i2f() + .invokestatic(methodHandleHelper, "invokeBasicI", MethodTypeDesc.of(CD_int, CD_MethodHandle, CD_float)) + .ireturn())) + .withMethod("bodyI", MethodTypeDesc.of(CD_int, CD_int), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .withCode(b -> b + .iload(0) + .sipush(1023) + .iand() + .ireturn())) + .withMethod("main", MethodTypeDesc.of(CD_void, CD_String.arrayType()), ACC_PUBLIC_STATIC, methodBuilder -> methodBuilder + .withCode(b -> b + .sipush(100) + .invokestatic(thisClass, "mainLink", MethodTypeDesc.of(CD_int, CD_int)) + .pop() + .sipush(100) + .invokestatic(thisClass, "mainInvoke", MethodTypeDesc.of(CD_int, CD_int)) + .pop() + .return_()))); + // @formatter:on } - cw.visitEnd(); - return cw.toByteArray(); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/MethodSubstitutionTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/MethodSubstitutionTest.java index 3e3b1b39770b..e42dae73ac9d 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/MethodSubstitutionTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/MethodSubstitutionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, 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 @@ -58,7 +58,6 @@ protected StructuredGraph testGraph(final String snippet, String name) { return testGraph(snippet, name, false); } - @SuppressWarnings("try") protected StructuredGraph testGraph(final String snippet, String name, boolean assertInvoke) { return testGraph(getResolvedJavaMethod(snippet), name, assertInvoke); } @@ -73,10 +72,9 @@ protected StructuredGraph testGraph(final String snippet, String name, boolean a * {@code assertInvoke == false}) contain an {@link Invoke} node * */ - @SuppressWarnings("try") protected StructuredGraph testGraph(final ResolvedJavaMethod method, String name, boolean assertInvoke) { DebugContext debug = getDebugContext(); - try (DebugContext.Scope s = debug.scope("MethodSubstitutionTest", method)) { + try (DebugContext.Scope _ = debug.scope("MethodSubstitutionTest", method)) { StructuredGraph graph = parseEager(method, AllowAssumptions.YES, debug); HighTierContext context = getDefaultHighTierContext(); debug.dump(DebugContext.BASIC_LEVEL, graph, "Graph"); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/NestedExceptionHandlerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/NestedExceptionHandlerTest.java index 489655e27bd5..b72eec7be3ea 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/NestedExceptionHandlerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/NestedExceptionHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -73,11 +73,10 @@ public void testNestedExceptionHandler() { test(new OptionValues(getInitialOptions(), HighTier.Options.Inline, false), "nestedExceptionHandler"); } - @SuppressWarnings("try") public static String snippet1() { try { synchronized (String.class) { - try (AutoCloseable scope = null) { + try (AutoCloseable _ = null) { return "RETURN"; } catch (Throwable t) { return t.toString(); @@ -92,11 +91,10 @@ public static void raise() { throw new RuntimeException(); } - @SuppressWarnings("try") public static String snippet2() { try { synchronized (String.class) { - try (AutoCloseable scope = null) { + try (AutoCloseable _ = null) { return performCompilation(); } catch (Throwable t) { return t.toString(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PEGraphDecoderTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PEGraphDecoderTest.java index 870dbab60f73..a253730b7607 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PEGraphDecoderTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PEGraphDecoderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -178,7 +178,6 @@ public void testSingleImplementor() { } @Test - @SuppressWarnings("try") public void test() { test("doTest", EconomicMap.create(), getInitialOptions()); } @@ -223,12 +222,11 @@ private static void assertInlinedMethodsEqual(InliningLog.Callsite expected, Inl } } - @SuppressWarnings("try") private StructuredGraph test(String methodName, EconomicMap graphCache, OptionValues optionValues) { ResolvedJavaMethod testMethod = getResolvedJavaMethod(methodName); StructuredGraph targetGraph = null; DebugContext debug = getDebugContext(optionValues, null, null); - try (DebugContext.Scope scope = debug.scope("GraphPETest", testMethod)) { + try (DebugContext.Scope _ = debug.scope("GraphPETest", testMethod)) { GraphBuilderConfiguration graphBuilderConfig = GraphBuilderConfiguration.getDefault(getDefaultGraphBuilderPlugins()).withEagerResolving(true).withUnresolvedIsError(true); graphBuilderConfig = editGraphBuilderConfiguration(graphBuilderConfig); registerPlugins(graphBuilderConfig.getPlugins().getInvocationPlugins()); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PointerTrackingTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PointerTrackingTest.java index 40ca7d348b54..547576256d48 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PointerTrackingTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/PointerTrackingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -93,10 +93,9 @@ public static String trackingSnippet() { } @Test(expected = GraalError.class) - @SuppressWarnings("try") public void testVerification() { DebugContext debug = getDebugContext(); - try (DebugCloseable d = debug.disableIntercept(); DebugContext.Scope s = debug.scope("PointerTrackingTest")) { + try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("PointerTrackingTest")) { compile(getResolvedJavaMethod("verificationSnippet"), null); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/UnsafeObjectReplacementsTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/UnsafeObjectReplacementsTest.java index 1cfefda2bc0e..716a8791d965 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/UnsafeObjectReplacementsTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/replacements/test/UnsafeObjectReplacementsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -25,18 +25,18 @@ package jdk.graal.compiler.replacements.test; import java.io.IOException; +import java.lang.classfile.ClassFile; +import java.lang.classfile.ClassTransform; +import java.lang.classfile.CodeTransform; +import java.lang.classfile.MethodTransform; +import java.lang.classfile.instruction.InvokeInstruction; import java.lang.reflect.Method; -import jdk.graal.compiler.core.test.CustomizedBytecodePatternTest.CachedLoader; -import jdk.graal.compiler.test.AddExports; import org.junit.Test; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.MethodVisitor; -import org.objectweb.asm.Opcodes; -import org.objectweb.asm.Type; +import jdk.graal.compiler.core.test.CustomizedBytecodePattern; +import jdk.graal.compiler.serviceprovider.GraalServices; +import jdk.graal.compiler.test.AddExports; import jdk.internal.misc.Unsafe; import jdk.vm.ci.meta.ResolvedJavaMethod; @@ -46,7 +46,7 @@ * @see "https://bugs.openjdk.java.net/browse/JDK-8207146" */ @AddExports("java.base/jdk.internal.misc") -public class UnsafeObjectReplacementsTest extends MethodSubstitutionTest { +public class UnsafeObjectReplacementsTest extends MethodSubstitutionTest implements CustomizedBytecodePattern { public static class Container { public volatile Object objectField = dummyValue; @@ -127,10 +127,8 @@ public void testUnsafeObjectMethods() { * rewritten to invoke the corresponding {@code *Reference*} methods. */ private Class loadModifiedMethodsClass() { - String className = Methods.class.getName(); - CachedLoader cl = new CachedLoader(getClass().getClassLoader(), className, Generator::generate); try { - return cl.findClass(className); + return getClass(Methods.class.getName()); } catch (ClassNotFoundException e) { throw new AssertionError(e); } @@ -145,34 +143,29 @@ private static boolean unsafeHasReferenceMethods() { } } - static class Generator { - static byte[] generate(String className) { - int api = Opcodes.ASM9; - try { - ClassReader cr = new ClassReader(className); - ClassWriter cw = new ClassWriter(cr, 0); - ClassVisitor cv = new ClassVisitor(api, cw) { - @Override - public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { - return new MethodVisitor(api, super.visitMethod(access, name, descriptor, signature, exceptions)) { - @Override - public void visitMethodInsn(int opcode, String owner, String methodName, String methodDescriptor, boolean isInterface) { - if (methodName.contains("Object") && owner.equals(Type.getInternalName(Unsafe.class))) { - super.visitMethodInsn(opcode, owner, methodName.replace("Object", "Reference"), methodDescriptor, isInterface); - } else { - super.visitMethodInsn(opcode, owner, methodName, methodDescriptor, isInterface); - } - } - }; + @Override + public byte[] generateClass(String className) { + // @formatter:off + CodeTransform codeTransform = (codeBuilder, e) -> { + switch (e) { + case InvokeInstruction i -> { + if (i.owner().asSymbol().equals(cd(Unsafe.class)) && i.method().name().stringValue().contains("Object")) { + codeBuilder.invoke(i.opcode(), i.owner().asSymbol(), i.method().name().stringValue().replace("Object", "Reference"), i.typeSymbol(), i.isInterface()); + } else { + codeBuilder.accept(i); } - }; - - cr.accept(cv, 0); - cw.visitEnd(); - return cw.toByteArray(); - } catch (IOException e) { - throw new RuntimeException(e); + } + default -> codeBuilder.accept(e); } + }; + + try { + ClassFile cf = ClassFile.of(); + return cf.transformClass(cf.parse(GraalServices.getClassfileAsStream(Methods.class).readAllBytes()), + ClassTransform.transformingMethods(MethodTransform.transformingCode(codeTransform))); + } catch (IOException e) { + return new byte[0]; } + // @formatter:on } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/test/SubprocessUtil.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/test/SubprocessUtil.java index 9c11b45fa550..b35f4d3600a3 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/test/SubprocessUtil.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/test/SubprocessUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -45,9 +45,9 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -import jdk.graal.compiler.serviceprovider.GraalServices; import org.junit.Assume; +import jdk.graal.compiler.serviceprovider.GraalServices; import jdk.graal.compiler.util.CollectionsUtil; /** @@ -205,7 +205,7 @@ public static boolean isJavaAgentAttached(Predicate agentPredicate) { * Detects whether a Java agent is specified in the VM arguments. */ public static boolean isJavaAgentAttached() { - return isJavaAgentAttached(javaAgentValue -> true); + return isJavaAgentAttached(_ -> true); } /** diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BeginNodeOptimizationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BeginNodeOptimizationTest.java index 299ea814f9d4..c9c7cef84f62 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BeginNodeOptimizationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BeginNodeOptimizationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -88,7 +88,7 @@ static TestRootNode createTreeOfDepth(int depth) { } static TestRootNode createTreeWithBlockOfSize(int count) { - return new TestRootNode(new WithChildrenNode(IntStream.range(0, count).mapToObj(i -> new LeafNode()).toArray(TestNode[]::new))); + return new TestRootNode(new WithChildrenNode(IntStream.range(0, count).mapToObj(_ -> new LeafNode()).toArray(TestNode[]::new))); } static class TestRootNode extends RootNode { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeDSLCompilationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeDSLCompilationTest.java index 34a5923a29c7..b259aa392f2d 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeDSLCompilationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeDSLCompilationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -58,9 +58,9 @@ import com.oracle.truffle.api.instrumentation.ExecutionEventNode; import com.oracle.truffle.api.instrumentation.Instrumenter; import com.oracle.truffle.api.instrumentation.SourceSectionFilter; -import com.oracle.truffle.api.instrumentation.TruffleInstrument; import com.oracle.truffle.api.instrumentation.StandardTags.RootTag; import com.oracle.truffle.api.instrumentation.StandardTags.StatementTag; +import com.oracle.truffle.api.instrumentation.TruffleInstrument; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; import com.oracle.truffle.runtime.OptimizedCallTarget; @@ -979,7 +979,7 @@ public void clear() { private Counter attachCounter(Class... tags) { Counter c = new Counter(); - instrumenter.attachExecutionEventFactory(SourceSectionFilter.newBuilder().tagIs(tags).build(), (e) -> { + instrumenter.attachExecutionEventFactory(SourceSectionFilter.newBuilder().tagIs(tags).build(), (_) -> { return new ExecutionEventNode() { @Override public void onEnter(VirtualFrame f) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeInterpreterPartialEvaluationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeInterpreterPartialEvaluationTest.java index 6ba6f3036267..fb35e1191d8d 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeInterpreterPartialEvaluationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/BytecodeInterpreterPartialEvaluationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -808,7 +808,6 @@ public void instArraySimpleIfProgram() { } @Test - @SuppressWarnings("try") public void simpleSwitchProgram() { byte[] bytecodes = new byte[]{ /* 0: */Bytecode.CONST, @@ -831,7 +830,6 @@ public void simpleSwitchProgram() { } @Test - @SuppressWarnings("try") public void loopSwitchProgram() { byte[] bytecodes = new byte[]{ /* 0: */Bytecode.CONST, diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilationFinalWeakReferencePartialEvaluationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilationFinalWeakReferencePartialEvaluationTest.java index 9f812f2d89c7..f00d147f605a 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilationFinalWeakReferencePartialEvaluationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilationFinalWeakReferencePartialEvaluationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -185,7 +185,7 @@ public void compilationFinalWeakReferenceTestGC() { } private static IntSupplier generateTestData() { - return IntStream.range(0, 42).mapToObj(i -> new TestData()).reduce((l, r) -> new TestData(l, r)).get(); + return IntStream.range(0, 42).mapToObj(_ -> new TestData()).reduce((l, r) -> new TestData(l, r)).get(); } /** diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilerAssertsTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilerAssertsTest.java index ecc7c910e066..4b8c1bb75c15 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilerAssertsTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/CompilerAssertsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, 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 @@ -76,11 +76,10 @@ public int execute(VirtualFrame frame) { } @Test - @SuppressWarnings("try") public void neverPartOfCompilationTest() { NeverPartOfCompilationTestNode result = new NeverPartOfCompilationTestNode(); RootTestNode rootNode = new RootTestNode(new FrameDescriptor(), "neverPartOfCompilation", result); - try (PreventDumping noDump = new PreventDumping()) { + try (PreventDumping _ = new PreventDumping()) { compileHelper("neverPartOfCompilation", rootNode, new Object[0]); Assert.fail("Expected bailout exception due to never part of compilation"); } catch (BailoutException e) { @@ -89,12 +88,11 @@ public void neverPartOfCompilationTest() { } @Test - @SuppressWarnings("try") public void compilationNonConstantTest() { FrameDescriptor descriptor = new FrameDescriptor(); CompilationConstantTestNode result = new CompilationConstantTestNode(new NonConstantTestNode(5)); RootTestNode rootNode = new RootTestNode(descriptor, "compilationConstant", result); - try (PreventDumping noDump = new PreventDumping()) { + try (PreventDumping _ = new PreventDumping()) { compileHelper("compilationConstant", rootNode, new Object[0]); Assert.fail("Expected bailout exception because expression is not compilation constant"); } catch (BailoutException e) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ContextLookupCompilationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ContextLookupCompilationTest.java index 5b8728a832b8..fee8e00f1212 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ContextLookupCompilationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ContextLookupCompilationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -650,8 +650,8 @@ static final class ContextLocalValue { @Registration(id = SHARED1, name = SHARED1, contextPolicy = ContextPolicy.SHARED) public static class Shared1 extends TruffleLanguage { - final ContextLocal local = locals.createContextLocal((e) -> new ContextLocalValue()); - final ContextThreadLocal threadLocal = locals.createContextThreadLocal((e, t) -> new ContextLocalValue()); + final ContextLocal local = locals.createContextLocal((_) -> new ContextLocalValue()); + final ContextThreadLocal threadLocal = locals.createContextThreadLocal((_, _) -> new ContextLocalValue()); @Override protected LanguageContext createContext(Env env) { @@ -676,8 +676,8 @@ public static Shared1 get() { @Registration(id = SHARED2, name = SHARED2, contextPolicy = ContextPolicy.SHARED) public static class Shared2 extends TruffleLanguage { - final ContextLocal local = locals.createContextLocal((e) -> new ContextLocalValue()); - final ContextThreadLocal threadLocal = locals.createContextThreadLocal((e, t) -> new ContextLocalValue()); + final ContextLocal local = locals.createContextLocal((_) -> new ContextLocalValue()); + final ContextThreadLocal threadLocal = locals.createContextThreadLocal((_, _) -> new ContextLocalValue()); @Override protected LanguageContext createContext(Env env) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/EncodedGraphCacheTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/EncodedGraphCacheTest.java index 5a0540b24807..9109c2eebb6e 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/EncodedGraphCacheTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/EncodedGraphCacheTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -132,12 +132,11 @@ private static boolean encodedGraphCacheContains(TruffleCompilerImpl compiler, R return cache1.containsKey(method); } - @SuppressWarnings("try") private static OptimizedCallTarget compileAST(RootNode rootNode) { OptimizedCallTarget target = (OptimizedCallTarget) rootNode.getCallTarget(); TruffleCompilerImpl compiler = getTruffleCompilerFromRuntime(target); DebugContext debug = new DebugContext.Builder(compiler.getOrCreateCompilerOptions(target)).build(); - try (DebugContext.Scope s = debug.scope("EncodedGraphCacheTest")) { + try (DebugContext.Scope _ = debug.scope("EncodedGraphCacheTest")) { TruffleCompilationTask task = newTask(); try (TruffleCompilation compilation = compiler.openCompilation(task, target)) { target.ensureInitialized(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ExecutionListenerCompilerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ExecutionListenerCompilerTest.java index 38d6ee74f8ad..4f0694967611 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ExecutionListenerCompilerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ExecutionListenerCompilerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -96,10 +96,10 @@ public static Object throwErrorAndIncrement() { } } - private final Consumer empty = (e) -> { + private final Consumer empty = (_) -> { }; - private final Consumer counting = (e) -> { + private final Consumer counting = (_) -> { counter++; }; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FinalBitSetCompilationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FinalBitSetCompilationTest.java index cf1502065aca..8ccbf78bf1bd 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FinalBitSetCompilationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FinalBitSetCompilationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -35,25 +35,25 @@ public class FinalBitSetCompilationTest extends PartialEvaluationTest { @Test public void testEmpty() { FinalBitSet set = FinalBitSet.valueOf(new long[]{}); - assertConstant(false, (f) -> set.get(42)); - assertConstant(false, (f) -> set.get(0)); - assertConstant(0, (f) -> set.size()); - assertConstant(0, (f) -> set.length()); - assertConstant(0, (f) -> set.cardinality()); - assertConstant(true, (f) -> set.isEmpty()); + assertConstant(false, (_) -> set.get(42)); + assertConstant(false, (_) -> set.get(0)); + assertConstant(0, (_) -> set.size()); + assertConstant(0, (_) -> set.length()); + assertConstant(0, (_) -> set.cardinality()); + assertConstant(true, (_) -> set.isEmpty()); } @Test public void testSingle() { FinalBitSet set = FinalBitSet.valueOf(new long[]{0x8000_0000_0000_0001L}); - assertConstant(true, (f) -> set.get(0)); - assertConstant(false, (f) -> set.get(1)); - assertConstant(true, (f) -> set.get(63)); - assertConstant(false, (f) -> set.get(64)); - assertConstant(64, (f) -> set.size()); - assertConstant(64, (f) -> set.length()); - assertConstant(2, (f) -> set.cardinality()); - assertConstant(false, (f) -> set.isEmpty()); + assertConstant(true, (_) -> set.get(0)); + assertConstant(false, (_) -> set.get(1)); + assertConstant(true, (_) -> set.get(63)); + assertConstant(false, (_) -> set.get(64)); + assertConstant(64, (_) -> set.size()); + assertConstant(64, (_) -> set.length()); + assertConstant(2, (_) -> set.cardinality()); + assertConstant(false, (_) -> set.isEmpty()); } @Test @@ -68,14 +68,14 @@ public void testMultiple() { for (int i = 0; i < size; i++) { final int index = i; int base = index * 64; - assertConstant(true, (f) -> set.get(base)); - assertConstant(true, (f) -> set.get(base + 63)); - assertConstant(false, (f) -> set.get(base + 1)); + assertConstant(true, (_) -> set.get(base)); + assertConstant(true, (_) -> set.get(base + 63)); + assertConstant(false, (_) -> set.get(base + 1)); } } } private void assertConstant(Object expectedConstant, FrameFunction ff) { - assertPartialEvalEquals(toRootNode((f) -> expectedConstant), toRootNode(ff), new Object[0]); + assertPartialEvalEquals(toRootNode((_) -> expectedConstant), toRootNode(ff), new Object[0]); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FlushEngineQueueTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FlushEngineQueueTest.java index 2892d90cd8ee..fd58de097411 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FlushEngineQueueTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/FlushEngineQueueTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -33,7 +33,6 @@ import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.runtime.OptimizedCallTarget; -@SuppressWarnings("try") public class FlushEngineQueueTest { @Test diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterExampleTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterExampleTest.java index 9c14be21cf9a..c1d4a70c3106 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterExampleTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterExampleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -54,7 +54,6 @@ public class HostInliningBytecodeInterpreterExampleTest extends TruffleCompilerImplTest { @Test - @SuppressWarnings("try") public void test() throws Throwable { // call the method to initialize classes interpreterSwitch(); @@ -66,7 +65,7 @@ public void test() throws Throwable { OptionValues options = HostInliningTest.createHostInliningOptions(30000, -1); StructuredGraph graph = parseForCompile(method, options); - try (DebugContext.Scope ds = graph.getDebug().scope("Testing", method, graph)) { + try (DebugContext.Scope _ = graph.getDebug().scope("Testing", method, graph)) { super.createSuites(options).getHighTier().apply(graph, getDefaultHighTierContext()); for (InvokeNode invoke : graph.getNodes().filter(InvokeNode.class)) { ResolvedJavaMethod invokedMethod = invoke.getTargetMethod(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterTest.java index f73a9a58914c..751cd8b0b070 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningBytecodeInterpreterTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -40,12 +40,11 @@ public class HostInliningBytecodeInterpreterTest extends GraalCompilerTest { @Test - @SuppressWarnings("try") public void test() throws Throwable { ResolvedJavaMethod method = getResolvedJavaMethod("interpreterSwitch"); OptionValues options = HostInliningTest.createHostInliningOptions(30000, -1); StructuredGraph graph = parseForCompile(method, options); - try (DebugContext.Scope ds = graph.getDebug().scope("Testing", method, graph)) { + try (DebugContext.Scope _ = graph.getDebug().scope("Testing", method, graph)) { super.createSuites(options).getHighTier().apply(graph, getDefaultHighTierContext()); for (InvokeNode invoke : graph.getNodes().filter(InvokeNode.class)) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningTest.java index 03c439690f36..5b84e96cd7d9 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/HostInliningTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -150,7 +150,6 @@ public void test() { runTest("testNativeCall"); } - @SuppressWarnings("try") void runTest(String methodName) { // initialize the Truffle runtime to ensure that all intrinsics are applied Truffle.getRuntime(); @@ -178,7 +177,7 @@ void runTest(String methodName) { } } - try (DebugContext.Scope ds = graph.getDebug().scope("Testing", method, graph)) { + try (DebugContext.Scope _ = graph.getDebug().scope("Testing", method, graph)) { HighTierContext context = getEagerHighTierContext(); CanonicalizerPhase canonicalizer = createCanonicalizerPhase(); if (run == TestRun.WITH_CONVERT_TO_GUARD) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/IndirectCallSiteTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/IndirectCallSiteTest.java index d19240b74276..b87a39786ff6 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/IndirectCallSiteTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/IndirectCallSiteTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -40,7 +40,6 @@ import com.oracle.truffle.runtime.OptimizedRuntimeOptions; import com.oracle.truffle.runtime.OptimizedTruffleRuntime; -@SuppressWarnings("try") public class IndirectCallSiteTest extends TestWithSynchronousCompiling { private static final OptimizedTruffleRuntime runtime = (OptimizedTruffleRuntime) Truffle.getRuntime(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/InstrumentationCompilerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/InstrumentationCompilerTest.java index 8bf6bc91d3c9..5cb043429319 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/InstrumentationCompilerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/InstrumentationCompilerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -182,7 +182,7 @@ protected void onCreate(Env env) { env.getInstrumenter().attachExecutionEventFactory( SourceSectionFilter.newBuilder().tagIs(StandardTags.ExpressionTag.class).build(), SourceSectionFilter.newBuilder().tagIs(StandardTags.ExpressionTag.class).build(), - context -> new SavingNode()); + _ -> new SavingNode()); } } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/JFRPartialEvaluationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/JFRPartialEvaluationTest.java index e05863c9ebc2..1f967a2d1aed 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/JFRPartialEvaluationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/JFRPartialEvaluationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -167,7 +167,7 @@ private static void runInSubprocessWithJFREnabled(Runnable action) throws IOExce try { SubprocessTestUtils.newBuilder(JFRPartialEvaluationTest.class, action) // .prefixVmOption(String.format("-XX:StartFlightRecording=exceptions=all,filename=%s", jfrFile)) // - .onExit((p) -> { + .onExit((_) -> { try { assertTrue(String.format("JFR event file %s is missing", jfrFile), Files.size(jfrFile) > 0); } catch (IOException ioe) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/LanguageContextFreedTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/LanguageContextFreedTest.java index 65eec4727dbb..f28a610fb2f9 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/LanguageContextFreedTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/LanguageContextFreedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, 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 @@ -32,10 +32,6 @@ import java.util.List; import java.util.function.Supplier; -import com.oracle.truffle.api.test.SubprocessTestUtils; -import com.oracle.truffle.runtime.OptimizedCallTarget; -import com.oracle.truffle.runtime.OptimizedRuntimeOptions; - import org.graalvm.collections.Pair; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Engine; @@ -51,6 +47,9 @@ import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.test.GCUtils; +import com.oracle.truffle.api.test.SubprocessTestUtils; +import com.oracle.truffle.runtime.OptimizedCallTarget; +import com.oracle.truffle.runtime.OptimizedRuntimeOptions; public class LanguageContextFreedTest { @@ -154,8 +153,8 @@ static final class LanguageContext { public abstract static class Base extends TruffleLanguage { - final ContextLocal contextLocal = locals.createContextLocal((e) -> new ContextLocalValue()); - final ContextThreadLocal threadLocal = locals.createContextThreadLocal((e, t) -> new ContextLocalValue()); + final ContextLocal contextLocal = locals.createContextLocal((_) -> new ContextLocalValue()); + final ContextThreadLocal threadLocal = locals.createContextThreadLocal((_, _) -> new ContextLocalValue()); @Override protected LanguageContext createContext(Env env) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/MultiTierCompilationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/MultiTierCompilationTest.java index 1b8e55df771e..d5c94ed09763 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/MultiTierCompilationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/MultiTierCompilationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2025, 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 @@ -182,7 +182,6 @@ public Object executeRepeatingWithValue(VirtualFrame frame) { private static void boundary() { } - @SuppressWarnings("try") @Test public void testDefault() { setupContext(Context.newBuilder().allowExperimentalOptions(true).option("engine.CompileImmediately", "false").option("engine.BackgroundCompilation", "false").option("engine.MultiTier", @@ -205,7 +204,6 @@ public void testDefault() { Assert.assertEquals("callee:inlined", multiTierTarget.call()); } - @SuppressWarnings("try") @Test public void testFirstTierInlining() { setupContext(Context.newBuilder().allowExperimentalOptions(true).option("engine.CompileImmediately", "false").option("engine.BackgroundCompilation", "false").option("engine.MultiTier", @@ -228,7 +226,6 @@ public void testFirstTierInlining() { Assert.assertEquals("callee:inlined", multiTierTarget.call()); } - @SuppressWarnings("try") @Test public void testWhenCalleeCompiledFirst() { setupContext(Context.newBuilder().allowExperimentalOptions(true).option("engine.CompileImmediately", "false").option("engine.BackgroundCompilation", "false").option("engine.MultiTier", @@ -262,7 +259,6 @@ public void testWhenCalleeCompiledFirst() { Assert.assertEquals("callee:inlined", multiTierTarget.call()); } - @SuppressWarnings("try") @Test public void testLoop() { int firstThreshold = 100; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/NodeLimitTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/NodeLimitTest.java index a1e51eda525f..154833e92b2c 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/NodeLimitTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/NodeLimitTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -171,7 +171,6 @@ private int getBaselineGraphNodeCount(RootNode rootNode) { return NodeCostUtil.computeGraphSize(baselineGraph); } - @SuppressWarnings("try") private void peRootNode(int nodeLimit, Supplier rootNodeFactory) { setupContext(Context.newBuilder().allowAllAccess(true).allowExperimentalOptions(true).option("compiler.MaximumGraalGraphSize", Integer.toString(nodeLimit)).build()); RootCallTarget target = rootNodeFactory.get().getCallTarget(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedCallTargetTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedCallTargetTest.java index 65e11b885ea1..33531a41fd37 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedCallTargetTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedCallTargetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -59,7 +59,6 @@ import com.oracle.truffle.runtime.OptimizedOSRLoopNode; import com.oracle.truffle.runtime.OptimizedRuntimeOptions; -@SuppressWarnings("try") public class OptimizedCallTargetTest extends TestWithSynchronousCompiling { private static final OptimizedTruffleRuntime runtime = (OptimizedTruffleRuntime) Truffle.getRuntime(); private static final Field nodeRewritingAssumptionField; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedOSRLoopNodeTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedOSRLoopNodeTest.java index 050aa1838fe1..952ecaf767a9 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedOSRLoopNodeTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OptimizedOSRLoopNodeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -67,17 +67,17 @@ import com.oracle.truffle.api.nodes.RepeatingNode; import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.test.polyglot.ProxyLanguage; -import com.oracle.truffle.runtime.OptimizedTruffleRuntime; import com.oracle.truffle.runtime.OptimizedCallTarget; import com.oracle.truffle.runtime.OptimizedDirectCallNode; import com.oracle.truffle.runtime.OptimizedOSRLoopNode; +import com.oracle.truffle.runtime.OptimizedTruffleRuntime; @RunWith(Theories.class) public class OptimizedOSRLoopNodeTest extends TestWithSynchronousCompiling { private static final OptimizedTruffleRuntime runtime = (OptimizedTruffleRuntime) Truffle.getRuntime(); - @DataPoint public static final OSRLoopFactory DEFAULT = (threshold, repeating) -> (OptimizedOSRLoopNode) OptimizedOSRLoopNode.create(repeating); + @DataPoint public static final OSRLoopFactory DEFAULT = (_, repeating) -> (OptimizedOSRLoopNode) OptimizedOSRLoopNode.create(repeating); private int osrThreshold; private Context context; @@ -134,7 +134,6 @@ public Object execute(VirtualFrame frame) { assertCompiled(rootNode.getOSRTarget()); } - @SuppressWarnings("try") @Theory public void testOSRAndRewriteDoesNotSuppressTargetCompilation(OSRLoopFactory factory) { setupContext("engine.SingleTierCompilationThreshold", "3"); @@ -327,15 +326,15 @@ public void testOSRMinInvocationThresholdPropagateLoopCounts(OSRLoopFactory fact @Theory public void testThreadSafety(OSRLoopFactory factory) { int threshold = osrThreshold; - IntStream.generate(() -> 10).limit(10).parallel().forEach(i -> { + IntStream.generate(() -> 10).limit(10).parallel().forEach(_ -> { TestRootNode rootNode = TestRootNode.create(osrThreshold, factory, new TestRepeatingNode()); - IntStream.generate(() -> threshold).limit(10).parallel().forEach(k -> executeNoCallTarget(rootNode, threshold + 1)); + IntStream.generate(() -> threshold).limit(10).parallel().forEach(_ -> executeNoCallTarget(rootNode, threshold + 1)); waitForCompiled(rootNode.getOSRTarget()); }); - IntStream.generate(() -> 10).limit(10).parallel().forEach(i -> { + IntStream.generate(() -> 10).limit(10).parallel().forEach(_ -> { TestRootNode rootNode = TestRootNode.create(osrThreshold, factory, new TestRepeatingNode()); - IntStream.generate(() -> threshold).limit(10).parallel().forEach(k -> executeNoCallTarget(rootNode, threshold)); + IntStream.generate(() -> threshold).limit(10).parallel().forEach(_ -> executeNoCallTarget(rootNode, threshold)); waitForCompiled(rootNode.getOSRTarget()); }); } diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OverrideOptionsTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OverrideOptionsTest.java index 15f7920b49f9..27b7966d25c1 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OverrideOptionsTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/OverrideOptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -36,7 +36,6 @@ public class OverrideOptionsTest extends TruffleCompilerImplTest { @Test - @SuppressWarnings("try") public void testOverrideOptionsUsingContext() { setupContext(Context.newBuilder().allowAllAccess(true).allowExperimentalOptions(true).option("engine.BackgroundCompilation", Boolean.FALSE.toString()).option("engine.CompileImmediately", Boolean.TRUE.toString()).build()); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PartialEvaluationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PartialEvaluationTest.java index 955410443010..3875cec924c5 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PartialEvaluationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PartialEvaluationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -264,7 +264,6 @@ protected StructuredGraph partialEvalWithNodeEventListener(OptimizedCallTarget c return partialEval(compilable, arguments, listener); } - @SuppressWarnings("try") private StructuredGraph partialEval(OptimizedCallTarget compilable, Object[] arguments, Graph.NodeEventListener nodeEventListener) { // Executed AST so that all classes are loaded and initialized. if (!preventProfileCalls) { @@ -287,7 +286,7 @@ private StructuredGraph partialEval(OptimizedCallTarget compilable, Object[] arg TruffleCompilationTask task = newTask(); TruffleCompilerImpl compiler = getTruffleCompiler(compilable); try (TruffleCompilation compilation = compiler.openCompilation(task, compilable)) { - try (DebugContext.Scope s = debug.scope("TruffleCompilation", new TruffleDebugJavaMethod(task, compilable))) { + try (DebugContext.Scope _ = debug.scope("TruffleCompilation", new TruffleDebugJavaMethod(task, compilable))) { SpeculationLog speculationLog = compilable.getCompilationSpeculationLog(); if (speculationLog != null) { speculationLog.collectFailedSpeculations(); @@ -305,7 +304,7 @@ private StructuredGraph partialEval(OptimizedCallTarget compilable, Object[] arg compilation.getCompilationId(), speculationLog, task, handler); - try (Graph.NodeEventScope nes = nodeEventListener == null ? null : context.graph.trackNodeEvents(nodeEventListener)) { + try (Graph.NodeEventScope _ = nodeEventListener == null ? null : context.graph.trackNodeEvents(nodeEventListener)) { truffleTier.apply(context.graph, context); lastCompiledGraph = context.graph; return context.graph; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PerformanceWarningTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PerformanceWarningTest.java index 585fe6793506..c3d1216b7a4d 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PerformanceWarningTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PerformanceWarningTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -117,7 +117,6 @@ public void testFrameAccessVerification() { testHelper(new RootNodeFrameAccessVerification(), true, "perf warn"); } - @SuppressWarnings("try") private void testHelper(RootNode rootNode, boolean expectException, String... outputStrings) { // Compile and capture output to logger's stream. boolean seenException = false; @@ -125,7 +124,7 @@ private void testHelper(RootNode rootNode, boolean expectException, String... ou OptimizedCallTarget target = (OptimizedCallTarget) rootNode.getCallTarget(); TruffleCompilerImpl compiler = getTruffleCompiler(target); DebugContext debug = new Builder(compiler.getOrCreateCompilerOptions(target)).build(); - try (DebugCloseable d = debug.disableIntercept(); DebugContext.Scope s = debug.scope("PerformanceWarningTest")) { + try (DebugCloseable _ = debug.disableIntercept(); DebugContext.Scope _ = debug.scope("PerformanceWarningTest")) { final OptimizedCallTarget compilable = target; compilable.ensureInitialized(); TruffleCompilationTask task = PartialEvaluationTest.newTask(); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PropagateHotnessToLexicalSingleCallerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PropagateHotnessToLexicalSingleCallerTest.java index 18a3adcc095e..93a86ebea9bd 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PropagateHotnessToLexicalSingleCallerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/PropagateHotnessToLexicalSingleCallerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2022, 2025, 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 @@ -39,8 +39,8 @@ import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.nodes.RepeatingNode; import com.oracle.truffle.api.nodes.RootNode; -import com.oracle.truffle.runtime.OptimizedTruffleRuntime; import com.oracle.truffle.runtime.OptimizedCallTarget; +import com.oracle.truffle.runtime.OptimizedTruffleRuntime; public class PropagateHotnessToLexicalSingleCallerTest extends TestWithSynchronousCompiling { @@ -140,7 +140,7 @@ public void basicTest() { public void basicNoReorderTest() { final String callerName = "Caller"; final String calleeName = "Callee"; - CallerRootNode callerRootNode = new CallerRootNode(callerName, frameDescriptor -> new RootNodeWithLoop(calleeName, null), null); + CallerRootNode callerRootNode = new CallerRootNode(callerName, _ -> new RootNodeWithLoop(calleeName, null), null); OptimizedCallTarget callTarget = ((OptimizedCallTarget) callerRootNode.getCallTarget()); compile(callTarget); Assert.assertTrue(callTarget.getCallAndLoopCount() < callerRootNode.target.getCallAndLoopCount()); @@ -152,7 +152,7 @@ public void withIntermediateTest() { final String intermediateName = "Intermediate"; final String calleeName = "Callee"; CallerRootNode callerRootNode = new CallerRootNode(callerName, frameDescriptor -> { - return new CallerRootNode(intermediateName, ignored -> { + return new CallerRootNode(intermediateName, _ -> { return new RootNodeWithLoop(calleeName, frameDescriptor); }, null); }, null); @@ -188,10 +188,10 @@ public void withIntermediateTangledTest() { public void testDepth() { final String name = "Caller"; CallerRootNode callerRootNode = new CallerRootNode(name + "0", frameDescriptor0 -> { - return new CallerRootNode(name + "1", frameDescriptor1 -> { - return new CallerRootNode(name + "2", frameDescriptor2 -> { - return new CallerRootNode(name + "3", frameDescriptor3 -> { - return new CallerRootNode(name + "4", frameDescriptor4 -> { + return new CallerRootNode(name + "1", _ -> { + return new CallerRootNode(name + "2", _ -> { + return new CallerRootNode(name + "3", _ -> { + return new CallerRootNode(name + "4", _ -> { return new RootNodeWithLoop("loop", frameDescriptor0); }, null); }, null); diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ResourceLimitsCompilationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ResourceLimitsCompilationTest.java index c69e968a6616..2f03cda3f9d6 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ResourceLimitsCompilationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/ResourceLimitsCompilationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, 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 @@ -50,7 +50,6 @@ public class ResourceLimitsCompilationTest extends PartialEvaluationTest { @Test - @SuppressWarnings("try") public void testStatementLimitSingleContext() { ResourceLimits limits = ResourceLimits.newBuilder().// statementLimit(5000, null).// @@ -71,7 +70,6 @@ public void testStatementLimitSingleContext() { } @Test - @SuppressWarnings("try") public void testStatementLimitMultiContext() { ResourceLimits limits = ResourceLimits.newBuilder().// statementLimit(5000, null).// @@ -84,7 +82,6 @@ public void testStatementLimitMultiContext() { } @Test - @SuppressWarnings("try") public void testStatementLimitMultiContextTwoEqualConfigs() { ResourceLimits limits0 = ResourceLimits.newBuilder().// statementLimit(5000, null).// @@ -103,7 +100,6 @@ public void testStatementLimitMultiContextTwoEqualConfigs() { } @Test - @SuppressWarnings("try") public void testStatementLimitMultiContextTwoDifferentConfigs() { ResourceLimits limits0 = ResourceLimits.newBuilder().// statementLimit(5000, null).// @@ -155,7 +151,6 @@ private void assertLimitCheckFastPath(Context context) { } @Test - @SuppressWarnings("try") public void testStatementLimitEngineMultiThread() throws InterruptedException { ResourceLimits limits = ResourceLimits.newBuilder().// statementLimit(5000, null).// @@ -183,7 +178,6 @@ public void testStatementLimitEngineMultiThread() throws InterruptedException { } @Test - @SuppressWarnings("try") public void testStatementLimitContextMultiThread() throws InterruptedException { ResourceLimits limits = ResourceLimits.newBuilder().// statementLimit(5000, null).// @@ -254,7 +248,7 @@ private static OptimizedCallTarget evalTestScript(Context context) { } private static int countNodes(StructuredGraph graph, NodeClass nodeClass) { - return countNodes(graph, nodeClass, (n) -> true); + return countNodes(graph, nodeClass, (_) -> true); } @SuppressWarnings("unchecked") diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/SimplePartialEvaluationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/SimplePartialEvaluationTest.java index afb86427801e..3fdfc73252f7 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/SimplePartialEvaluationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/SimplePartialEvaluationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2025, 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 @@ -99,14 +99,13 @@ public void addConstants() { } @Test - @SuppressWarnings("try") public void neverPartOfCompilationTest() { FrameDescriptor fd = new FrameDescriptor(); AbstractTestNode firstTree = new NeverPartOfCompilationTestNode(new ConstantTestNode(1), 2); assertPartialEvalEquals(SimplePartialEvaluationTest::constant42, new RootTestNode(fd, "neverPartOfCompilationTest", firstTree)); AbstractTestNode secondTree = new NeverPartOfCompilationTestNode(new ConstantTestNode(1), 1); - try (PreventDumping noDump = new PreventDumping()) { + try (PreventDumping _ = new PreventDumping()) { assertPartialEvalEquals(SimplePartialEvaluationTest::constant42, new RootTestNode(fd, "neverPartOfCompilationTest", secondTree)); Assert.fail("Expected verification error!"); } catch (GraalBailoutException t) { @@ -501,7 +500,6 @@ public void complexUnrollFullUnrollUntilReturn() { } @Test - @SuppressWarnings("try") public void complexUnrollFullExplodeUntilReturn() throws Exception { FrameDescriptor fd = new FrameDescriptor(); final int loopIterations = 5; diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/StaticObjectCompilationTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/StaticObjectCompilationTest.java index c63b358b4d69..0abfda85bc8b 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/StaticObjectCompilationTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/StaticObjectCompilationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2021, 2025, 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 @@ -26,17 +26,6 @@ import java.io.Closeable; -import jdk.graal.compiler.nodes.StructuredGraph; -import jdk.graal.compiler.nodes.calc.AddNode; -import jdk.graal.compiler.nodes.calc.LeftShiftNode; -import jdk.graal.compiler.nodes.extended.RawLoadNode; -import jdk.graal.compiler.nodes.extended.RawStoreNode; -import jdk.graal.compiler.nodes.java.InstanceOfNode; -import jdk.graal.compiler.nodes.java.LoadFieldNode; -import jdk.graal.compiler.nodes.java.MethodCallTargetNode; -import jdk.graal.compiler.nodes.java.StoreFieldNode; -import jdk.graal.compiler.nodes.virtual.VirtualArrayNode; -import jdk.graal.compiler.nodes.virtual.VirtualInstanceNode; import org.graalvm.polyglot.Context; import org.junit.AfterClass; import org.junit.Assert; @@ -57,6 +46,18 @@ import com.oracle.truffle.api.staticobject.StaticProperty; import com.oracle.truffle.api.staticobject.StaticShape; +import jdk.graal.compiler.nodes.StructuredGraph; +import jdk.graal.compiler.nodes.calc.AddNode; +import jdk.graal.compiler.nodes.calc.LeftShiftNode; +import jdk.graal.compiler.nodes.extended.RawLoadNode; +import jdk.graal.compiler.nodes.extended.RawStoreNode; +import jdk.graal.compiler.nodes.java.InstanceOfNode; +import jdk.graal.compiler.nodes.java.LoadFieldNode; +import jdk.graal.compiler.nodes.java.MethodCallTargetNode; +import jdk.graal.compiler.nodes.java.StoreFieldNode; +import jdk.graal.compiler.nodes.virtual.VirtualArrayNode; +import jdk.graal.compiler.nodes.virtual.VirtualInstanceNode; + @RunWith(Parameterized.class) public class StaticObjectCompilationTest extends PartialEvaluationTest { static final StaticObjectTestEnvironment[] environments = StaticObjectTestEnvironment.getEnvironments(); @@ -102,20 +103,20 @@ public void simplePropertyAccesses() { FieldBasedStorage fbs = new FieldBasedStorage(); // Property set - assertPartialEvalEquals(toRootNode((f) -> fbs.property = 42), toRootNode((f) -> { + assertPartialEvalEquals(toRootNode((_) -> fbs.property = 42), toRootNode((_) -> { finalProperty.setInt(staticObject, 42); return finalProperty.getInt(staticObject); }), new Object[0]); - assertPartialEvalEquals(toRootNode((f) -> fbs.property = 42), toRootNode((f) -> { + assertPartialEvalEquals(toRootNode((_) -> fbs.property = 42), toRootNode((_) -> { property.setInt(staticObject, 42); return property.getInt(staticObject); }), new Object[0]); finalProperty.setInt(staticObject, 42); // Property get - assertPartialEvalEquals(toRootNode((f) -> 42), toRootNode((f) -> finalProperty.getInt(staticObject)), new Object[0]); - assertPartialEvalEquals(toRootNode((f) -> fbs.finalProperty), toRootNode((f) -> finalProperty.getInt(staticObject)), new Object[0]); - assertPartialEvalEquals(toRootNode((f) -> fbs.property), toRootNode((f) -> property.getInt(staticObject)), new Object[0]); + assertPartialEvalEquals(toRootNode((_) -> 42), toRootNode((_) -> finalProperty.getInt(staticObject)), new Object[0]); + assertPartialEvalEquals(toRootNode((_) -> fbs.finalProperty), toRootNode((_) -> finalProperty.getInt(staticObject)), new Object[0]); + assertPartialEvalEquals(toRootNode((_) -> fbs.property), toRootNode((_) -> property.getInt(staticObject)), new Object[0]); } @Test @@ -136,8 +137,8 @@ public void propertyAccessesInHierarchy() { s1p1.setInt(o2, 24); s2p1.setInt(o2, 42); - assertPartialEvalEquals(toRootNode((f) -> 24), toRootNode((f) -> s1p1.getInt(o2)), new Object[0]); - assertPartialEvalEquals(toRootNode((f) -> 42), toRootNode((f) -> s2p1.getInt(o2)), new Object[0]); + assertPartialEvalEquals(toRootNode((_) -> 24), toRootNode((_) -> s1p1.getInt(o2)), new Object[0]); + assertPartialEvalEquals(toRootNode((_) -> 42), toRootNode((_) -> s2p1.getInt(o2)), new Object[0]); } @Test diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleBoundaryExceptionsTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleBoundaryExceptionsTest.java index 248272581d4a..6f8d1bc189b1 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleBoundaryExceptionsTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleBoundaryExceptionsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2025, 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 @@ -52,7 +52,6 @@ public void before() { } @Test - @SuppressWarnings("try") public void testExceptionOnTruffleBoundaryDeoptsOnce() { class DeoptCountingExceptionOverBoundaryRootNode extends RootNode { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleExplicitOOMETest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleExplicitOOMETest.java index 5e26aeaf4950..3abba0c2b7e8 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleExplicitOOMETest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleExplicitOOMETest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2024, 2025, 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 @@ -93,7 +93,6 @@ protected OptionValues getGraalOptions() { } @Test - @SuppressWarnings("try") public void testNeverSeenExceptionHandlerSkipped() { /* * We disable truffle AST inlining to not inline the callee diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleHostInliningTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleHostInliningTest.java index 6dceb7896ced..452853936abb 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleHostInliningTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleHostInliningTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2025, 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 @@ -29,13 +29,13 @@ import java.nio.file.Files; import java.util.function.Consumer; -import com.oracle.truffle.api.test.SubprocessTestUtils; import org.junit.Assert; import org.junit.Test; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.HostCompilerDirectives.BytecodeInterpreterSwitch; import com.oracle.truffle.api.Truffle; +import com.oracle.truffle.api.test.SubprocessTestUtils; /** * Test to ensure that host inlining is enabled only if a Truffle runtime is enabled. @@ -83,7 +83,7 @@ private void runHostCompilationTest(Runnable inProcess, Consumer log) th String.format("-XX:CompileCommand=compileonly,%s::*", TruffleHostInliningTest.class.getName()), "-Xbatch").// force synchronous compilation postfixVmOption("-XX:+UseJVMCICompiler").// force Graal host compilation - onExit((process) -> { + onExit((_) -> { try { log.accept((Files.readString(logFile.toPath()))); } catch (IOException e) { diff --git a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleToTruffleCallExceptionHandlerTest.java b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleToTruffleCallExceptionHandlerTest.java index 6754b4d49fe5..3d18c99dd3bd 100644 --- a/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleToTruffleCallExceptionHandlerTest.java +++ b/compiler/src/jdk.graal.compiler.test/src/jdk/graal/compiler/truffle/test/TruffleToTruffleCallExceptionHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2025, 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 @@ -105,7 +105,6 @@ public String toString() { } @Test - @SuppressWarnings("try") public void testNeverSeenExceptionHandlerSkipped() { /* * We disable truffle AST inlining to not inline the callee @@ -117,7 +116,6 @@ public void testNeverSeenExceptionHandlerSkipped() { } @Test - @SuppressWarnings("try") public void testExceptionOnceCompileExceptionHandler() { preventProfileCalls = true; try { diff --git a/substratevm/mx.substratevm/suite.py b/substratevm/mx.substratevm/suite.py index 3d9609bb3da5..eb34e882e892 100644 --- a/substratevm/mx.substratevm/suite.py +++ b/substratevm/mx.substratevm/suite.py @@ -35,6 +35,27 @@ }, "libraries" : { + "ASM_9.7.1" : { + "digest" : "sha512:4767b01603dad5c79cc1e2b5f3722f72b1059d928f184f446ba11badeb1b381b3a3a9a801cc43d25d396df950b09d19597c73173c411b1da890de808b94f1f50", + "sourceDigest" : "sha512:d7c0de5912d04949a3d06cad366ff35a877da2682d9c74579625d62686032ea9349aff6102b17f92e9ec7eb4e9b1cd906b649c6a3ac798bfb9e31e5425de009d", + "maven" : { + "groupId" : "org.ow2.asm", + "artifactId" : "asm", + "version" : "9.7.1", + }, + "license" : "BSD-new", + }, + "ASM_TREE_9.7.1" : { + "digest" : "sha512:e55008c392fdd35e95d3404766b12dd4b46e13d5c362fcd0ab42a65751a82737eaf0ebc857691d1916190d34407adfde4437615d69c278785416fd911e00978d", + "sourceDigest" : "sha512:3cea80bc7b55679dfa3d2065c6cb6951007cc7817082e9fcf4c5e3cdc073c22eddf7c7899cff60b1092049ec9038e8d3aa9a8828ef731739bda8b5afcec30e86", + "maven" : { + "groupId" : "org.ow2.asm", + "artifactId" : "asm-tree", + "version" : "9.7.1", + }, + "dependencies" : ["ASM_9.7.1"], + "license" : "BSD-new", + }, "RENAISSANCE_HARNESS_v0.9" : { "urls" : ["https://lafo.ssw.uni-linz.ac.at/pub/graal-external-deps/renaissance/renaissance-harness_v0.9.0.tar.gz"], "digest" : "sha512:068207adf6bbd0a934429f7d6ddba8810e55992d06e131479658a7933bb352ea892d4304f745806dc342a6f7187a434ff2f106c6f8a6ee35ee696ea4fc998f7b", @@ -290,8 +311,8 @@ "javaCompliance" : "17+", "spotbugsIgnoresGenerated" : True, "shadedDependencies" : [ - "compiler:ASM_9.7.1", - "compiler:ASM_TREE_9.7.1", + "ASM_9.7.1", + "ASM_TREE_9.7.1", ], "class" : "ShadedLibraryProject", "shade" : {