1 /*
2 * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.hpp"
26 #include "ci/ciArrayKlass.hpp"
27 #include "ci/ciFlatArrayKlass.hpp"
28 #include "ci/ciInstanceKlass.hpp"
29 #include "ci/ciSymbols.hpp"
30 #include "ci/ciUtilities.inline.hpp"
31 #include "classfile/vmIntrinsics.hpp"
32 #include "compiler/compileBroker.hpp"
33 #include "compiler/compileLog.hpp"
34 #include "gc/shared/barrierSet.hpp"
35 #include "gc/shared/c2/barrierSetC2.hpp"
36 #include "jfr/support/jfrIntrinsics.hpp"
37 #include "memory/resourceArea.hpp"
38 #include "oops/accessDecorators.hpp"
39 #include "oops/klass.inline.hpp"
40 #include "oops/layoutKind.hpp"
41 #include "oops/objArrayKlass.hpp"
42 #include "opto/addnode.hpp"
43 #include "opto/arraycopynode.hpp"
44 #include "opto/c2compiler.hpp"
45 #include "opto/castnode.hpp"
46 #include "opto/cfgnode.hpp"
47 #include "opto/convertnode.hpp"
48 #include "opto/countbitsnode.hpp"
49 #include "opto/graphKit.hpp"
50 #include "opto/idealKit.hpp"
51 #include "opto/inlinetypenode.hpp"
52 #include "opto/library_call.hpp"
53 #include "opto/mathexactnode.hpp"
54 #include "opto/mulnode.hpp"
55 #include "opto/narrowptrnode.hpp"
56 #include "opto/opaquenode.hpp"
57 #include "opto/opcodes.hpp"
58 #include "opto/parse.hpp"
59 #include "opto/rootnode.hpp"
60 #include "opto/runtime.hpp"
61 #include "opto/subnode.hpp"
62 #include "opto/type.hpp"
63 #include "opto/vectornode.hpp"
64 #include "prims/jvmtiExport.hpp"
65 #include "prims/jvmtiThreadState.hpp"
66 #include "prims/unsafe.hpp"
67 #include "runtime/globals.hpp"
68 #include "runtime/jniHandles.inline.hpp"
69 #include "runtime/mountUnmountDisabler.hpp"
70 #include "runtime/objectMonitor.hpp"
71 #include "runtime/sharedRuntime.hpp"
72 #include "runtime/stubRoutines.hpp"
73 #include "utilities/globalDefinitions.hpp"
74 #include "utilities/macros.hpp"
75 #include "utilities/powerOfTwo.hpp"
76
77 //---------------------------make_vm_intrinsic----------------------------
78 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
79 vmIntrinsicID id = m->intrinsic_id();
80 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
81
82 if (!m->is_loaded()) {
83 // Do not attempt to inline unloaded methods.
84 return nullptr;
85 }
86
87 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
88 bool is_available = false;
89
90 {
91 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
92 // the compiler must transition to '_thread_in_vm' state because both
93 // methods access VM-internal data.
94 VM_ENTRY_MARK;
95 methodHandle mh(THREAD, m->get_Method());
96 is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
97 if (is_available && is_virtual) {
98 is_available = vmIntrinsics::does_virtual_dispatch(id);
99 }
100 }
101
102 if (is_available) {
103 assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
104 assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
105 return new LibraryIntrinsic(m, is_virtual,
106 vmIntrinsics::predicates_needed(id),
107 vmIntrinsics::does_virtual_dispatch(id),
108 id);
109 } else {
110 return nullptr;
111 }
112 }
113
114 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
115 LibraryCallKit kit(jvms, this);
116 Compile* C = kit.C;
117 int nodes = C->unique();
118 #ifndef PRODUCT
119 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
120 char buf[1000];
121 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
122 tty->print_cr("Intrinsic %s", str);
123 }
124 #endif
125 ciMethod* callee = kit.callee();
126 const int bci = kit.bci();
127 #ifdef ASSERT
128 Node* ctrl = kit.control();
129 #endif
130 // Try to inline the intrinsic.
131 if (callee->check_intrinsic_candidate() &&
132 kit.try_to_inline(_last_predicate)) {
133 const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
134 : "(intrinsic)";
135 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
136 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
137 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
138 if (C->log()) {
139 C->log()->elem("intrinsic id='%s'%s nodes='%d'",
140 vmIntrinsics::name_at(intrinsic_id()),
141 (is_virtual() ? " virtual='1'" : ""),
142 C->unique() - nodes);
143 }
144 // Push the result from the inlined method onto the stack.
145 kit.push_result();
146 return kit.transfer_exceptions_into_jvms();
147 }
148
149 // The intrinsic bailed out
150 assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
151 assert(jvms->map() == kit.map(), "Out of sync JVM state");
152 if (jvms->has_method()) {
153 // Not a root compile.
154 const char* msg;
155 if (callee->intrinsic_candidate()) {
156 msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
157 } else {
158 msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
159 : "failed to inline (intrinsic), method not annotated";
160 }
161 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
162 C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
163 } else {
164 // Root compile
165 ResourceMark rm;
166 stringStream msg_stream;
167 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
168 vmIntrinsics::name_at(intrinsic_id()),
169 is_virtual() ? " (virtual)" : "", bci);
170 const char *msg = msg_stream.freeze();
171 log_debug(jit, inlining)("%s", msg);
172 if (C->print_intrinsics() || C->print_inlining()) {
173 tty->print("%s", msg);
174 }
175 }
176 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
177
178 return nullptr;
179 }
180
181 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
182 LibraryCallKit kit(jvms, this);
183 Compile* C = kit.C;
184 int nodes = C->unique();
185 _last_predicate = predicate;
186 #ifndef PRODUCT
187 assert(is_predicated() && predicate < predicates_count(), "sanity");
188 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
189 char buf[1000];
190 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
191 tty->print_cr("Predicate for intrinsic %s", str);
192 }
193 #endif
194 ciMethod* callee = kit.callee();
195 const int bci = kit.bci();
196
197 Node* slow_ctl = kit.try_to_predicate(predicate);
198 if (!kit.failing()) {
199 const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
200 : "(intrinsic, predicate)";
201 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
202 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
203
204 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
205 if (C->log()) {
206 C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
207 vmIntrinsics::name_at(intrinsic_id()),
208 (is_virtual() ? " virtual='1'" : ""),
209 C->unique() - nodes);
210 }
211 return slow_ctl; // Could be null if the check folds.
212 }
213
214 // The intrinsic bailed out
215 if (jvms->has_method()) {
216 // Not a root compile.
217 const char* msg = "failed to generate predicate for intrinsic";
218 CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
219 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
220 } else {
221 // Root compile
222 ResourceMark rm;
223 stringStream msg_stream;
224 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
225 vmIntrinsics::name_at(intrinsic_id()),
226 is_virtual() ? " (virtual)" : "", bci);
227 const char *msg = msg_stream.freeze();
228 log_debug(jit, inlining)("%s", msg);
229 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
230 }
231 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
232 return nullptr;
233 }
234
235 bool LibraryCallKit::try_to_inline(int predicate) {
236 // Handle symbolic names for otherwise undistinguished boolean switches:
237 const bool is_store = true;
238 const bool is_compress = true;
239 const bool is_static = true;
240 const bool is_volatile = true;
241
242 if (!jvms()->has_method()) {
243 // Root JVMState has a null method.
244 assert(map()->memory()->Opcode() == Op_Parm, "");
245 // Insert the memory aliasing node
246 set_all_memory(reset_memory());
247 }
248 assert(merged_memory(), "");
249
250 switch (intrinsic_id()) {
251 case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
252 case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);
253 case vmIntrinsics::_getClass: return inline_native_getClass();
254
255 case vmIntrinsics::_ceil:
256 case vmIntrinsics::_floor:
257 case vmIntrinsics::_rint:
258 case vmIntrinsics::_dsin:
259 case vmIntrinsics::_dcos:
260 case vmIntrinsics::_dtan:
261 case vmIntrinsics::_dsinh:
262 case vmIntrinsics::_dtanh:
263 case vmIntrinsics::_dcbrt:
264 case vmIntrinsics::_dabs:
265 case vmIntrinsics::_fabs:
266 case vmIntrinsics::_iabs:
267 case vmIntrinsics::_labs:
268 case vmIntrinsics::_datan2:
269 case vmIntrinsics::_dsqrt:
270 case vmIntrinsics::_dsqrt_strict:
271 case vmIntrinsics::_dexp:
272 case vmIntrinsics::_dlog:
273 case vmIntrinsics::_dlog10:
274 case vmIntrinsics::_dpow:
275 case vmIntrinsics::_dcopySign:
276 case vmIntrinsics::_fcopySign:
277 case vmIntrinsics::_dsignum:
278 case vmIntrinsics::_roundF:
279 case vmIntrinsics::_roundD:
280 case vmIntrinsics::_fsignum: return inline_math_native(intrinsic_id());
281
282 case vmIntrinsics::_notify:
283 case vmIntrinsics::_notifyAll:
284 return inline_notify(intrinsic_id());
285
286 case vmIntrinsics::_addExactI: return inline_math_addExactI(false /* add */);
287 case vmIntrinsics::_addExactL: return inline_math_addExactL(false /* add */);
288 case vmIntrinsics::_decrementExactI: return inline_math_subtractExactI(true /* decrement */);
289 case vmIntrinsics::_decrementExactL: return inline_math_subtractExactL(true /* decrement */);
290 case vmIntrinsics::_incrementExactI: return inline_math_addExactI(true /* increment */);
291 case vmIntrinsics::_incrementExactL: return inline_math_addExactL(true /* increment */);
292 case vmIntrinsics::_multiplyExactI: return inline_math_multiplyExactI();
293 case vmIntrinsics::_multiplyExactL: return inline_math_multiplyExactL();
294 case vmIntrinsics::_multiplyHigh: return inline_math_multiplyHigh();
295 case vmIntrinsics::_unsignedMultiplyHigh: return inline_math_unsignedMultiplyHigh();
296 case vmIntrinsics::_negateExactI: return inline_math_negateExactI();
297 case vmIntrinsics::_negateExactL: return inline_math_negateExactL();
298 case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);
299 case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);
300
301 case vmIntrinsics::_arraycopy: return inline_arraycopy();
302
303 case vmIntrinsics::_arraySort: return inline_array_sort();
304 case vmIntrinsics::_arrayPartition: return inline_array_partition();
305
306 case vmIntrinsics::_compareToL: return inline_string_compareTo(StrIntrinsicNode::LL);
307 case vmIntrinsics::_compareToU: return inline_string_compareTo(StrIntrinsicNode::UU);
308 case vmIntrinsics::_compareToLU: return inline_string_compareTo(StrIntrinsicNode::LU);
309 case vmIntrinsics::_compareToUL: return inline_string_compareTo(StrIntrinsicNode::UL);
310
311 case vmIntrinsics::_indexOfL: return inline_string_indexOf(StrIntrinsicNode::LL);
312 case vmIntrinsics::_indexOfU: return inline_string_indexOf(StrIntrinsicNode::UU);
313 case vmIntrinsics::_indexOfUL: return inline_string_indexOf(StrIntrinsicNode::UL);
314 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
315 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
316 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
317 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
318 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
319
320 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
321
322 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
323
324 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
325 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
326 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
327 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
328
329 case vmIntrinsics::_compressStringC:
330 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
331 case vmIntrinsics::_inflateStringC:
332 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
333
334 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
335 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
336 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
337 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
338 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
339 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
340 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
341 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
342 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
343
344 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
345 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
346 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
347 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
348 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
349 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
350 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
351 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
352 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
353
354 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
355 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
356 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
357 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
358 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
359 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
360 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
361 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
362 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
363
364 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
365 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
366 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
367 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
368 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
369 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
370 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
371 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
372 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
373
374 case vmIntrinsics::_getShortUnaligned: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, true);
375 case vmIntrinsics::_getCharUnaligned: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, true);
376 case vmIntrinsics::_getIntUnaligned: return inline_unsafe_access(!is_store, T_INT, Relaxed, true);
377 case vmIntrinsics::_getLongUnaligned: return inline_unsafe_access(!is_store, T_LONG, Relaxed, true);
378
379 case vmIntrinsics::_putShortUnaligned: return inline_unsafe_access( is_store, T_SHORT, Relaxed, true);
380 case vmIntrinsics::_putCharUnaligned: return inline_unsafe_access( is_store, T_CHAR, Relaxed, true);
381 case vmIntrinsics::_putIntUnaligned: return inline_unsafe_access( is_store, T_INT, Relaxed, true);
382 case vmIntrinsics::_putLongUnaligned: return inline_unsafe_access( is_store, T_LONG, Relaxed, true);
383
384 case vmIntrinsics::_getReferenceAcquire: return inline_unsafe_access(!is_store, T_OBJECT, Acquire, false);
385 case vmIntrinsics::_getBooleanAcquire: return inline_unsafe_access(!is_store, T_BOOLEAN, Acquire, false);
386 case vmIntrinsics::_getByteAcquire: return inline_unsafe_access(!is_store, T_BYTE, Acquire, false);
387 case vmIntrinsics::_getShortAcquire: return inline_unsafe_access(!is_store, T_SHORT, Acquire, false);
388 case vmIntrinsics::_getCharAcquire: return inline_unsafe_access(!is_store, T_CHAR, Acquire, false);
389 case vmIntrinsics::_getIntAcquire: return inline_unsafe_access(!is_store, T_INT, Acquire, false);
390 case vmIntrinsics::_getLongAcquire: return inline_unsafe_access(!is_store, T_LONG, Acquire, false);
391 case vmIntrinsics::_getFloatAcquire: return inline_unsafe_access(!is_store, T_FLOAT, Acquire, false);
392 case vmIntrinsics::_getDoubleAcquire: return inline_unsafe_access(!is_store, T_DOUBLE, Acquire, false);
393
394 case vmIntrinsics::_putReferenceRelease: return inline_unsafe_access( is_store, T_OBJECT, Release, false);
395 case vmIntrinsics::_putBooleanRelease: return inline_unsafe_access( is_store, T_BOOLEAN, Release, false);
396 case vmIntrinsics::_putByteRelease: return inline_unsafe_access( is_store, T_BYTE, Release, false);
397 case vmIntrinsics::_putShortRelease: return inline_unsafe_access( is_store, T_SHORT, Release, false);
398 case vmIntrinsics::_putCharRelease: return inline_unsafe_access( is_store, T_CHAR, Release, false);
399 case vmIntrinsics::_putIntRelease: return inline_unsafe_access( is_store, T_INT, Release, false);
400 case vmIntrinsics::_putLongRelease: return inline_unsafe_access( is_store, T_LONG, Release, false);
401 case vmIntrinsics::_putFloatRelease: return inline_unsafe_access( is_store, T_FLOAT, Release, false);
402 case vmIntrinsics::_putDoubleRelease: return inline_unsafe_access( is_store, T_DOUBLE, Release, false);
403
404 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
405 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
406 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
407 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
408 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
409 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
410 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
411 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
412 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
413
414 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
415 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
416 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
417 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
418 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
419 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
420 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
421 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
422 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
423
424 case vmIntrinsics::_getFlatValue: return inline_unsafe_flat_access(!is_store, Relaxed);
425 case vmIntrinsics::_putFlatValue: return inline_unsafe_flat_access( is_store, Relaxed);
426
427 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
428 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
429 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
430 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
431 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
432
433 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
434 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
435 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
436 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
437 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
438 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
439 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
440 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
441 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
442 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
443 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
444 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
445 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
446 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
447 case vmIntrinsics::_weakCompareAndSetIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Release);
448 case vmIntrinsics::_weakCompareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Volatile);
449 case vmIntrinsics::_weakCompareAndSetLongPlain: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Relaxed);
450 case vmIntrinsics::_weakCompareAndSetLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Acquire);
451 case vmIntrinsics::_weakCompareAndSetLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Release);
452 case vmIntrinsics::_weakCompareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Volatile);
453
454 case vmIntrinsics::_compareAndExchangeReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Volatile);
455 case vmIntrinsics::_compareAndExchangeReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Acquire);
456 case vmIntrinsics::_compareAndExchangeReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Release);
457 case vmIntrinsics::_compareAndExchangeByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Volatile);
458 case vmIntrinsics::_compareAndExchangeByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Acquire);
459 case vmIntrinsics::_compareAndExchangeByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Release);
460 case vmIntrinsics::_compareAndExchangeShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Volatile);
461 case vmIntrinsics::_compareAndExchangeShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Acquire);
462 case vmIntrinsics::_compareAndExchangeShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Release);
463 case vmIntrinsics::_compareAndExchangeInt: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Volatile);
464 case vmIntrinsics::_compareAndExchangeIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Acquire);
465 case vmIntrinsics::_compareAndExchangeIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Release);
466 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
467 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
468 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
469
470 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
471 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
472 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
473 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
474
475 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
476 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
477 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
478 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
479 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
480
481 case vmIntrinsics::_loadFence:
482 case vmIntrinsics::_storeFence:
483 case vmIntrinsics::_storeStoreFence:
484 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
485
486 case vmIntrinsics::_arrayInstanceBaseOffset: return inline_arrayInstanceBaseOffset();
487 case vmIntrinsics::_arrayInstanceIndexScale: return inline_arrayInstanceIndexScale();
488 case vmIntrinsics::_arrayLayout: return inline_arrayLayout();
489 case vmIntrinsics::_getFieldMap: return inline_getFieldMap();
490
491 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
492
493 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
494 case vmIntrinsics::_currentThread: return inline_native_currentThread();
495 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
496
497 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
498 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
499
500 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
501 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
502
503 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
504 "endFirstTransition", true);
505 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
506 "startFinalTransition", true);
507 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
508 "startTransition", false);
509 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
510 "endTransition", false);
511 #if INCLUDE_JVMTI
512 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
513 #endif
514
515 #ifdef JFR_HAVE_INTRINSICS
516 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
517 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
518 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
519 case vmIntrinsics::_tryUpdateEpochField: return inline_native_try_update_epoch();
520 #endif
521 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
522 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
523 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
524 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
525 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
526 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
527 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
528 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
529 case vmIntrinsics::_getLength: return inline_native_getLength();
530 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
531 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
532 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
533 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
534 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
535 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
536 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
537
538 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
539 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
540 case vmIntrinsics::_newNullRestrictedNonAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ false);
541 case vmIntrinsics::_newNullRestrictedAtomicArray: return inline_newArray(/* null_free */ true, /* atomic */ true);
542 case vmIntrinsics::_newNullableAtomicArray: return inline_newArray(/* null_free */ false, /* atomic */ true);
543 case vmIntrinsics::_isFlatArray: return inline_getArrayProperties(IsFlat);
544 case vmIntrinsics::_isNullRestrictedArray: return inline_getArrayProperties(IsNullRestricted);
545 case vmIntrinsics::_isAtomicArray: return inline_getArrayProperties(IsAtomic);
546
547 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
548
549 case vmIntrinsics::_isInstance:
550 case vmIntrinsics::_isHidden:
551 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
552
553 case vmIntrinsics::_floatToRawIntBits:
554 case vmIntrinsics::_floatToIntBits:
555 case vmIntrinsics::_intBitsToFloat:
556 case vmIntrinsics::_doubleToRawLongBits:
557 case vmIntrinsics::_doubleToLongBits:
558 case vmIntrinsics::_longBitsToDouble:
559 case vmIntrinsics::_floatToFloat16:
560 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
561 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
562 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
563 case vmIntrinsics::_floatIsFinite:
564 case vmIntrinsics::_floatIsInfinite:
565 case vmIntrinsics::_doubleIsFinite:
566 case vmIntrinsics::_doubleIsInfinite: return inline_fp_range_check(intrinsic_id());
567
568 case vmIntrinsics::_numberOfLeadingZeros_i:
569 case vmIntrinsics::_numberOfLeadingZeros_l:
570 case vmIntrinsics::_numberOfTrailingZeros_i:
571 case vmIntrinsics::_numberOfTrailingZeros_l:
572 case vmIntrinsics::_bitCount_i:
573 case vmIntrinsics::_bitCount_l:
574 case vmIntrinsics::_reverse_i:
575 case vmIntrinsics::_reverse_l:
576 case vmIntrinsics::_reverseBytes_i:
577 case vmIntrinsics::_reverseBytes_l:
578 case vmIntrinsics::_reverseBytes_s:
579 case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());
580
581 case vmIntrinsics::_compress_i:
582 case vmIntrinsics::_compress_l:
583 case vmIntrinsics::_expand_i:
584 case vmIntrinsics::_expand_l: return inline_bitshuffle_methods(intrinsic_id());
585
586 case vmIntrinsics::_compareUnsigned_i:
587 case vmIntrinsics::_compareUnsigned_l: return inline_compare_unsigned(intrinsic_id());
588
589 case vmIntrinsics::_divideUnsigned_i:
590 case vmIntrinsics::_divideUnsigned_l:
591 case vmIntrinsics::_remainderUnsigned_i:
592 case vmIntrinsics::_remainderUnsigned_l: return inline_divmod_methods(intrinsic_id());
593
594 case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();
595
596 case vmIntrinsics::_Reference_get0: return inline_reference_get0();
597 case vmIntrinsics::_Reference_refersTo0: return inline_reference_refersTo0(false);
598 case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
599 case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
600 case vmIntrinsics::_Reference_clear0: return inline_reference_clear0(false);
601 case vmIntrinsics::_PhantomReference_clear0: return inline_reference_clear0(true);
602
603 case vmIntrinsics::_Class_cast: return inline_Class_cast();
604
605 case vmIntrinsics::_aescrypt_encryptBlock:
606 case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());
607
608 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
609 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
610 return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
611
612 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
613 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
614 return inline_electronicCodeBook_AESCrypt(intrinsic_id());
615
616 case vmIntrinsics::_counterMode_AESCrypt:
617 return inline_counterMode_AESCrypt(intrinsic_id());
618
619 case vmIntrinsics::_galoisCounterMode_AESCrypt:
620 return inline_galoisCounterMode_AESCrypt();
621
622 case vmIntrinsics::_md5_implCompress:
623 case vmIntrinsics::_sha_implCompress:
624 case vmIntrinsics::_sha2_implCompress:
625 case vmIntrinsics::_sha5_implCompress:
626 case vmIntrinsics::_sha3_implCompress:
627 return inline_digestBase_implCompress(intrinsic_id());
628 case vmIntrinsics::_double_keccak:
629 case vmIntrinsics::_quad_keccak:
630 return inline_keccak(intrinsic_id());
631
632 case vmIntrinsics::_digestBase_implCompressMB:
633 return inline_digestBase_implCompressMB(predicate);
634
635 case vmIntrinsics::_multiplyToLen:
636 return inline_multiplyToLen();
637
638 case vmIntrinsics::_squareToLen:
639 return inline_squareToLen();
640
641 case vmIntrinsics::_mulAdd:
642 return inline_mulAdd();
643
644 case vmIntrinsics::_montgomeryMultiply:
645 return inline_montgomeryMultiply();
646 case vmIntrinsics::_montgomerySquare:
647 return inline_montgomerySquare();
648
649 case vmIntrinsics::_bigIntegerRightShiftWorker:
650 return inline_bigIntegerShift(true);
651 case vmIntrinsics::_bigIntegerLeftShiftWorker:
652 return inline_bigIntegerShift(false);
653
654 case vmIntrinsics::_vectorizedMismatch:
655 return inline_vectorizedMismatch();
656
657 case vmIntrinsics::_ghash_processBlocks:
658 return inline_ghash_processBlocks();
659 case vmIntrinsics::_chacha20Block:
660 return inline_chacha20Block();
661 case vmIntrinsics::_kyberNtt:
662 return inline_kyberNtt();
663 case vmIntrinsics::_kyberInverseNtt:
664 return inline_kyberInverseNtt();
665 case vmIntrinsics::_kyberNttMult:
666 return inline_kyberNttMult();
667 case vmIntrinsics::_kyberAddPoly_2:
668 return inline_kyberAddPoly_2();
669 case vmIntrinsics::_kyberAddPoly_3:
670 return inline_kyberAddPoly_3();
671 case vmIntrinsics::_kyber12To16:
672 return inline_kyber12To16();
673 case vmIntrinsics::_kyberBarrettReduce:
674 return inline_kyberBarrettReduce();
675 case vmIntrinsics::_dilithiumAlmostNtt:
676 return inline_dilithiumAlmostNtt();
677 case vmIntrinsics::_dilithiumAlmostInverseNtt:
678 return inline_dilithiumAlmostInverseNtt();
679 case vmIntrinsics::_dilithiumNttMult:
680 return inline_dilithiumNttMult();
681 case vmIntrinsics::_dilithiumMontMulByConstant:
682 return inline_dilithiumMontMulByConstant();
683 case vmIntrinsics::_dilithiumDecomposePoly:
684 return inline_dilithiumDecomposePoly();
685 case vmIntrinsics::_base64_encodeBlock:
686 return inline_base64_encodeBlock();
687 case vmIntrinsics::_base64_decodeBlock:
688 return inline_base64_decodeBlock();
689 case vmIntrinsics::_poly1305_processBlocks:
690 return inline_poly1305_processBlocks();
691 case vmIntrinsics::_intpoly_montgomeryMult_P256:
692 return inline_intpoly_montgomeryMult_P256();
693 case vmIntrinsics::_intpoly_assign:
694 return inline_intpoly_assign();
695 case vmIntrinsics::_intpoly_mult_25519:
696 return inline_intpoly_mult_25519();
697 case vmIntrinsics::_intpoly_square_25519:
698 return inline_intpoly_square_25519();
699 case vmIntrinsics::_encodeISOArray:
700 case vmIntrinsics::_encodeByteISOArray:
701 return inline_encodeISOArray(false);
702 case vmIntrinsics::_encodeAsciiArray:
703 return inline_encodeISOArray(true);
704
705 case vmIntrinsics::_updateCRC32:
706 return inline_updateCRC32();
707 case vmIntrinsics::_updateBytesCRC32:
708 return inline_updateBytesCRC32();
709 case vmIntrinsics::_updateByteBufferCRC32:
710 return inline_updateByteBufferCRC32();
711
712 case vmIntrinsics::_updateBytesCRC32C:
713 return inline_updateBytesCRC32C();
714 case vmIntrinsics::_updateDirectByteBufferCRC32C:
715 return inline_updateDirectByteBufferCRC32C();
716
717 case vmIntrinsics::_updateBytesAdler32:
718 return inline_updateBytesAdler32();
719 case vmIntrinsics::_updateByteBufferAdler32:
720 return inline_updateByteBufferAdler32();
721
722 case vmIntrinsics::_profileBoolean:
723 return inline_profileBoolean();
724 case vmIntrinsics::_isCompileConstant:
725 return inline_isCompileConstant();
726
727 case vmIntrinsics::_countPositives:
728 return inline_countPositives();
729
730 case vmIntrinsics::_fmaD:
731 case vmIntrinsics::_fmaF:
732 return inline_fma(intrinsic_id());
733
734 case vmIntrinsics::_isDigit:
735 case vmIntrinsics::_isLowerCase:
736 case vmIntrinsics::_isUpperCase:
737 case vmIntrinsics::_isWhitespace:
738 return inline_character_compare(intrinsic_id());
739
740 case vmIntrinsics::_min:
741 case vmIntrinsics::_max:
742 case vmIntrinsics::_min_strict:
743 case vmIntrinsics::_max_strict:
744 case vmIntrinsics::_minL:
745 case vmIntrinsics::_maxL:
746 case vmIntrinsics::_minF:
747 case vmIntrinsics::_maxF:
748 case vmIntrinsics::_minD:
749 case vmIntrinsics::_maxD:
750 case vmIntrinsics::_minF_strict:
751 case vmIntrinsics::_maxF_strict:
752 case vmIntrinsics::_minD_strict:
753 case vmIntrinsics::_maxD_strict:
754 return inline_min_max(intrinsic_id());
755
756 case vmIntrinsics::_VectorUnaryOp:
757 return inline_vector_nary_operation(1);
758 case vmIntrinsics::_VectorBinaryOp:
759 return inline_vector_nary_operation(2);
760 case vmIntrinsics::_VectorUnaryLibOp:
761 return inline_vector_call(1);
762 case vmIntrinsics::_VectorBinaryLibOp:
763 return inline_vector_call(2);
764 case vmIntrinsics::_VectorTernaryOp:
765 return inline_vector_nary_operation(3);
766 case vmIntrinsics::_VectorFromBitsCoerced:
767 return inline_vector_frombits_coerced();
768 case vmIntrinsics::_VectorMaskOp:
769 return inline_vector_mask_operation();
770 case vmIntrinsics::_VectorLoadOp:
771 return inline_vector_mem_operation(/*is_store=*/false);
772 case vmIntrinsics::_VectorLoadMaskedOp:
773 return inline_vector_mem_masked_operation(/*is_store*/false);
774 case vmIntrinsics::_VectorStoreOp:
775 return inline_vector_mem_operation(/*is_store=*/true);
776 case vmIntrinsics::_VectorStoreMaskedOp:
777 return inline_vector_mem_masked_operation(/*is_store=*/true);
778 case vmIntrinsics::_VectorGatherOp:
779 return inline_vector_gather_scatter(/*is_scatter*/ false);
780 case vmIntrinsics::_VectorScatterOp:
781 return inline_vector_gather_scatter(/*is_scatter*/ true);
782 case vmIntrinsics::_VectorReductionCoerced:
783 return inline_vector_reduction();
784 case vmIntrinsics::_VectorTest:
785 return inline_vector_test();
786 case vmIntrinsics::_VectorBlend:
787 return inline_vector_blend();
788 case vmIntrinsics::_VectorRearrange:
789 return inline_vector_rearrange();
790 case vmIntrinsics::_VectorSelectFrom:
791 return inline_vector_select_from();
792 case vmIntrinsics::_VectorCompare:
793 return inline_vector_compare();
794 case vmIntrinsics::_VectorBroadcastInt:
795 return inline_vector_broadcast_int();
796 case vmIntrinsics::_VectorConvert:
797 return inline_vector_convert();
798 case vmIntrinsics::_VectorInsert:
799 return inline_vector_insert();
800 case vmIntrinsics::_VectorExtract:
801 return inline_vector_extract();
802 case vmIntrinsics::_VectorCompressExpand:
803 return inline_vector_compress_expand();
804 case vmIntrinsics::_VectorSelectFromTwoVectorOp:
805 return inline_vector_select_from_two_vectors();
806 case vmIntrinsics::_IndexVector:
807 return inline_index_vector();
808 case vmIntrinsics::_IndexPartiallyInUpperRange:
809 return inline_index_partially_in_upper_range();
810
811 case vmIntrinsics::_getObjectSize:
812 return inline_getObjectSize();
813
814 case vmIntrinsics::_blackhole:
815 return inline_blackhole();
816
817 default:
818 // If you get here, it may be that someone has added a new intrinsic
819 // to the list in vmIntrinsics.hpp without implementing it here.
820 #ifndef PRODUCT
821 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
822 tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
823 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
824 }
825 #endif
826 return false;
827 }
828 }
829
830 Node* LibraryCallKit::try_to_predicate(int predicate) {
831 if (!jvms()->has_method()) {
832 // Root JVMState has a null method.
833 assert(map()->memory()->Opcode() == Op_Parm, "");
834 // Insert the memory aliasing node
835 set_all_memory(reset_memory());
836 }
837 assert(merged_memory(), "");
838
839 switch (intrinsic_id()) {
840 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
841 return inline_cipherBlockChaining_AESCrypt_predicate(false);
842 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
843 return inline_cipherBlockChaining_AESCrypt_predicate(true);
844 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
845 return inline_electronicCodeBook_AESCrypt_predicate(false);
846 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
847 return inline_electronicCodeBook_AESCrypt_predicate(true);
848 case vmIntrinsics::_counterMode_AESCrypt:
849 return inline_counterMode_AESCrypt_predicate();
850 case vmIntrinsics::_digestBase_implCompressMB:
851 return inline_digestBase_implCompressMB_predicate(predicate);
852 case vmIntrinsics::_galoisCounterMode_AESCrypt:
853 return inline_galoisCounterMode_AESCrypt_predicate();
854
855 default:
856 // If you get here, it may be that someone has added a new intrinsic
857 // to the list in vmIntrinsics.hpp without implementing it here.
858 #ifndef PRODUCT
859 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
860 tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
861 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
862 }
863 #endif
864 Node* slow_ctl = control();
865 set_control(top()); // No fast path intrinsic
866 return slow_ctl;
867 }
868 }
869
870 //------------------------------set_result-------------------------------
871 // Helper function for finishing intrinsics.
872 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
873 record_for_igvn(region);
874 set_control(_gvn.transform(region));
875 set_result( _gvn.transform(value));
876 assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
877 }
878
879 RegionNode* LibraryCallKit::create_bailout() {
880 RegionNode* bailout = new RegionNode(1);
881 record_for_igvn(bailout);
882 return bailout;
883 }
884
885 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
886 if (bailout->req() > 1) {
887 bailout = _gvn.transform(bailout)->as_Region();
888 Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
889 Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
890 C->root()->add_req(halt);
891 }
892 return stopped();
893 }
894
895 //------------------------------generate_guard---------------------------
896 // Helper function for generating guarded fast-slow graph structures.
897 // The given 'test', if true, guards a slow path. If the test fails
898 // then a fast path can be taken. (We generally hope it fails.)
899 // In all cases, GraphKit::control() is updated to the fast path.
900 // The returned value represents the control for the slow path.
901 // The return value is never 'top'; it is either a valid control
902 // or null if it is obvious that the slow path can never be taken.
903 // Also, if region and the slow control are not null, the slow edge
904 // is appended to the region.
905 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
906 if (stopped()) {
907 // Already short circuited.
908 return nullptr;
909 }
910
911 // Build an if node and its projections.
912 // If test is true we take the slow path, which we assume is uncommon.
913 if (_gvn.type(test) == TypeInt::ZERO) {
914 // The slow branch is never taken. No need to build this guard.
915 return nullptr;
916 }
917
918 IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
919
920 Node* if_slow = _gvn.transform(new IfTrueNode(iff));
921 if (if_slow == top()) {
922 // The slow branch is never taken. No need to build this guard.
923 return nullptr;
924 }
925
926 if (region != nullptr)
927 region->add_req(if_slow);
928
929 Node* if_fast = _gvn.transform(new IfFalseNode(iff));
930 set_control(if_fast);
931
932 return if_slow;
933 }
934
935 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
936 return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
937 }
938 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
939 return generate_guard(test, region, PROB_FAIR);
940 }
941
942 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
943 Node** pos_index, bool with_opaque) {
944 if (stopped())
945 return nullptr; // already stopped
946 if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
947 return nullptr; // index is already adequately typed
948 Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
949 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
950 if (with_opaque) {
951 bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
952 }
953 Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
954 if (is_neg != nullptr && pos_index != nullptr) {
955 // Emulate effect of Parse::adjust_map_after_if.
956 Node* ccast = new CastIINode(control(), index, TypeInt::POS);
957 (*pos_index) = _gvn.transform(ccast);
958 }
959 return is_neg;
960 }
961
962 // Make sure that 'position' is a valid limit index, in [0..length].
963 // There are two equivalent plans for checking this:
964 // A. (offset + copyLength) unsigned<= arrayLength
965 // B. offset <= (arrayLength - copyLength)
966 // We require that all of the values above, except for the sum and
967 // difference, are already known to be non-negative.
968 // Plan A is robust in the face of overflow, if offset and copyLength
969 // are both hugely positive.
970 //
971 // Plan B is less direct and intuitive, but it does not overflow at
972 // all, since the difference of two non-negatives is always
973 // representable. Whenever Java methods must perform the equivalent
974 // check they generally use Plan B instead of Plan A.
975 // For the moment we use Plan A.
976 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
977 Node* subseq_length,
978 Node* array_length,
979 RegionNode* region,
980 bool with_opaque) {
981 if (stopped())
982 return nullptr; // already stopped
983 bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
984 if (zero_offset && subseq_length->eqv_uncast(array_length))
985 return nullptr; // common case of whole-array copy
986 Node* last = subseq_length;
987 if (!zero_offset) // last += offset
988 last = _gvn.transform(new AddINode(last, offset));
989 Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
990 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
991 if (with_opaque) {
992 bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
993 }
994 Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
995 return is_over;
996 }
997
998 // Emit range checks for the given String.value byte array
999 void LibraryCallKit::generate_string_range_check(Node* array,
1000 Node* offset,
1001 Node* count,
1002 bool char_count,
1003 RegionNode* region) {
1004 if (stopped()) {
1005 return; // already stopped
1006 }
1007 if (char_count) {
1008 // Convert char count to byte count
1009 count = _gvn.transform(new LShiftINode(count, intcon(1)));
1010 }
1011 // Offset and count must not be negative
1012 generate_negative_guard(offset, region, nullptr, true);
1013 generate_negative_guard(count, region, nullptr, true);
1014 // Offset + count must not exceed length of array
1015 generate_limit_guard(offset, count, load_array_length(array), region, true);
1016 }
1017
1018 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
1019 bool is_immutable) {
1020 ciKlass* thread_klass = env()->Thread_klass();
1021 const Type* thread_type
1022 = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
1023
1024 Node* thread = _gvn.transform(new ThreadLocalNode());
1025 Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1026 tls_output = thread;
1027
1028 Node* thread_obj_handle
1029 = (is_immutable
1030 ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1031 TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1032 : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1033 thread_obj_handle = _gvn.transform(thread_obj_handle);
1034
1035 DecoratorSet decorators = IN_NATIVE;
1036 if (is_immutable) {
1037 decorators |= C2_IMMUTABLE_MEMORY;
1038 }
1039 return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1040 }
1041
1042 //--------------------------generate_current_thread--------------------
1043 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1044 return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1045 /*is_immutable*/false);
1046 }
1047
1048 //--------------------------generate_virtual_thread--------------------
1049 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1050 return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1051 !C->method()->changes_current_thread());
1052 }
1053
1054 //------------------------------make_string_method_node------------------------
1055 // Helper method for String intrinsic functions. This version is called with
1056 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1057 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1058 // containing the lengths of str1 and str2.
1059 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1060 Node* result = nullptr;
1061 switch (opcode) {
1062 case Op_StrIndexOf:
1063 result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1064 str1_start, cnt1, str2_start, cnt2, ae);
1065 break;
1066 case Op_StrComp:
1067 result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1068 str1_start, cnt1, str2_start, cnt2, ae);
1069 break;
1070 case Op_StrEquals:
1071 // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1072 // Use the constant length if there is one because optimized match rule may exist.
1073 result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1074 str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1075 break;
1076 default:
1077 ShouldNotReachHere();
1078 return nullptr;
1079 }
1080
1081 // All these intrinsics have checks.
1082 C->set_has_split_ifs(true); // Has chance for split-if optimization
1083 clear_upper_avx();
1084
1085 return _gvn.transform(result);
1086 }
1087
1088 //------------------------------inline_string_compareTo------------------------
1089 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1090 Node* arg1 = argument(0);
1091 Node* arg2 = argument(1);
1092
1093 arg1 = must_be_not_null(arg1, true);
1094 arg2 = must_be_not_null(arg2, true);
1095
1096 // Get start addr and length of first argument
1097 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1098 Node* arg1_cnt = load_array_length(arg1);
1099
1100 // Get start addr and length of second argument
1101 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1102 Node* arg2_cnt = load_array_length(arg2);
1103
1104 Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1105 set_result(result);
1106 return true;
1107 }
1108
1109 //------------------------------inline_string_equals------------------------
1110 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1111 Node* arg1 = argument(0);
1112 Node* arg2 = argument(1);
1113
1114 // paths (plus control) merge
1115 RegionNode* region = new RegionNode(3);
1116 Node* phi = new PhiNode(region, TypeInt::BOOL);
1117
1118 if (!stopped()) {
1119
1120 arg1 = must_be_not_null(arg1, true);
1121 arg2 = must_be_not_null(arg2, true);
1122
1123 // Get start addr and length of first argument
1124 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1125 Node* arg1_cnt = load_array_length(arg1);
1126
1127 // Get start addr and length of second argument
1128 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1129 Node* arg2_cnt = load_array_length(arg2);
1130
1131 // Check for arg1_cnt != arg2_cnt
1132 Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1133 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1134 Node* if_ne = generate_slow_guard(bol, nullptr);
1135 if (if_ne != nullptr) {
1136 phi->init_req(2, intcon(0));
1137 region->init_req(2, if_ne);
1138 }
1139
1140 // Check for count == 0 is done by assembler code for StrEquals.
1141
1142 if (!stopped()) {
1143 Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1144 phi->init_req(1, equals);
1145 region->init_req(1, control());
1146 }
1147 }
1148
1149 // post merge
1150 set_control(_gvn.transform(region));
1151 record_for_igvn(region);
1152
1153 set_result(_gvn.transform(phi));
1154 return true;
1155 }
1156
1157 //------------------------------inline_array_equals----------------------------
1158 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1159 assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1160 Node* arg1 = argument(0);
1161 Node* arg2 = argument(1);
1162
1163 const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1164 set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), mtype, arg1, arg2, ae)));
1165 clear_upper_avx();
1166
1167 return true;
1168 }
1169
1170
1171 //------------------------------inline_countPositives------------------------------
1172 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1173 bool LibraryCallKit::inline_countPositives() {
1174 assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1175 // no receiver since it is static method
1176 Node* ba = argument(0);
1177 Node* offset = argument(1);
1178 Node* len = argument(2);
1179
1180 ba = must_be_not_null(ba, true);
1181 RegionNode* bailout = create_bailout();
1182 generate_string_range_check(ba, offset, len, false, bailout);
1183 if (check_bailout(bailout)) {
1184 return true;
1185 }
1186
1187 Node* ba_start = array_element_address(ba, offset, T_BYTE);
1188 Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1189 set_result(_gvn.transform(result));
1190 clear_upper_avx();
1191 return true;
1192 }
1193
1194 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1195 Node* index = argument(0);
1196 Node* length = bt == T_INT ? argument(1) : argument(2);
1197 if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1198 return false;
1199 }
1200
1201 // check that length is positive
1202 Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1203 Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1204
1205 {
1206 BuildCutout unless(this, len_pos_bol, PROB_MAX);
1207 uncommon_trap(Deoptimization::Reason_intrinsic,
1208 Deoptimization::Action_make_not_entrant);
1209 }
1210
1211 if (stopped()) {
1212 // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1213 return true;
1214 }
1215
1216 // length is now known positive, add a cast node to make this explicit
1217 jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1218 Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1219 control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1220 ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1221 casted_length = _gvn.transform(casted_length);
1222 replace_in_map(length, casted_length);
1223 length = casted_length;
1224
1225 // Use an unsigned comparison for the range check itself
1226 Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1227 BoolTest::mask btest = BoolTest::lt;
1228 Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1229 RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1230 _gvn.set_type(rc, rc->Value(&_gvn));
1231 if (!rc_bool->is_Con()) {
1232 record_for_igvn(rc);
1233 }
1234 set_control(_gvn.transform(new IfTrueNode(rc)));
1235 {
1236 PreserveJVMState pjvms(this);
1237 set_control(_gvn.transform(new IfFalseNode(rc)));
1238 uncommon_trap(Deoptimization::Reason_range_check,
1239 Deoptimization::Action_make_not_entrant);
1240 }
1241
1242 if (stopped()) {
1243 // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1244 return true;
1245 }
1246
1247 // index is now known to be >= 0 and < length, cast it
1248 Node* result = ConstraintCastNode::make_cast_for_basic_type(
1249 control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1250 ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1251 result = _gvn.transform(result);
1252 set_result(result);
1253 replace_in_map(index, result);
1254 return true;
1255 }
1256
1257 //------------------------------inline_string_indexOf------------------------
1258 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1259 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1260 return false;
1261 }
1262 Node* src = argument(0);
1263 Node* tgt = argument(1);
1264
1265 // Make the merge point
1266 RegionNode* result_rgn = new RegionNode(4);
1267 Node* result_phi = new PhiNode(result_rgn, TypeInt::INT);
1268
1269 src = must_be_not_null(src, true);
1270 tgt = must_be_not_null(tgt, true);
1271
1272 // Get start addr and length of source string
1273 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1274 Node* src_count = load_array_length(src);
1275
1276 // Get start addr and length of substring
1277 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1278 Node* tgt_count = load_array_length(tgt);
1279
1280 Node* result = nullptr;
1281 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1282
1283 if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1284 // Divide src size by 2 if String is UTF16 encoded
1285 src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1286 }
1287 if (ae == StrIntrinsicNode::UU) {
1288 // Divide substring size by 2 if String is UTF16 encoded
1289 tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1290 }
1291
1292 if (call_opt_stub) {
1293 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1294 StubRoutines::_string_indexof_array[ae],
1295 "stringIndexOf", TypePtr::BOTTOM, src_start,
1296 src_count, tgt_start, tgt_count);
1297 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1298 } else {
1299 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1300 result_rgn, result_phi, ae);
1301 }
1302 if (result != nullptr) {
1303 result_phi->init_req(3, result);
1304 result_rgn->init_req(3, control());
1305 }
1306 set_control(_gvn.transform(result_rgn));
1307 record_for_igvn(result_rgn);
1308 set_result(_gvn.transform(result_phi));
1309
1310 return true;
1311 }
1312
1313 //-----------------------------inline_string_indexOfI-----------------------
1314 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1315 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1316 return false;
1317 }
1318
1319 assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1320 Node* src = argument(0); // byte[]
1321 Node* src_count = argument(1); // char count
1322 Node* tgt = argument(2); // byte[]
1323 Node* tgt_count = argument(3); // char count
1324 Node* from_index = argument(4); // char index
1325
1326 src = must_be_not_null(src, true);
1327 tgt = must_be_not_null(tgt, true);
1328
1329 // Multiply byte array index by 2 if String is UTF16 encoded
1330 Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1331 src_count = _gvn.transform(new SubINode(src_count, from_index));
1332 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1333 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1334
1335 // Range checks
1336 RegionNode* bailout = create_bailout();
1337 generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1338 generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1339 if (check_bailout(bailout)) {
1340 return true;
1341 }
1342
1343 RegionNode* region = new RegionNode(5);
1344 Node* phi = new PhiNode(region, TypeInt::INT);
1345 Node* result = nullptr;
1346
1347 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1348
1349 if (call_opt_stub) {
1350 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1351 StubRoutines::_string_indexof_array[ae],
1352 "stringIndexOf", TypePtr::BOTTOM, src_start,
1353 src_count, tgt_start, tgt_count);
1354 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1355 } else {
1356 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1357 region, phi, ae);
1358 }
1359 if (result != nullptr) {
1360 // The result is index relative to from_index if substring was found, -1 otherwise.
1361 // Generate code which will fold into cmove.
1362 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1363 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1364
1365 Node* if_lt = generate_slow_guard(bol, nullptr);
1366 if (if_lt != nullptr) {
1367 // result == -1
1368 phi->init_req(3, result);
1369 region->init_req(3, if_lt);
1370 }
1371 if (!stopped()) {
1372 result = _gvn.transform(new AddINode(result, from_index));
1373 phi->init_req(4, result);
1374 region->init_req(4, control());
1375 }
1376 }
1377
1378 set_control(_gvn.transform(region));
1379 record_for_igvn(region);
1380 set_result(_gvn.transform(phi));
1381 clear_upper_avx();
1382
1383 return true;
1384 }
1385
1386 // Create StrIndexOfNode with fast path checks
1387 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1388 RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1389 // Check for substr count > string count
1390 Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1391 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1392 Node* if_gt = generate_slow_guard(bol, nullptr);
1393 if (if_gt != nullptr) {
1394 phi->init_req(1, intcon(-1));
1395 region->init_req(1, if_gt);
1396 }
1397 if (!stopped()) {
1398 // Check for substr count == 0
1399 cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1400 bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1401 Node* if_zero = generate_slow_guard(bol, nullptr);
1402 if (if_zero != nullptr) {
1403 phi->init_req(2, intcon(0));
1404 region->init_req(2, if_zero);
1405 }
1406 }
1407 if (!stopped()) {
1408 return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1409 }
1410 return nullptr;
1411 }
1412
1413 //-----------------------------inline_string_indexOfChar-----------------------
1414 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1415 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1416 return false;
1417 }
1418 if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1419 return false;
1420 }
1421 assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1422 Node* src = argument(0); // byte[]
1423 Node* int_ch = argument(1);
1424 Node* from_index = argument(2);
1425 Node* max = argument(3);
1426
1427 src = must_be_not_null(src, true);
1428
1429 Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1430 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1431 Node* src_count = _gvn.transform(new SubINode(max, from_index));
1432
1433 // Range checks
1434 RegionNode* bailout = create_bailout();
1435 generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1436 if (check_bailout(bailout)) {
1437 return true;
1438 }
1439
1440 // Check for int_ch >= 0
1441 Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1442 Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1443 {
1444 BuildCutout unless(this, int_ch_bol, PROB_MAX);
1445 uncommon_trap(Deoptimization::Reason_intrinsic,
1446 Deoptimization::Action_maybe_recompile);
1447 }
1448 if (stopped()) {
1449 return true;
1450 }
1451
1452 RegionNode* region = new RegionNode(3);
1453 Node* phi = new PhiNode(region, TypeInt::INT);
1454
1455 Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1456 C->set_has_split_ifs(true); // Has chance for split-if optimization
1457 _gvn.transform(result);
1458
1459 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1460 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1461
1462 Node* if_lt = generate_slow_guard(bol, nullptr);
1463 if (if_lt != nullptr) {
1464 // result == -1
1465 phi->init_req(2, result);
1466 region->init_req(2, if_lt);
1467 }
1468 if (!stopped()) {
1469 result = _gvn.transform(new AddINode(result, from_index));
1470 phi->init_req(1, result);
1471 region->init_req(1, control());
1472 }
1473 set_control(_gvn.transform(region));
1474 record_for_igvn(region);
1475 set_result(_gvn.transform(phi));
1476 clear_upper_avx();
1477
1478 return true;
1479 }
1480 //---------------------------inline_string_copy---------------------
1481 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1482 // int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1483 // int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1484 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1485 // void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1486 // void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1487 bool LibraryCallKit::inline_string_copy(bool compress) {
1488 int nargs = 5; // 2 oops, 3 ints
1489 assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1490
1491 Node* src = argument(0);
1492 Node* src_offset = argument(1);
1493 Node* dst = argument(2);
1494 Node* dst_offset = argument(3);
1495 Node* length = argument(4);
1496
1497 // Check for allocation before we add nodes that would confuse
1498 // tightly_coupled_allocation()
1499 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1500
1501 // Figure out the size and type of the elements we will be copying.
1502 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1503 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1504 if (src_type == nullptr || dst_type == nullptr) {
1505 return false;
1506 }
1507 BasicType src_elem = src_type->elem()->array_element_basic_type();
1508 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1509 assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1510 (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1511 "Unsupported array types for inline_string_copy");
1512
1513 src = must_be_not_null(src, true);
1514 dst = must_be_not_null(dst, true);
1515
1516 // Convert char[] offsets to byte[] offsets
1517 bool convert_src = (compress && src_elem == T_BYTE);
1518 bool convert_dst = (!compress && dst_elem == T_BYTE);
1519 if (convert_src) {
1520 src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1521 } else if (convert_dst) {
1522 dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1523 }
1524
1525 // Range checks
1526 RegionNode* bailout = create_bailout();
1527 generate_string_range_check(src, src_offset, length, convert_src, bailout);
1528 generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1529 if (check_bailout(bailout)) {
1530 return true;
1531 }
1532
1533 Node* src_start = array_element_address(src, src_offset, src_elem);
1534 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1535 // 'src_start' points to src array + scaled offset
1536 // 'dst_start' points to dst array + scaled offset
1537 Node* count = nullptr;
1538 if (compress) {
1539 count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1540 } else {
1541 inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1542 }
1543
1544 if (alloc != nullptr) {
1545 if (alloc->maybe_set_complete(&_gvn)) {
1546 // "You break it, you buy it."
1547 InitializeNode* init = alloc->initialization();
1548 assert(init->is_complete(), "we just did this");
1549 init->set_complete_with_arraycopy();
1550 assert(dst->is_CheckCastPP(), "sanity");
1551 assert(dst->in(0)->in(0) == init, "dest pinned");
1552 }
1553 // Do not let stores that initialize this object be reordered with
1554 // a subsequent store that would make this object accessible by
1555 // other threads.
1556 // Record what AllocateNode this StoreStore protects so that
1557 // escape analysis can go from the MemBarStoreStoreNode to the
1558 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1559 // based on the escape status of the AllocateNode.
1560 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1561 }
1562 if (compress) {
1563 set_result(_gvn.transform(count));
1564 }
1565 clear_upper_avx();
1566
1567 return true;
1568 }
1569
1570 #ifdef _LP64
1571 #define XTOP ,top() /*additional argument*/
1572 #else //_LP64
1573 #define XTOP /*no additional argument*/
1574 #endif //_LP64
1575
1576 //------------------------inline_string_toBytesU--------------------------
1577 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1578 bool LibraryCallKit::inline_string_toBytesU() {
1579 // Get the arguments.
1580 assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1581 Node* value = argument(0);
1582 Node* offset = argument(1);
1583 Node* length = argument(2);
1584
1585 Node* newcopy = nullptr;
1586
1587 // Set the original stack and the reexecute bit for the interpreter to reexecute
1588 // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1589 { PreserveReexecuteState preexecs(this);
1590 jvms()->set_should_reexecute(true);
1591
1592 value = must_be_not_null(value, true);
1593 RegionNode* bailout = create_bailout();
1594 generate_negative_guard(offset, bailout, nullptr, true);
1595 generate_negative_guard(length, bailout, nullptr, true);
1596 generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1597 // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1598 generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1599 if (check_bailout(bailout)) {
1600 return true;
1601 }
1602
1603 Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1604 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1605 newcopy = new_array(klass_node, size, 0); // no arguments to push
1606 AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1607 guarantee(alloc != nullptr, "created above");
1608
1609 // Calculate starting addresses.
1610 Node* src_start = array_element_address(value, offset, T_CHAR);
1611 Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1612
1613 // Check if dst array address is aligned to HeapWordSize
1614 bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1615 // If true, then check if src array address is aligned to HeapWordSize
1616 if (aligned) {
1617 const TypeInt* toffset = gvn().type(offset)->is_int();
1618 aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1619 toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1620 }
1621
1622 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1623 const char* copyfunc_name = "arraycopy";
1624 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1625 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1626 OptoRuntime::fast_arraycopy_Type(),
1627 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1628 src_start, dst_start, ConvI2X(length) XTOP);
1629 // Do not let reads from the cloned object float above the arraycopy.
1630 if (alloc->maybe_set_complete(&_gvn)) {
1631 // "You break it, you buy it."
1632 InitializeNode* init = alloc->initialization();
1633 assert(init->is_complete(), "we just did this");
1634 init->set_complete_with_arraycopy();
1635 assert(newcopy->is_CheckCastPP(), "sanity");
1636 assert(newcopy->in(0)->in(0) == init, "dest pinned");
1637 }
1638 // Do not let stores that initialize this object be reordered with
1639 // a subsequent store that would make this object accessible by
1640 // other threads.
1641 // Record what AllocateNode this StoreStore protects so that
1642 // escape analysis can go from the MemBarStoreStoreNode to the
1643 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1644 // based on the escape status of the AllocateNode.
1645 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1646 } // original reexecute is set back here
1647
1648 C->set_has_split_ifs(true); // Has chance for split-if optimization
1649 if (!stopped()) {
1650 set_result(newcopy);
1651 }
1652 clear_upper_avx();
1653
1654 return true;
1655 }
1656
1657 //------------------------inline_string_getCharsU--------------------------
1658 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1659 bool LibraryCallKit::inline_string_getCharsU() {
1660 assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1661 // Get the arguments.
1662 Node* src = argument(0);
1663 Node* src_begin = argument(1);
1664 Node* src_end = argument(2); // exclusive offset (i < src_end)
1665 Node* dst = argument(3);
1666 Node* dst_begin = argument(4);
1667
1668 // Check for allocation before we add nodes that would confuse
1669 // tightly_coupled_allocation()
1670 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1671
1672 // Check if a null path was taken unconditionally.
1673 src = must_be_not_null(src, true);
1674 dst = must_be_not_null(dst, true);
1675 if (stopped()) {
1676 return true;
1677 }
1678
1679 // Get length and convert char[] offset to byte[] offset
1680 Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1681 src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1682
1683 // Range checks
1684 RegionNode* bailout = create_bailout();
1685 generate_string_range_check(src, src_begin, length, true, bailout);
1686 generate_string_range_check(dst, dst_begin, length, false, bailout);
1687 if (check_bailout(bailout)) {
1688 return true;
1689 }
1690
1691 // Calculate starting addresses.
1692 Node* src_start = array_element_address(src, src_begin, T_BYTE);
1693 Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1694
1695 // Check if array addresses are aligned to HeapWordSize
1696 const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1697 const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1698 bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1699 tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1700
1701 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1702 const char* copyfunc_name = "arraycopy";
1703 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1704 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1705 OptoRuntime::fast_arraycopy_Type(),
1706 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1707 src_start, dst_start, ConvI2X(length) XTOP);
1708 // Do not let reads from the cloned object float above the arraycopy.
1709 if (alloc != nullptr) {
1710 if (alloc->maybe_set_complete(&_gvn)) {
1711 // "You break it, you buy it."
1712 InitializeNode* init = alloc->initialization();
1713 assert(init->is_complete(), "we just did this");
1714 init->set_complete_with_arraycopy();
1715 assert(dst->is_CheckCastPP(), "sanity");
1716 assert(dst->in(0)->in(0) == init, "dest pinned");
1717 }
1718 // Do not let stores that initialize this object be reordered with
1719 // a subsequent store that would make this object accessible by
1720 // other threads.
1721 // Record what AllocateNode this StoreStore protects so that
1722 // escape analysis can go from the MemBarStoreStoreNode to the
1723 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1724 // based on the escape status of the AllocateNode.
1725 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1726 } else {
1727 insert_mem_bar(Op_MemBarCPUOrder);
1728 }
1729
1730 C->set_has_split_ifs(true); // Has chance for split-if optimization
1731 return true;
1732 }
1733
1734 //----------------------inline_string_char_access----------------------------
1735 // Store/Load char to/from byte[] array.
1736 // static void StringUTF16.putChar(byte[] val, int index, int c)
1737 // static char StringUTF16.getChar(byte[] val, int index)
1738 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1739 Node* ch;
1740 if (is_store) {
1741 assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1742 ch = argument(2);
1743 } else {
1744 assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1745 ch = nullptr;
1746 }
1747 Node* value = argument(0);
1748 Node* index = argument(1);
1749
1750 // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1751 // correctly requires matched array shapes.
1752 assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1753 "sanity: byte[] and char[] bases agree");
1754 assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1755 "sanity: byte[] and char[] scales agree");
1756
1757 // Bail when getChar over constants is requested: constant folding would
1758 // reject folding mismatched char access over byte[]. A normal inlining for getChar
1759 // Java method would constant fold nicely instead.
1760 if (!is_store && value->is_Con() && index->is_Con()) {
1761 return false;
1762 }
1763
1764 // Save state and restore on bailout
1765 SavedState old_state(this);
1766
1767 value = must_be_not_null(value, true);
1768
1769 Node* adr = array_element_address(value, index, T_CHAR);
1770 if (adr->is_top()) {
1771 return false;
1772 }
1773 old_state.discard();
1774 if (is_store) {
1775 access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1776 } else {
1777 ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
1778 set_result(ch);
1779 }
1780 return true;
1781 }
1782
1783
1784 //------------------------------inline_math-----------------------------------
1785 // public static double Math.abs(double)
1786 // public static double Math.sqrt(double)
1787 // public static double Math.log(double)
1788 // public static double Math.log10(double)
1789 // public static double Math.round(double)
1790 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1791 Node* arg = argument(0);
1792 Node* n = nullptr;
1793 switch (id) {
1794 case vmIntrinsics::_dabs: n = new AbsDNode( arg); break;
1795 case vmIntrinsics::_dsqrt:
1796 case vmIntrinsics::_dsqrt_strict:
1797 n = new SqrtDNode(C, control(), arg); break;
1798 case vmIntrinsics::_ceil: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1799 case vmIntrinsics::_floor: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1800 case vmIntrinsics::_rint: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1801 case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1802 case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1803 case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1804 default: fatal_unexpected_iid(id); break;
1805 }
1806 set_result(_gvn.transform(n));
1807 return true;
1808 }
1809
1810 //------------------------------inline_math-----------------------------------
1811 // public static float Math.abs(float)
1812 // public static int Math.abs(int)
1813 // public static long Math.abs(long)
1814 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1815 Node* arg = argument(0);
1816 Node* n = nullptr;
1817 switch (id) {
1818 case vmIntrinsics::_fabs: n = new AbsFNode( arg); break;
1819 case vmIntrinsics::_iabs: n = new AbsINode( arg); break;
1820 case vmIntrinsics::_labs: n = new AbsLNode( arg); break;
1821 case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1822 case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1823 case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1824 default: fatal_unexpected_iid(id); break;
1825 }
1826 set_result(_gvn.transform(n));
1827 return true;
1828 }
1829
1830 //------------------------------runtime_math-----------------------------
1831 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1832 assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1833 "must be (DD)D or (D)D type");
1834
1835 // Inputs
1836 Node* a = argument(0);
1837 Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1838
1839 const TypePtr* no_memory_effects = nullptr;
1840 Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1841 no_memory_effects,
1842 a, top(), b, b ? top() : nullptr);
1843 Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1844 #ifdef ASSERT
1845 Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1846 assert(value_top == top(), "second value must be top");
1847 #endif
1848
1849 set_result(value);
1850 return true;
1851 }
1852
1853 //------------------------------inline_math_pow-----------------------------
1854 bool LibraryCallKit::inline_math_pow() {
1855 Node* base = argument(0);
1856 Node* exp = argument(2);
1857
1858 CallNode* pow = new PowDNode(C, base, exp);
1859 set_predefined_input_for_runtime_call(pow);
1860 pow = _gvn.transform(pow)->as_CallLeafPure();
1861 set_predefined_output_for_runtime_call(pow);
1862 Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1863 record_for_igvn(pow);
1864 set_result(result);
1865 return true;
1866 }
1867
1868 //------------------------------inline_math_native-----------------------------
1869 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1870 switch (id) {
1871 case vmIntrinsics::_dsin:
1872 return StubRoutines::dsin() != nullptr ?
1873 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1874 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
1875 case vmIntrinsics::_dcos:
1876 return StubRoutines::dcos() != nullptr ?
1877 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1878 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
1879 case vmIntrinsics::_dtan:
1880 return StubRoutines::dtan() != nullptr ?
1881 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1882 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1883 case vmIntrinsics::_dsinh:
1884 return StubRoutines::dsinh() != nullptr ?
1885 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1886 case vmIntrinsics::_dtanh:
1887 return StubRoutines::dtanh() != nullptr ?
1888 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1889 case vmIntrinsics::_dcbrt:
1890 return StubRoutines::dcbrt() != nullptr ?
1891 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1892 case vmIntrinsics::_dexp:
1893 return StubRoutines::dexp() != nullptr ?
1894 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(), "dexp") :
1895 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1896 case vmIntrinsics::_dlog:
1897 return StubRoutines::dlog() != nullptr ?
1898 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1899 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
1900 case vmIntrinsics::_dlog10:
1901 return StubRoutines::dlog10() != nullptr ?
1902 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1903 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1904
1905 case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1906 case vmIntrinsics::_ceil:
1907 case vmIntrinsics::_floor:
1908 case vmIntrinsics::_rint: return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1909
1910 case vmIntrinsics::_dsqrt:
1911 case vmIntrinsics::_dsqrt_strict:
1912 return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1913 case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_double_math(id) : false;
1914 case vmIntrinsics::_fabs: return Matcher::match_rule_supported(Op_AbsF) ? inline_math(id) : false;
1915 case vmIntrinsics::_iabs: return Matcher::match_rule_supported(Op_AbsI) ? inline_math(id) : false;
1916 case vmIntrinsics::_labs: return Matcher::match_rule_supported(Op_AbsL) ? inline_math(id) : false;
1917
1918 case vmIntrinsics::_dpow: return inline_math_pow();
1919 case vmIntrinsics::_dcopySign: return inline_double_math(id);
1920 case vmIntrinsics::_fcopySign: return inline_math(id);
1921 case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1922 case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1923 case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1924
1925 // These intrinsics are not yet correctly implemented
1926 case vmIntrinsics::_datan2:
1927 return false;
1928
1929 default:
1930 fatal_unexpected_iid(id);
1931 return false;
1932 }
1933 }
1934
1935 //----------------------------inline_notify-----------------------------------*
1936 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1937 const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1938 address func;
1939 if (id == vmIntrinsics::_notify) {
1940 func = OptoRuntime::monitor_notify_Java();
1941 } else {
1942 func = OptoRuntime::monitor_notifyAll_Java();
1943 }
1944 Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1945 make_slow_call_ex(call, env()->Throwable_klass(), false);
1946 return true;
1947 }
1948
1949
1950 //----------------------------inline_min_max-----------------------------------
1951 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1952 Node* a = nullptr;
1953 Node* b = nullptr;
1954 Node* n = nullptr;
1955 switch (id) {
1956 case vmIntrinsics::_min:
1957 case vmIntrinsics::_max:
1958 case vmIntrinsics::_minF:
1959 case vmIntrinsics::_maxF:
1960 case vmIntrinsics::_minF_strict:
1961 case vmIntrinsics::_maxF_strict:
1962 case vmIntrinsics::_min_strict:
1963 case vmIntrinsics::_max_strict:
1964 assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1965 a = argument(0);
1966 b = argument(1);
1967 break;
1968 case vmIntrinsics::_minD:
1969 case vmIntrinsics::_maxD:
1970 case vmIntrinsics::_minD_strict:
1971 case vmIntrinsics::_maxD_strict:
1972 assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1973 a = argument(0);
1974 b = argument(2);
1975 break;
1976 case vmIntrinsics::_minL:
1977 case vmIntrinsics::_maxL:
1978 assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1979 a = argument(0);
1980 b = argument(2);
1981 break;
1982 default:
1983 fatal_unexpected_iid(id);
1984 break;
1985 }
1986
1987 switch (id) {
1988 case vmIntrinsics::_min:
1989 case vmIntrinsics::_min_strict:
1990 n = new MinINode(a, b);
1991 break;
1992 case vmIntrinsics::_max:
1993 case vmIntrinsics::_max_strict:
1994 n = new MaxINode(a, b);
1995 break;
1996 case vmIntrinsics::_minF:
1997 case vmIntrinsics::_minF_strict:
1998 n = new MinFNode(a, b);
1999 break;
2000 case vmIntrinsics::_maxF:
2001 case vmIntrinsics::_maxF_strict:
2002 n = new MaxFNode(a, b);
2003 break;
2004 case vmIntrinsics::_minD:
2005 case vmIntrinsics::_minD_strict:
2006 n = new MinDNode(a, b);
2007 break;
2008 case vmIntrinsics::_maxD:
2009 case vmIntrinsics::_maxD_strict:
2010 n = new MaxDNode(a, b);
2011 break;
2012 case vmIntrinsics::_minL:
2013 n = new MinLNode(_gvn.C, a, b);
2014 break;
2015 case vmIntrinsics::_maxL:
2016 n = new MaxLNode(_gvn.C, a, b);
2017 break;
2018 default:
2019 fatal_unexpected_iid(id);
2020 break;
2021 }
2022
2023 set_result(_gvn.transform(n));
2024 return true;
2025 }
2026
2027 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2028 if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2029 env()->ArithmeticException_instance())) {
2030 // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2031 // so let's bail out intrinsic rather than risking deopting again.
2032 return false;
2033 }
2034
2035 Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2036 IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2037 Node* fast_path = _gvn.transform( new IfFalseNode(check));
2038 Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2039
2040 {
2041 PreserveJVMState pjvms(this);
2042 PreserveReexecuteState preexecs(this);
2043 jvms()->set_should_reexecute(true);
2044
2045 set_control(slow_path);
2046 set_i_o(i_o());
2047
2048 builtin_throw(Deoptimization::Reason_intrinsic,
2049 env()->ArithmeticException_instance(),
2050 /*allow_too_many_traps*/ false);
2051 }
2052
2053 set_control(fast_path);
2054 set_result(math);
2055 return true;
2056 }
2057
2058 template <typename OverflowOp>
2059 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2060 typedef typename OverflowOp::MathOp MathOp;
2061
2062 MathOp* mathOp = new MathOp(arg1, arg2);
2063 Node* operation = _gvn.transform( mathOp );
2064 Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2065 return inline_math_mathExact(operation, ofcheck);
2066 }
2067
2068 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2069 return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2070 }
2071
2072 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2073 return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2074 }
2075
2076 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2077 return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2078 }
2079
2080 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2081 return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2082 }
2083
2084 bool LibraryCallKit::inline_math_negateExactI() {
2085 return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2086 }
2087
2088 bool LibraryCallKit::inline_math_negateExactL() {
2089 return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2090 }
2091
2092 bool LibraryCallKit::inline_math_multiplyExactI() {
2093 return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2094 }
2095
2096 bool LibraryCallKit::inline_math_multiplyExactL() {
2097 return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2098 }
2099
2100 bool LibraryCallKit::inline_math_multiplyHigh() {
2101 set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2102 return true;
2103 }
2104
2105 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2106 set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2107 return true;
2108 }
2109
2110 inline int
2111 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2112 const TypePtr* base_type = TypePtr::NULL_PTR;
2113 if (base != nullptr) base_type = _gvn.type(base)->isa_ptr();
2114 if (base_type == nullptr) {
2115 // Unknown type.
2116 return Type::AnyPtr;
2117 } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2118 // Since this is a null+long form, we have to switch to a rawptr.
2119 base = _gvn.transform(new CastX2PNode(offset));
2120 offset = MakeConX(0);
2121 return Type::RawPtr;
2122 } else if (base_type->base() == Type::RawPtr) {
2123 return Type::RawPtr;
2124 } else if (base_type->isa_oopptr()) {
2125 // Base is never null => always a heap address.
2126 if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2127 return Type::OopPtr;
2128 }
2129 // Offset is small => always a heap address.
2130 const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2131 if (offset_type != nullptr &&
2132 base_type->offset() == 0 && // (should always be?)
2133 offset_type->_lo >= 0 &&
2134 !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2135 return Type::OopPtr;
2136 } else if (type == T_OBJECT) {
2137 // off heap access to an oop doesn't make any sense. Has to be on
2138 // heap.
2139 return Type::OopPtr;
2140 }
2141 // Otherwise, it might either be oop+off or null+addr.
2142 return Type::AnyPtr;
2143 } else {
2144 // No information:
2145 return Type::AnyPtr;
2146 }
2147 }
2148
2149 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2150 Node* uncasted_base = base;
2151 int kind = classify_unsafe_addr(uncasted_base, offset, type);
2152 if (kind == Type::RawPtr) {
2153 return off_heap_plus_addr(uncasted_base, offset);
2154 } else if (kind == Type::AnyPtr) {
2155 assert(base == uncasted_base, "unexpected base change");
2156 if (can_cast) {
2157 if (!_gvn.type(base)->speculative_maybe_null() &&
2158 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2159 // According to profiling, this access is always on
2160 // heap. Casting the base to not null and thus avoiding membars
2161 // around the access should allow better optimizations
2162 Node* null_ctl = top();
2163 base = null_check_oop(base, &null_ctl, true, true, true);
2164 assert(null_ctl->is_top(), "no null control here");
2165 return basic_plus_adr(base, offset);
2166 } else if (_gvn.type(base)->speculative_always_null() &&
2167 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2168 // According to profiling, this access is always off
2169 // heap.
2170 base = null_assert(base);
2171 Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2172 offset = MakeConX(0);
2173 return off_heap_plus_addr(raw_base, offset);
2174 }
2175 }
2176 // We don't know if it's an on heap or off heap access. Fall back
2177 // to raw memory access.
2178 Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2179 return off_heap_plus_addr(raw, offset);
2180 } else {
2181 assert(base == uncasted_base, "unexpected base change");
2182 // We know it's an on heap access so base can't be null
2183 if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2184 base = must_be_not_null(base, true);
2185 }
2186 return basic_plus_adr(base, offset);
2187 }
2188 }
2189
2190 //--------------------------inline_number_methods-----------------------------
2191 // inline int Integer.numberOfLeadingZeros(int)
2192 // inline int Long.numberOfLeadingZeros(long)
2193 //
2194 // inline int Integer.numberOfTrailingZeros(int)
2195 // inline int Long.numberOfTrailingZeros(long)
2196 //
2197 // inline int Integer.bitCount(int)
2198 // inline int Long.bitCount(long)
2199 //
2200 // inline char Character.reverseBytes(char)
2201 // inline short Short.reverseBytes(short)
2202 // inline int Integer.reverseBytes(int)
2203 // inline long Long.reverseBytes(long)
2204 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2205 Node* arg = argument(0);
2206 Node* n = nullptr;
2207 switch (id) {
2208 case vmIntrinsics::_numberOfLeadingZeros_i: n = new CountLeadingZerosINode( arg); break;
2209 case vmIntrinsics::_numberOfLeadingZeros_l: n = new CountLeadingZerosLNode( arg); break;
2210 case vmIntrinsics::_numberOfTrailingZeros_i: n = new CountTrailingZerosINode(arg); break;
2211 case vmIntrinsics::_numberOfTrailingZeros_l: n = new CountTrailingZerosLNode(arg); break;
2212 case vmIntrinsics::_bitCount_i: n = new PopCountINode( arg); break;
2213 case vmIntrinsics::_bitCount_l: n = new PopCountLNode( arg); break;
2214 case vmIntrinsics::_reverseBytes_c: n = new ReverseBytesUSNode( arg); break;
2215 case vmIntrinsics::_reverseBytes_s: n = new ReverseBytesSNode( arg); break;
2216 case vmIntrinsics::_reverseBytes_i: n = new ReverseBytesINode( arg); break;
2217 case vmIntrinsics::_reverseBytes_l: n = new ReverseBytesLNode( arg); break;
2218 case vmIntrinsics::_reverse_i: n = new ReverseINode( arg); break;
2219 case vmIntrinsics::_reverse_l: n = new ReverseLNode( arg); break;
2220 default: fatal_unexpected_iid(id); break;
2221 }
2222 set_result(_gvn.transform(n));
2223 return true;
2224 }
2225
2226 //--------------------------inline_bitshuffle_methods-----------------------------
2227 // inline int Integer.compress(int, int)
2228 // inline int Integer.expand(int, int)
2229 // inline long Long.compress(long, long)
2230 // inline long Long.expand(long, long)
2231 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2232 Node* n = nullptr;
2233 switch (id) {
2234 case vmIntrinsics::_compress_i: n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2235 case vmIntrinsics::_expand_i: n = new ExpandBitsNode(argument(0), argument(1), TypeInt::INT); break;
2236 case vmIntrinsics::_compress_l: n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2237 case vmIntrinsics::_expand_l: n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2238 default: fatal_unexpected_iid(id); break;
2239 }
2240 set_result(_gvn.transform(n));
2241 return true;
2242 }
2243
2244 //--------------------------inline_number_methods-----------------------------
2245 // inline int Integer.compareUnsigned(int, int)
2246 // inline int Long.compareUnsigned(long, long)
2247 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2248 Node* arg1 = argument(0);
2249 Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2250 Node* n = nullptr;
2251 switch (id) {
2252 case vmIntrinsics::_compareUnsigned_i: n = new CmpU3Node(arg1, arg2); break;
2253 case vmIntrinsics::_compareUnsigned_l: n = new CmpUL3Node(arg1, arg2); break;
2254 default: fatal_unexpected_iid(id); break;
2255 }
2256 set_result(_gvn.transform(n));
2257 return true;
2258 }
2259
2260 //--------------------------inline_unsigned_divmod_methods-----------------------------
2261 // inline int Integer.divideUnsigned(int, int)
2262 // inline int Integer.remainderUnsigned(int, int)
2263 // inline long Long.divideUnsigned(long, long)
2264 // inline long Long.remainderUnsigned(long, long)
2265 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2266 Node* n = nullptr;
2267 switch (id) {
2268 case vmIntrinsics::_divideUnsigned_i: {
2269 zero_check_int(argument(1));
2270 // Compile-time detect of null-exception
2271 if (stopped()) {
2272 return true; // keep the graph constructed so far
2273 }
2274 n = new UDivINode(control(), argument(0), argument(1));
2275 break;
2276 }
2277 case vmIntrinsics::_divideUnsigned_l: {
2278 zero_check_long(argument(2));
2279 // Compile-time detect of null-exception
2280 if (stopped()) {
2281 return true; // keep the graph constructed so far
2282 }
2283 n = new UDivLNode(control(), argument(0), argument(2));
2284 break;
2285 }
2286 case vmIntrinsics::_remainderUnsigned_i: {
2287 zero_check_int(argument(1));
2288 // Compile-time detect of null-exception
2289 if (stopped()) {
2290 return true; // keep the graph constructed so far
2291 }
2292 n = new UModINode(control(), argument(0), argument(1));
2293 break;
2294 }
2295 case vmIntrinsics::_remainderUnsigned_l: {
2296 zero_check_long(argument(2));
2297 // Compile-time detect of null-exception
2298 if (stopped()) {
2299 return true; // keep the graph constructed so far
2300 }
2301 n = new UModLNode(control(), argument(0), argument(2));
2302 break;
2303 }
2304 default: fatal_unexpected_iid(id); break;
2305 }
2306 set_result(_gvn.transform(n));
2307 return true;
2308 }
2309
2310 //----------------------------inline_unsafe_access----------------------------
2311
2312 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2313 // Attempt to infer a sharper value type from the offset and base type.
2314 ciKlass* sharpened_klass = nullptr;
2315 bool null_free = false;
2316
2317 // See if it is an instance field, with an object type.
2318 if (alias_type->field() != nullptr) {
2319 if (alias_type->field()->type()->is_klass()) {
2320 sharpened_klass = alias_type->field()->type()->as_klass();
2321 null_free = alias_type->field()->is_null_free();
2322 }
2323 }
2324
2325 const TypeOopPtr* result = nullptr;
2326 // See if it is a narrow oop array.
2327 if (adr_type->isa_aryptr()) {
2328 if (adr_type->offset() >= refArrayOopDesc::base_offset_in_bytes()) {
2329 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2330 null_free = adr_type->is_aryptr()->is_null_free();
2331 if (elem_type != nullptr && elem_type->is_loaded()) {
2332 // Sharpen the value type.
2333 result = elem_type;
2334 }
2335 }
2336 }
2337
2338 // The sharpened class might be unloaded if there is no class loader
2339 // contraint in place.
2340 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2341 // Sharpen the value type.
2342 result = TypeOopPtr::make_from_klass(sharpened_klass);
2343 if (null_free) {
2344 result = result->join_speculative(TypePtr::NOTNULL)->is_oopptr();
2345 }
2346 }
2347 if (result != nullptr) {
2348 #ifndef PRODUCT
2349 if (C->print_intrinsics() || C->print_inlining()) {
2350 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2351 tty->print(" sharpened value: "); result->dump(); tty->cr();
2352 }
2353 #endif
2354 }
2355 return result;
2356 }
2357
2358 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2359 switch (kind) {
2360 case Relaxed:
2361 return MO_UNORDERED;
2362 case Opaque:
2363 return MO_RELAXED;
2364 case Acquire:
2365 return MO_ACQUIRE;
2366 case Release:
2367 return MO_RELEASE;
2368 case Volatile:
2369 return MO_SEQ_CST;
2370 default:
2371 ShouldNotReachHere();
2372 return 0;
2373 }
2374 }
2375
2376 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2377 if (callee()->is_static()) return false; // caller must have the capability!
2378 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2379 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2380 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2381 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2382
2383 if (is_reference_type(type)) {
2384 decorators |= ON_UNKNOWN_OOP_REF;
2385 }
2386
2387 if (unaligned) {
2388 decorators |= C2_UNALIGNED;
2389 }
2390
2391 #ifndef PRODUCT
2392 {
2393 ResourceMark rm;
2394 // Check the signatures.
2395 ciSignature* sig = callee()->signature();
2396 #ifdef ASSERT
2397 if (!is_store) {
2398 // Object getReference(Object base, int/long offset), etc.
2399 BasicType rtype = sig->return_type()->basic_type();
2400 assert(rtype == type, "getter must return the expected value");
2401 assert(sig->count() == 2, "oop getter has 2 arguments");
2402 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2403 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2404 } else {
2405 // void putReference(Object base, int/long offset, Object x), etc.
2406 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2407 assert(sig->count() == 3, "oop putter has 3 arguments");
2408 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2409 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2410 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2411 assert(vtype == type, "putter must accept the expected value");
2412 }
2413 #endif // ASSERT
2414 }
2415 #endif //PRODUCT
2416
2417 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2418
2419 Node* receiver = argument(0); // type: oop
2420
2421 // Build address expression.
2422 Node* heap_base_oop = top();
2423
2424 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2425 Node* base = argument(1); // type: oop
2426 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2427 Node* offset = argument(2); // type: long
2428 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2429 // to be plain byte offsets, which are also the same as those accepted
2430 // by oopDesc::field_addr.
2431 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2432 "fieldOffset must be byte-scaled");
2433
2434 if (base->is_InlineType()) {
2435 assert(!is_store, "InlineTypeNodes are non-larval value objects");
2436 InlineTypeNode* vt = base->as_InlineType();
2437 if (offset->is_Con()) {
2438 long off = find_long_con(offset, 0);
2439 ciInlineKlass* vk = vt->type()->inline_klass();
2440 if ((long)(int)off != off || !vk->contains_field_offset(off)) {
2441 return false;
2442 }
2443
2444 ciField* field = vk->get_non_flat_field_by_offset(off);
2445 if (field != nullptr) {
2446 BasicType bt = type2field[field->type()->basic_type()];
2447 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2448 bt = T_OBJECT;
2449 }
2450 if (bt == type && !field->is_flat()) {
2451 Node* value = vt->field_value_by_offset(off, false);
2452 const Type* value_type = _gvn.type(value);
2453 if (value_type->is_inlinetypeptr()) {
2454 value = InlineTypeNode::make_from_oop(this, value, value_type->inline_klass());
2455 }
2456 set_result(value);
2457 return true;
2458 }
2459 }
2460 }
2461 {
2462 // Re-execute the unsafe access if allocation triggers deoptimization.
2463 PreserveReexecuteState preexecs(this);
2464 jvms()->set_should_reexecute(true);
2465 vt = vt->buffer(this);
2466 }
2467 base = vt->get_oop();
2468 }
2469
2470 // 32-bit machines ignore the high half!
2471 offset = ConvL2X(offset);
2472
2473 // Save state and restore on bailout
2474 SavedState old_state(this);
2475
2476 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2477 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2478
2479 if (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR) {
2480 if (type != T_OBJECT) {
2481 decorators |= IN_NATIVE; // off-heap primitive access
2482 } else {
2483 return false; // off-heap oop accesses are not supported
2484 }
2485 } else {
2486 heap_base_oop = base; // on-heap or mixed access
2487 }
2488
2489 // Can base be null? Otherwise, always on-heap access.
2490 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2491
2492 if (!can_access_non_heap) {
2493 decorators |= IN_HEAP;
2494 }
2495
2496 Node* val = is_store ? argument(4) : nullptr;
2497
2498 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2499 if (adr_type == TypePtr::NULL_PTR) {
2500 return false; // off-heap access with zero address
2501 }
2502
2503 // Try to categorize the address.
2504 Compile::AliasType* alias_type = C->alias_type(adr_type);
2505 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2506
2507 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2508 alias_type->adr_type() == TypeAryPtr::RANGE) {
2509 return false; // not supported
2510 }
2511
2512 bool mismatched = false;
2513 BasicType bt = T_ILLEGAL;
2514 ciField* field = nullptr;
2515 if (adr_type->isa_instptr()) {
2516 const TypeInstPtr* instptr = adr_type->is_instptr();
2517 ciInstanceKlass* k = instptr->instance_klass();
2518 int off = instptr->offset();
2519 if (instptr->const_oop() != nullptr &&
2520 k == ciEnv::current()->Class_klass() &&
2521 instptr->offset() >= (k->size_helper() * wordSize)) {
2522 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2523 field = k->get_field_by_offset(off, true);
2524 } else {
2525 field = k->get_non_flat_field_by_offset(off);
2526 }
2527 if (field != nullptr) {
2528 bt = type2field[field->type()->basic_type()];
2529 }
2530 if (bt != alias_type->basic_type()) {
2531 // Type mismatch. Is it an access to a nested flat field?
2532 field = k->get_field_by_offset(off, false);
2533 if (field != nullptr) {
2534 bt = type2field[field->type()->basic_type()];
2535 }
2536 }
2537 assert(bt == alias_type->basic_type(), "should match");
2538 } else {
2539 bt = alias_type->basic_type();
2540 }
2541
2542 if (bt != T_ILLEGAL) {
2543 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2544 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2545 // Alias type doesn't differentiate between byte[] and boolean[]).
2546 // Use address type to get the element type.
2547 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2548 }
2549 if (is_reference_type(bt, true)) {
2550 // accessing an array field with getReference is not a mismatch
2551 bt = T_OBJECT;
2552 }
2553 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2554 // Don't intrinsify mismatched object accesses
2555 return false;
2556 }
2557 mismatched = (bt != type);
2558 } else if (alias_type->adr_type()->isa_oopptr()) {
2559 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2560 }
2561
2562 old_state.discard();
2563 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2564
2565 if (mismatched) {
2566 decorators |= C2_MISMATCHED;
2567 }
2568
2569 // First guess at the value type.
2570 const Type *value_type = Type::get_const_basic_type(type);
2571
2572 // Figure out the memory ordering.
2573 decorators |= mo_decorator_for_access_kind(kind);
2574
2575 if (!is_store) {
2576 if (type == T_OBJECT) {
2577 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2578 if (tjp != nullptr) {
2579 value_type = tjp;
2580 }
2581 }
2582 }
2583
2584 receiver = null_check(receiver);
2585 if (stopped()) {
2586 return true;
2587 }
2588 // Heap pointers get a null-check from the interpreter,
2589 // as a courtesy. However, this is not guaranteed by Unsafe,
2590 // and it is not possible to fully distinguish unintended nulls
2591 // from intended ones in this API.
2592
2593 if (!is_store) {
2594 Node* p = nullptr;
2595 // Try to constant fold a load from a constant field
2596
2597 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2598 // final or stable field
2599 p = make_constant_from_field(field, heap_base_oop);
2600 }
2601
2602 if (p == nullptr) { // Could not constant fold the load
2603 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2604 const TypeOopPtr* ptr = value_type->make_oopptr();
2605 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2606 // Load a non-flattened inline type from memory
2607 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2608 }
2609 // Normalize the value returned by getBoolean in the following cases
2610 if (type == T_BOOLEAN &&
2611 (mismatched ||
2612 heap_base_oop == top() || // - heap_base_oop is null or
2613 (can_access_non_heap && field == nullptr)) // - heap_base_oop is potentially null
2614 // and the unsafe access is made to large offset
2615 // (i.e., larger than the maximum offset necessary for any
2616 // field access)
2617 ) {
2618 IdealKit ideal = IdealKit(this);
2619 #define __ ideal.
2620 IdealVariable normalized_result(ideal);
2621 __ declarations_done();
2622 __ set(normalized_result, p);
2623 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2624 __ set(normalized_result, ideal.ConI(1));
2625 ideal.end_if();
2626 final_sync(ideal);
2627 p = __ value(normalized_result);
2628 #undef __
2629 }
2630 }
2631 if (type == T_ADDRESS) {
2632 p = gvn().transform(new CastP2XNode(nullptr, p));
2633 p = ConvX2UL(p);
2634 }
2635 // The load node has the control of the preceding MemBarCPUOrder. All
2636 // following nodes will have the control of the MemBarCPUOrder inserted at
2637 // the end of this method. So, pushing the load onto the stack at a later
2638 // point is fine.
2639 set_result(p);
2640 } else {
2641 if (bt == T_ADDRESS) {
2642 // Repackage the long as a pointer.
2643 val = ConvL2X(val);
2644 val = gvn().transform(new CastX2PNode(val));
2645 }
2646 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2647 }
2648
2649 return true;
2650 }
2651
2652 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2653 #ifdef ASSERT
2654 {
2655 ResourceMark rm;
2656 // Check the signatures.
2657 ciSignature* sig = callee()->signature();
2658 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2659 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2660 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2661 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2662 if (is_store) {
2663 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2664 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2665 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2666 } else {
2667 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2668 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2669 }
2670 }
2671 #endif // ASSERT
2672
2673 assert(kind == Relaxed, "Only plain accesses for now");
2674 if (callee()->is_static()) {
2675 // caller must have the capability!
2676 return false;
2677 }
2678 C->set_has_unsafe_access(true);
2679
2680 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2681 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2682 // parameter valueType is not a constant
2683 return false;
2684 }
2685 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2686 if (!mirror_type->is_inlinetype()) {
2687 // Dead code
2688 return false;
2689 }
2690 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2691
2692 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2693 if (layout_type == nullptr || !layout_type->is_con()) {
2694 // parameter layoutKind is not a constant
2695 return false;
2696 }
2697 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2698 layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2699 "invalid layoutKind %d", layout_type->get_con());
2700 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2701 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2702 layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2703 "unexpected layoutKind %d", layout_type->get_con());
2704
2705 null_check(argument(0));
2706 if (stopped()) {
2707 return true;
2708 }
2709
2710 Node* base = must_be_not_null(argument(1), true);
2711 Node* offset = argument(2);
2712 const Type* base_type = _gvn.type(base);
2713
2714 Node* ptr;
2715 bool immutable_memory = false;
2716 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2717 if (base_type->isa_instptr()) {
2718 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2719 if (offset_type == nullptr || !offset_type->is_con()) {
2720 // Offset into a non-array should be a constant
2721 decorators |= C2_MISMATCHED;
2722 } else {
2723 int offset_con = checked_cast<int>(offset_type->get_con());
2724 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2725 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2726 if (field == nullptr) {
2727 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2728 decorators |= C2_MISMATCHED;
2729 } else {
2730 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2731 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2732 immutable_memory = field->is_strict() && field->is_final();
2733
2734 if (base->is_InlineType()) {
2735 assert(!is_store, "Cannot store into a non-larval value object");
2736 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2737 return true;
2738 }
2739 }
2740 }
2741
2742 if (base->is_InlineType()) {
2743 assert(!is_store, "Cannot store into a non-larval value object");
2744 base = base->as_InlineType()->buffer(this, true);
2745 }
2746 ptr = basic_plus_adr(base, ConvL2X(offset));
2747 } else if (base_type->isa_aryptr()) {
2748 decorators |= IS_ARRAY;
2749 if (layout == LayoutKind::REFERENCE) {
2750 if (!base_type->is_aryptr()->is_not_flat()) {
2751 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2752 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2753 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2754 replace_in_map(base, new_base);
2755 base = new_base;
2756 }
2757 ptr = basic_plus_adr(base, ConvL2X(offset));
2758 } else {
2759 if (UseArrayFlattening) {
2760 // Flat array must have an exact type
2761 bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2762 bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2763 Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2764 replace_in_map(base, new_base);
2765 base = new_base;
2766 ptr = basic_plus_adr(base, ConvL2X(offset));
2767 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2768 if (ptr_type->field_offset().get() != 0) {
2769 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2770 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2771 }
2772 } else {
2773 uncommon_trap(Deoptimization::Reason_intrinsic,
2774 Deoptimization::Action_none);
2775 return true;
2776 }
2777 }
2778 } else {
2779 decorators |= C2_MISMATCHED;
2780 ptr = basic_plus_adr(base, ConvL2X(offset));
2781 }
2782
2783 if (is_store) {
2784 Node* value = argument(6);
2785 const Type* value_type = _gvn.type(value);
2786 if (!value_type->is_inlinetypeptr()) {
2787 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2788 Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2789 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2790 replace_in_map(value, new_value);
2791 value = new_value;
2792 }
2793
2794 assert(value_type->inline_klass() == value_klass, "value is of type %s while valueType is %s", value_type->inline_klass()->name()->as_utf8(), value_klass->name()->as_utf8());
2795 if (layout == LayoutKind::REFERENCE) {
2796 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2797 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2798 } else {
2799 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2800 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2801 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2802 }
2803
2804 return true;
2805 } else {
2806 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2807 InlineTypeNode* result;
2808 if (layout == LayoutKind::REFERENCE) {
2809 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2810 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2811 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2812 } else {
2813 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2814 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2815 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2816 }
2817
2818 set_result(result);
2819 return true;
2820 }
2821 }
2822
2823 //----------------------------inline_unsafe_load_store----------------------------
2824 // This method serves a couple of different customers (depending on LoadStoreKind):
2825 //
2826 // LS_cmp_swap:
2827 //
2828 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2829 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2830 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2831 //
2832 // LS_cmp_swap_weak:
2833 //
2834 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2835 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2836 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2837 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2838 //
2839 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2840 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2841 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2842 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2843 //
2844 // boolean weakCompareAndSetLong( Object o, long offset, long expected, long x);
2845 // boolean weakCompareAndSetLongPlain( Object o, long offset, long expected, long x);
2846 // boolean weakCompareAndSetLongAcquire( Object o, long offset, long expected, long x);
2847 // boolean weakCompareAndSetLongRelease( Object o, long offset, long expected, long x);
2848 //
2849 // LS_cmp_exchange:
2850 //
2851 // Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2852 // Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2853 // Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2854 //
2855 // Object compareAndExchangeIntVolatile( Object o, long offset, Object expected, Object x);
2856 // Object compareAndExchangeIntAcquire( Object o, long offset, Object expected, Object x);
2857 // Object compareAndExchangeIntRelease( Object o, long offset, Object expected, Object x);
2858 //
2859 // Object compareAndExchangeLongVolatile( Object o, long offset, Object expected, Object x);
2860 // Object compareAndExchangeLongAcquire( Object o, long offset, Object expected, Object x);
2861 // Object compareAndExchangeLongRelease( Object o, long offset, Object expected, Object x);
2862 //
2863 // LS_get_add:
2864 //
2865 // int getAndAddInt( Object o, long offset, int delta)
2866 // long getAndAddLong(Object o, long offset, long delta)
2867 //
2868 // LS_get_set:
2869 //
2870 // int getAndSet(Object o, long offset, int newValue)
2871 // long getAndSet(Object o, long offset, long newValue)
2872 // Object getAndSet(Object o, long offset, Object newValue)
2873 //
2874 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2875 // This basic scheme here is the same as inline_unsafe_access, but
2876 // differs in enough details that combining them would make the code
2877 // overly confusing. (This is a true fact! I originally combined
2878 // them, but even I was confused by it!) As much code/comments as
2879 // possible are retained from inline_unsafe_access though to make
2880 // the correspondences clearer. - dl
2881
2882 if (callee()->is_static()) return false; // caller must have the capability!
2883
2884 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2885 decorators |= mo_decorator_for_access_kind(access_kind);
2886
2887 #ifndef PRODUCT
2888 BasicType rtype;
2889 {
2890 ResourceMark rm;
2891 // Check the signatures.
2892 ciSignature* sig = callee()->signature();
2893 rtype = sig->return_type()->basic_type();
2894 switch(kind) {
2895 case LS_get_add:
2896 case LS_get_set: {
2897 // Check the signatures.
2898 #ifdef ASSERT
2899 assert(rtype == type, "get and set must return the expected type");
2900 assert(sig->count() == 3, "get and set has 3 arguments");
2901 assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2902 assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2903 assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2904 assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2905 #endif // ASSERT
2906 break;
2907 }
2908 case LS_cmp_swap:
2909 case LS_cmp_swap_weak: {
2910 // Check the signatures.
2911 #ifdef ASSERT
2912 assert(rtype == T_BOOLEAN, "CAS must return boolean");
2913 assert(sig->count() == 4, "CAS has 4 arguments");
2914 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2915 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2916 #endif // ASSERT
2917 break;
2918 }
2919 case LS_cmp_exchange: {
2920 // Check the signatures.
2921 #ifdef ASSERT
2922 assert(rtype == type, "CAS must return the expected type");
2923 assert(sig->count() == 4, "CAS has 4 arguments");
2924 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2925 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2926 #endif // ASSERT
2927 break;
2928 }
2929 default:
2930 ShouldNotReachHere();
2931 }
2932 }
2933 #endif //PRODUCT
2934
2935 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2936
2937 // Get arguments:
2938 Node* receiver = nullptr;
2939 Node* base = nullptr;
2940 Node* offset = nullptr;
2941 Node* oldval = nullptr;
2942 Node* newval = nullptr;
2943 switch(kind) {
2944 case LS_cmp_swap:
2945 case LS_cmp_swap_weak:
2946 case LS_cmp_exchange: {
2947 const bool two_slot_type = type2size[type] == 2;
2948 receiver = argument(0); // type: oop
2949 base = argument(1); // type: oop
2950 offset = argument(2); // type: long
2951 oldval = argument(4); // type: oop, int, or long
2952 newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long
2953 break;
2954 }
2955 case LS_get_add:
2956 case LS_get_set: {
2957 receiver = argument(0); // type: oop
2958 base = argument(1); // type: oop
2959 offset = argument(2); // type: long
2960 oldval = nullptr;
2961 newval = argument(4); // type: oop, int, or long
2962 break;
2963 }
2964 default:
2965 ShouldNotReachHere();
2966 }
2967
2968 // Build field offset expression.
2969 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2970 // to be plain byte offsets, which are also the same as those accepted
2971 // by oopDesc::field_addr.
2972 assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2973 // 32-bit machines ignore the high half of long offsets
2974 offset = ConvL2X(offset);
2975 // Save state and restore on bailout
2976 SavedState old_state(this);
2977 Node* adr = make_unsafe_address(base, offset,type, false);
2978 const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2979
2980 Compile::AliasType* alias_type = C->alias_type(adr_type);
2981 BasicType bt = alias_type->basic_type();
2982 if (bt != T_ILLEGAL &&
2983 (is_reference_type(bt) != (type == T_OBJECT))) {
2984 // Don't intrinsify mismatched object accesses.
2985 return false;
2986 }
2987
2988 old_state.discard();
2989
2990 // For CAS, unlike inline_unsafe_access, there seems no point in
2991 // trying to refine types. Just use the coarse types here.
2992 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2993 const Type *value_type = Type::get_const_basic_type(type);
2994
2995 switch (kind) {
2996 case LS_get_set:
2997 case LS_cmp_exchange: {
2998 if (type == T_OBJECT) {
2999 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
3000 if (tjp != nullptr) {
3001 value_type = tjp;
3002 }
3003 }
3004 break;
3005 }
3006 case LS_cmp_swap:
3007 case LS_cmp_swap_weak:
3008 case LS_get_add:
3009 break;
3010 default:
3011 ShouldNotReachHere();
3012 }
3013
3014 // Null check receiver.
3015 receiver = null_check(receiver);
3016 if (stopped()) {
3017 return true;
3018 }
3019
3020 int alias_idx = C->get_alias_index(adr_type);
3021
3022 if (is_reference_type(type)) {
3023 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3024
3025 if (oldval != nullptr && oldval->is_InlineType()) {
3026 // Re-execute the unsafe access if allocation triggers deoptimization.
3027 PreserveReexecuteState preexecs(this);
3028 jvms()->set_should_reexecute(true);
3029 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3030 }
3031 if (newval != nullptr && newval->is_InlineType()) {
3032 // Re-execute the unsafe access if allocation triggers deoptimization.
3033 PreserveReexecuteState preexecs(this);
3034 jvms()->set_should_reexecute(true);
3035 newval = newval->as_InlineType()->buffer(this)->get_oop();
3036 }
3037
3038 // Transformation of a value which could be null pointer (CastPP #null)
3039 // could be delayed during Parse (for example, in adjust_map_after_if()).
3040 // Execute transformation here to avoid barrier generation in such case.
3041 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3042 newval = _gvn.makecon(TypePtr::NULL_PTR);
3043
3044 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3045 // Refine the value to a null constant, when it is known to be null
3046 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3047 }
3048 }
3049
3050 Node* result = nullptr;
3051 switch (kind) {
3052 case LS_cmp_exchange: {
3053 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3054 oldval, newval, value_type, type, decorators);
3055 break;
3056 }
3057 case LS_cmp_swap_weak:
3058 decorators |= C2_WEAK_CMPXCHG;
3059 case LS_cmp_swap: {
3060 result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3061 oldval, newval, value_type, type, decorators);
3062 break;
3063 }
3064 case LS_get_set: {
3065 result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3066 newval, value_type, type, decorators);
3067 break;
3068 }
3069 case LS_get_add: {
3070 result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3071 newval, value_type, type, decorators);
3072 break;
3073 }
3074 default:
3075 ShouldNotReachHere();
3076 }
3077
3078 assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3079 set_result(result);
3080 return true;
3081 }
3082
3083 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3084 // Regardless of form, don't allow previous ld/st to move down,
3085 // then issue acquire, release, or volatile mem_bar.
3086 insert_mem_bar(Op_MemBarCPUOrder);
3087 switch(id) {
3088 case vmIntrinsics::_loadFence:
3089 insert_mem_bar(Op_LoadFence);
3090 return true;
3091 case vmIntrinsics::_storeFence:
3092 insert_mem_bar(Op_StoreFence);
3093 return true;
3094 case vmIntrinsics::_storeStoreFence:
3095 insert_mem_bar(Op_StoreStoreFence);
3096 return true;
3097 case vmIntrinsics::_fullFence:
3098 insert_mem_bar(Op_MemBarFull);
3099 return true;
3100 default:
3101 fatal_unexpected_iid(id);
3102 return false;
3103 }
3104 }
3105
3106 // private native int arrayInstanceBaseOffset0(Object[] array);
3107 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3108 Node* array = argument(1);
3109 Node* klass_node = load_object_klass(array);
3110
3111 jint layout_con = Klass::_lh_neutral_value;
3112 Node* layout_val = get_layout_helper(klass_node, layout_con);
3113 int layout_is_con = (layout_val == nullptr);
3114
3115 Node* header_size = nullptr;
3116 if (layout_is_con) {
3117 int hsize = Klass::layout_helper_header_size(layout_con);
3118 header_size = intcon(hsize);
3119 } else {
3120 Node* hss = intcon(Klass::_lh_header_size_shift);
3121 Node* hsm = intcon(Klass::_lh_header_size_mask);
3122 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3123 header_size = _gvn.transform(new AndINode(header_size, hsm));
3124 }
3125 set_result(header_size);
3126 return true;
3127 }
3128
3129 // private native int arrayInstanceIndexScale0(Object[] array);
3130 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3131 Node* array = argument(1);
3132 Node* klass_node = load_object_klass(array);
3133
3134 jint layout_con = Klass::_lh_neutral_value;
3135 Node* layout_val = get_layout_helper(klass_node, layout_con);
3136 int layout_is_con = (layout_val == nullptr);
3137
3138 Node* element_size = nullptr;
3139 if (layout_is_con) {
3140 int log_element_size = Klass::layout_helper_log2_element_size(layout_con);
3141 int elem_size = 1 << log_element_size;
3142 element_size = intcon(elem_size);
3143 } else {
3144 Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3145 Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3146 Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3147 log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3148 element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3149 }
3150 set_result(element_size);
3151 return true;
3152 }
3153
3154 // private native int arrayLayout0(Object[] array);
3155 bool LibraryCallKit::inline_arrayLayout() {
3156 RegionNode* region = new RegionNode(2);
3157 Node* phi = new PhiNode(region, TypeInt::POS);
3158
3159 Node* array = argument(1);
3160 Node* klass_node = load_object_klass(array);
3161 generate_refArray_guard(klass_node, region);
3162 if (region->req() == 3) {
3163 phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3164 }
3165
3166 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3167 Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3168 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3169
3170 region->init_req(1, control());
3171 phi->init_req(1, layout_kind);
3172
3173 set_control(_gvn.transform(region));
3174 set_result(_gvn.transform(phi));
3175 return true;
3176 }
3177
3178 // private native int[] getFieldMap0(Class <?> c);
3179 // int offset = c._klass._acmp_maps_offset;
3180 // return (int[])c.obj_field(offset);
3181 bool LibraryCallKit::inline_getFieldMap() {
3182 Node* mirror = argument(1);
3183 Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3184
3185 int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3186 Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3187 Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3188 field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3189
3190 Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3191 const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3192 Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3193
3194 set_result(map);
3195 return true;
3196 }
3197
3198 bool LibraryCallKit::inline_onspinwait() {
3199 insert_mem_bar(Op_OnSpinWait);
3200 return true;
3201 }
3202
3203 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3204 if (!kls->is_Con()) {
3205 return true;
3206 }
3207 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3208 if (klsptr == nullptr) {
3209 return true;
3210 }
3211 ciInstanceKlass* ik = klsptr->instance_klass();
3212 // don't need a guard for a klass that is already initialized
3213 return !ik->is_initialized();
3214 }
3215
3216 //----------------------------inline_unsafe_writeback0-------------------------
3217 // public native void Unsafe.writeback0(long address)
3218 bool LibraryCallKit::inline_unsafe_writeback0() {
3219 if (!Matcher::has_match_rule(Op_CacheWB)) {
3220 return false;
3221 }
3222 #ifndef PRODUCT
3223 assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3224 assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3225 ciSignature* sig = callee()->signature();
3226 assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3227 #endif
3228 null_check_receiver(); // null-check, then ignore
3229 Node *addr = argument(1);
3230 addr = new CastX2PNode(addr);
3231 addr = _gvn.transform(addr);
3232 Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3233 flush = _gvn.transform(flush);
3234 set_memory(flush, TypeRawPtr::BOTTOM);
3235 return true;
3236 }
3237
3238 //----------------------------inline_unsafe_writeback0-------------------------
3239 // public native void Unsafe.writeback0(long address)
3240 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3241 if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3242 return false;
3243 }
3244 if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3245 return false;
3246 }
3247 #ifndef PRODUCT
3248 assert(Matcher::has_match_rule(Op_CacheWB),
3249 (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3250 : "found match rule for CacheWBPostSync but not CacheWB"));
3251
3252 #endif
3253 null_check_receiver(); // null-check, then ignore
3254 Node *sync;
3255 if (is_pre) {
3256 sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3257 } else {
3258 sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3259 }
3260 sync = _gvn.transform(sync);
3261 set_memory(sync, TypeRawPtr::BOTTOM);
3262 return true;
3263 }
3264
3265 //----------------------------inline_unsafe_allocate---------------------------
3266 // public native Object Unsafe.allocateInstance(Class<?> cls);
3267 bool LibraryCallKit::inline_unsafe_allocate() {
3268
3269 #if INCLUDE_JVMTI
3270 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3271 return false;
3272 }
3273 #endif //INCLUDE_JVMTI
3274
3275 if (callee()->is_static()) return false; // caller must have the capability!
3276
3277 null_check_receiver(); // null-check, then ignore
3278 Node* cls = null_check(argument(1));
3279 if (stopped()) return true;
3280
3281 Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3282 kls = null_check(kls);
3283 if (stopped()) return true; // argument was like int.class
3284
3285 #if INCLUDE_JVMTI
3286 // Don't try to access new allocated obj in the intrinsic.
3287 // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3288 // Deoptimize and allocate in interpreter instead.
3289 Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3290 Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3291 Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3292 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3293 {
3294 BuildCutout unless(this, tst, PROB_MAX);
3295 uncommon_trap(Deoptimization::Reason_intrinsic,
3296 Deoptimization::Action_make_not_entrant);
3297 }
3298 if (stopped()) {
3299 return true;
3300 }
3301 #endif //INCLUDE_JVMTI
3302
3303 Node* test = nullptr;
3304 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3305 // Note: The argument might still be an illegal value like
3306 // Serializable.class or Object[].class. The runtime will handle it.
3307 // But we must make an explicit check for initialization.
3308 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3309 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3310 // can generate code to load it as unsigned byte.
3311 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3312 Node* bits = intcon(InstanceKlass::fully_initialized);
3313 test = _gvn.transform(new SubINode(inst, bits));
3314 // The 'test' is non-zero if we need to take a slow path.
3315 }
3316 Node* obj = new_instance(kls, test);
3317 set_result(obj);
3318 return true;
3319 }
3320
3321 //------------------------inline_native_time_funcs--------------
3322 // inline code for System.currentTimeMillis() and System.nanoTime()
3323 // these have the same type and signature
3324 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3325 const TypeFunc* tf = OptoRuntime::void_long_Type();
3326 const TypePtr* no_memory_effects = nullptr;
3327 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3328 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3329 #ifdef ASSERT
3330 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3331 assert(value_top == top(), "second value must be top");
3332 #endif
3333 set_result(value);
3334 return true;
3335 }
3336
3337 //--------------------inline_native_vthread_start_transition--------------------
3338 // inline void startTransition(boolean is_mount);
3339 // inline void startFinalTransition();
3340 // Pseudocode of implementation:
3341 //
3342 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3343 // carrier->set_is_in_vthread_transition(true);
3344 // OrderAccess::storeload();
3345 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3346 // + global_vthread_transition_disable_count();
3347 // if (disable_requests > 0) {
3348 // slow path: runtime call
3349 // }
3350 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3351 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3352 IdealKit ideal(this);
3353
3354 Node* thread = ideal.thread();
3355 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3356 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3357 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3358 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3359 insert_mem_bar(Op_MemBarStoreLoad);
3360 ideal.sync_kit(this);
3361
3362 Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3363 Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3364 Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3365 const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3366 Node* vt_disable = ideal.load(ideal.ctrl(), vt_disable_addr, TypeInt::INT, T_INT, C->get_alias_index(vt_disable_addr_t), true /*require_atomic_access*/);
3367 Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3368
3369 ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3370 sync_kit(ideal);
3371 Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3372 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3373 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3374 ideal.sync_kit(this);
3375 }
3376 ideal.end_if();
3377
3378 final_sync(ideal);
3379 return true;
3380 }
3381
3382 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3383 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3384 IdealKit ideal(this);
3385
3386 Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3387 Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3388
3389 ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3390 sync_kit(ideal);
3391 Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3392 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3393 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3394 ideal.sync_kit(this);
3395 } ideal.else_(); {
3396 Node* thread = ideal.thread();
3397 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3398 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3399
3400 sync_kit(ideal);
3401 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3402 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3403 ideal.sync_kit(this);
3404 } ideal.end_if();
3405
3406 final_sync(ideal);
3407 return true;
3408 }
3409
3410 #if INCLUDE_JVMTI
3411
3412 // Always update the is_disable_suspend bit.
3413 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3414 if (!DoJVMTIVirtualThreadTransitions) {
3415 return true;
3416 }
3417 IdealKit ideal(this);
3418
3419 {
3420 // unconditionally update the is_disable_suspend bit in current JavaThread
3421 Node* thread = ideal.thread();
3422 Node* arg = argument(0); // argument for notification
3423 Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3424 const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3425
3426 sync_kit(ideal);
3427 access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3428 ideal.sync_kit(this);
3429 }
3430 final_sync(ideal);
3431
3432 return true;
3433 }
3434
3435 #endif // INCLUDE_JVMTI
3436
3437 #ifdef JFR_HAVE_INTRINSICS
3438
3439 /**
3440 * if oop->klass != null
3441 * // normal class
3442 * epoch = _epoch_state ? 2 : 1
3443 * if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3444 * ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3445 * }
3446 * id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3447 * else
3448 * // primitive class
3449 * if oop->array_klass != null
3450 * id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3451 * else
3452 * id = LAST_TYPE_ID + 1 // void class path
3453 * if (!signaled)
3454 * signaled = true
3455 */
3456 bool LibraryCallKit::inline_native_classID() {
3457 Node* cls = argument(0);
3458
3459 IdealKit ideal(this);
3460 #define __ ideal.
3461 IdealVariable result(ideal); __ declarations_done();
3462 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3463 basic_plus_adr(cls, java_lang_Class::klass_offset()),
3464 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3465
3466
3467 __ if_then(kls, BoolTest::ne, null()); {
3468 Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3469 Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3470
3471 Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3472 Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3473 epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3474 Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3475 mask = _gvn.transform(new OrLNode(mask, epoch));
3476 Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3477
3478 float unlikely = PROB_UNLIKELY(0.999);
3479 __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3480 sync_kit(ideal);
3481 make_runtime_call(RC_LEAF,
3482 OptoRuntime::class_id_load_barrier_Type(),
3483 CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3484 "class id load barrier",
3485 TypePtr::BOTTOM,
3486 kls);
3487 ideal.sync_kit(this);
3488 } __ end_if();
3489
3490 ideal.set(result, _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3491 } __ else_(); {
3492 Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3493 basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3494 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3495 __ if_then(array_kls, BoolTest::ne, null()); {
3496 Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3497 Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3498 Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3499 ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3500 } __ else_(); {
3501 // void class case
3502 ideal.set(result, longcon(LAST_TYPE_ID + 1));
3503 } __ end_if();
3504
3505 Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3506 Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3507 __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3508 ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3509 } __ end_if();
3510 } __ end_if();
3511
3512 final_sync(ideal);
3513 set_result(ideal.value(result));
3514 #undef __
3515 return true;
3516 }
3517
3518 //------------------------inline_native_jvm_commit------------------
3519 bool LibraryCallKit::inline_native_jvm_commit() {
3520 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3521
3522 // Save input memory and i_o state.
3523 Node* input_memory_state = reset_memory();
3524 set_all_memory(input_memory_state);
3525 Node* input_io_state = i_o();
3526
3527 // TLS.
3528 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3529 // Jfr java buffer.
3530 Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3531 Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3532 Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3533
3534 // Load the current value of the notified field in the JfrThreadLocal.
3535 Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3536 Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3537
3538 // Test for notification.
3539 Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3540 Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3541 IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3542
3543 // True branch, is notified.
3544 Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3545 set_control(is_notified);
3546
3547 // Reset notified state.
3548 store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3549 Node* notified_reset_memory = reset_memory();
3550
3551 // Iff notified, the return address of the commit method is the current position of the backing java buffer. This is used to reset the event writer.
3552 Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3553 // Convert the machine-word to a long.
3554 Node* current_pos = ConvX2L(current_pos_X);
3555
3556 // False branch, not notified.
3557 Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3558 set_control(not_notified);
3559 set_all_memory(input_memory_state);
3560
3561 // Arg is the next position as a long.
3562 Node* arg = argument(0);
3563 // Convert long to machine-word.
3564 Node* next_pos_X = ConvL2X(arg);
3565
3566 // Store the next_position to the underlying jfr java buffer.
3567 store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3568
3569 Node* commit_memory = reset_memory();
3570 set_all_memory(commit_memory);
3571
3572 // Now load the flags from off the java buffer and decide if the buffer is a lease. If so, it needs to be returned post-commit.
3573 Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3574 Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3575 Node* lease_constant = _gvn.intcon(4);
3576
3577 // And flags with lease constant.
3578 Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3579
3580 // Branch on lease to conditionalize returning the leased java buffer.
3581 Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3582 Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3583 IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3584
3585 // False branch, not a lease.
3586 Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3587
3588 // True branch, is lease.
3589 Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3590 set_control(is_lease);
3591
3592 // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3593 Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3594 OptoRuntime::void_void_Type(),
3595 SharedRuntime::jfr_return_lease(),
3596 "return_lease", TypePtr::BOTTOM);
3597 Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3598
3599 RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3600 record_for_igvn(lease_compare_rgn);
3601 PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3602 record_for_igvn(lease_compare_mem);
3603 PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3604 record_for_igvn(lease_compare_io);
3605 PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3606 record_for_igvn(lease_result_value);
3607
3608 // Update control and phi nodes.
3609 lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3610 lease_compare_rgn->init_req(_false_path, not_lease);
3611
3612 lease_compare_mem->init_req(_true_path, reset_memory());
3613 lease_compare_mem->init_req(_false_path, commit_memory);
3614
3615 lease_compare_io->init_req(_true_path, i_o());
3616 lease_compare_io->init_req(_false_path, input_io_state);
3617
3618 lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3619 lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3620
3621 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3622 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3623 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3624 PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3625
3626 // Update control and phi nodes.
3627 result_rgn->init_req(_true_path, is_notified);
3628 result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3629
3630 result_mem->init_req(_true_path, notified_reset_memory);
3631 result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3632
3633 result_io->init_req(_true_path, input_io_state);
3634 result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3635
3636 result_value->init_req(_true_path, current_pos);
3637 result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3638
3639 // Set output state.
3640 set_control(_gvn.transform(result_rgn));
3641 set_all_memory(_gvn.transform(result_mem));
3642 set_i_o(_gvn.transform(result_io));
3643 set_result(result_rgn, result_value);
3644 return true;
3645 }
3646
3647 /*
3648 * The intrinsic is a model of this pseudo-code:
3649 *
3650 * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3651 * jobject h_event_writer = tl->java_event_writer();
3652 * if (h_event_writer == nullptr) {
3653 * return nullptr;
3654 * }
3655 * oop threadObj = Thread::threadObj();
3656 * oop vthread = java_lang_Thread::vthread(threadObj);
3657 * traceid tid;
3658 * bool pinVirtualThread;
3659 * bool excluded;
3660 * if (vthread != threadObj) { // i.e. current thread is virtual
3661 * tid = java_lang_Thread::tid(vthread);
3662 * u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3663 * pinVirtualThread = VMContinuations;
3664 * excluded = vthread_epoch_raw & excluded_mask;
3665 * if (!excluded) {
3666 * traceid current_epoch = JfrTraceIdEpoch::current_generation();
3667 * u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3668 * if (vthread_epoch != current_epoch) {
3669 * write_checkpoint();
3670 * }
3671 * }
3672 * } else {
3673 * tid = java_lang_Thread::tid(threadObj);
3674 * u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3675 * pinVirtualThread = false;
3676 * excluded = thread_epoch_raw & excluded_mask;
3677 * }
3678 * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3679 * traceid tid_in_event_writer = getField(event_writer, "threadID");
3680 * if (tid_in_event_writer != tid) {
3681 * setField(event_writer, "pinVirtualThread", pinVirtualThread);
3682 * setField(event_writer, "excluded", excluded);
3683 * setField(event_writer, "threadID", tid);
3684 * }
3685 * return event_writer
3686 */
3687 bool LibraryCallKit::inline_native_getEventWriter() {
3688 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3689
3690 // Save input memory and i_o state.
3691 Node* input_memory_state = reset_memory();
3692 set_all_memory(input_memory_state);
3693 Node* input_io_state = i_o();
3694
3695 // The most significant bit of the u2 is used to denote thread exclusion
3696 Node* excluded_shift = _gvn.intcon(15);
3697 Node* excluded_mask = _gvn.intcon(1 << 15);
3698 // The epoch generation is the range [1-32767]
3699 Node* epoch_mask = _gvn.intcon(32767);
3700
3701 // TLS
3702 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3703
3704 // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3705 Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3706
3707 // Load the eventwriter jobject handle.
3708 Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3709
3710 // Null check the jobject handle.
3711 Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3712 Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3713 IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3714
3715 // False path, jobj is null.
3716 Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3717
3718 // True path, jobj is not null.
3719 Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3720
3721 set_control(jobj_is_not_null);
3722
3723 // Load the threadObj for the CarrierThread.
3724 Node* threadObj = generate_current_thread(tls_ptr);
3725
3726 // Load the vthread.
3727 Node* vthread = generate_virtual_thread(tls_ptr);
3728
3729 // If vthread != threadObj, this is a virtual thread.
3730 Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3731 Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3732 IfNode* iff_vthread_not_equal_threadObj =
3733 create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3734
3735 // False branch, fallback to threadObj.
3736 Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3737 set_control(vthread_equal_threadObj);
3738
3739 // Load the tid field from the vthread object.
3740 Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3741
3742 // Load the raw epoch value from the threadObj.
3743 Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3744 Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3745 _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3746 TypeInt::CHAR, T_CHAR,
3747 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3748
3749 // Mask off the excluded information from the epoch.
3750 Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3751
3752 // True branch, this is a virtual thread.
3753 Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3754 set_control(vthread_not_equal_threadObj);
3755
3756 // Load the tid field from the vthread object.
3757 Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3758
3759 // Continuation support determines if a virtual thread should be pinned.
3760 Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3761 Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3762
3763 // Load the raw epoch value from the vthread.
3764 Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3765 Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3766 TypeInt::CHAR, T_CHAR,
3767 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3768
3769 // Mask off the excluded information from the epoch.
3770 Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3771
3772 // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3773 Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3774 Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3775 IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3776
3777 // False branch, vthread is excluded, no need to write epoch info.
3778 Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3779
3780 // True branch, vthread is included, update epoch info.
3781 Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3782 set_control(included);
3783
3784 // Get epoch value.
3785 Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3786
3787 // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3788 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3789 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3790
3791 // Compare the epoch in the vthread to the current epoch generation.
3792 Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3793 Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3794 IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3795
3796 // False path, epoch is equal, checkpoint information is valid.
3797 Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3798
3799 // True path, epoch is not equal, write a checkpoint for the vthread.
3800 Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3801
3802 set_control(epoch_is_not_equal);
3803
3804 // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3805 // The call also updates the native thread local thread id and the vthread with the current epoch.
3806 Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3807 OptoRuntime::jfr_write_checkpoint_Type(),
3808 SharedRuntime::jfr_write_checkpoint(),
3809 "write_checkpoint", TypePtr::BOTTOM);
3810 Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3811
3812 // vthread epoch != current epoch
3813 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3814 record_for_igvn(epoch_compare_rgn);
3815 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3816 record_for_igvn(epoch_compare_mem);
3817 PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3818 record_for_igvn(epoch_compare_io);
3819
3820 // Update control and phi nodes.
3821 epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3822 epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3823 epoch_compare_mem->init_req(_true_path, reset_memory());
3824 epoch_compare_mem->init_req(_false_path, input_memory_state);
3825 epoch_compare_io->init_req(_true_path, i_o());
3826 epoch_compare_io->init_req(_false_path, input_io_state);
3827
3828 // excluded != true
3829 RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3830 record_for_igvn(exclude_compare_rgn);
3831 PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3832 record_for_igvn(exclude_compare_mem);
3833 PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3834 record_for_igvn(exclude_compare_io);
3835
3836 // Update control and phi nodes.
3837 exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3838 exclude_compare_rgn->init_req(_false_path, excluded);
3839 exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3840 exclude_compare_mem->init_req(_false_path, input_memory_state);
3841 exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3842 exclude_compare_io->init_req(_false_path, input_io_state);
3843
3844 // vthread != threadObj
3845 RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3846 record_for_igvn(vthread_compare_rgn);
3847 PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3848 PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3849 record_for_igvn(vthread_compare_io);
3850 PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3851 record_for_igvn(tid);
3852 PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3853 record_for_igvn(exclusion);
3854 PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3855 record_for_igvn(pinVirtualThread);
3856
3857 // Update control and phi nodes.
3858 vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3859 vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3860 vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3861 vthread_compare_mem->init_req(_false_path, input_memory_state);
3862 vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3863 vthread_compare_io->init_req(_false_path, input_io_state);
3864 tid->init_req(_true_path, vthread_tid);
3865 tid->init_req(_false_path, thread_obj_tid);
3866 exclusion->init_req(_true_path, vthread_is_excluded);
3867 exclusion->init_req(_false_path, threadObj_is_excluded);
3868 pinVirtualThread->init_req(_true_path, continuation_support);
3869 pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3870
3871 // Update branch state.
3872 set_control(_gvn.transform(vthread_compare_rgn));
3873 set_all_memory(_gvn.transform(vthread_compare_mem));
3874 set_i_o(_gvn.transform(vthread_compare_io));
3875
3876 // Load the event writer oop by dereferencing the jobject handle.
3877 ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3878 assert(klass_EventWriter->is_loaded(), "invariant");
3879 ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3880 const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3881 const TypeOopPtr* const xtype = aklass->as_instance_type();
3882 Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3883 Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3884
3885 // Load the current thread id from the event writer object.
3886 Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3887 // Get the field offset to, conditionally, store an updated tid value later.
3888 Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3889 // Get the field offset to, conditionally, store an updated exclusion value later.
3890 Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3891 // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3892 Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3893
3894 RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3895 record_for_igvn(event_writer_tid_compare_rgn);
3896 PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3897 record_for_igvn(event_writer_tid_compare_mem);
3898 PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3899 record_for_igvn(event_writer_tid_compare_io);
3900
3901 // Compare the current tid from the thread object to what is currently stored in the event writer object.
3902 Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3903 Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3904 IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3905
3906 // False path, tids are the same.
3907 Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3908
3909 // True path, tid is not equal, need to update the tid in the event writer.
3910 Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3911 record_for_igvn(tid_is_not_equal);
3912
3913 // Store the pin state to the event writer.
3914 store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3915
3916 // Store the exclusion state to the event writer.
3917 Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3918 store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3919
3920 // Store the tid to the event writer.
3921 store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3922
3923 // Update control and phi nodes.
3924 event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3925 event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3926 event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3927 event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3928 event_writer_tid_compare_io->init_req(_true_path, i_o());
3929 event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3930
3931 // Result of top level CFG, Memory, IO and Value.
3932 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3933 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3934 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3935 PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3936
3937 // Result control.
3938 result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3939 result_rgn->init_req(_false_path, jobj_is_null);
3940
3941 // Result memory.
3942 result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3943 result_mem->init_req(_false_path, input_memory_state);
3944
3945 // Result IO.
3946 result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3947 result_io->init_req(_false_path, input_io_state);
3948
3949 // Result value.
3950 result_value->init_req(_true_path, event_writer); // return event writer oop
3951 result_value->init_req(_false_path, null()); // return null
3952
3953 // Set output state.
3954 set_control(_gvn.transform(result_rgn));
3955 set_all_memory(_gvn.transform(result_mem));
3956 set_i_o(_gvn.transform(result_io));
3957 set_result(result_rgn, result_value);
3958 return true;
3959 }
3960
3961 /*
3962 * The intrinsic is a model of this pseudo-code:
3963 *
3964 * JfrThreadLocal* const tl = thread->jfr_thread_local();
3965 * if (carrierThread != thread) { // is virtual thread
3966 * const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3967 * bool excluded = vthread_epoch_raw & excluded_mask;
3968 * AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3969 * AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3970 * if (!excluded) {
3971 * const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3972 * AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3973 * }
3974 * AtomicAccess::release_store(&tl->_vthread, true);
3975 * return;
3976 * }
3977 * AtomicAccess::release_store(&tl->_vthread, false);
3978 */
3979 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3980 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3981
3982 Node* input_memory_state = reset_memory();
3983 set_all_memory(input_memory_state);
3984
3985 // The most significant bit of the u2 is used to denote thread exclusion
3986 Node* excluded_mask = _gvn.intcon(1 << 15);
3987 // The epoch generation is the range [1-32767]
3988 Node* epoch_mask = _gvn.intcon(32767);
3989
3990 Node* const carrierThread = generate_current_thread(jt);
3991 // If thread != carrierThread, this is a virtual thread.
3992 Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3993 Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3994 IfNode* iff_thread_not_equal_carrierThread =
3995 create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3996
3997 Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3998
3999 // False branch, is carrierThread.
4000 Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
4001 // Store release
4002 Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
4003
4004 set_all_memory(input_memory_state);
4005
4006 // True branch, is virtual thread.
4007 Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4008 set_control(thread_not_equal_carrierThread);
4009
4010 // Load the raw epoch value from the vthread.
4011 Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4012 Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4013 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4014
4015 // Mask off the excluded information from the epoch.
4016 Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4017
4018 // Load the tid field from the thread.
4019 Node* tid = load_field_from_object(thread, "tid", "J");
4020
4021 // Store the vthread tid to the jfr thread local.
4022 Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4023 Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4024
4025 // Branch is_excluded to conditionalize updating the epoch .
4026 Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4027 Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4028 IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4029
4030 // True branch, vthread is excluded, no need to write epoch info.
4031 Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4032 set_control(excluded);
4033 Node* vthread_is_excluded = _gvn.intcon(1);
4034
4035 // False branch, vthread is included, update epoch info.
4036 Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4037 set_control(included);
4038 Node* vthread_is_included = _gvn.intcon(0);
4039
4040 // Get epoch value.
4041 Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4042
4043 // Store the vthread epoch to the jfr thread local.
4044 Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4045 Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4046
4047 RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4048 record_for_igvn(excluded_rgn);
4049 PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4050 record_for_igvn(excluded_mem);
4051 PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4052 record_for_igvn(exclusion);
4053
4054 // Merge the excluded control and memory.
4055 excluded_rgn->init_req(_true_path, excluded);
4056 excluded_rgn->init_req(_false_path, included);
4057 excluded_mem->init_req(_true_path, tid_memory);
4058 excluded_mem->init_req(_false_path, included_memory);
4059 exclusion->init_req(_true_path, vthread_is_excluded);
4060 exclusion->init_req(_false_path, vthread_is_included);
4061
4062 // Set intermediate state.
4063 set_control(_gvn.transform(excluded_rgn));
4064 set_all_memory(excluded_mem);
4065
4066 // Store the vthread exclusion state to the jfr thread local.
4067 Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4068 store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4069
4070 // Store release
4071 Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4072
4073 RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4074 record_for_igvn(thread_compare_rgn);
4075 PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4076 record_for_igvn(thread_compare_mem);
4077 PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4078 record_for_igvn(vthread);
4079
4080 // Merge the thread_compare control and memory.
4081 thread_compare_rgn->init_req(_true_path, control());
4082 thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4083 thread_compare_mem->init_req(_true_path, vthread_true_memory);
4084 thread_compare_mem->init_req(_false_path, vthread_false_memory);
4085
4086 // Set output state.
4087 set_control(_gvn.transform(thread_compare_rgn));
4088 set_all_memory(_gvn.transform(thread_compare_mem));
4089 }
4090
4091 //------------------------inline_native_try_update_epoch------------------
4092 //
4093 // The generated code is a function of the argument type.
4094 //
4095 bool LibraryCallKit::inline_native_try_update_epoch() {
4096 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4097
4098 // Save input memory.
4099 Node* input_memory_state = reset_memory();
4100 set_all_memory(input_memory_state);
4101
4102 // Argument is an oop whose class has an injected instance field,
4103 // called 'jfr_epoch' of type T_INT, used for holding a jfr epoch value.
4104 Node* oop = argument(0);
4105 const TypeInstPtr* tinst = _gvn.type(oop)->isa_instptr();
4106 assert(tinst != nullptr, "oop is null");
4107 assert(tinst->is_loaded(), "klass is not loaded");
4108 ciInstanceKlass* const ik = tinst->instance_klass();
4109
4110 ciField* const field = ik->get_injected_instance_field_by_name(ciSymbol::make("jfr_epoch"),
4111 ciSymbol::make("I"));
4112
4113 assert(field != nullptr, "field 'jfr_epoch' of type I not injected in klass %s", ik->name()->as_utf8());
4114
4115 const int jfr_epoch_field_offset = field->offset_in_bytes();
4116 Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset);
4117 const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr();
4118 const int alias_idx = C->get_alias_index(adr_type);
4119 BasicType bt = field->layout_type();
4120 const Type * oop_epoch_field_type = Type::get_const_basic_type(bt);
4121
4122 // Load the epoch value from the oop.
4123 Node* oop_epoch = access_load_at(oop,
4124 oop_epoch_field_offset,
4125 adr_type, oop_epoch_field_type,
4126 bt, IN_HEAP | MO_UNORDERED);
4127
4128 // Load the current JFR epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
4129 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
4130 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4131
4132 // Compare the epoch in the oop against the current JFR epoch generation.
4133 Node* const epochs_cmp = _gvn.transform(new CmpINode(current_epoch_generation, oop_epoch));
4134 Node* epochs_equal_test = _gvn.transform(new BoolNode(epochs_cmp, BoolTest::eq));
4135 IfNode* iff_epochs_equal = create_and_map_if(control(), epochs_equal_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
4136
4137 // True path.
4138 Node* epochs_are_equal = _gvn.transform(new IfTrueNode(iff_epochs_equal));
4139
4140 // False path.
4141 Node* epochs_are_not_equal = _gvn.transform(new IfFalseNode(iff_epochs_equal));
4142
4143 set_control(_gvn.transform(epochs_are_not_equal));
4144
4145 // Attempt to cas the current JFR epoch generation into the oop epoch field.
4146 DecoratorSet decorators = IN_HEAP;
4147 decorators |= mo_decorator_for_access_kind(Volatile);
4148
4149 Node* result = access_atomic_cmpxchg_val_at(oop,
4150 oop_epoch_field_offset,
4151 adr_type, alias_idx,
4152 oop_epoch, // expected value
4153 current_epoch_generation, // new value
4154 oop_epoch_field_type,
4155 bt,
4156 decorators);
4157
4158 // Compare the result of the cas operation to the expected value.
4159 Node* const cas_cmp_to_expected_value = _gvn.transform(new CmpINode(result, oop_epoch));
4160 Node* cas_operation_test = _gvn.transform(new BoolNode(cas_cmp_to_expected_value, BoolTest::eq));
4161 IfNode* iff_cas_success = create_and_map_if(control(), cas_operation_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
4162
4163 // True path.
4164 Node* cas_success = _gvn.transform(new IfTrueNode(iff_cas_success));
4165
4166 // False path.
4167 Node* cas_failure = _gvn.transform(new IfFalseNode(iff_cas_success));
4168
4169 // Cas result region and phi nodes.
4170 RegionNode* cas_operation_rgn = new RegionNode(PATH_LIMIT);
4171 record_for_igvn(cas_operation_rgn);
4172 PhiNode* cas_operation_mem = new PhiNode(cas_operation_rgn, Type::MEMORY, TypePtr::BOTTOM);
4173 record_for_igvn(cas_operation_mem);
4174 PhiNode* cas_result = new PhiNode(cas_operation_rgn, TypeInt::BOOL);
4175 record_for_igvn(cas_result);
4176
4177 cas_operation_rgn->init_req(_true_path, _gvn.transform(cas_success));
4178 cas_operation_rgn->init_req(_false_path, _gvn.transform(cas_failure));
4179 cas_operation_mem->init_req(_true_path, reset_memory());
4180 cas_operation_mem->init_req(_false_path, input_memory_state);
4181 cas_result->init_req(_true_path, _gvn.intcon(1));
4182 cas_result->init_req(_false_path, _gvn.intcon(0));
4183
4184 // Epoch compare region and phi nodes.
4185 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
4186 record_for_igvn(epoch_compare_rgn);
4187 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4188 record_for_igvn(epoch_compare_mem);
4189 PhiNode* result_value = new PhiNode(epoch_compare_rgn, TypeInt::BOOL);
4190 record_for_igvn(result_value);
4191
4192 epoch_compare_rgn->init_req(_true_path, _gvn.transform(epochs_are_equal));
4193 epoch_compare_rgn->init_req(_false_path, _gvn.transform(cas_operation_rgn));
4194 epoch_compare_mem->init_req(_true_path, _gvn.transform(input_memory_state));
4195 epoch_compare_mem->init_req(_false_path, _gvn.transform(cas_operation_mem));
4196 result_value->init_req(_true_path, _gvn.intcon(0));
4197 result_value->init_req(_false_path, _gvn.transform(cas_result));
4198
4199 // Set output state.
4200 set_result(epoch_compare_rgn, result_value);
4201 set_all_memory(_gvn.transform(epoch_compare_mem));
4202
4203 return true;
4204 }
4205
4206 #endif // JFR_HAVE_INTRINSICS
4207
4208 //------------------------inline_native_currentCarrierThread------------------
4209 bool LibraryCallKit::inline_native_currentCarrierThread() {
4210 Node* junk = nullptr;
4211 set_result(generate_current_thread(junk));
4212 return true;
4213 }
4214
4215 //------------------------inline_native_currentThread------------------
4216 bool LibraryCallKit::inline_native_currentThread() {
4217 Node* junk = nullptr;
4218 set_result(generate_virtual_thread(junk));
4219 return true;
4220 }
4221
4222 //------------------------inline_native_setVthread------------------
4223 bool LibraryCallKit::inline_native_setCurrentThread() {
4224 assert(C->method()->changes_current_thread(),
4225 "method changes current Thread but is not annotated ChangesCurrentThread");
4226 Node* arr = argument(1);
4227 Node* thread = _gvn.transform(new ThreadLocalNode());
4228 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4229 Node* thread_obj_handle
4230 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4231 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4232 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4233
4234 // Change the _monitor_owner_id of the JavaThread
4235 Node* tid = load_field_from_object(arr, "tid", "J");
4236 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4237 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4238
4239 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4240 return true;
4241 }
4242
4243 const Type* LibraryCallKit::scopedValueCache_type() {
4244 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4245 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4246 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4247
4248 // Because we create the scopedValue cache lazily we have to make the
4249 // type of the result BotPTR.
4250 bool xk = etype->klass_is_exact();
4251 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4252 return objects_type;
4253 }
4254
4255 Node* LibraryCallKit::scopedValueCache_helper() {
4256 Node* thread = _gvn.transform(new ThreadLocalNode());
4257 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4258 // We cannot use immutable_memory() because we might flip onto a
4259 // different carrier thread, at which point we'll need to use that
4260 // carrier thread's cache.
4261 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4262 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4263 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4264 }
4265
4266 //------------------------inline_native_scopedValueCache------------------
4267 bool LibraryCallKit::inline_native_scopedValueCache() {
4268 Node* cache_obj_handle = scopedValueCache_helper();
4269 const Type* objects_type = scopedValueCache_type();
4270 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4271
4272 return true;
4273 }
4274
4275 //------------------------inline_native_setScopedValueCache------------------
4276 bool LibraryCallKit::inline_native_setScopedValueCache() {
4277 Node* arr = argument(0);
4278 Node* cache_obj_handle = scopedValueCache_helper();
4279 const Type* objects_type = scopedValueCache_type();
4280
4281 const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4282 access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4283
4284 return true;
4285 }
4286
4287 //------------------------inline_native_Continuation_pin and unpin-----------
4288
4289 // Shared implementation routine for both pin and unpin.
4290 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4291 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4292
4293 // Save input memory.
4294 Node* input_memory_state = reset_memory();
4295 set_all_memory(input_memory_state);
4296
4297 // TLS
4298 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4299 Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4300 Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4301
4302 // Null check the last continuation object.
4303 Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4304 Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4305 IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4306
4307 // False path, last continuation is null.
4308 Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4309
4310 // True path, last continuation is not null.
4311 Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4312
4313 set_control(continuation_is_not_null);
4314
4315 // Load the pin count from the last continuation.
4316 Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4317 Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4318
4319 // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4320 Node* pin_count_rhs;
4321 if (unpin) {
4322 pin_count_rhs = _gvn.intcon(0);
4323 } else {
4324 pin_count_rhs = _gvn.intcon(UINT32_MAX);
4325 }
4326 Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4327 Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4328 IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4329
4330 // True branch, pin count over/underflow.
4331 Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4332 {
4333 // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4334 // which will throw IllegalStateException for pin count over/underflow.
4335 // No memory changed so far - we can use memory create by reset_memory()
4336 // at the beginning of this intrinsic. No need to call reset_memory() again.
4337 PreserveJVMState pjvms(this);
4338 set_control(pin_count_over_underflow);
4339 uncommon_trap(Deoptimization::Reason_intrinsic,
4340 Deoptimization::Action_none);
4341 assert(stopped(), "invariant");
4342 }
4343
4344 // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4345 Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4346 set_control(valid_pin_count);
4347
4348 Node* next_pin_count;
4349 if (unpin) {
4350 next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4351 } else {
4352 next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4353 }
4354
4355 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4356
4357 // Result of top level CFG and Memory.
4358 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4359 record_for_igvn(result_rgn);
4360 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4361 record_for_igvn(result_mem);
4362
4363 result_rgn->init_req(_true_path, valid_pin_count);
4364 result_rgn->init_req(_false_path, continuation_is_null);
4365 result_mem->init_req(_true_path, reset_memory());
4366 result_mem->init_req(_false_path, input_memory_state);
4367
4368 // Set output state.
4369 set_control(_gvn.transform(result_rgn));
4370 set_all_memory(_gvn.transform(result_mem));
4371
4372 return true;
4373 }
4374
4375 //---------------------------load_mirror_from_klass----------------------------
4376 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4377 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4378 Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4379 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4380 // mirror = ((OopHandle)mirror)->resolve();
4381 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4382 }
4383
4384 //-----------------------load_klass_from_mirror_common-------------------------
4385 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4386 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4387 // and branch to the given path on the region.
4388 // If never_see_null, take an uncommon trap on null, so we can optimistically
4389 // compile for the non-null case.
4390 // If the region is null, force never_see_null = true.
4391 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4392 bool never_see_null,
4393 RegionNode* region,
4394 int null_path,
4395 int offset) {
4396 if (region == nullptr) never_see_null = true;
4397 Node* p = basic_plus_adr(mirror, offset);
4398 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4399 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4400 Node* null_ctl = top();
4401 kls = null_check_oop(kls, &null_ctl, never_see_null);
4402 if (region != nullptr) {
4403 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4404 region->init_req(null_path, null_ctl);
4405 } else {
4406 assert(null_ctl == top(), "no loose ends");
4407 }
4408 return kls;
4409 }
4410
4411 //--------------------(inline_native_Class_query helpers)---------------------
4412 // Use this for JVM_ACC_INTERFACE.
4413 // Fall through if (mods & mask) == bits, take the guard otherwise.
4414 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4415 ByteSize offset, const Type* type, BasicType bt) {
4416 // Branch around if the given klass has the given modifier bit set.
4417 // Like generate_guard, adds a new path onto the region.
4418 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4419 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4420 Node* mask = intcon(modifier_mask);
4421 Node* bits = intcon(modifier_bits);
4422 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4423 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4424 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4425 return generate_fair_guard(bol, region);
4426 }
4427
4428 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4429 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4430 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4431 }
4432
4433 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4434 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4435 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4436 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4437 }
4438
4439 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4440 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4441 }
4442
4443 //-------------------------inline_native_Class_query-------------------
4444 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4445 const Type* return_type = TypeInt::BOOL;
4446 Node* prim_return_value = top(); // what happens if it's a primitive class?
4447 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4448 bool expect_prim = false; // most of these guys expect to work on refs
4449
4450 enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4451
4452 Node* mirror = argument(0);
4453 Node* obj = top();
4454
4455 switch (id) {
4456 case vmIntrinsics::_isInstance:
4457 // nothing is an instance of a primitive type
4458 prim_return_value = intcon(0);
4459 obj = argument(1);
4460 break;
4461 case vmIntrinsics::_isHidden:
4462 prim_return_value = intcon(0);
4463 break;
4464 case vmIntrinsics::_getSuperclass:
4465 prim_return_value = null();
4466 return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4467 break;
4468 default:
4469 fatal_unexpected_iid(id);
4470 break;
4471 }
4472
4473 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4474 if (mirror_con == nullptr) return false; // cannot happen?
4475
4476 #ifndef PRODUCT
4477 if (C->print_intrinsics() || C->print_inlining()) {
4478 ciType* k = mirror_con->java_mirror_type();
4479 if (k) {
4480 tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4481 k->print_name();
4482 tty->cr();
4483 }
4484 }
4485 #endif
4486
4487 // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4488 RegionNode* region = new RegionNode(PATH_LIMIT);
4489 record_for_igvn(region);
4490 PhiNode* phi = new PhiNode(region, return_type);
4491
4492 // The mirror will never be null of Reflection.getClassAccessFlags, however
4493 // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4494 // if it is. See bug 4774291.
4495
4496 // For Reflection.getClassAccessFlags(), the null check occurs in
4497 // the wrong place; see inline_unsafe_access(), above, for a similar
4498 // situation.
4499 mirror = null_check(mirror);
4500 // If mirror or obj is dead, only null-path is taken.
4501 if (stopped()) return true;
4502
4503 if (expect_prim) never_see_null = false; // expect nulls (meaning prims)
4504
4505 // Now load the mirror's klass metaobject, and null-check it.
4506 // Side-effects region with the control path if the klass is null.
4507 Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4508 // If kls is null, we have a primitive mirror.
4509 phi->init_req(_prim_path, prim_return_value);
4510 if (stopped()) { set_result(region, phi); return true; }
4511 bool safe_for_replace = (region->in(_prim_path) == top());
4512
4513 Node* p; // handy temp
4514 Node* null_ctl;
4515
4516 // Now that we have the non-null klass, we can perform the real query.
4517 // For constant classes, the query will constant-fold in LoadNode::Value.
4518 Node* query_value = top();
4519 switch (id) {
4520 case vmIntrinsics::_isInstance:
4521 // nothing is an instance of a primitive type
4522 query_value = gen_instanceof(obj, kls, safe_for_replace);
4523 break;
4524
4525 case vmIntrinsics::_isHidden:
4526 // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4527 if (generate_hidden_class_guard(kls, region) != nullptr)
4528 // A guard was added. If the guard is taken, it was an hidden class.
4529 phi->add_req(intcon(1));
4530 // If we fall through, it's a plain class.
4531 query_value = intcon(0);
4532 break;
4533
4534
4535 case vmIntrinsics::_getSuperclass:
4536 // The rules here are somewhat unfortunate, but we can still do better
4537 // with random logic than with a JNI call.
4538 // Interfaces store null or Object as _super, but must report null.
4539 // Arrays store an intermediate super as _super, but must report Object.
4540 // Other types can report the actual _super.
4541 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4542 if (generate_array_guard(kls, region) != nullptr) {
4543 // A guard was added. If the guard is taken, it was an array.
4544 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4545 }
4546 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4547 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4548 if (generate_interface_guard(kls, region) != nullptr) {
4549 // A guard was added. If the guard is taken, it was an interface.
4550 phi->add_req(null());
4551 }
4552 // If we fall through, it's a plain class. Get its _super.
4553 if (!stopped()) {
4554 p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4555 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4556 null_ctl = top();
4557 kls = null_check_oop(kls, &null_ctl);
4558 if (null_ctl != top()) {
4559 // If the guard is taken, Object.superClass is null (both klass and mirror).
4560 region->add_req(null_ctl);
4561 phi ->add_req(null());
4562 }
4563 if (!stopped()) {
4564 query_value = load_mirror_from_klass(kls);
4565 }
4566 }
4567 break;
4568
4569 default:
4570 fatal_unexpected_iid(id);
4571 break;
4572 }
4573
4574 // Fall-through is the normal case of a query to a real class.
4575 phi->init_req(1, query_value);
4576 region->init_req(1, control());
4577
4578 C->set_has_split_ifs(true); // Has chance for split-if optimization
4579 set_result(region, phi);
4580 return true;
4581 }
4582
4583
4584 //-------------------------inline_Class_cast-------------------
4585 bool LibraryCallKit::inline_Class_cast() {
4586 Node* mirror = argument(0); // Class
4587 Node* obj = argument(1);
4588 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4589 if (mirror_con == nullptr) {
4590 return false; // dead path (mirror->is_top()).
4591 }
4592 if (obj == nullptr || obj->is_top()) {
4593 return false; // dead path
4594 }
4595 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4596
4597 // First, see if Class.cast() can be folded statically.
4598 // java_mirror_type() returns non-null for compile-time Class constants.
4599 ciType* tm = mirror_con->java_mirror_type();
4600 if (tm != nullptr && tm->is_klass() &&
4601 tp != nullptr) {
4602 if (!tp->is_loaded()) {
4603 // Don't use intrinsic when class is not loaded.
4604 return false;
4605 } else {
4606 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4607 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4608 if (static_res == Compile::SSC_always_true) {
4609 // isInstance() is true - fold the code.
4610 set_result(obj);
4611 return true;
4612 } else if (static_res == Compile::SSC_always_false) {
4613 // Don't use intrinsic, have to throw ClassCastException.
4614 // If the reference is null, the non-intrinsic bytecode will
4615 // be optimized appropriately.
4616 return false;
4617 }
4618 }
4619 }
4620
4621 // Bailout intrinsic and do normal inlining if exception path is frequent.
4622 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4623 return false;
4624 }
4625
4626 // Generate dynamic checks.
4627 // Class.cast() is java implementation of _checkcast bytecode.
4628 // Do checkcast (Parse::do_checkcast()) optimizations here.
4629
4630 mirror = null_check(mirror);
4631 // If mirror is dead, only null-path is taken.
4632 if (stopped()) {
4633 return true;
4634 }
4635
4636 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4637 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4638 RegionNode* region = new RegionNode(PATH_LIMIT);
4639 record_for_igvn(region);
4640
4641 // Now load the mirror's klass metaobject, and null-check it.
4642 // If kls is null, we have a primitive mirror and
4643 // nothing is an instance of a primitive type.
4644 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4645
4646 Node* res = top();
4647 Node* io = i_o();
4648 Node* mem = merged_memory();
4649 SafePointNode* new_cast_failure_map = nullptr;
4650
4651 if (!stopped()) {
4652
4653 Node* bad_type_ctrl = top();
4654 // Do checkcast optimizations.
4655 res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4656 region->init_req(_bad_type_path, bad_type_ctrl);
4657 }
4658 if (region->in(_prim_path) != top() ||
4659 region->in(_bad_type_path) != top() ||
4660 region->in(_npe_path) != top()) {
4661 // Let Interpreter throw ClassCastException.
4662 PreserveJVMState pjvms(this);
4663 if (new_cast_failure_map != nullptr) {
4664 // The current map on the success path could have been modified. Use the dedicated failure path map.
4665 set_map(new_cast_failure_map);
4666 }
4667 set_control(_gvn.transform(region));
4668 // Set IO and memory because gen_checkcast may override them when buffering inline types
4669 set_i_o(io);
4670 set_all_memory(mem);
4671 uncommon_trap(Deoptimization::Reason_intrinsic,
4672 Deoptimization::Action_maybe_recompile);
4673 }
4674 if (!stopped()) {
4675 set_result(res);
4676 }
4677 return true;
4678 }
4679
4680
4681 //--------------------------inline_native_subtype_check------------------------
4682 // This intrinsic takes the JNI calls out of the heart of
4683 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4684 bool LibraryCallKit::inline_native_subtype_check() {
4685 // Pull both arguments off the stack.
4686 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4687 args[0] = argument(0);
4688 args[1] = argument(1);
4689 Node* klasses[2]; // corresponding Klasses: superk, subk
4690 klasses[0] = klasses[1] = top();
4691
4692 enum {
4693 // A full decision tree on {superc is prim, subc is prim}:
4694 _prim_0_path = 1, // {P,N} => false
4695 // {P,P} & superc!=subc => false
4696 _prim_same_path, // {P,P} & superc==subc => true
4697 _prim_1_path, // {N,P} => false
4698 _ref_subtype_path, // {N,N} & subtype check wins => true
4699 _both_ref_path, // {N,N} & subtype check loses => false
4700 PATH_LIMIT
4701 };
4702
4703 RegionNode* region = new RegionNode(PATH_LIMIT);
4704 RegionNode* prim_region = new RegionNode(2);
4705 Node* phi = new PhiNode(region, TypeInt::BOOL);
4706 record_for_igvn(region);
4707 record_for_igvn(prim_region);
4708
4709 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4710 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4711 int class_klass_offset = java_lang_Class::klass_offset();
4712
4713 // First null-check both mirrors and load each mirror's klass metaobject.
4714 int which_arg;
4715 for (which_arg = 0; which_arg <= 1; which_arg++) {
4716 Node* arg = args[which_arg];
4717 arg = null_check(arg);
4718 if (stopped()) break;
4719 args[which_arg] = arg;
4720
4721 Node* p = basic_plus_adr(arg, class_klass_offset);
4722 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4723 klasses[which_arg] = _gvn.transform(kls);
4724 }
4725
4726 // Having loaded both klasses, test each for null.
4727 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4728 for (which_arg = 0; which_arg <= 1; which_arg++) {
4729 Node* kls = klasses[which_arg];
4730 Node* null_ctl = top();
4731 kls = null_check_oop(kls, &null_ctl, never_see_null);
4732 if (which_arg == 0) {
4733 prim_region->init_req(1, null_ctl);
4734 } else {
4735 region->init_req(_prim_1_path, null_ctl);
4736 }
4737 if (stopped()) break;
4738 klasses[which_arg] = kls;
4739 }
4740
4741 if (!stopped()) {
4742 // now we have two reference types, in klasses[0..1]
4743 Node* subk = klasses[1]; // the argument to isAssignableFrom
4744 Node* superk = klasses[0]; // the receiver
4745 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4746 region->set_req(_ref_subtype_path, control());
4747 }
4748
4749 // If both operands are primitive (both klasses null), then
4750 // we must return true when they are identical primitives.
4751 // It is convenient to test this after the first null klass check.
4752 // This path is also used if superc is a value mirror.
4753 set_control(_gvn.transform(prim_region));
4754 if (!stopped()) {
4755 // Since superc is primitive, make a guard for the superc==subc case.
4756 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4757 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4758 generate_fair_guard(bol_eq, region);
4759 if (region->req() == PATH_LIMIT+1) {
4760 // A guard was added. If the added guard is taken, superc==subc.
4761 region->swap_edges(PATH_LIMIT, _prim_same_path);
4762 region->del_req(PATH_LIMIT);
4763 }
4764 region->set_req(_prim_0_path, control()); // Not equal after all.
4765 }
4766
4767 // these are the only paths that produce 'true':
4768 phi->set_req(_prim_same_path, intcon(1));
4769 phi->set_req(_ref_subtype_path, intcon(1));
4770
4771 // pull together the cases:
4772 assert(region->req() == PATH_LIMIT, "sane region");
4773 for (uint i = 1; i < region->req(); i++) {
4774 Node* ctl = region->in(i);
4775 if (ctl == nullptr || ctl == top()) {
4776 region->set_req(i, top());
4777 phi ->set_req(i, top());
4778 } else if (phi->in(i) == nullptr) {
4779 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4780 }
4781 }
4782
4783 set_control(_gvn.transform(region));
4784 set_result(_gvn.transform(phi));
4785 return true;
4786 }
4787
4788 //---------------------generate_array_guard_common------------------------
4789 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4790
4791 if (stopped()) {
4792 return nullptr;
4793 }
4794
4795 // Like generate_guard, adds a new path onto the region.
4796 jint layout_con = 0;
4797 Node* layout_val = get_layout_helper(kls, layout_con);
4798 if (layout_val == nullptr) {
4799 bool query = 0;
4800 switch(kind) {
4801 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4802 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4803 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4804 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4805 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4806 default:
4807 ShouldNotReachHere();
4808 }
4809 if (!query) {
4810 return nullptr; // never a branch
4811 } else { // always a branch
4812 Node* always_branch = control();
4813 if (region != nullptr)
4814 region->add_req(always_branch);
4815 set_control(top());
4816 return always_branch;
4817 }
4818 }
4819 unsigned int value = 0;
4820 BoolTest::mask btest = BoolTest::illegal;
4821 switch(kind) {
4822 case RefArray:
4823 case NonRefArray: {
4824 value = Klass::_lh_array_tag_ref_value;
4825 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4826 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4827 break;
4828 }
4829 case TypeArray: {
4830 value = Klass::_lh_array_tag_type_value;
4831 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4832 btest = BoolTest::eq;
4833 break;
4834 }
4835 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4836 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4837 default:
4838 ShouldNotReachHere();
4839 }
4840 // Now test the correct condition.
4841 jint nval = (jint)value;
4842 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4843 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4844 Node* ctrl = generate_fair_guard(bol, region);
4845 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4846 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4847 // Keep track of the fact that 'obj' is an array to prevent
4848 // array specific accesses from floating above the guard.
4849 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4850 }
4851 return ctrl;
4852 }
4853
4854 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4855 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4856 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4857 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4858 assert(null_free || atomic, "nullable implies atomic");
4859 Node* componentType = argument(0);
4860 Node* length = argument(1);
4861 Node* init_val = null_free ? argument(2) : nullptr;
4862
4863 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4864 if (tp != nullptr) {
4865 ciInstanceKlass* ik = tp->instance_klass();
4866 if (ik == C->env()->Class_klass()) {
4867 ciType* t = tp->java_mirror_type();
4868 if (t != nullptr && t->is_inlinetype()) {
4869
4870 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4871 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4872
4873 // TODO 8350865 ZGC needs card marks on initializing oop stores
4874 if ((UseZGC || UseShenandoahGC) && null_free && !array_klass->is_flat_array_klass()) {
4875 return false;
4876 }
4877
4878 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4879 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4880 if (null_free) {
4881 if (init_val->is_InlineType()) {
4882 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4883 // Zeroing is enough because the init value is the all-zero value
4884 init_val = nullptr;
4885 } else {
4886 init_val = init_val->as_InlineType()->buffer(this);
4887 }
4888 }
4889 if (init_val != nullptr) {
4890 #ifdef ASSERT
4891 init_val = null_check(init_val);
4892 Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
4893 {
4894 PreserveJVMState pjvms(this);
4895 set_control(wrong_type_ctl);
4896 halt(control(), frameptr(), "incompatible type for initVal in newArray");
4897 stop_and_kill_map();
4898 }
4899 #endif
4900 init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
4901 }
4902 }
4903 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4904 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4905 assert(arytype->is_null_free() == null_free, "inconsistency");
4906 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4907 set_result(obj);
4908 return true;
4909 }
4910 }
4911 }
4912 }
4913 return false;
4914 }
4915
4916 // public static native boolean ValueClass::isFlatArray(Object array);
4917 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4918 // public static native boolean ValueClass::isAtomicArray(Object array);
4919 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4920 Node* array = argument(0);
4921
4922 Node* bol;
4923 switch(check) {
4924 case IsFlat:
4925 bol = flat_array_test(load_object_klass(array));
4926 break;
4927 case IsNullRestricted:
4928 bol = null_free_array_test(array);
4929 break;
4930 case IsAtomic: {
4931 // See conditions in JVM_IsAtomicArray
4932 // 1. If not flat, then atomic, or else...
4933 RegionNode* atomic_region = new RegionNode(1);
4934 RegionNode* non_atomic_region = new RegionNode(1);
4935 Node* array_klass = load_object_klass(array);
4936 Node* is_flat_bol = flat_array_test(array_klass);
4937 IfNode* iff_is_flat = create_and_xform_if(control(), is_flat_bol, PROB_FAIR, COUNT_UNKNOWN);
4938 atomic_region->add_req(_gvn.transform(new IfFalseNode(iff_is_flat)));
4939 set_control(_gvn.transform(new IfTrueNode(iff_is_flat)));
4940
4941 // 2. ...if the layout is atomic, then atomic, or else...
4942 Node* layout_kind = atomic_layout_array_test_and_get_layout_kind(array, atomic_region);
4943
4944 // 3. ...if the element type is naturally atomic and null-free OR empty and nullable, then atomic, or else...
4945 int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
4946 Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset);
4947 Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr()));
4948 int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset());
4949 Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset);
4950 Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
4951
4952 // Here, layout can only be non-atomic, otherwise atomic_layout_array_test_and_get_layout_kind already decides the array to be atomic.
4953 Node* is_null_free_cmp = _gvn.transform(new CmpINode(layout_kind, intcon(static_cast<jint>(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT))));
4954 Node* is_null_free_bol = _gvn.transform(new BoolNode(is_null_free_cmp, BoolTest::eq));
4955 IfNode* iff_is_null_free_bol = create_and_xform_if(control(), is_null_free_bol, PROB_FAIR, COUNT_UNKNOWN);
4956 Node* is_null_free_ctl = _gvn.transform(new IfTrueNode(iff_is_null_free_bol));
4957 Node* is_nullable_ctl = _gvn.transform(new IfFalseNode(iff_is_null_free_bol));
4958
4959 Node* is_naturally_atomic_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_naturally_atomic)));
4960 Node* is_naturally_atomic_cmp = _gvn.transform(new CmpINode(is_naturally_atomic_flag, intcon(0)));
4961 Node* is_naturally_atomic_bol = _gvn.transform(new BoolNode(is_naturally_atomic_cmp, BoolTest::ne));
4962 IfNode* iff_is_naturally_atomic = create_and_xform_if(is_null_free_ctl, is_naturally_atomic_bol, PROB_FAIR, COUNT_UNKNOWN);
4963 Node* is_naturally_atomic_ctl = _gvn.transform(new IfTrueNode(iff_is_naturally_atomic));
4964 Node* is_not_naturally_atomic_ctl = _gvn.transform(new IfFalseNode(iff_is_naturally_atomic));
4965 atomic_region->add_req(is_naturally_atomic_ctl);
4966 non_atomic_region->add_req(is_not_naturally_atomic_ctl);
4967
4968 Node* is_empty_inline_type_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_empty_inline_type)));
4969 Node* is_empty_inline_type_cmp = _gvn.transform(new CmpINode(is_empty_inline_type_flag, intcon(0)));
4970 Node* is_empty_inline_type_bol = _gvn.transform(new BoolNode(is_empty_inline_type_cmp, BoolTest::ne));
4971 IfNode* iff_is_empty_inline_type = create_and_xform_if(is_nullable_ctl, is_empty_inline_type_bol, PROB_FAIR, COUNT_UNKNOWN);
4972 Node* is_empty_inline_type_ctl = _gvn.transform(new IfTrueNode(iff_is_empty_inline_type));
4973 Node* is_nonempty_inline_type_ctl = _gvn.transform(new IfFalseNode(iff_is_empty_inline_type));
4974 atomic_region->add_req(is_empty_inline_type_ctl);
4975 non_atomic_region->add_req(is_nonempty_inline_type_ctl);
4976
4977 // ...non-atomic, but we tried everything.
4978 RegionNode* decision = new RegionNode(3);
4979 decision->set_req(1, _gvn.transform(atomic_region));
4980 decision->set_req(2, _gvn.transform(non_atomic_region));
4981 PhiNode* result = PhiNode::make(decision, intcon(1), TypeInt::BOOL);
4982 result->set_req(2, intcon(0));
4983 set_control(_gvn.transform(decision));
4984 set_result(_gvn.transform(result));
4985 return true;
4986 }
4987 default:
4988 ShouldNotReachHere();
4989 }
4990
4991 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4992 set_result(res);
4993 return true;
4994 }
4995
4996 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4997 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4998 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4999 RegionNode* region = new RegionNode(2);
5000 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
5001
5002 if (type_array_guard) {
5003 generate_typeArray_guard(klass_node, region);
5004 if (region->req() == 3) {
5005 phi->add_req(klass_node);
5006 }
5007 }
5008 Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
5009 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
5010
5011 // Can be null if not initialized yet, just deopt
5012 Node* null_ctl = top();
5013 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
5014
5015 region->init_req(1, control());
5016 phi->init_req(1, refined_klass);
5017
5018 set_control(_gvn.transform(region));
5019 return _gvn.transform(phi);
5020 }
5021
5022 // Load the non-refined array klass from an ObjArrayKlass.
5023 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5024 const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5025 if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5026 return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5027 }
5028
5029 RegionNode* region = new RegionNode(2);
5030 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5031
5032 generate_typeArray_guard(klass_node, region);
5033 if (region->req() == 3) {
5034 phi->add_req(klass_node);
5035 }
5036 Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
5037 Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5038
5039 region->init_req(1, control());
5040 phi->init_req(1, super_klass);
5041
5042 set_control(_gvn.transform(region));
5043 return _gvn.transform(phi);
5044 }
5045
5046 //-----------------------inline_native_newArray--------------------------
5047 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5048 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5049 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5050 Node* mirror;
5051 Node* count_val;
5052 if (uninitialized) {
5053 null_check_receiver();
5054 mirror = argument(1);
5055 count_val = argument(2);
5056 } else {
5057 mirror = argument(0);
5058 count_val = argument(1);
5059 }
5060
5061 mirror = null_check(mirror);
5062 // If mirror or obj is dead, only null-path is taken.
5063 if (stopped()) return true;
5064
5065 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5066 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5067 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5068 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5069 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5070
5071 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5072 Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5073 result_reg, _slow_path);
5074 Node* normal_ctl = control();
5075 Node* no_array_ctl = result_reg->in(_slow_path);
5076
5077 // Generate code for the slow case. We make a call to newArray().
5078 set_control(no_array_ctl);
5079 if (!stopped()) {
5080 // Either the input type is void.class, or else the
5081 // array klass has not yet been cached. Either the
5082 // ensuing call will throw an exception, or else it
5083 // will cache the array klass for next time.
5084 PreserveJVMState pjvms(this);
5085 CallJavaNode* slow_call = nullptr;
5086 if (uninitialized) {
5087 // Generate optimized virtual call (holder class 'Unsafe' is final)
5088 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5089 } else {
5090 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5091 }
5092 Node* slow_result = set_results_for_java_call(slow_call);
5093 // this->control() comes from set_results_for_java_call
5094 result_reg->set_req(_slow_path, control());
5095 result_val->set_req(_slow_path, slow_result);
5096 result_io ->set_req(_slow_path, i_o());
5097 result_mem->set_req(_slow_path, reset_memory());
5098 }
5099
5100 set_control(normal_ctl);
5101 if (!stopped()) {
5102 // Normal case: The array type has been cached in the java.lang.Class.
5103 // The following call works fine even if the array type is polymorphic.
5104 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5105
5106 klass_node = load_default_refined_array_klass(klass_node);
5107
5108 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
5109 result_reg->init_req(_normal_path, control());
5110 result_val->init_req(_normal_path, obj);
5111 result_io ->init_req(_normal_path, i_o());
5112 result_mem->init_req(_normal_path, reset_memory());
5113
5114 if (uninitialized) {
5115 // Mark the allocation so that zeroing is skipped
5116 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5117 alloc->maybe_set_complete(&_gvn);
5118 }
5119 }
5120
5121 // Return the combined state.
5122 set_i_o( _gvn.transform(result_io) );
5123 set_all_memory( _gvn.transform(result_mem));
5124
5125 C->set_has_split_ifs(true); // Has chance for split-if optimization
5126 set_result(result_reg, result_val);
5127 return true;
5128 }
5129
5130 //----------------------inline_native_getLength--------------------------
5131 // public static native int java.lang.reflect.Array.getLength(Object array);
5132 bool LibraryCallKit::inline_native_getLength() {
5133 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
5134
5135 Node* array = null_check(argument(0));
5136 // If array is dead, only null-path is taken.
5137 if (stopped()) return true;
5138
5139 // Deoptimize if it is a non-array.
5140 Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5141
5142 if (non_array != nullptr) {
5143 PreserveJVMState pjvms(this);
5144 set_control(non_array);
5145 uncommon_trap(Deoptimization::Reason_intrinsic,
5146 Deoptimization::Action_maybe_recompile);
5147 }
5148
5149 // If control is dead, only non-array-path is taken.
5150 if (stopped()) return true;
5151
5152 // The works fine even if the array type is polymorphic.
5153 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5154 Node* result = load_array_length(array);
5155
5156 C->set_has_split_ifs(true); // Has chance for split-if optimization
5157 set_result(result);
5158 return true;
5159 }
5160
5161 //------------------------inline_array_copyOf----------------------------
5162 // public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);
5163 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);
5164 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5165 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
5166
5167 // Get the arguments.
5168 Node* original = argument(0);
5169 Node* start = is_copyOfRange? argument(1): intcon(0);
5170 Node* end = is_copyOfRange? argument(2): argument(1);
5171 Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5172
5173 Node* newcopy = nullptr;
5174
5175 // Set the original stack and the reexecute bit for the interpreter to reexecute
5176 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5177 { PreserveReexecuteState preexecs(this);
5178 jvms()->set_should_reexecute(true);
5179
5180 array_type_mirror = null_check(array_type_mirror);
5181 original = null_check(original);
5182
5183 // Check if a null path was taken unconditionally.
5184 if (stopped()) return true;
5185
5186 Node* orig_length = load_array_length(original);
5187
5188 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5189 klass_node = null_check(klass_node);
5190
5191 RegionNode* bailout = new RegionNode(1);
5192 record_for_igvn(bailout);
5193
5194 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5195 // Bail out if that is so.
5196 // Inline type array may have object field that would require a
5197 // write barrier. Conservatively, go to slow path.
5198 // TODO 8251971: Optimize for the case when flat src/dst are later found
5199 // to not contain oops (i.e., move this check to the macro expansion phase).
5200 // TODO 8382226: Revisit for flat abstract value class arrays
5201 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5202 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5203 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5204 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5205 // Can src array be flat and contain oops?
5206 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5207 // Can dest array be flat and contain oops?
5208 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5209 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5210
5211 Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5212
5213 if (not_objArray != nullptr) {
5214 // Improve the klass node's type from the new optimistic assumption:
5215 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5216 bool not_flat = !UseArrayFlattening;
5217 bool not_null_free = !Arguments::is_valhalla_enabled();
5218 const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5219 Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5220 refined_klass_node = _gvn.transform(cast);
5221 }
5222
5223 // Bail out if either start or end is negative.
5224 generate_negative_guard(start, bailout, &start);
5225 generate_negative_guard(end, bailout, &end);
5226
5227 Node* length = end;
5228 if (_gvn.type(start) != TypeInt::ZERO) {
5229 length = _gvn.transform(new SubINode(end, start));
5230 }
5231
5232 // Bail out if length is negative (i.e., if start > end).
5233 // Without this the new_array would throw
5234 // NegativeArraySizeException but IllegalArgumentException is what
5235 // should be thrown
5236 generate_negative_guard(length, bailout, &length);
5237
5238 // Handle inline type arrays
5239 // TODO 8251971 This is too strong
5240 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5241 generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5242 generate_fair_guard(null_free_array_test(original), bailout);
5243
5244 // Bail out if start is larger than the original length
5245 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5246 generate_negative_guard(orig_tail, bailout, &orig_tail);
5247
5248 if (bailout->req() > 1) {
5249 PreserveJVMState pjvms(this);
5250 set_control(_gvn.transform(bailout));
5251 uncommon_trap(Deoptimization::Reason_intrinsic,
5252 Deoptimization::Action_maybe_recompile);
5253 }
5254
5255 if (!stopped()) {
5256 // How many elements will we copy from the original?
5257 // The answer is MinI(orig_tail, length).
5258 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5259
5260 // Generate a direct call to the right arraycopy function(s).
5261 // We know the copy is disjoint but we might not know if the
5262 // oop stores need checking.
5263 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5264 // This will fail a store-check if x contains any non-nulls.
5265
5266 // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5267 // loads/stores but it is legal only if we're sure the
5268 // Arrays.copyOf would succeed. So we need all input arguments
5269 // to the copyOf to be validated, including that the copy to the
5270 // new array won't trigger an ArrayStoreException. That subtype
5271 // check can be optimized if we know something on the type of
5272 // the input array from type speculation.
5273 if (_gvn.type(klass_node)->singleton()) {
5274 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5275 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5276
5277 int test = C->static_subtype_check(superk, subk);
5278 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5279 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5280 if (t_original->speculative_type() != nullptr) {
5281 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5282 }
5283 }
5284 }
5285
5286 bool validated = false;
5287 // Reason_class_check rather than Reason_intrinsic because we
5288 // want to intrinsify even if this traps.
5289 if (!too_many_traps(Deoptimization::Reason_class_check)) {
5290 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5291
5292 if (not_subtype_ctrl != top()) {
5293 PreserveJVMState pjvms(this);
5294 set_control(not_subtype_ctrl);
5295 uncommon_trap(Deoptimization::Reason_class_check,
5296 Deoptimization::Action_make_not_entrant);
5297 assert(stopped(), "Should be stopped");
5298 }
5299 validated = true;
5300 }
5301
5302 if (!stopped()) {
5303 newcopy = new_array(refined_klass_node, length, 0); // no arguments to push
5304
5305 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5306 load_object_klass(original), klass_node);
5307 if (!is_copyOfRange) {
5308 ac->set_copyof(validated);
5309 } else {
5310 ac->set_copyofrange(validated);
5311 }
5312 Node* n = _gvn.transform(ac);
5313 if (n == ac) {
5314 ac->connect_outputs(this);
5315 } else {
5316 assert(validated, "shouldn't transform if all arguments not validated");
5317 set_all_memory(n);
5318 }
5319 }
5320 }
5321 } // original reexecute is set back here
5322
5323 C->set_has_split_ifs(true); // Has chance for split-if optimization
5324 if (!stopped()) {
5325 set_result(newcopy);
5326 }
5327 return true;
5328 }
5329
5330
5331 //----------------------generate_virtual_guard---------------------------
5332 // Helper for hashCode and clone. Peeks inside the vtable to avoid a call.
5333 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5334 RegionNode* slow_region) {
5335 ciMethod* method = callee();
5336 int vtable_index = method->vtable_index();
5337 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5338 "bad index %d", vtable_index);
5339 // Get the Method* out of the appropriate vtable entry.
5340 int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5341 vtable_index*vtableEntry::size_in_bytes() +
5342 in_bytes(vtableEntry::method_offset());
5343 Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5344 Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5345
5346 // Compare the target method with the expected method (e.g., Object.hashCode).
5347 const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5348
5349 Node* native_call = makecon(native_call_addr);
5350 Node* chk_native = _gvn.transform(new CmpPNode(target_call, native_call));
5351 Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5352
5353 return generate_slow_guard(test_native, slow_region);
5354 }
5355
5356 //-----------------------generate_method_call----------------------------
5357 // Use generate_method_call to make a slow-call to the real
5358 // method if the fast path fails. An alternative would be to
5359 // use a stub like OptoRuntime::slow_arraycopy_Java.
5360 // This only works for expanding the current library call,
5361 // not another intrinsic. (E.g., don't use this for making an
5362 // arraycopy call inside of the copyOf intrinsic.)
5363 CallJavaNode*
5364 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5365 // When compiling the intrinsic method itself, do not use this technique.
5366 guarantee(callee() != C->method(), "cannot make slow-call to self");
5367
5368 ciMethod* method = callee();
5369 // ensure the JVMS we have will be correct for this call
5370 guarantee(method_id == method->intrinsic_id(), "must match");
5371
5372 const TypeFunc* tf = TypeFunc::make(method);
5373 if (res_not_null) {
5374 assert(tf->return_type() == T_OBJECT, "");
5375 const TypeTuple* range = tf->range_cc();
5376 const Type** fields = TypeTuple::fields(range->cnt());
5377 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5378 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5379 tf = TypeFunc::make(tf->domain_cc(), new_range);
5380 }
5381 CallJavaNode* slow_call;
5382 if (is_static) {
5383 assert(!is_virtual, "");
5384 slow_call = new CallStaticJavaNode(C, tf,
5385 SharedRuntime::get_resolve_static_call_stub(), method);
5386 } else if (is_virtual) {
5387 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5388 int vtable_index = Method::invalid_vtable_index;
5389 if (UseInlineCaches) {
5390 // Suppress the vtable call
5391 } else {
5392 // hashCode and clone are not a miranda methods,
5393 // so the vtable index is fixed.
5394 // No need to use the linkResolver to get it.
5395 vtable_index = method->vtable_index();
5396 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5397 "bad index %d", vtable_index);
5398 }
5399 slow_call = new CallDynamicJavaNode(tf,
5400 SharedRuntime::get_resolve_virtual_call_stub(),
5401 method, vtable_index);
5402 } else { // neither virtual nor static: opt_virtual
5403 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5404 slow_call = new CallStaticJavaNode(C, tf,
5405 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5406 slow_call->set_optimized_virtual(true);
5407 }
5408 if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5409 // To be able to issue a direct call (optimized virtual or virtual)
5410 // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5411 // about the method being invoked should be attached to the call site to
5412 // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5413 slow_call->set_override_symbolic_info(true);
5414 }
5415 set_arguments_for_java_call(slow_call);
5416 set_edges_for_java_call(slow_call);
5417 return slow_call;
5418 }
5419
5420
5421 /**
5422 * Build special case code for calls to hashCode on an object. This call may
5423 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5424 * slightly different code.
5425 */
5426 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5427 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5428 assert(!(is_virtual && is_static), "either virtual, special, or static");
5429
5430 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5431
5432 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5433 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5434 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5435 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5436 Node* obj = argument(0);
5437
5438 // Don't intrinsify hashcode on inline types for now.
5439 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5440 if (gvn().type(obj)->is_inlinetypeptr()) {
5441 return false;
5442 }
5443
5444 if (!is_static) {
5445 // Check for hashing null object
5446 obj = null_check_receiver();
5447 if (stopped()) return true; // unconditionally null
5448 result_reg->init_req(_null_path, top());
5449 result_val->init_req(_null_path, top());
5450 } else {
5451 // Do a null check, and return zero if null.
5452 // System.identityHashCode(null) == 0
5453 Node* null_ctl = top();
5454 obj = null_check_oop(obj, &null_ctl);
5455 result_reg->init_req(_null_path, null_ctl);
5456 result_val->init_req(_null_path, _gvn.intcon(0));
5457 }
5458
5459 // Unconditionally null? Then return right away.
5460 if (stopped()) {
5461 set_control( result_reg->in(_null_path));
5462 if (!stopped())
5463 set_result(result_val->in(_null_path));
5464 return true;
5465 }
5466
5467 // We only go to the fast case code if we pass a number of guards. The
5468 // paths which do not pass are accumulated in the slow_region.
5469 RegionNode* slow_region = new RegionNode(1);
5470 record_for_igvn(slow_region);
5471
5472 // If this is a virtual call, we generate a funny guard. We pull out
5473 // the vtable entry corresponding to hashCode() from the target object.
5474 // If the target method which we are calling happens to be the native
5475 // Object hashCode() method, we pass the guard. We do not need this
5476 // guard for non-virtual calls -- the caller is known to be the native
5477 // Object hashCode().
5478 if (is_virtual) {
5479 // After null check, get the object's klass.
5480 Node* obj_klass = load_object_klass(obj);
5481 generate_virtual_guard(obj_klass, slow_region);
5482 }
5483
5484 // Get the header out of the object, use LoadMarkNode when available
5485 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5486 // The control of the load must be null. Otherwise, the load can move before
5487 // the null check after castPP removal.
5488 Node* no_ctrl = nullptr;
5489 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5490
5491 if (!UseObjectMonitorTable) {
5492 // Test the header to see if it is safe to read w.r.t. locking.
5493 // We cannot use the inline type mask as this may check bits that are overridden
5494 // by an object monitor's pointer when inflating locking.
5495 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5496 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5497 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5498 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5499 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5500
5501 generate_slow_guard(test_monitor, slow_region);
5502 }
5503
5504 // Get the hash value and check to see that it has been properly assigned.
5505 // We depend on hash_mask being at most 32 bits and avoid the use of
5506 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5507 // vm: see markWord.hpp.
5508 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5509 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5510 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5511 // This hack lets the hash bits live anywhere in the mark object now, as long
5512 // as the shift drops the relevant bits into the low 32 bits. Note that
5513 // Java spec says that HashCode is an int so there's no point in capturing
5514 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5515 hshifted_header = ConvX2I(hshifted_header);
5516 Node *hash_val = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5517
5518 Node *no_hash_val = _gvn.intcon(markWord::no_hash);
5519 Node *chk_assigned = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5520 Node *test_assigned = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5521
5522 generate_slow_guard(test_assigned, slow_region);
5523
5524 Node* init_mem = reset_memory();
5525 // fill in the rest of the null path:
5526 result_io ->init_req(_null_path, i_o());
5527 result_mem->init_req(_null_path, init_mem);
5528
5529 result_val->init_req(_fast_path, hash_val);
5530 result_reg->init_req(_fast_path, control());
5531 result_io ->init_req(_fast_path, i_o());
5532 result_mem->init_req(_fast_path, init_mem);
5533
5534 // Generate code for the slow case. We make a call to hashCode().
5535 set_control(_gvn.transform(slow_region));
5536 if (!stopped()) {
5537 // No need for PreserveJVMState, because we're using up the present state.
5538 set_all_memory(init_mem);
5539 vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5540 CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5541 Node* slow_result = set_results_for_java_call(slow_call);
5542 // this->control() comes from set_results_for_java_call
5543 result_reg->init_req(_slow_path, control());
5544 result_val->init_req(_slow_path, slow_result);
5545 result_io ->set_req(_slow_path, i_o());
5546 result_mem ->set_req(_slow_path, reset_memory());
5547 }
5548
5549 // Return the combined state.
5550 set_i_o( _gvn.transform(result_io) );
5551 set_all_memory( _gvn.transform(result_mem));
5552
5553 set_result(result_reg, result_val);
5554 return true;
5555 }
5556
5557 //---------------------------inline_native_getClass----------------------------
5558 // public final native Class<?> java.lang.Object.getClass();
5559 //
5560 // Build special case code for calls to getClass on an object.
5561 bool LibraryCallKit::inline_native_getClass() {
5562 Node* obj = argument(0);
5563 if (obj->is_InlineType()) {
5564 const Type* t = _gvn.type(obj);
5565 if (t->maybe_null()) {
5566 null_check(obj);
5567 }
5568 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5569 return true;
5570 }
5571 obj = null_check_receiver();
5572 if (stopped()) return true;
5573 set_result(load_mirror_from_klass(load_object_klass(obj)));
5574 return true;
5575 }
5576
5577 //-----------------inline_native_Reflection_getCallerClass---------------------
5578 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5579 //
5580 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5581 //
5582 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5583 // in that it must skip particular security frames and checks for
5584 // caller sensitive methods.
5585 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5586 #ifndef PRODUCT
5587 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5588 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5589 }
5590 #endif
5591
5592 if (!jvms()->has_method()) {
5593 #ifndef PRODUCT
5594 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5595 tty->print_cr(" Bailing out because intrinsic was inlined at top level");
5596 }
5597 #endif
5598 return false;
5599 }
5600
5601 // Walk back up the JVM state to find the caller at the required
5602 // depth.
5603 JVMState* caller_jvms = jvms();
5604
5605 // Cf. JVM_GetCallerClass
5606 // NOTE: Start the loop at depth 1 because the current JVM state does
5607 // not include the Reflection.getCallerClass() frame.
5608 for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5609 ciMethod* m = caller_jvms->method();
5610 switch (n) {
5611 case 0:
5612 fatal("current JVM state does not include the Reflection.getCallerClass frame");
5613 break;
5614 case 1:
5615 // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5616 if (!m->caller_sensitive()) {
5617 #ifndef PRODUCT
5618 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5619 tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);
5620 }
5621 #endif
5622 return false; // bail-out; let JVM_GetCallerClass do the work
5623 }
5624 break;
5625 default:
5626 if (!m->is_ignored_by_security_stack_walk()) {
5627 // We have reached the desired frame; return the holder class.
5628 // Acquire method holder as java.lang.Class and push as constant.
5629 ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5630 ciInstance* caller_mirror = caller_klass->java_mirror();
5631 set_result(makecon(TypeInstPtr::make(caller_mirror)));
5632
5633 #ifndef PRODUCT
5634 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5635 tty->print_cr(" Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
5636 tty->print_cr(" JVM state at this point:");
5637 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5638 ciMethod* m = jvms()->of_depth(i)->method();
5639 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5640 }
5641 }
5642 #endif
5643 return true;
5644 }
5645 break;
5646 }
5647 }
5648
5649 #ifndef PRODUCT
5650 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5651 tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5652 tty->print_cr(" JVM state at this point:");
5653 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5654 ciMethod* m = jvms()->of_depth(i)->method();
5655 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5656 }
5657 }
5658 #endif
5659
5660 return false; // bail-out; let JVM_GetCallerClass do the work
5661 }
5662
5663 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5664 Node* arg = argument(0);
5665 Node* result = nullptr;
5666
5667 switch (id) {
5668 case vmIntrinsics::_floatToRawIntBits: result = new MoveF2INode(arg); break;
5669 case vmIntrinsics::_intBitsToFloat: result = new MoveI2FNode(arg); break;
5670 case vmIntrinsics::_doubleToRawLongBits: result = new MoveD2LNode(arg); break;
5671 case vmIntrinsics::_longBitsToDouble: result = new MoveL2DNode(arg); break;
5672 case vmIntrinsics::_floatToFloat16: result = new ConvF2HFNode(arg); break;
5673 case vmIntrinsics::_float16ToFloat: result = new ConvHF2FNode(arg); break;
5674
5675 case vmIntrinsics::_doubleToLongBits: {
5676 // two paths (plus control) merge in a wood
5677 RegionNode *r = new RegionNode(3);
5678 Node *phi = new PhiNode(r, TypeLong::LONG);
5679
5680 Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5681 // Build the boolean node
5682 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5683
5684 // Branch either way.
5685 // NaN case is less traveled, which makes all the difference.
5686 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5687 Node *opt_isnan = _gvn.transform(ifisnan);
5688 assert( opt_isnan->is_If(), "Expect an IfNode");
5689 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5690 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5691
5692 set_control(iftrue);
5693
5694 static const jlong nan_bits = CONST64(0x7ff8000000000000);
5695 Node *slow_result = longcon(nan_bits); // return NaN
5696 phi->init_req(1, _gvn.transform( slow_result ));
5697 r->init_req(1, iftrue);
5698
5699 // Else fall through
5700 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5701 set_control(iffalse);
5702
5703 phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5704 r->init_req(2, iffalse);
5705
5706 // Post merge
5707 set_control(_gvn.transform(r));
5708 record_for_igvn(r);
5709
5710 C->set_has_split_ifs(true); // Has chance for split-if optimization
5711 result = phi;
5712 assert(result->bottom_type()->isa_long(), "must be");
5713 break;
5714 }
5715
5716 case vmIntrinsics::_floatToIntBits: {
5717 // two paths (plus control) merge in a wood
5718 RegionNode *r = new RegionNode(3);
5719 Node *phi = new PhiNode(r, TypeInt::INT);
5720
5721 Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5722 // Build the boolean node
5723 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5724
5725 // Branch either way.
5726 // NaN case is less traveled, which makes all the difference.
5727 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5728 Node *opt_isnan = _gvn.transform(ifisnan);
5729 assert( opt_isnan->is_If(), "Expect an IfNode");
5730 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5731 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5732
5733 set_control(iftrue);
5734
5735 static const jint nan_bits = 0x7fc00000;
5736 Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5737 phi->init_req(1, _gvn.transform( slow_result ));
5738 r->init_req(1, iftrue);
5739
5740 // Else fall through
5741 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5742 set_control(iffalse);
5743
5744 phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5745 r->init_req(2, iffalse);
5746
5747 // Post merge
5748 set_control(_gvn.transform(r));
5749 record_for_igvn(r);
5750
5751 C->set_has_split_ifs(true); // Has chance for split-if optimization
5752 result = phi;
5753 assert(result->bottom_type()->isa_int(), "must be");
5754 break;
5755 }
5756
5757 default:
5758 fatal_unexpected_iid(id);
5759 break;
5760 }
5761 set_result(_gvn.transform(result));
5762 return true;
5763 }
5764
5765 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5766 Node* arg = argument(0);
5767 Node* result = nullptr;
5768
5769 switch (id) {
5770 case vmIntrinsics::_floatIsInfinite:
5771 result = new IsInfiniteFNode(arg);
5772 break;
5773 case vmIntrinsics::_floatIsFinite:
5774 result = new IsFiniteFNode(arg);
5775 break;
5776 case vmIntrinsics::_doubleIsInfinite:
5777 result = new IsInfiniteDNode(arg);
5778 break;
5779 case vmIntrinsics::_doubleIsFinite:
5780 result = new IsFiniteDNode(arg);
5781 break;
5782 default:
5783 fatal_unexpected_iid(id);
5784 break;
5785 }
5786 set_result(_gvn.transform(result));
5787 return true;
5788 }
5789
5790 //----------------------inline_unsafe_copyMemory-------------------------
5791 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5792
5793 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5794 const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5795 const Type* base_t = gvn.type(base);
5796
5797 bool in_native = (base_t == TypePtr::NULL_PTR);
5798 bool in_heap = !TypePtr::NULL_PTR->higher_equal(base_t);
5799 bool is_mixed = !in_heap && !in_native;
5800
5801 if (is_mixed) {
5802 return true; // mixed accesses can touch both on-heap and off-heap memory
5803 }
5804 if (in_heap) {
5805 bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5806 if (!is_prim_array) {
5807 // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5808 // there's not enough type information available to determine proper memory slice for it.
5809 return true;
5810 }
5811 }
5812 return false;
5813 }
5814
5815 bool LibraryCallKit::inline_unsafe_copyMemory() {
5816 if (callee()->is_static()) return false; // caller must have the capability!
5817 null_check_receiver(); // null-check receiver
5818 if (stopped()) return true;
5819
5820 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5821
5822 Node* src_base = argument(1); // type: oop
5823 Node* src_off = ConvL2X(argument(2)); // type: long
5824 Node* dst_base = argument(4); // type: oop
5825 Node* dst_off = ConvL2X(argument(5)); // type: long
5826 Node* size = ConvL2X(argument(7)); // type: long
5827
5828 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5829 "fieldOffset must be byte-scaled");
5830
5831 Node* src_addr = make_unsafe_address(src_base, src_off);
5832 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5833
5834 Node* thread = _gvn.transform(new ThreadLocalNode());
5835 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5836 BasicType doing_unsafe_access_bt = T_BYTE;
5837 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5838
5839 // update volatile field
5840 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5841
5842 int flags = RC_LEAF | RC_NO_FP;
5843
5844 const TypePtr* dst_type = TypePtr::BOTTOM;
5845
5846 // Adjust memory effects of the runtime call based on input values.
5847 if (!has_wide_mem(_gvn, src_addr, src_base) &&
5848 !has_wide_mem(_gvn, dst_addr, dst_base)) {
5849 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5850
5851 const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5852 if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5853 flags |= RC_NARROW_MEM; // narrow in memory
5854 }
5855 }
5856
5857 // Call it. Note that the length argument is not scaled.
5858 make_runtime_call(flags,
5859 OptoRuntime::fast_arraycopy_Type(),
5860 StubRoutines::unsafe_arraycopy(),
5861 "unsafe_arraycopy",
5862 dst_type,
5863 src_addr, dst_addr, size XTOP);
5864
5865 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5866
5867 return true;
5868 }
5869
5870 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5871 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5872 bool LibraryCallKit::inline_unsafe_setMemory() {
5873 if (callee()->is_static()) return false; // caller must have the capability!
5874 null_check_receiver(); // null-check receiver
5875 if (stopped()) return true;
5876
5877 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5878
5879 Node* dst_base = argument(1); // type: oop
5880 Node* dst_off = ConvL2X(argument(2)); // type: long
5881 Node* size = ConvL2X(argument(4)); // type: long
5882 Node* byte = argument(6); // type: byte
5883
5884 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5885 "fieldOffset must be byte-scaled");
5886
5887 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5888
5889 Node* thread = _gvn.transform(new ThreadLocalNode());
5890 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5891 BasicType doing_unsafe_access_bt = T_BYTE;
5892 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5893
5894 // update volatile field
5895 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5896
5897 int flags = RC_LEAF | RC_NO_FP;
5898
5899 const TypePtr* dst_type = TypePtr::BOTTOM;
5900
5901 // Adjust memory effects of the runtime call based on input values.
5902 if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5903 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5904
5905 flags |= RC_NARROW_MEM; // narrow in memory
5906 }
5907
5908 // Call it. Note that the length argument is not scaled.
5909 make_runtime_call(flags,
5910 OptoRuntime::unsafe_setmemory_Type(),
5911 StubRoutines::unsafe_setmemory(),
5912 "unsafe_setmemory",
5913 dst_type,
5914 dst_addr, size XTOP, byte);
5915
5916 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5917
5918 return true;
5919 }
5920
5921 #undef XTOP
5922
5923 //------------------------clone_coping-----------------------------------
5924 // Helper function for inline_native_clone.
5925 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5926 assert(obj_size != nullptr, "");
5927 Node* raw_obj = alloc_obj->in(1);
5928 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5929
5930 AllocateNode* alloc = nullptr;
5931 if (ReduceBulkZeroing &&
5932 // If we are implementing an array clone without knowing its source type
5933 // (can happen when compiling the array-guarded branch of a reflective
5934 // Object.clone() invocation), initialize the array within the allocation.
5935 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5936 // to a runtime clone call that assumes fully initialized source arrays.
5937 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5938 // We will be completely responsible for initializing this object -
5939 // mark Initialize node as complete.
5940 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5941 // The object was just allocated - there should be no any stores!
5942 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5943 // Mark as complete_with_arraycopy so that on AllocateNode
5944 // expansion, we know this AllocateNode is initialized by an array
5945 // copy and a StoreStore barrier exists after the array copy.
5946 alloc->initialization()->set_complete_with_arraycopy();
5947 }
5948
5949 Node* size = _gvn.transform(obj_size);
5950 access_clone(obj, alloc_obj, size, is_array);
5951
5952 // Do not let reads from the cloned object float above the arraycopy.
5953 if (alloc != nullptr) {
5954 // Do not let stores that initialize this object be reordered with
5955 // a subsequent store that would make this object accessible by
5956 // other threads.
5957 // Record what AllocateNode this StoreStore protects so that
5958 // escape analysis can go from the MemBarStoreStoreNode to the
5959 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5960 // based on the escape status of the AllocateNode.
5961 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5962 } else {
5963 insert_mem_bar(Op_MemBarCPUOrder);
5964 }
5965 }
5966
5967 //------------------------inline_native_clone----------------------------
5968 // protected native Object java.lang.Object.clone();
5969 //
5970 // Here are the simple edge cases:
5971 // null receiver => normal trap
5972 // virtual and clone was overridden => slow path to out-of-line clone
5973 // not cloneable or finalizer => slow path to out-of-line Object.clone
5974 //
5975 // The general case has two steps, allocation and copying.
5976 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5977 //
5978 // Copying also has two cases, oop arrays and everything else.
5979 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5980 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5981 //
5982 // These steps fold up nicely if and when the cloned object's klass
5983 // can be sharply typed as an object array, a type array, or an instance.
5984 //
5985 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5986 PhiNode* result_val;
5987
5988 // Set the reexecute bit for the interpreter to reexecute
5989 // the bytecode that invokes Object.clone if deoptimization happens.
5990 { PreserveReexecuteState preexecs(this);
5991 jvms()->set_should_reexecute(true);
5992
5993 Node* obj = argument(0);
5994 obj = null_check_receiver();
5995 if (stopped()) return true;
5996
5997 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5998 if (obj_type->is_inlinetypeptr()) {
5999 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
6000 // no identity.
6001 set_result(obj);
6002 return true;
6003 }
6004
6005 // If we are going to clone an instance, we need its exact type to
6006 // know the number and types of fields to convert the clone to
6007 // loads/stores. Maybe a speculative type can help us.
6008 if (!obj_type->klass_is_exact() &&
6009 obj_type->speculative_type() != nullptr &&
6010 obj_type->speculative_type()->is_instance_klass() &&
6011 !obj_type->speculative_type()->is_inlinetype()) {
6012 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6013 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6014 !spec_ik->has_injected_fields()) {
6015 if (!obj_type->isa_instptr() ||
6016 obj_type->is_instptr()->instance_klass()->has_subklass()) {
6017 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6018 }
6019 }
6020 }
6021
6022 // Conservatively insert a memory barrier on all memory slices.
6023 // Do not let writes into the original float below the clone.
6024 insert_mem_bar(Op_MemBarCPUOrder);
6025
6026 // paths into result_reg:
6027 enum {
6028 _slow_path = 1, // out-of-line call to clone method (virtual or not)
6029 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
6030 _array_path, // plain array allocation, plus arrayof_long_arraycopy
6031 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
6032 PATH_LIMIT
6033 };
6034 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6035 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6036 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
6037 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6038 record_for_igvn(result_reg);
6039
6040 Node* obj_klass = load_object_klass(obj);
6041 // We only go to the fast case code if we pass a number of guards.
6042 // The paths which do not pass are accumulated in the slow_region.
6043 RegionNode* slow_region = new RegionNode(1);
6044 record_for_igvn(slow_region);
6045
6046 Node* array_obj = obj;
6047 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6048 if (array_ctl != nullptr) {
6049 // It's an array.
6050 PreserveJVMState pjvms(this);
6051 set_control(array_ctl);
6052
6053 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6054 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6055 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6056 obj_type->can_be_inline_array() &&
6057 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6058 // Flat inline type array may have object field that would require a
6059 // write barrier. Conservatively, go to slow path.
6060 generate_fair_guard(flat_array_test(obj_klass), slow_region);
6061 }
6062
6063 if (!stopped()) {
6064 Node* obj_length = load_array_length(array_obj);
6065 Node* array_size = nullptr; // Size of the array without object alignment padding.
6066 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6067
6068 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6069 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6070 // If it is an oop array, it requires very special treatment,
6071 // because gc barriers are required when accessing the array.
6072 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6073 if (is_obja != nullptr) {
6074 PreserveJVMState pjvms2(this);
6075 set_control(is_obja);
6076 // Generate a direct call to the right arraycopy function(s).
6077 // Clones are always tightly coupled.
6078 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6079 ac->set_clone_oop_array();
6080 Node* n = _gvn.transform(ac);
6081 assert(n == ac, "cannot disappear");
6082 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6083
6084 result_reg->init_req(_objArray_path, control());
6085 result_val->init_req(_objArray_path, alloc_obj);
6086 result_i_o ->set_req(_objArray_path, i_o());
6087 result_mem ->set_req(_objArray_path, reset_memory());
6088 }
6089 }
6090 // Otherwise, there are no barriers to worry about.
6091 // (We can dispense with card marks if we know the allocation
6092 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
6093 // causes the non-eden paths to take compensating steps to
6094 // simulate a fresh allocation, so that no further
6095 // card marks are required in compiled code to initialize
6096 // the object.)
6097
6098 if (!stopped()) {
6099 copy_to_clone(obj, alloc_obj, array_size, true);
6100
6101 // Present the results of the copy.
6102 result_reg->init_req(_array_path, control());
6103 result_val->init_req(_array_path, alloc_obj);
6104 result_i_o ->set_req(_array_path, i_o());
6105 result_mem ->set_req(_array_path, reset_memory());
6106 }
6107 }
6108 }
6109
6110 if (!stopped()) {
6111 // It's an instance (we did array above). Make the slow-path tests.
6112 // If this is a virtual call, we generate a funny guard. We grab
6113 // the vtable entry corresponding to clone() from the target object.
6114 // If the target method which we are calling happens to be the
6115 // Object clone() method, we pass the guard. We do not need this
6116 // guard for non-virtual calls; the caller is known to be the native
6117 // Object clone().
6118 if (is_virtual) {
6119 generate_virtual_guard(obj_klass, slow_region);
6120 }
6121
6122 // The object must be easily cloneable and must not have a finalizer.
6123 // Both of these conditions may be checked in a single test.
6124 // We could optimize the test further, but we don't care.
6125 generate_misc_flags_guard(obj_klass,
6126 // Test both conditions:
6127 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6128 // Must be cloneable but not finalizer:
6129 KlassFlags::_misc_is_cloneable_fast,
6130 slow_region);
6131 }
6132
6133 if (!stopped()) {
6134 // It's an instance, and it passed the slow-path tests.
6135 PreserveJVMState pjvms(this);
6136 Node* obj_size = nullptr; // Total object size, including object alignment padding.
6137 // Need to deoptimize on exception from allocation since Object.clone intrinsic
6138 // is reexecuted if deoptimization occurs and there could be problems when merging
6139 // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6140 Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6141
6142 copy_to_clone(obj, alloc_obj, obj_size, false);
6143
6144 // Present the results of the slow call.
6145 result_reg->init_req(_instance_path, control());
6146 result_val->init_req(_instance_path, alloc_obj);
6147 result_i_o ->set_req(_instance_path, i_o());
6148 result_mem ->set_req(_instance_path, reset_memory());
6149 }
6150
6151 // Generate code for the slow case. We make a call to clone().
6152 set_control(_gvn.transform(slow_region));
6153 if (!stopped()) {
6154 PreserveJVMState pjvms(this);
6155 CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6156 // We need to deoptimize on exception (see comment above)
6157 Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6158 // this->control() comes from set_results_for_java_call
6159 result_reg->init_req(_slow_path, control());
6160 result_val->init_req(_slow_path, slow_result);
6161 result_i_o ->set_req(_slow_path, i_o());
6162 result_mem ->set_req(_slow_path, reset_memory());
6163 }
6164
6165 // Return the combined state.
6166 set_control( _gvn.transform(result_reg));
6167 set_i_o( _gvn.transform(result_i_o));
6168 set_all_memory( _gvn.transform(result_mem));
6169 } // original reexecute is set back here
6170
6171 set_result(_gvn.transform(result_val));
6172 return true;
6173 }
6174
6175 // If we have a tightly coupled allocation, the arraycopy may take care
6176 // of the array initialization. If one of the guards we insert between
6177 // the allocation and the arraycopy causes a deoptimization, an
6178 // uninitialized array will escape the compiled method. To prevent that
6179 // we set the JVM state for uncommon traps between the allocation and
6180 // the arraycopy to the state before the allocation so, in case of
6181 // deoptimization, we'll reexecute the allocation and the
6182 // initialization.
6183 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6184 if (alloc != nullptr) {
6185 ciMethod* trap_method = alloc->jvms()->method();
6186 int trap_bci = alloc->jvms()->bci();
6187
6188 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6189 !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6190 // Make sure there's no store between the allocation and the
6191 // arraycopy otherwise visible side effects could be rexecuted
6192 // in case of deoptimization and cause incorrect execution.
6193 bool no_interfering_store = true;
6194 Node* mem = alloc->in(TypeFunc::Memory);
6195 if (mem->is_MergeMem()) {
6196 for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6197 Node* n = mms.memory();
6198 if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6199 assert(n->is_Store(), "what else?");
6200 no_interfering_store = false;
6201 break;
6202 }
6203 }
6204 } else {
6205 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6206 Node* n = mms.memory();
6207 if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6208 assert(n->is_Store(), "what else?");
6209 no_interfering_store = false;
6210 break;
6211 }
6212 }
6213 }
6214
6215 if (no_interfering_store) {
6216 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6217
6218 JVMState* saved_jvms = jvms();
6219 saved_reexecute_sp = _reexecute_sp;
6220
6221 set_jvms(sfpt->jvms());
6222 _reexecute_sp = jvms()->sp();
6223
6224 return saved_jvms;
6225 }
6226 }
6227 }
6228 return nullptr;
6229 }
6230
6231 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6232 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6233 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6234 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6235 uint size = alloc->req();
6236 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6237 old_jvms->set_map(sfpt);
6238 for (uint i = 0; i < size; i++) {
6239 sfpt->init_req(i, alloc->in(i));
6240 }
6241 int adjustment = 1;
6242 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6243 if (ary_klass_ptr->is_null_free()) {
6244 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6245 // also requires the componentType and initVal on stack for re-execution.
6246 // Re-create and push the componentType.
6247 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6248 ciInstance* instance = klass->component_mirror_instance();
6249 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6250 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6251 adjustment++;
6252 }
6253 // re-push array length for deoptimization
6254 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6255 if (ary_klass_ptr->is_null_free()) {
6256 // Re-create and push the initVal.
6257 Node* init_val = alloc->in(AllocateNode::InitValue);
6258 if (init_val == nullptr) {
6259 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6260 } else if (UseCompressedOops) {
6261 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6262 }
6263 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6264 adjustment++;
6265 }
6266 old_jvms->set_sp(old_jvms->sp() + adjustment);
6267 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6268 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6269 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6270 old_jvms->set_should_reexecute(true);
6271
6272 sfpt->set_i_o(map()->i_o());
6273 sfpt->set_memory(map()->memory());
6274 sfpt->set_control(map()->control());
6275 return sfpt;
6276 }
6277
6278 // In case of a deoptimization, we restart execution at the
6279 // allocation, allocating a new array. We would leave an uninitialized
6280 // array in the heap that GCs wouldn't expect. Move the allocation
6281 // after the traps so we don't allocate the array if we
6282 // deoptimize. This is possible because tightly_coupled_allocation()
6283 // guarantees there's no observer of the allocated array at this point
6284 // and the control flow is simple enough.
6285 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6286 int saved_reexecute_sp, uint new_idx) {
6287 if (saved_jvms_before_guards != nullptr && !stopped()) {
6288 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6289
6290 assert(alloc != nullptr, "only with a tightly coupled allocation");
6291 // restore JVM state to the state at the arraycopy
6292 saved_jvms_before_guards->map()->set_control(map()->control());
6293 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6294 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6295 // If we've improved the types of some nodes (null check) while
6296 // emitting the guards, propagate them to the current state
6297 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6298 set_jvms(saved_jvms_before_guards);
6299 _reexecute_sp = saved_reexecute_sp;
6300
6301 // Remove the allocation from above the guards
6302 CallProjections* callprojs = alloc->extract_projections(true);
6303 InitializeNode* init = alloc->initialization();
6304 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6305 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6306 init->replace_mem_projs_by(alloc_mem, C);
6307
6308 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6309 // the allocation (i.e. is only valid if the allocation succeeds):
6310 // 1) replace CastIINode with AllocateArrayNode's length here
6311 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6312 //
6313 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6314 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6315 Node* init_control = init->proj_out(TypeFunc::Control);
6316 Node* alloc_length = alloc->Ideal_length();
6317 #ifdef ASSERT
6318 Node* prev_cast = nullptr;
6319 #endif
6320 for (uint i = 0; i < init_control->outcnt(); i++) {
6321 Node* init_out = init_control->raw_out(i);
6322 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6323 #ifdef ASSERT
6324 if (prev_cast == nullptr) {
6325 prev_cast = init_out;
6326 } else {
6327 if (prev_cast->cmp(*init_out) == false) {
6328 prev_cast->dump();
6329 init_out->dump();
6330 assert(false, "not equal CastIINode");
6331 }
6332 }
6333 #endif
6334 C->gvn_replace_by(init_out, alloc_length);
6335 }
6336 }
6337 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6338
6339 // move the allocation here (after the guards)
6340 _gvn.hash_delete(alloc);
6341 alloc->set_req(TypeFunc::Control, control());
6342 alloc->set_req(TypeFunc::I_O, i_o());
6343 Node *mem = reset_memory();
6344 set_all_memory(mem);
6345 alloc->set_req(TypeFunc::Memory, mem);
6346 set_control(init->proj_out_or_null(TypeFunc::Control));
6347 set_i_o(callprojs->fallthrough_ioproj);
6348
6349 // Update memory as done in GraphKit::set_output_for_allocation()
6350 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6351 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6352 if (ary_type->isa_aryptr() && length_type != nullptr) {
6353 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6354 }
6355 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6356 int elemidx = C->get_alias_index(telemref);
6357 // Need to properly move every memory projection for the Initialize
6358 #ifdef ASSERT
6359 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6360 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6361 #endif
6362 auto move_proj = [&](ProjNode* proj) {
6363 int alias_idx = C->get_alias_index(proj->adr_type());
6364 assert(alias_idx == Compile::AliasIdxRaw ||
6365 alias_idx == elemidx ||
6366 alias_idx == mark_idx ||
6367 alias_idx == klass_idx, "should be raw memory or array element type");
6368 set_memory(proj, alias_idx);
6369 };
6370 init->for_each_proj(move_proj, TypeFunc::Memory);
6371
6372 Node* allocx = _gvn.transform(alloc);
6373 assert(allocx == alloc, "where has the allocation gone?");
6374 assert(dest->is_CheckCastPP(), "not an allocation result?");
6375
6376 _gvn.hash_delete(dest);
6377 dest->set_req(0, control());
6378 Node* destx = _gvn.transform(dest);
6379 assert(destx == dest, "where has the allocation result gone?");
6380
6381 array_ideal_length(alloc, ary_type, true);
6382 }
6383 }
6384
6385 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6386 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6387 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6388 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6389 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6390 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6391 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6392 JVMState* saved_jvms_before_guards) {
6393 if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6394 // There is at least one unrelated uncommon trap which needs to be replaced.
6395 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6396
6397 JVMState* saved_jvms = jvms();
6398 const int saved_reexecute_sp = _reexecute_sp;
6399 set_jvms(sfpt->jvms());
6400 _reexecute_sp = jvms()->sp();
6401
6402 replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6403
6404 // Restore state
6405 set_jvms(saved_jvms);
6406 _reexecute_sp = saved_reexecute_sp;
6407 }
6408 }
6409
6410 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6411 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6412 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6413 Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6414 while (if_proj->is_IfProj()) {
6415 CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6416 if (uncommon_trap != nullptr) {
6417 create_new_uncommon_trap(uncommon_trap);
6418 }
6419 assert(if_proj->in(0)->is_If(), "must be If");
6420 if_proj = if_proj->in(0)->in(0);
6421 }
6422 assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6423 "must have reached control projection of init node");
6424 }
6425
6426 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6427 const int trap_request = uncommon_trap_call->uncommon_trap_request();
6428 assert(trap_request != 0, "no valid UCT trap request");
6429 PreserveJVMState pjvms(this);
6430 set_control(uncommon_trap_call->in(0));
6431 uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6432 Deoptimization::trap_request_action(trap_request));
6433 assert(stopped(), "Should be stopped");
6434 _gvn.hash_delete(uncommon_trap_call);
6435 uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6436 }
6437
6438 // Common checks for array sorting intrinsics arguments.
6439 // Returns `true` if checks passed.
6440 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6441 // check address of the class
6442 if (elementType == nullptr || elementType->is_top()) {
6443 return false; // dead path
6444 }
6445 const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6446 if (elem_klass == nullptr) {
6447 return false; // dead path
6448 }
6449 // java_mirror_type() returns non-null for compile-time Class constants only
6450 ciType* elem_type = elem_klass->java_mirror_type();
6451 if (elem_type == nullptr) {
6452 return false;
6453 }
6454 bt = elem_type->basic_type();
6455 // Disable the intrinsic if the CPU does not support SIMD sort
6456 if (!Matcher::supports_simd_sort(bt)) {
6457 return false;
6458 }
6459 // check address of the array
6460 if (obj == nullptr || obj->is_top()) {
6461 return false; // dead path
6462 }
6463 const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6464 if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6465 return false; // failed input validation
6466 }
6467 return true;
6468 }
6469
6470 //------------------------------inline_array_partition-----------------------
6471 bool LibraryCallKit::inline_array_partition() {
6472 address stubAddr = StubRoutines::select_array_partition_function();
6473 if (stubAddr == nullptr) {
6474 return false; // Intrinsic's stub is not implemented on this platform
6475 }
6476 assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6477
6478 // no receiver because it is a static method
6479 Node* elementType = argument(0);
6480 Node* obj = argument(1);
6481 Node* offset = argument(2); // long
6482 Node* fromIndex = argument(4);
6483 Node* toIndex = argument(5);
6484 Node* indexPivot1 = argument(6);
6485 Node* indexPivot2 = argument(7);
6486 // PartitionOperation: argument(8) is ignored
6487
6488 Node* pivotIndices = nullptr;
6489 BasicType bt = T_ILLEGAL;
6490
6491 if (!check_array_sort_arguments(elementType, obj, bt)) {
6492 return false;
6493 }
6494 null_check(obj);
6495 // If obj is dead, only null-path is taken.
6496 if (stopped()) {
6497 return true;
6498 }
6499 // Set the original stack and the reexecute bit for the interpreter to reexecute
6500 // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6501 { PreserveReexecuteState preexecs(this);
6502 jvms()->set_should_reexecute(true);
6503
6504 Node* obj_adr = make_unsafe_address(obj, offset);
6505
6506 // create the pivotIndices array of type int and size = 2
6507 Node* size = intcon(2);
6508 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6509 pivotIndices = new_array(klass_node, size, 0); // no arguments to push
6510 AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6511 guarantee(alloc != nullptr, "created above");
6512 Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6513
6514 // pass the basic type enum to the stub
6515 Node* elemType = intcon(bt);
6516
6517 // Call the stub
6518 const char *stubName = "array_partition_stub";
6519 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6520 stubAddr, stubName, TypePtr::BOTTOM,
6521 obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6522 indexPivot1, indexPivot2);
6523
6524 } // original reexecute is set back here
6525
6526 if (!stopped()) {
6527 set_result(pivotIndices);
6528 }
6529
6530 return true;
6531 }
6532
6533
6534 //------------------------------inline_array_sort-----------------------
6535 bool LibraryCallKit::inline_array_sort() {
6536 address stubAddr = StubRoutines::select_arraysort_function();
6537 if (stubAddr == nullptr) {
6538 return false; // Intrinsic's stub is not implemented on this platform
6539 }
6540 assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6541
6542 // no receiver because it is a static method
6543 Node* elementType = argument(0);
6544 Node* obj = argument(1);
6545 Node* offset = argument(2); // long
6546 Node* fromIndex = argument(4);
6547 Node* toIndex = argument(5);
6548 // SortOperation: argument(6) is ignored
6549
6550 BasicType bt = T_ILLEGAL;
6551
6552 if (!check_array_sort_arguments(elementType, obj, bt)) {
6553 return false;
6554 }
6555 null_check(obj);
6556 // If obj is dead, only null-path is taken.
6557 if (stopped()) {
6558 return true;
6559 }
6560 Node* obj_adr = make_unsafe_address(obj, offset);
6561
6562 // pass the basic type enum to the stub
6563 Node* elemType = intcon(bt);
6564
6565 // Call the stub.
6566 const char *stubName = "arraysort_stub";
6567 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6568 stubAddr, stubName, TypePtr::BOTTOM,
6569 obj_adr, elemType, fromIndex, toIndex);
6570
6571 return true;
6572 }
6573
6574
6575 //------------------------------inline_arraycopy-----------------------
6576 // public static native void java.lang.System.arraycopy(Object src, int srcPos,
6577 // Object dest, int destPos,
6578 // int length);
6579 bool LibraryCallKit::inline_arraycopy() {
6580 // Get the arguments.
6581 Node* src = argument(0); // type: oop
6582 Node* src_offset = argument(1); // type: int
6583 Node* dest = argument(2); // type: oop
6584 Node* dest_offset = argument(3); // type: int
6585 Node* length = argument(4); // type: int
6586
6587 uint new_idx = C->unique();
6588
6589 // Check for allocation before we add nodes that would confuse
6590 // tightly_coupled_allocation()
6591 AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6592
6593 int saved_reexecute_sp = -1;
6594 JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6595 // See arraycopy_restore_alloc_state() comment
6596 // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6597 // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6598 // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6599 bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6600
6601 // The following tests must be performed
6602 // (1) src and dest are arrays.
6603 // (2) src and dest arrays must have elements of the same BasicType
6604 // (3) src and dest must not be null.
6605 // (4) src_offset must not be negative.
6606 // (5) dest_offset must not be negative.
6607 // (6) length must not be negative.
6608 // (7) src_offset + length must not exceed length of src.
6609 // (8) dest_offset + length must not exceed length of dest.
6610 // (9) each element of an oop array must be assignable
6611
6612 // (3) src and dest must not be null.
6613 // always do this here because we need the JVM state for uncommon traps
6614 Node* null_ctl = top();
6615 src = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6616 assert(null_ctl->is_top(), "no null control here");
6617 dest = null_check(dest, T_ARRAY);
6618
6619 if (!can_emit_guards) {
6620 // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6621 // guards but the arraycopy node could still take advantage of a
6622 // tightly allocated allocation. tightly_coupled_allocation() is
6623 // called again to make sure it takes the null check above into
6624 // account: the null check is mandatory and if it caused an
6625 // uncommon trap to be emitted then the allocation can't be
6626 // considered tightly coupled in this context.
6627 alloc = tightly_coupled_allocation(dest);
6628 }
6629
6630 bool validated = false;
6631
6632 const Type* src_type = _gvn.type(src);
6633 const Type* dest_type = _gvn.type(dest);
6634 const TypeAryPtr* top_src = src_type->isa_aryptr();
6635 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6636
6637 // Do we have the type of src?
6638 bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6639 // Do we have the type of dest?
6640 bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6641 // Is the type for src from speculation?
6642 bool src_spec = false;
6643 // Is the type for dest from speculation?
6644 bool dest_spec = false;
6645
6646 if ((!has_src || !has_dest) && can_emit_guards) {
6647 // We don't have sufficient type information, let's see if
6648 // speculative types can help. We need to have types for both src
6649 // and dest so that it pays off.
6650
6651 // Do we already have or could we have type information for src
6652 bool could_have_src = has_src;
6653 // Do we already have or could we have type information for dest
6654 bool could_have_dest = has_dest;
6655
6656 ciKlass* src_k = nullptr;
6657 if (!has_src) {
6658 src_k = src_type->speculative_type_not_null();
6659 if (src_k != nullptr && src_k->is_array_klass()) {
6660 could_have_src = true;
6661 }
6662 }
6663
6664 ciKlass* dest_k = nullptr;
6665 if (!has_dest) {
6666 dest_k = dest_type->speculative_type_not_null();
6667 if (dest_k != nullptr && dest_k->is_array_klass()) {
6668 could_have_dest = true;
6669 }
6670 }
6671
6672 if (could_have_src && could_have_dest) {
6673 // This is going to pay off so emit the required guards
6674 if (!has_src) {
6675 src = maybe_cast_profiled_obj(src, src_k, true);
6676 src_type = _gvn.type(src);
6677 top_src = src_type->isa_aryptr();
6678 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6679 src_spec = true;
6680 }
6681 if (!has_dest) {
6682 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6683 dest_type = _gvn.type(dest);
6684 top_dest = dest_type->isa_aryptr();
6685 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6686 dest_spec = true;
6687 }
6688 }
6689 }
6690
6691 if (has_src && has_dest && can_emit_guards) {
6692 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6693 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6694 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6695 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6696
6697 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6698 // If both arrays are object arrays then having the exact types
6699 // for both will remove the need for a subtype check at runtime
6700 // before the call and may make it possible to pick a faster copy
6701 // routine (without a subtype check on every element)
6702 // Do we have the exact type of src?
6703 bool could_have_src = src_spec;
6704 // Do we have the exact type of dest?
6705 bool could_have_dest = dest_spec;
6706 ciKlass* src_k = nullptr;
6707 ciKlass* dest_k = nullptr;
6708 if (!src_spec) {
6709 src_k = src_type->speculative_type_not_null();
6710 if (src_k != nullptr && src_k->is_array_klass()) {
6711 could_have_src = true;
6712 }
6713 }
6714 if (!dest_spec) {
6715 dest_k = dest_type->speculative_type_not_null();
6716 if (dest_k != nullptr && dest_k->is_array_klass()) {
6717 could_have_dest = true;
6718 }
6719 }
6720 if (could_have_src && could_have_dest) {
6721 // If we can have both exact types, emit the missing guards
6722 if (could_have_src && !src_spec) {
6723 src = maybe_cast_profiled_obj(src, src_k, true);
6724 src_type = _gvn.type(src);
6725 top_src = src_type->isa_aryptr();
6726 }
6727 if (could_have_dest && !dest_spec) {
6728 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6729 dest_type = _gvn.type(dest);
6730 top_dest = dest_type->isa_aryptr();
6731 }
6732 }
6733 }
6734 }
6735
6736 ciMethod* trap_method = method();
6737 int trap_bci = bci();
6738 if (saved_jvms_before_guards != nullptr) {
6739 trap_method = alloc->jvms()->method();
6740 trap_bci = alloc->jvms()->bci();
6741 }
6742
6743 bool negative_length_guard_generated = false;
6744
6745 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6746 can_emit_guards && !src->is_top() && !dest->is_top()) {
6747 // validate arguments: enables transformation the ArrayCopyNode
6748 validated = true;
6749
6750 RegionNode* slow_region = new RegionNode(1);
6751 record_for_igvn(slow_region);
6752
6753 // (1) src and dest are arrays.
6754 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6755 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6756
6757 // (2) src and dest arrays must have elements of the same BasicType
6758 // done at macro expansion or at Ideal transformation time
6759
6760 // (4) src_offset must not be negative.
6761 generate_negative_guard(src_offset, slow_region);
6762
6763 // (5) dest_offset must not be negative.
6764 generate_negative_guard(dest_offset, slow_region);
6765
6766 // (7) src_offset + length must not exceed length of src.
6767 generate_limit_guard(src_offset, length,
6768 load_array_length(src),
6769 slow_region);
6770
6771 // (8) dest_offset + length must not exceed length of dest.
6772 generate_limit_guard(dest_offset, length,
6773 load_array_length(dest),
6774 slow_region);
6775
6776 // (6) length must not be negative.
6777 // This is also checked in generate_arraycopy() during macro expansion, but
6778 // we also have to check it here for the case where the ArrayCopyNode will
6779 // be eliminated by Escape Analysis.
6780 if (EliminateAllocations) {
6781 generate_negative_guard(length, slow_region);
6782 negative_length_guard_generated = true;
6783 }
6784
6785 // (9) each element of an oop array must be assignable
6786 Node* dest_klass = load_object_klass(dest);
6787 Node* refined_dest_klass = dest_klass;
6788 if (src != dest) {
6789 dest_klass = load_non_refined_array_klass(refined_dest_klass);
6790 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6791 slow_region->add_req(not_subtype_ctrl);
6792 }
6793
6794 // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6795 // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6796 Node* src_klass = load_object_klass(src);
6797 Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6798 Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6799 _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6800 MemNode::unordered));
6801 Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6802 Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6803 _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6804 MemNode::unordered));
6805
6806 const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6807 jint props_value = (jint)props_null_restricted.value();
6808
6809 prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6810 prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6811 prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6812
6813 Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6814 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6815 generate_fair_guard(tst, slow_region);
6816
6817 // TODO 8251971 This is too strong
6818 generate_fair_guard(flat_array_test(src), slow_region);
6819 generate_fair_guard(flat_array_test(dest), slow_region);
6820
6821 {
6822 PreserveJVMState pjvms(this);
6823 set_control(_gvn.transform(slow_region));
6824 uncommon_trap(Deoptimization::Reason_intrinsic,
6825 Deoptimization::Action_make_not_entrant);
6826 assert(stopped(), "Should be stopped");
6827 }
6828
6829 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6830 if (dest_klass_t == nullptr) {
6831 // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6832 // are in a dead path.
6833 uncommon_trap(Deoptimization::Reason_intrinsic,
6834 Deoptimization::Action_make_not_entrant);
6835 return true;
6836 }
6837
6838 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6839 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6840 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6841 }
6842
6843 if (stopped()) {
6844 return true;
6845 }
6846
6847 Node* dest_klass = load_object_klass(dest);
6848 dest_klass = load_non_refined_array_klass(dest_klass);
6849
6850 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6851 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6852 // so the compiler has a chance to eliminate them: during macro expansion,
6853 // we have to set their control (CastPP nodes are eliminated).
6854 load_object_klass(src), dest_klass,
6855 load_array_length(src), load_array_length(dest));
6856
6857 ac->set_arraycopy(validated);
6858
6859 Node* n = _gvn.transform(ac);
6860 if (n == ac) {
6861 ac->connect_outputs(this);
6862 } else {
6863 assert(validated, "shouldn't transform if all arguments not validated");
6864 set_all_memory(n);
6865 }
6866 clear_upper_avx();
6867
6868
6869 return true;
6870 }
6871
6872
6873 // Helper function which determines if an arraycopy immediately follows
6874 // an allocation, with no intervening tests or other escapes for the object.
6875 AllocateArrayNode*
6876 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6877 if (stopped()) return nullptr; // no fast path
6878 if (!C->do_aliasing()) return nullptr; // no MergeMems around
6879
6880 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6881 if (alloc == nullptr) return nullptr;
6882
6883 Node* rawmem = memory(Compile::AliasIdxRaw);
6884 // Is the allocation's memory state untouched?
6885 if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6886 // Bail out if there have been raw-memory effects since the allocation.
6887 // (Example: There might have been a call or safepoint.)
6888 return nullptr;
6889 }
6890 rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6891 if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6892 return nullptr;
6893 }
6894
6895 // There must be no unexpected observers of this allocation.
6896 for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6897 Node* obs = ptr->fast_out(i);
6898 if (obs != this->map()) {
6899 return nullptr;
6900 }
6901 }
6902
6903 // This arraycopy must unconditionally follow the allocation of the ptr.
6904 Node* alloc_ctl = ptr->in(0);
6905 Node* ctl = control();
6906 while (ctl != alloc_ctl) {
6907 // There may be guards which feed into the slow_region.
6908 // Any other control flow means that we might not get a chance
6909 // to finish initializing the allocated object.
6910 // Various low-level checks bottom out in uncommon traps. These
6911 // are considered safe since we've already checked above that
6912 // there is no unexpected observer of this allocation.
6913 if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6914 assert(ctl->in(0)->is_If(), "must be If");
6915 ctl = ctl->in(0)->in(0);
6916 } else {
6917 return nullptr;
6918 }
6919 }
6920
6921 // If we get this far, we have an allocation which immediately
6922 // precedes the arraycopy, and we can take over zeroing the new object.
6923 // The arraycopy will finish the initialization, and provide
6924 // a new control state to which we will anchor the destination pointer.
6925
6926 return alloc;
6927 }
6928
6929 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6930 if (node->is_IfProj()) {
6931 IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6932 for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6933 Node* obs = other_proj->fast_out(j);
6934 if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6935 (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6936 return obs->as_CallStaticJava();
6937 }
6938 }
6939 }
6940 return nullptr;
6941 }
6942
6943 //-------------inline_encodeISOArray-----------------------------------
6944 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6945 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6946 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6947 // encode char[] to byte[] in ISO_8859_1 or ASCII
6948 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6949 assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6950 // no receiver since it is static method
6951 Node *src = argument(0);
6952 Node *src_offset = argument(1);
6953 Node *dst = argument(2);
6954 Node *dst_offset = argument(3);
6955 Node *length = argument(4);
6956
6957 // Cast source & target arrays to not-null
6958 src = must_be_not_null(src, true);
6959 dst = must_be_not_null(dst, true);
6960 if (stopped()) {
6961 return true;
6962 }
6963
6964 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6965 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6966 if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6967 dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6968 // failed array check
6969 return false;
6970 }
6971
6972 // Figure out the size and type of the elements we will be copying.
6973 BasicType src_elem = src_type->elem()->array_element_basic_type();
6974 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6975 if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6976 return false;
6977 }
6978
6979 // Check source & target bounds
6980 RegionNode* bailout = create_bailout();
6981 generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6982 generate_string_range_check(dst, dst_offset, length, false, bailout);
6983 if (check_bailout(bailout)) {
6984 return true;
6985 }
6986
6987 Node* src_start = array_element_address(src, src_offset, T_CHAR);
6988 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6989 // 'src_start' points to src array + scaled offset
6990 // 'dst_start' points to dst array + scaled offset
6991
6992 // See GraphKit::compress_string
6993 const TypePtr* adr_type;
6994 Node* mem = capture_memory(adr_type, src_type, dst_type);
6995 Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii);
6996 enc = _gvn.transform(enc);
6997 Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6998 memory_effect(res_mem, src_type, dst_type);
6999
7000 set_result(enc);
7001 clear_upper_avx();
7002
7003 return true;
7004 }
7005
7006 //-------------inline_multiplyToLen-----------------------------------
7007 bool LibraryCallKit::inline_multiplyToLen() {
7008 assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
7009
7010 address stubAddr = StubRoutines::multiplyToLen();
7011 if (stubAddr == nullptr) {
7012 return false; // Intrinsic's stub is not implemented on this platform
7013 }
7014 const char* stubName = "multiplyToLen";
7015
7016 assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
7017
7018 // no receiver because it is a static method
7019 Node* x = argument(0);
7020 Node* xlen = argument(1);
7021 Node* y = argument(2);
7022 Node* ylen = argument(3);
7023 Node* z = argument(4);
7024
7025 x = must_be_not_null(x, true);
7026 y = must_be_not_null(y, true);
7027
7028 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7029 const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
7030 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7031 y_type == nullptr || y_type->elem() == Type::BOTTOM) {
7032 // failed array check
7033 return false;
7034 }
7035
7036 BasicType x_elem = x_type->elem()->array_element_basic_type();
7037 BasicType y_elem = y_type->elem()->array_element_basic_type();
7038 if (x_elem != T_INT || y_elem != T_INT) {
7039 return false;
7040 }
7041
7042 Node* x_start = array_element_address(x, intcon(0), x_elem);
7043 Node* y_start = array_element_address(y, intcon(0), y_elem);
7044 // 'x_start' points to x array + scaled xlen
7045 // 'y_start' points to y array + scaled ylen
7046
7047 Node* z_start = array_element_address(z, intcon(0), T_INT);
7048
7049 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7050 OptoRuntime::multiplyToLen_Type(),
7051 stubAddr, stubName, TypePtr::BOTTOM,
7052 x_start, xlen, y_start, ylen, z_start);
7053
7054 C->set_has_split_ifs(true); // Has chance for split-if optimization
7055 set_result(z);
7056 return true;
7057 }
7058
7059 //-------------inline_squareToLen------------------------------------
7060 bool LibraryCallKit::inline_squareToLen() {
7061 assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7062
7063 address stubAddr = StubRoutines::squareToLen();
7064 if (stubAddr == nullptr) {
7065 return false; // Intrinsic's stub is not implemented on this platform
7066 }
7067 const char* stubName = "squareToLen";
7068
7069 assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7070
7071 Node* x = argument(0);
7072 Node* len = argument(1);
7073 Node* z = argument(2);
7074 Node* zlen = argument(3);
7075
7076 x = must_be_not_null(x, true);
7077 z = must_be_not_null(z, true);
7078
7079 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7080 const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7081 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7082 z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7083 // failed array check
7084 return false;
7085 }
7086
7087 BasicType x_elem = x_type->elem()->array_element_basic_type();
7088 BasicType z_elem = z_type->elem()->array_element_basic_type();
7089 if (x_elem != T_INT || z_elem != T_INT) {
7090 return false;
7091 }
7092
7093
7094 Node* x_start = array_element_address(x, intcon(0), x_elem);
7095 Node* z_start = array_element_address(z, intcon(0), z_elem);
7096
7097 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7098 OptoRuntime::squareToLen_Type(),
7099 stubAddr, stubName, TypePtr::BOTTOM,
7100 x_start, len, z_start, zlen);
7101
7102 set_result(z);
7103 return true;
7104 }
7105
7106 //-------------inline_mulAdd------------------------------------------
7107 bool LibraryCallKit::inline_mulAdd() {
7108 assert(UseMulAddIntrinsic, "not implemented on this platform");
7109
7110 address stubAddr = StubRoutines::mulAdd();
7111 if (stubAddr == nullptr) {
7112 return false; // Intrinsic's stub is not implemented on this platform
7113 }
7114 const char* stubName = "mulAdd";
7115
7116 assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7117
7118 Node* out = argument(0);
7119 Node* in = argument(1);
7120 Node* offset = argument(2);
7121 Node* len = argument(3);
7122 Node* k = argument(4);
7123
7124 in = must_be_not_null(in, true);
7125 out = must_be_not_null(out, true);
7126
7127 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7128 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7129 if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7130 in_type == nullptr || in_type->elem() == Type::BOTTOM) {
7131 // failed array check
7132 return false;
7133 }
7134
7135 BasicType out_elem = out_type->elem()->array_element_basic_type();
7136 BasicType in_elem = in_type->elem()->array_element_basic_type();
7137 if (out_elem != T_INT || in_elem != T_INT) {
7138 return false;
7139 }
7140
7141 Node* outlen = load_array_length(out);
7142 Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7143 Node* out_start = array_element_address(out, intcon(0), out_elem);
7144 Node* in_start = array_element_address(in, intcon(0), in_elem);
7145
7146 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7147 OptoRuntime::mulAdd_Type(),
7148 stubAddr, stubName, TypePtr::BOTTOM,
7149 out_start,in_start, new_offset, len, k);
7150 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7151 set_result(result);
7152 return true;
7153 }
7154
7155 //-------------inline_montgomeryMultiply-----------------------------------
7156 bool LibraryCallKit::inline_montgomeryMultiply() {
7157 address stubAddr = StubRoutines::montgomeryMultiply();
7158 if (stubAddr == nullptr) {
7159 return false; // Intrinsic's stub is not implemented on this platform
7160 }
7161
7162 assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7163 const char* stubName = "montgomery_multiply";
7164
7165 assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7166
7167 Node* a = argument(0);
7168 Node* b = argument(1);
7169 Node* n = argument(2);
7170 Node* len = argument(3);
7171 Node* inv = argument(4);
7172 Node* m = argument(6);
7173
7174 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7175 const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7176 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7177 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7178 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7179 b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7180 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7181 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7182 // failed array check
7183 return false;
7184 }
7185
7186 BasicType a_elem = a_type->elem()->array_element_basic_type();
7187 BasicType b_elem = b_type->elem()->array_element_basic_type();
7188 BasicType n_elem = n_type->elem()->array_element_basic_type();
7189 BasicType m_elem = m_type->elem()->array_element_basic_type();
7190 if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7191 return false;
7192 }
7193
7194 // Make the call
7195 {
7196 Node* a_start = array_element_address(a, intcon(0), a_elem);
7197 Node* b_start = array_element_address(b, intcon(0), b_elem);
7198 Node* n_start = array_element_address(n, intcon(0), n_elem);
7199 Node* m_start = array_element_address(m, intcon(0), m_elem);
7200
7201 Node* call = make_runtime_call(RC_LEAF,
7202 OptoRuntime::montgomeryMultiply_Type(),
7203 stubAddr, stubName, TypePtr::BOTTOM,
7204 a_start, b_start, n_start, len, inv, top(),
7205 m_start);
7206 set_result(m);
7207 }
7208
7209 return true;
7210 }
7211
7212 bool LibraryCallKit::inline_montgomerySquare() {
7213 address stubAddr = StubRoutines::montgomerySquare();
7214 if (stubAddr == nullptr) {
7215 return false; // Intrinsic's stub is not implemented on this platform
7216 }
7217
7218 assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7219 const char* stubName = "montgomery_square";
7220
7221 assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7222
7223 Node* a = argument(0);
7224 Node* n = argument(1);
7225 Node* len = argument(2);
7226 Node* inv = argument(3);
7227 Node* m = argument(5);
7228
7229 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7230 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7231 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7232 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7233 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7234 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7235 // failed array check
7236 return false;
7237 }
7238
7239 BasicType a_elem = a_type->elem()->array_element_basic_type();
7240 BasicType n_elem = n_type->elem()->array_element_basic_type();
7241 BasicType m_elem = m_type->elem()->array_element_basic_type();
7242 if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7243 return false;
7244 }
7245
7246 // Make the call
7247 {
7248 Node* a_start = array_element_address(a, intcon(0), a_elem);
7249 Node* n_start = array_element_address(n, intcon(0), n_elem);
7250 Node* m_start = array_element_address(m, intcon(0), m_elem);
7251
7252 Node* call = make_runtime_call(RC_LEAF,
7253 OptoRuntime::montgomerySquare_Type(),
7254 stubAddr, stubName, TypePtr::BOTTOM,
7255 a_start, n_start, len, inv, top(),
7256 m_start);
7257 set_result(m);
7258 }
7259
7260 return true;
7261 }
7262
7263 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7264 address stubAddr = nullptr;
7265 const char* stubName = nullptr;
7266
7267 stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7268 if (stubAddr == nullptr) {
7269 return false; // Intrinsic's stub is not implemented on this platform
7270 }
7271
7272 stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7273
7274 assert(callee()->signature()->size() == 5, "expected 5 arguments");
7275
7276 Node* newArr = argument(0);
7277 Node* oldArr = argument(1);
7278 Node* newIdx = argument(2);
7279 Node* shiftCount = argument(3);
7280 Node* numIter = argument(4);
7281
7282 const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7283 const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7284 if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7285 oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7286 return false;
7287 }
7288
7289 BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7290 BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7291 if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7292 return false;
7293 }
7294
7295 // Make the call
7296 {
7297 Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7298 Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7299
7300 Node* call = make_runtime_call(RC_LEAF,
7301 OptoRuntime::bigIntegerShift_Type(),
7302 stubAddr,
7303 stubName,
7304 TypePtr::BOTTOM,
7305 newArr_start,
7306 oldArr_start,
7307 newIdx,
7308 shiftCount,
7309 numIter);
7310 }
7311
7312 return true;
7313 }
7314
7315 //-------------inline_vectorizedMismatch------------------------------
7316 bool LibraryCallKit::inline_vectorizedMismatch() {
7317 assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7318
7319 assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7320 Node* obja = argument(0); // Object
7321 Node* aoffset = argument(1); // long
7322 Node* objb = argument(3); // Object
7323 Node* boffset = argument(4); // long
7324 Node* length = argument(6); // int
7325 Node* scale = argument(7); // int
7326
7327 const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7328 const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7329 if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7330 objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7331 scale == top()) {
7332 return false; // failed input validation
7333 }
7334
7335 Node* obja_adr = make_unsafe_address(obja, aoffset);
7336 Node* objb_adr = make_unsafe_address(objb, boffset);
7337
7338 // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7339 //
7340 // inline_limit = ArrayOperationPartialInlineSize / element_size;
7341 // if (length <= inline_limit) {
7342 // inline_path:
7343 // vmask = VectorMaskGen length
7344 // vload1 = LoadVectorMasked obja, vmask
7345 // vload2 = LoadVectorMasked objb, vmask
7346 // result1 = VectorCmpMasked vload1, vload2, vmask
7347 // } else {
7348 // call_stub_path:
7349 // result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7350 // }
7351 // exit_block:
7352 // return Phi(result1, result2);
7353 //
7354 enum { inline_path = 1, // input is small enough to process it all at once
7355 stub_path = 2, // input is too large; call into the VM
7356 PATH_LIMIT = 3
7357 };
7358
7359 Node* exit_block = new RegionNode(PATH_LIMIT);
7360 Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7361 Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7362
7363 Node* call_stub_path = control();
7364
7365 BasicType elem_bt = T_ILLEGAL;
7366
7367 const TypeInt* scale_t = _gvn.type(scale)->is_int();
7368 if (scale_t->is_con()) {
7369 switch (scale_t->get_con()) {
7370 case 0: elem_bt = T_BYTE; break;
7371 case 1: elem_bt = T_SHORT; break;
7372 case 2: elem_bt = T_INT; break;
7373 case 3: elem_bt = T_LONG; break;
7374
7375 default: elem_bt = T_ILLEGAL; break; // not supported
7376 }
7377 }
7378
7379 int inline_limit = 0;
7380 bool do_partial_inline = false;
7381
7382 if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7383 inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7384 do_partial_inline = inline_limit >= 16;
7385 }
7386
7387 if (do_partial_inline) {
7388 assert(elem_bt != T_ILLEGAL, "sanity");
7389
7390 if (Matcher::match_rule_supported_vector(Op_VectorMaskGen, inline_limit, elem_bt) &&
7391 Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7392 Matcher::match_rule_supported_vector(Op_VectorCmpMasked, inline_limit, elem_bt)) {
7393
7394 const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7395 Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7396 Node* bol_gt = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7397
7398 call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7399
7400 if (!stopped()) {
7401 Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7402
7403 const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7404 const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7405 Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7406 Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7407
7408 Node* vmask = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7409 Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7410 Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7411 Node* result = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7412
7413 exit_block->init_req(inline_path, control());
7414 memory_phi->init_req(inline_path, map()->memory());
7415 result_phi->init_req(inline_path, result);
7416
7417 C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7418 clear_upper_avx();
7419 }
7420 }
7421 }
7422
7423 if (call_stub_path != nullptr) {
7424 set_control(call_stub_path);
7425
7426 Node* call = make_runtime_call(RC_LEAF,
7427 OptoRuntime::vectorizedMismatch_Type(),
7428 StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7429 obja_adr, objb_adr, length, scale);
7430
7431 exit_block->init_req(stub_path, control());
7432 memory_phi->init_req(stub_path, map()->memory());
7433 result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7434 }
7435
7436 exit_block = _gvn.transform(exit_block);
7437 memory_phi = _gvn.transform(memory_phi);
7438 result_phi = _gvn.transform(result_phi);
7439
7440 record_for_igvn(exit_block);
7441 record_for_igvn(memory_phi);
7442 record_for_igvn(result_phi);
7443
7444 set_control(exit_block);
7445 set_all_memory(memory_phi);
7446 set_result(result_phi);
7447
7448 return true;
7449 }
7450
7451 //------------------------------inline_vectorizedHashcode----------------------------
7452 bool LibraryCallKit::inline_vectorizedHashCode() {
7453 assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7454
7455 assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7456 Node* array = argument(0);
7457 Node* offset = argument(1);
7458 Node* length = argument(2);
7459 Node* initialValue = argument(3);
7460 Node* basic_type = argument(4);
7461
7462 if (basic_type == top()) {
7463 return false; // failed input validation
7464 }
7465
7466 const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7467 if (!basic_type_t->is_con()) {
7468 return false; // Only intrinsify if mode argument is constant
7469 }
7470
7471 array = must_be_not_null(array, true);
7472
7473 BasicType bt = (BasicType)basic_type_t->get_con();
7474
7475 // Resolve address of first element
7476 Node* array_start = array_element_address(array, offset, bt);
7477
7478 const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt);
7479 set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type,
7480 array_start, length, initialValue, basic_type)));
7481 clear_upper_avx();
7482
7483 return true;
7484 }
7485
7486 /**
7487 * Calculate CRC32 for byte.
7488 * int java.util.zip.CRC32.update(int crc, int b)
7489 */
7490 bool LibraryCallKit::inline_updateCRC32() {
7491 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7492 assert(callee()->signature()->size() == 2, "update has 2 parameters");
7493 // no receiver since it is static method
7494 Node* crc = argument(0); // type: int
7495 Node* b = argument(1); // type: int
7496
7497 /*
7498 * int c = ~ crc;
7499 * b = timesXtoThe32[(b ^ c) & 0xFF];
7500 * b = b ^ (c >>> 8);
7501 * crc = ~b;
7502 */
7503
7504 Node* M1 = intcon(-1);
7505 crc = _gvn.transform(new XorINode(crc, M1));
7506 Node* result = _gvn.transform(new XorINode(crc, b));
7507 result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7508
7509 Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7510 Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7511 Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7512 result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7513
7514 crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7515 result = _gvn.transform(new XorINode(crc, result));
7516 result = _gvn.transform(new XorINode(result, M1));
7517 set_result(result);
7518 return true;
7519 }
7520
7521 /**
7522 * Calculate CRC32 for byte[] array.
7523 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7524 */
7525 bool LibraryCallKit::inline_updateBytesCRC32() {
7526 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7527 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7528 // no receiver since it is static method
7529 Node* crc = argument(0); // type: int
7530 Node* src = argument(1); // type: oop
7531 Node* offset = argument(2); // type: int
7532 Node* length = argument(3); // type: int
7533
7534 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7535 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7536 // failed array check
7537 return false;
7538 }
7539
7540 // Figure out the size and type of the elements we will be copying.
7541 BasicType src_elem = src_type->elem()->array_element_basic_type();
7542 if (src_elem != T_BYTE) {
7543 return false;
7544 }
7545
7546 // 'src_start' points to src array + scaled offset
7547 src = must_be_not_null(src, true);
7548 Node* src_start = array_element_address(src, offset, src_elem);
7549
7550 // We assume that range check is done by caller.
7551 // TODO: generate range check (offset+length < src.length) in debug VM.
7552
7553 // Call the stub.
7554 address stubAddr = StubRoutines::updateBytesCRC32();
7555 const char *stubName = "updateBytesCRC32";
7556
7557 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7558 stubAddr, stubName, TypePtr::BOTTOM,
7559 crc, src_start, length);
7560 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7561 set_result(result);
7562 return true;
7563 }
7564
7565 /**
7566 * Calculate CRC32 for ByteBuffer.
7567 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7568 */
7569 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7570 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7571 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7572 // no receiver since it is static method
7573 Node* crc = argument(0); // type: int
7574 Node* src = argument(1); // type: long
7575 Node* offset = argument(3); // type: int
7576 Node* length = argument(4); // type: int
7577
7578 src = ConvL2X(src); // adjust Java long to machine word
7579 Node* base = _gvn.transform(new CastX2PNode(src));
7580 offset = ConvI2X(offset);
7581
7582 // 'src_start' points to src array + scaled offset
7583 Node* src_start = off_heap_plus_addr(base, offset);
7584
7585 // Call the stub.
7586 address stubAddr = StubRoutines::updateBytesCRC32();
7587 const char *stubName = "updateBytesCRC32";
7588
7589 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7590 stubAddr, stubName, TypePtr::BOTTOM,
7591 crc, src_start, length);
7592 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7593 set_result(result);
7594 return true;
7595 }
7596
7597 //------------------------------get_table_from_crc32c_class-----------------------
7598 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7599 Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7600 assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7601
7602 return table;
7603 }
7604
7605 //------------------------------inline_updateBytesCRC32C-----------------------
7606 //
7607 // Calculate CRC32C for byte[] array.
7608 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7609 //
7610 bool LibraryCallKit::inline_updateBytesCRC32C() {
7611 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7612 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7613 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7614 // no receiver since it is a static method
7615 Node* crc = argument(0); // type: int
7616 Node* src = argument(1); // type: oop
7617 Node* offset = argument(2); // type: int
7618 Node* end = argument(3); // type: int
7619
7620 Node* length = _gvn.transform(new SubINode(end, offset));
7621
7622 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7623 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7624 // failed array check
7625 return false;
7626 }
7627
7628 // Figure out the size and type of the elements we will be copying.
7629 BasicType src_elem = src_type->elem()->array_element_basic_type();
7630 if (src_elem != T_BYTE) {
7631 return false;
7632 }
7633
7634 // 'src_start' points to src array + scaled offset
7635 src = must_be_not_null(src, true);
7636 Node* src_start = array_element_address(src, offset, src_elem);
7637
7638 // static final int[] byteTable in class CRC32C
7639 Node* table = get_table_from_crc32c_class(callee()->holder());
7640 table = must_be_not_null(table, true);
7641 Node* table_start = array_element_address(table, intcon(0), T_INT);
7642
7643 // We assume that range check is done by caller.
7644 // TODO: generate range check (offset+length < src.length) in debug VM.
7645
7646 // Call the stub.
7647 address stubAddr = StubRoutines::updateBytesCRC32C();
7648 const char *stubName = "updateBytesCRC32C";
7649
7650 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7651 stubAddr, stubName, TypePtr::BOTTOM,
7652 crc, src_start, length, table_start);
7653 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7654 set_result(result);
7655 return true;
7656 }
7657
7658 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7659 //
7660 // Calculate CRC32C for DirectByteBuffer.
7661 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7662 //
7663 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7664 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7665 assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7666 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7667 // no receiver since it is a static method
7668 Node* crc = argument(0); // type: int
7669 Node* src = argument(1); // type: long
7670 Node* offset = argument(3); // type: int
7671 Node* end = argument(4); // type: int
7672
7673 Node* length = _gvn.transform(new SubINode(end, offset));
7674
7675 src = ConvL2X(src); // adjust Java long to machine word
7676 Node* base = _gvn.transform(new CastX2PNode(src));
7677 offset = ConvI2X(offset);
7678
7679 // 'src_start' points to src array + scaled offset
7680 Node* src_start = off_heap_plus_addr(base, offset);
7681
7682 // static final int[] byteTable in class CRC32C
7683 Node* table = get_table_from_crc32c_class(callee()->holder());
7684 table = must_be_not_null(table, true);
7685 Node* table_start = array_element_address(table, intcon(0), T_INT);
7686
7687 // Call the stub.
7688 address stubAddr = StubRoutines::updateBytesCRC32C();
7689 const char *stubName = "updateBytesCRC32C";
7690
7691 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7692 stubAddr, stubName, TypePtr::BOTTOM,
7693 crc, src_start, length, table_start);
7694 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7695 set_result(result);
7696 return true;
7697 }
7698
7699 //------------------------------inline_updateBytesAdler32----------------------
7700 //
7701 // Calculate Adler32 checksum for byte[] array.
7702 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7703 //
7704 bool LibraryCallKit::inline_updateBytesAdler32() {
7705 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7706 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7707 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7708 // no receiver since it is static method
7709 Node* crc = argument(0); // type: int
7710 Node* src = argument(1); // type: oop
7711 Node* offset = argument(2); // type: int
7712 Node* length = argument(3); // type: int
7713
7714 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7715 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7716 // failed array check
7717 return false;
7718 }
7719
7720 // Figure out the size and type of the elements we will be copying.
7721 BasicType src_elem = src_type->elem()->array_element_basic_type();
7722 if (src_elem != T_BYTE) {
7723 return false;
7724 }
7725
7726 // 'src_start' points to src array + scaled offset
7727 Node* src_start = array_element_address(src, offset, src_elem);
7728
7729 // We assume that range check is done by caller.
7730 // TODO: generate range check (offset+length < src.length) in debug VM.
7731
7732 // Call the stub.
7733 address stubAddr = StubRoutines::updateBytesAdler32();
7734 const char *stubName = "updateBytesAdler32";
7735
7736 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7737 stubAddr, stubName, TypePtr::BOTTOM,
7738 crc, src_start, length);
7739 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7740 set_result(result);
7741 return true;
7742 }
7743
7744 //------------------------------inline_updateByteBufferAdler32---------------
7745 //
7746 // Calculate Adler32 checksum for DirectByteBuffer.
7747 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7748 //
7749 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7750 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7751 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7752 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7753 // no receiver since it is static method
7754 Node* crc = argument(0); // type: int
7755 Node* src = argument(1); // type: long
7756 Node* offset = argument(3); // type: int
7757 Node* length = argument(4); // type: int
7758
7759 src = ConvL2X(src); // adjust Java long to machine word
7760 Node* base = _gvn.transform(new CastX2PNode(src));
7761 offset = ConvI2X(offset);
7762
7763 // 'src_start' points to src array + scaled offset
7764 Node* src_start = off_heap_plus_addr(base, offset);
7765
7766 // Call the stub.
7767 address stubAddr = StubRoutines::updateBytesAdler32();
7768 const char *stubName = "updateBytesAdler32";
7769
7770 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7771 stubAddr, stubName, TypePtr::BOTTOM,
7772 crc, src_start, length);
7773
7774 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7775 set_result(result);
7776 return true;
7777 }
7778
7779 //----------------------------inline_reference_get0----------------------------
7780 // public T java.lang.ref.Reference.get();
7781 bool LibraryCallKit::inline_reference_get0() {
7782 const int referent_offset = java_lang_ref_Reference::referent_offset();
7783
7784 // Get the argument:
7785 Node* reference_obj = null_check_receiver();
7786 if (stopped()) return true;
7787
7788 DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7789 Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7790 decorators, /*is_static*/ false,
7791 env()->Reference_klass());
7792 if (result == nullptr) return false;
7793
7794 // Add memory barrier to prevent commoning reads from this field
7795 // across safepoint since GC can change its value.
7796 insert_mem_bar(Op_MemBarCPUOrder);
7797
7798 set_result(result);
7799 return true;
7800 }
7801
7802 //----------------------------inline_reference_refersTo0----------------------------
7803 // bool java.lang.ref.Reference.refersTo0();
7804 // bool java.lang.ref.PhantomReference.refersTo0();
7805 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7806 // Get arguments:
7807 Node* reference_obj = null_check_receiver();
7808 Node* other_obj = argument(1);
7809 if (stopped()) return true;
7810
7811 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7812 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7813 Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7814 decorators, /*is_static*/ false,
7815 env()->Reference_klass());
7816 if (referent == nullptr) return false;
7817
7818 // Add memory barrier to prevent commoning reads from this field
7819 // across safepoint since GC can change its value.
7820 insert_mem_bar(Op_MemBarCPUOrder);
7821
7822 Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7823 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7824 IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7825
7826 RegionNode* region = new RegionNode(3);
7827 PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7828
7829 Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7830 region->init_req(1, if_true);
7831 phi->init_req(1, intcon(1));
7832
7833 Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7834 region->init_req(2, if_false);
7835 phi->init_req(2, intcon(0));
7836
7837 set_control(_gvn.transform(region));
7838 record_for_igvn(region);
7839 set_result(_gvn.transform(phi));
7840 return true;
7841 }
7842
7843 //----------------------------inline_reference_clear0----------------------------
7844 // void java.lang.ref.Reference.clear0();
7845 // void java.lang.ref.PhantomReference.clear0();
7846 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7847 // This matches the implementation in JVM_ReferenceClear, see the comments there.
7848
7849 // Get arguments
7850 Node* reference_obj = null_check_receiver();
7851 if (stopped()) return true;
7852
7853 // Common access parameters
7854 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7855 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7856 Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7857 const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7858 const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7859
7860 Node* referent = access_load_at(reference_obj,
7861 referent_field_addr,
7862 referent_field_addr_type,
7863 val_type,
7864 T_OBJECT,
7865 decorators);
7866
7867 IdealKit ideal(this);
7868 #define __ ideal.
7869 __ if_then(referent, BoolTest::ne, null());
7870 sync_kit(ideal);
7871 access_store_at(reference_obj,
7872 referent_field_addr,
7873 referent_field_addr_type,
7874 null(),
7875 val_type,
7876 T_OBJECT,
7877 decorators);
7878 __ sync_kit(this);
7879 __ end_if();
7880 final_sync(ideal);
7881 #undef __
7882
7883 return true;
7884 }
7885
7886 //-----------------------inline_reference_reachabilityFence-----------------
7887 // bool java.lang.ref.Reference.reachabilityFence();
7888 bool LibraryCallKit::inline_reference_reachabilityFence() {
7889 Node* referent = argument(0);
7890 insert_reachability_fence(referent);
7891 return true;
7892 }
7893
7894 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7895 DecoratorSet decorators, bool is_static,
7896 ciInstanceKlass* fromKls) {
7897 if (fromKls == nullptr) {
7898 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7899 assert(tinst != nullptr, "obj is null");
7900 assert(tinst->is_loaded(), "obj is not loaded");
7901 fromKls = tinst->instance_klass();
7902 }
7903 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7904 ciSymbol::make(fieldTypeString),
7905 is_static);
7906
7907 assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7908 if (field == nullptr) return (Node *) nullptr;
7909
7910 if (is_static) {
7911 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7912 fromObj = makecon(tip);
7913 }
7914
7915 // Next code copied from Parse::do_get_xxx():
7916
7917 // Compute address and memory type.
7918 int offset = field->offset_in_bytes();
7919 bool is_vol = field->is_volatile();
7920 ciType* field_klass = field->type();
7921 assert(field_klass->is_loaded(), "should be loaded");
7922 const TypePtr* adr_type = C->alias_type(field)->adr_type();
7923 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7924 assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7925 "slice of address and input slice don't match");
7926 BasicType bt = field->layout_type();
7927
7928 // Build the resultant type of the load
7929 const Type *type;
7930 if (bt == T_OBJECT) {
7931 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7932 } else {
7933 type = Type::get_const_basic_type(bt);
7934 }
7935
7936 if (is_vol) {
7937 decorators |= MO_SEQ_CST;
7938 }
7939
7940 return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7941 }
7942
7943 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7944 bool is_exact /* true */, bool is_static /* false */,
7945 ciInstanceKlass * fromKls /* nullptr */) {
7946 if (fromKls == nullptr) {
7947 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7948 assert(tinst != nullptr, "obj is null");
7949 assert(tinst->is_loaded(), "obj is not loaded");
7950 assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7951 fromKls = tinst->instance_klass();
7952 }
7953 else {
7954 assert(is_static, "only for static field access");
7955 }
7956 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7957 ciSymbol::make(fieldTypeString),
7958 is_static);
7959
7960 assert(field != nullptr, "undefined field");
7961 assert(!field->is_volatile(), "not defined for volatile fields");
7962
7963 if (is_static) {
7964 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7965 fromObj = makecon(tip);
7966 }
7967
7968 // Next code copied from Parse::do_get_xxx():
7969
7970 // Compute address and memory type.
7971 int offset = field->offset_in_bytes();
7972 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7973
7974 return adr;
7975 }
7976
7977 //------------------------------inline_aescrypt_Block-----------------------
7978 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7979 address stubAddr = nullptr;
7980 const char *stubName;
7981 bool is_decrypt = false;
7982 assert(UseAES, "need AES instruction support");
7983
7984 switch(id) {
7985 case vmIntrinsics::_aescrypt_encryptBlock:
7986 stubAddr = StubRoutines::aescrypt_encryptBlock();
7987 stubName = "aescrypt_encryptBlock";
7988 break;
7989 case vmIntrinsics::_aescrypt_decryptBlock:
7990 stubAddr = StubRoutines::aescrypt_decryptBlock();
7991 stubName = "aescrypt_decryptBlock";
7992 is_decrypt = true;
7993 break;
7994 default:
7995 break;
7996 }
7997 if (stubAddr == nullptr) return false;
7998
7999 Node* aescrypt_object = argument(0);
8000 Node* src = argument(1);
8001 Node* src_offset = argument(2);
8002 Node* dest = argument(3);
8003 Node* dest_offset = argument(4);
8004
8005 src = must_be_not_null(src, true);
8006 dest = must_be_not_null(dest, true);
8007
8008 // (1) src and dest are arrays.
8009 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8010 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8011 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8012 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8013
8014 // for the quick and dirty code we will skip all the checks.
8015 // we are just trying to get the call to be generated.
8016 Node* src_start = src;
8017 Node* dest_start = dest;
8018 if (src_offset != nullptr || dest_offset != nullptr) {
8019 assert(src_offset != nullptr && dest_offset != nullptr, "");
8020 src_start = array_element_address(src, src_offset, T_BYTE);
8021 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8022 }
8023
8024 // now need to get the start of its expanded key array
8025 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8026 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8027 if (k_start == nullptr) return false;
8028
8029 // Call the stub.
8030 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
8031 stubAddr, stubName, TypePtr::BOTTOM,
8032 src_start, dest_start, k_start);
8033
8034 return true;
8035 }
8036
8037 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
8038 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
8039 address stubAddr = nullptr;
8040 const char *stubName = nullptr;
8041 bool is_decrypt = false;
8042 assert(UseAES, "need AES instruction support");
8043
8044 switch(id) {
8045 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8046 stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8047 stubName = "cipherBlockChaining_encryptAESCrypt";
8048 break;
8049 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8050 stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8051 stubName = "cipherBlockChaining_decryptAESCrypt";
8052 is_decrypt = true;
8053 break;
8054 default:
8055 break;
8056 }
8057 if (stubAddr == nullptr) return false;
8058
8059 Node* cipherBlockChaining_object = argument(0);
8060 Node* src = argument(1);
8061 Node* src_offset = argument(2);
8062 Node* len = argument(3);
8063 Node* dest = argument(4);
8064 Node* dest_offset = argument(5);
8065
8066 src = must_be_not_null(src, false);
8067 dest = must_be_not_null(dest, false);
8068
8069 // (1) src and dest are arrays.
8070 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8071 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8072 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8073 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8074
8075 // checks are the responsibility of the caller
8076 Node* src_start = src;
8077 Node* dest_start = dest;
8078 if (src_offset != nullptr || dest_offset != nullptr) {
8079 assert(src_offset != nullptr && dest_offset != nullptr, "");
8080 src_start = array_element_address(src, src_offset, T_BYTE);
8081 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8082 }
8083
8084 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8085 // (because of the predicated logic executed earlier).
8086 // so we cast it here safely.
8087 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8088
8089 Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8090 if (embeddedCipherObj == nullptr) return false;
8091
8092 // cast it to what we know it will be at runtime
8093 const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8094 assert(tinst != nullptr, "CBC obj is null");
8095 assert(tinst->is_loaded(), "CBC obj is not loaded");
8096 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8097 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8098
8099 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8100 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8101 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8102 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8103 aescrypt_object = _gvn.transform(aescrypt_object);
8104
8105 // we need to get the start of the aescrypt_object's expanded key array
8106 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8107 if (k_start == nullptr) return false;
8108
8109 // similarly, get the start address of the r vector
8110 Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8111 if (objRvec == nullptr) return false;
8112 Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8113
8114 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8115 Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8116 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8117 stubAddr, stubName, TypePtr::BOTTOM,
8118 src_start, dest_start, k_start, r_start, len);
8119
8120 // return cipher length (int)
8121 Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8122 set_result(retvalue);
8123 return true;
8124 }
8125
8126 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8127 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8128 address stubAddr = nullptr;
8129 const char *stubName = nullptr;
8130 bool is_decrypt = false;
8131 assert(UseAES, "need AES instruction support");
8132
8133 switch (id) {
8134 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8135 stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8136 stubName = "electronicCodeBook_encryptAESCrypt";
8137 break;
8138 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8139 stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8140 stubName = "electronicCodeBook_decryptAESCrypt";
8141 is_decrypt = true;
8142 break;
8143 default:
8144 break;
8145 }
8146
8147 if (stubAddr == nullptr) return false;
8148
8149 Node* electronicCodeBook_object = argument(0);
8150 Node* src = argument(1);
8151 Node* src_offset = argument(2);
8152 Node* len = argument(3);
8153 Node* dest = argument(4);
8154 Node* dest_offset = argument(5);
8155
8156 // (1) src and dest are arrays.
8157 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8158 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8159 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8160 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8161
8162 // checks are the responsibility of the caller
8163 Node* src_start = src;
8164 Node* dest_start = dest;
8165 if (src_offset != nullptr || dest_offset != nullptr) {
8166 assert(src_offset != nullptr && dest_offset != nullptr, "");
8167 src_start = array_element_address(src, src_offset, T_BYTE);
8168 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8169 }
8170
8171 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8172 // (because of the predicated logic executed earlier).
8173 // so we cast it here safely.
8174 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8175
8176 Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8177 if (embeddedCipherObj == nullptr) return false;
8178
8179 // cast it to what we know it will be at runtime
8180 const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8181 assert(tinst != nullptr, "ECB obj is null");
8182 assert(tinst->is_loaded(), "ECB obj is not loaded");
8183 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8184 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8185
8186 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8187 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8188 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8189 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8190 aescrypt_object = _gvn.transform(aescrypt_object);
8191
8192 // we need to get the start of the aescrypt_object's expanded key array
8193 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8194 if (k_start == nullptr) return false;
8195
8196 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8197 Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8198 OptoRuntime::electronicCodeBook_aescrypt_Type(),
8199 stubAddr, stubName, TypePtr::BOTTOM,
8200 src_start, dest_start, k_start, len);
8201
8202 // return cipher length (int)
8203 Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8204 set_result(retvalue);
8205 return true;
8206 }
8207
8208 //------------------------------inline_counterMode_AESCrypt-----------------------
8209 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8210 assert(UseAES, "need AES instruction support");
8211 if (!UseAESCTRIntrinsics) return false;
8212
8213 address stubAddr = nullptr;
8214 const char *stubName = nullptr;
8215 if (id == vmIntrinsics::_counterMode_AESCrypt) {
8216 stubAddr = StubRoutines::counterMode_AESCrypt();
8217 stubName = "counterMode_AESCrypt";
8218 }
8219 if (stubAddr == nullptr) return false;
8220
8221 Node* counterMode_object = argument(0);
8222 Node* src = argument(1);
8223 Node* src_offset = argument(2);
8224 Node* len = argument(3);
8225 Node* dest = argument(4);
8226 Node* dest_offset = argument(5);
8227
8228 // (1) src and dest are arrays.
8229 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8230 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8231 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8232 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8233
8234 // checks are the responsibility of the caller
8235 Node* src_start = src;
8236 Node* dest_start = dest;
8237 if (src_offset != nullptr || dest_offset != nullptr) {
8238 assert(src_offset != nullptr && dest_offset != nullptr, "");
8239 src_start = array_element_address(src, src_offset, T_BYTE);
8240 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8241 }
8242
8243 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8244 // (because of the predicated logic executed earlier).
8245 // so we cast it here safely.
8246 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8247 Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8248 if (embeddedCipherObj == nullptr) return false;
8249 // cast it to what we know it will be at runtime
8250 const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8251 assert(tinst != nullptr, "CTR obj is null");
8252 assert(tinst->is_loaded(), "CTR obj is not loaded");
8253 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8254 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8255 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8256 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8257 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8258 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8259 aescrypt_object = _gvn.transform(aescrypt_object);
8260 // we need to get the start of the aescrypt_object's expanded key array
8261 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8262 if (k_start == nullptr) return false;
8263 // similarly, get the start address of the r vector
8264 Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8265 if (obj_counter == nullptr) return false;
8266 Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8267
8268 Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8269 if (saved_encCounter == nullptr) return false;
8270 Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8271 Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8272
8273 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8274 Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8275 OptoRuntime::counterMode_aescrypt_Type(),
8276 stubAddr, stubName, TypePtr::BOTTOM,
8277 src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8278
8279 // return cipher length (int)
8280 Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8281 set_result(retvalue);
8282 return true;
8283 }
8284
8285 //------------------------------get_key_start_from_aescrypt_object-----------------------
8286 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8287 // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8288 // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8289 // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8290 // The following platform specific stubs of encryption and decryption use the same round keys.
8291 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8292 bool use_decryption_key = false;
8293 #else
8294 bool use_decryption_key = is_decrypt;
8295 #endif
8296 Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8297 assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8298 if (objAESCryptKey == nullptr) return (Node *) nullptr;
8299
8300 // now have the array, need to get the start address of the selected key array
8301 Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8302 return k_start;
8303 }
8304
8305 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8306 // Return node representing slow path of predicate check.
8307 // the pseudo code we want to emulate with this predicate is:
8308 // for encryption:
8309 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8310 // for decryption:
8311 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8312 // note cipher==plain is more conservative than the original java code but that's OK
8313 //
8314 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8315 // The receiver was checked for null already.
8316 Node* objCBC = argument(0);
8317
8318 Node* src = argument(1);
8319 Node* dest = argument(4);
8320
8321 // Load embeddedCipher field of CipherBlockChaining object.
8322 Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8323
8324 // get AESCrypt klass for instanceOf check
8325 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8326 // will have same classloader as CipherBlockChaining object
8327 const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8328 assert(tinst != nullptr, "CBCobj is null");
8329 assert(tinst->is_loaded(), "CBCobj is not loaded");
8330
8331 // we want to do an instanceof comparison against the AESCrypt class
8332 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8333 if (!klass_AESCrypt->is_loaded()) {
8334 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8335 Node* ctrl = control();
8336 set_control(top()); // no regular fast path
8337 return ctrl;
8338 }
8339
8340 src = must_be_not_null(src, true);
8341 dest = must_be_not_null(dest, true);
8342
8343 // Resolve oops to stable for CmpP below.
8344 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8345
8346 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8347 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8348 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8349
8350 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8351
8352 // for encryption, we are done
8353 if (!decrypting)
8354 return instof_false; // even if it is null
8355
8356 // for decryption, we need to add a further check to avoid
8357 // taking the intrinsic path when cipher and plain are the same
8358 // see the original java code for why.
8359 RegionNode* region = new RegionNode(3);
8360 region->init_req(1, instof_false);
8361
8362 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8363 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8364 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8365 region->init_req(2, src_dest_conjoint);
8366
8367 record_for_igvn(region);
8368 return _gvn.transform(region);
8369 }
8370
8371 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8372 // Return node representing slow path of predicate check.
8373 // the pseudo code we want to emulate with this predicate is:
8374 // for encryption:
8375 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8376 // for decryption:
8377 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8378 // note cipher==plain is more conservative than the original java code but that's OK
8379 //
8380 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8381 // The receiver was checked for null already.
8382 Node* objECB = argument(0);
8383
8384 // Load embeddedCipher field of ElectronicCodeBook object.
8385 Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8386
8387 // get AESCrypt klass for instanceOf check
8388 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8389 // will have same classloader as ElectronicCodeBook object
8390 const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8391 assert(tinst != nullptr, "ECBobj is null");
8392 assert(tinst->is_loaded(), "ECBobj is not loaded");
8393
8394 // we want to do an instanceof comparison against the AESCrypt class
8395 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8396 if (!klass_AESCrypt->is_loaded()) {
8397 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8398 Node* ctrl = control();
8399 set_control(top()); // no regular fast path
8400 return ctrl;
8401 }
8402 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8403
8404 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8405 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8406 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8407
8408 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8409
8410 // for encryption, we are done
8411 if (!decrypting)
8412 return instof_false; // even if it is null
8413
8414 // for decryption, we need to add a further check to avoid
8415 // taking the intrinsic path when cipher and plain are the same
8416 // see the original java code for why.
8417 RegionNode* region = new RegionNode(3);
8418 region->init_req(1, instof_false);
8419 Node* src = argument(1);
8420 Node* dest = argument(4);
8421 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8422 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8423 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8424 region->init_req(2, src_dest_conjoint);
8425
8426 record_for_igvn(region);
8427 return _gvn.transform(region);
8428 }
8429
8430 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8431 // Return node representing slow path of predicate check.
8432 // the pseudo code we want to emulate with this predicate is:
8433 // for encryption:
8434 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8435 // for decryption:
8436 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8437 // note cipher==plain is more conservative than the original java code but that's OK
8438 //
8439
8440 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8441 // The receiver was checked for null already.
8442 Node* objCTR = argument(0);
8443
8444 // Load embeddedCipher field of CipherBlockChaining object.
8445 Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8446
8447 // get AESCrypt klass for instanceOf check
8448 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8449 // will have same classloader as CipherBlockChaining object
8450 const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8451 assert(tinst != nullptr, "CTRobj is null");
8452 assert(tinst->is_loaded(), "CTRobj is not loaded");
8453
8454 // we want to do an instanceof comparison against the AESCrypt class
8455 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8456 if (!klass_AESCrypt->is_loaded()) {
8457 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8458 Node* ctrl = control();
8459 set_control(top()); // no regular fast path
8460 return ctrl;
8461 }
8462
8463 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8464 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8465 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8466 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8467 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8468
8469 return instof_false; // even if it is null
8470 }
8471
8472 //------------------------------inline_ghash_processBlocks
8473 bool LibraryCallKit::inline_ghash_processBlocks() {
8474 address stubAddr;
8475 const char *stubName;
8476 assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8477
8478 stubAddr = StubRoutines::ghash_processBlocks();
8479 stubName = "ghash_processBlocks";
8480
8481 Node* data = argument(0);
8482 Node* offset = argument(1);
8483 Node* len = argument(2);
8484 Node* state = argument(3);
8485 Node* subkeyH = argument(4);
8486
8487 state = must_be_not_null(state, true);
8488 subkeyH = must_be_not_null(subkeyH, true);
8489 data = must_be_not_null(data, true);
8490
8491 Node* state_start = array_element_address(state, intcon(0), T_LONG);
8492 assert(state_start, "state is null");
8493 Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);
8494 assert(subkeyH_start, "subkeyH is null");
8495 Node* data_start = array_element_address(data, offset, T_BYTE);
8496 assert(data_start, "data is null");
8497
8498 Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8499 OptoRuntime::ghash_processBlocks_Type(),
8500 stubAddr, stubName, TypePtr::BOTTOM,
8501 state_start, subkeyH_start, data_start, len);
8502 return true;
8503 }
8504
8505 //------------------------------inline_chacha20Block
8506 bool LibraryCallKit::inline_chacha20Block() {
8507 address stubAddr;
8508 const char *stubName;
8509 assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8510
8511 stubAddr = StubRoutines::chacha20Block();
8512 stubName = "chacha20Block";
8513
8514 Node* state = argument(0);
8515 Node* result = argument(1);
8516
8517 state = must_be_not_null(state, true);
8518 result = must_be_not_null(result, true);
8519
8520 Node* state_start = array_element_address(state, intcon(0), T_INT);
8521 assert(state_start, "state is null");
8522 Node* result_start = array_element_address(result, intcon(0), T_BYTE);
8523 assert(result_start, "result is null");
8524
8525 Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8526 OptoRuntime::chacha20Block_Type(),
8527 stubAddr, stubName, TypePtr::BOTTOM,
8528 state_start, result_start);
8529 // return key stream length (int)
8530 Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8531 set_result(retvalue);
8532 return true;
8533 }
8534
8535 //------------------------------inline_kyberNtt
8536 bool LibraryCallKit::inline_kyberNtt() {
8537 address stubAddr;
8538 const char *stubName;
8539 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8540 assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8541
8542 stubAddr = StubRoutines::kyberNtt();
8543 stubName = "kyberNtt";
8544 if (!stubAddr) return false;
8545
8546 Node* coeffs = argument(0);
8547 Node* ntt_zetas = argument(1);
8548
8549 coeffs = must_be_not_null(coeffs, true);
8550 ntt_zetas = must_be_not_null(ntt_zetas, true);
8551
8552 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8553 assert(coeffs_start, "coeffs is null");
8554 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8555 assert(ntt_zetas_start, "ntt_zetas is null");
8556 Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8557 OptoRuntime::kyberNtt_Type(),
8558 stubAddr, stubName, TypePtr::BOTTOM,
8559 coeffs_start, ntt_zetas_start);
8560 // return an int
8561 Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8562 set_result(retvalue);
8563 return true;
8564 }
8565
8566 //------------------------------inline_kyberInverseNtt
8567 bool LibraryCallKit::inline_kyberInverseNtt() {
8568 address stubAddr;
8569 const char *stubName;
8570 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8571 assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8572
8573 stubAddr = StubRoutines::kyberInverseNtt();
8574 stubName = "kyberInverseNtt";
8575 if (!stubAddr) return false;
8576
8577 Node* coeffs = argument(0);
8578 Node* zetas = argument(1);
8579
8580 coeffs = must_be_not_null(coeffs, true);
8581 zetas = must_be_not_null(zetas, true);
8582
8583 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8584 assert(coeffs_start, "coeffs is null");
8585 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
8586 assert(zetas_start, "inverseNtt_zetas is null");
8587 Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8588 OptoRuntime::kyberInverseNtt_Type(),
8589 stubAddr, stubName, TypePtr::BOTTOM,
8590 coeffs_start, zetas_start);
8591
8592 // return an int
8593 Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8594 set_result(retvalue);
8595 return true;
8596 }
8597
8598 //------------------------------inline_kyberNttMult
8599 bool LibraryCallKit::inline_kyberNttMult() {
8600 address stubAddr;
8601 const char *stubName;
8602 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8603 assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8604
8605 stubAddr = StubRoutines::kyberNttMult();
8606 stubName = "kyberNttMult";
8607 if (!stubAddr) return false;
8608
8609 Node* result = argument(0);
8610 Node* ntta = argument(1);
8611 Node* nttb = argument(2);
8612 Node* zetas = argument(3);
8613
8614 result = must_be_not_null(result, true);
8615 ntta = must_be_not_null(ntta, true);
8616 nttb = must_be_not_null(nttb, true);
8617 zetas = must_be_not_null(zetas, true);
8618
8619 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8620 assert(result_start, "result is null");
8621 Node* ntta_start = array_element_address(ntta, intcon(0), T_SHORT);
8622 assert(ntta_start, "ntta is null");
8623 Node* nttb_start = array_element_address(nttb, intcon(0), T_SHORT);
8624 assert(nttb_start, "nttb is null");
8625 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
8626 assert(zetas_start, "nttMult_zetas is null");
8627 Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8628 OptoRuntime::kyberNttMult_Type(),
8629 stubAddr, stubName, TypePtr::BOTTOM,
8630 result_start, ntta_start, nttb_start,
8631 zetas_start);
8632
8633 // return an int
8634 Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8635 set_result(retvalue);
8636
8637 return true;
8638 }
8639
8640 //------------------------------inline_kyberAddPoly_2
8641 bool LibraryCallKit::inline_kyberAddPoly_2() {
8642 address stubAddr;
8643 const char *stubName;
8644 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8645 assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8646
8647 stubAddr = StubRoutines::kyberAddPoly_2();
8648 stubName = "kyberAddPoly_2";
8649 if (!stubAddr) return false;
8650
8651 Node* result = argument(0);
8652 Node* a = argument(1);
8653 Node* b = argument(2);
8654
8655 result = must_be_not_null(result, true);
8656 a = must_be_not_null(a, true);
8657 b = must_be_not_null(b, true);
8658
8659 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8660 assert(result_start, "result is null");
8661 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
8662 assert(a_start, "a is null");
8663 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
8664 assert(b_start, "b is null");
8665 Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8666 OptoRuntime::kyberAddPoly_2_Type(),
8667 stubAddr, stubName, TypePtr::BOTTOM,
8668 result_start, a_start, b_start);
8669 // return an int
8670 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8671 set_result(retvalue);
8672 return true;
8673 }
8674
8675 //------------------------------inline_kyberAddPoly_3
8676 bool LibraryCallKit::inline_kyberAddPoly_3() {
8677 address stubAddr;
8678 const char *stubName;
8679 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8680 assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8681
8682 stubAddr = StubRoutines::kyberAddPoly_3();
8683 stubName = "kyberAddPoly_3";
8684 if (!stubAddr) return false;
8685
8686 Node* result = argument(0);
8687 Node* a = argument(1);
8688 Node* b = argument(2);
8689 Node* c = argument(3);
8690
8691 result = must_be_not_null(result, true);
8692 a = must_be_not_null(a, true);
8693 b = must_be_not_null(b, true);
8694 c = must_be_not_null(c, true);
8695
8696 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8697 assert(result_start, "result is null");
8698 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
8699 assert(a_start, "a is null");
8700 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
8701 assert(b_start, "b is null");
8702 Node* c_start = array_element_address(c, intcon(0), T_SHORT);
8703 assert(c_start, "c is null");
8704 Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8705 OptoRuntime::kyberAddPoly_3_Type(),
8706 stubAddr, stubName, TypePtr::BOTTOM,
8707 result_start, a_start, b_start, c_start);
8708 // return an int
8709 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8710 set_result(retvalue);
8711 return true;
8712 }
8713
8714 //------------------------------inline_kyber12To16
8715 bool LibraryCallKit::inline_kyber12To16() {
8716 address stubAddr;
8717 const char *stubName;
8718 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8719 assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8720
8721 stubAddr = StubRoutines::kyber12To16();
8722 stubName = "kyber12To16";
8723 if (!stubAddr) return false;
8724
8725 Node* condensed = argument(0);
8726 Node* condensedOffs = argument(1);
8727 Node* parsed = argument(2);
8728 Node* parsedLength = argument(3);
8729
8730 condensed = must_be_not_null(condensed, true);
8731 parsed = must_be_not_null(parsed, true);
8732
8733 Node* condensed_start = array_element_address(condensed, intcon(0), T_BYTE);
8734 assert(condensed_start, "condensed is null");
8735 Node* parsed_start = array_element_address(parsed, intcon(0), T_SHORT);
8736 assert(parsed_start, "parsed is null");
8737 Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8738 OptoRuntime::kyber12To16_Type(),
8739 stubAddr, stubName, TypePtr::BOTTOM,
8740 condensed_start, condensedOffs, parsed_start, parsedLength);
8741 // return an int
8742 Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8743 set_result(retvalue);
8744 return true;
8745
8746 }
8747
8748 //------------------------------inline_kyberBarrettReduce
8749 bool LibraryCallKit::inline_kyberBarrettReduce() {
8750 address stubAddr;
8751 const char *stubName;
8752 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8753 assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8754
8755 stubAddr = StubRoutines::kyberBarrettReduce();
8756 stubName = "kyberBarrettReduce";
8757 if (!stubAddr) return false;
8758
8759 Node* coeffs = argument(0);
8760
8761 coeffs = must_be_not_null(coeffs, true);
8762
8763 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8764 assert(coeffs_start, "coeffs is null");
8765 Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8766 OptoRuntime::kyberBarrettReduce_Type(),
8767 stubAddr, stubName, TypePtr::BOTTOM,
8768 coeffs_start);
8769 // return an int
8770 Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8771 set_result(retvalue);
8772 return true;
8773 }
8774
8775 //------------------------------inline_dilithiumAlmostNtt
8776 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8777 address stubAddr;
8778 const char *stubName;
8779 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8780 assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8781
8782 stubAddr = StubRoutines::dilithiumAlmostNtt();
8783 stubName = "dilithiumAlmostNtt";
8784 if (!stubAddr) return false;
8785
8786 Node* coeffs = argument(0);
8787 Node* ntt_zetas = argument(1);
8788
8789 coeffs = must_be_not_null(coeffs, true);
8790 ntt_zetas = must_be_not_null(ntt_zetas, true);
8791
8792 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8793 assert(coeffs_start, "coeffs is null");
8794 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_INT);
8795 assert(ntt_zetas_start, "ntt_zetas is null");
8796 Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8797 OptoRuntime::dilithiumAlmostNtt_Type(),
8798 stubAddr, stubName, TypePtr::BOTTOM,
8799 coeffs_start, ntt_zetas_start);
8800 // return an int
8801 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8802 set_result(retvalue);
8803 return true;
8804 }
8805
8806 //------------------------------inline_dilithiumAlmostInverseNtt
8807 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8808 address stubAddr;
8809 const char *stubName;
8810 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8811 assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8812
8813 stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8814 stubName = "dilithiumAlmostInverseNtt";
8815 if (!stubAddr) return false;
8816
8817 Node* coeffs = argument(0);
8818 Node* zetas = argument(1);
8819
8820 coeffs = must_be_not_null(coeffs, true);
8821 zetas = must_be_not_null(zetas, true);
8822
8823 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8824 assert(coeffs_start, "coeffs is null");
8825 Node* zetas_start = array_element_address(zetas, intcon(0), T_INT);
8826 assert(zetas_start, "inverseNtt_zetas is null");
8827 Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8828 OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8829 stubAddr, stubName, TypePtr::BOTTOM,
8830 coeffs_start, zetas_start);
8831 // return an int
8832 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8833 set_result(retvalue);
8834 return true;
8835 }
8836
8837 //------------------------------inline_dilithiumNttMult
8838 bool LibraryCallKit::inline_dilithiumNttMult() {
8839 address stubAddr;
8840 const char *stubName;
8841 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8842 assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8843
8844 stubAddr = StubRoutines::dilithiumNttMult();
8845 stubName = "dilithiumNttMult";
8846 if (!stubAddr) return false;
8847
8848 Node* result = argument(0);
8849 Node* ntta = argument(1);
8850 Node* nttb = argument(2);
8851 Node* zetas = argument(3);
8852
8853 result = must_be_not_null(result, true);
8854 ntta = must_be_not_null(ntta, true);
8855 nttb = must_be_not_null(nttb, true);
8856 zetas = must_be_not_null(zetas, true);
8857
8858 Node* result_start = array_element_address(result, intcon(0), T_INT);
8859 assert(result_start, "result is null");
8860 Node* ntta_start = array_element_address(ntta, intcon(0), T_INT);
8861 assert(ntta_start, "ntta is null");
8862 Node* nttb_start = array_element_address(nttb, intcon(0), T_INT);
8863 assert(nttb_start, "nttb is null");
8864 Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8865 OptoRuntime::dilithiumNttMult_Type(),
8866 stubAddr, stubName, TypePtr::BOTTOM,
8867 result_start, ntta_start, nttb_start);
8868
8869 // return an int
8870 Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8871 set_result(retvalue);
8872
8873 return true;
8874 }
8875
8876 //------------------------------inline_dilithiumMontMulByConstant
8877 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8878 address stubAddr;
8879 const char *stubName;
8880 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8881 assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8882
8883 stubAddr = StubRoutines::dilithiumMontMulByConstant();
8884 stubName = "dilithiumMontMulByConstant";
8885 if (!stubAddr) return false;
8886
8887 Node* coeffs = argument(0);
8888 Node* constant = argument(1);
8889
8890 coeffs = must_be_not_null(coeffs, true);
8891
8892 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8893 assert(coeffs_start, "coeffs is null");
8894 Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8895 OptoRuntime::dilithiumMontMulByConstant_Type(),
8896 stubAddr, stubName, TypePtr::BOTTOM,
8897 coeffs_start, constant);
8898
8899 // return an int
8900 Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8901 set_result(retvalue);
8902 return true;
8903 }
8904
8905
8906 //------------------------------inline_dilithiumDecomposePoly
8907 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8908 address stubAddr;
8909 const char *stubName;
8910 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8911 assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8912
8913 stubAddr = StubRoutines::dilithiumDecomposePoly();
8914 stubName = "dilithiumDecomposePoly";
8915 if (!stubAddr) return false;
8916
8917 Node* input = argument(0);
8918 Node* lowPart = argument(1);
8919 Node* highPart = argument(2);
8920 Node* twoGamma2 = argument(3);
8921 Node* multiplier = argument(4);
8922
8923 input = must_be_not_null(input, true);
8924 lowPart = must_be_not_null(lowPart, true);
8925 highPart = must_be_not_null(highPart, true);
8926
8927 Node* input_start = array_element_address(input, intcon(0), T_INT);
8928 assert(input_start, "input is null");
8929 Node* lowPart_start = array_element_address(lowPart, intcon(0), T_INT);
8930 assert(lowPart_start, "lowPart is null");
8931 Node* highPart_start = array_element_address(highPart, intcon(0), T_INT);
8932 assert(highPart_start, "highPart is null");
8933
8934 Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8935 OptoRuntime::dilithiumDecomposePoly_Type(),
8936 stubAddr, stubName, TypePtr::BOTTOM,
8937 input_start, lowPart_start, highPart_start,
8938 twoGamma2, multiplier);
8939
8940 // return an int
8941 Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8942 set_result(retvalue);
8943 return true;
8944 }
8945
8946 bool LibraryCallKit::inline_base64_encodeBlock() {
8947 address stubAddr;
8948 const char *stubName;
8949 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8950 assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8951 stubAddr = StubRoutines::base64_encodeBlock();
8952 stubName = "encodeBlock";
8953
8954 if (!stubAddr) return false;
8955 Node* base64obj = argument(0);
8956 Node* src = argument(1);
8957 Node* offset = argument(2);
8958 Node* len = argument(3);
8959 Node* dest = argument(4);
8960 Node* dp = argument(5);
8961 Node* isURL = argument(6);
8962
8963 src = must_be_not_null(src, true);
8964 dest = must_be_not_null(dest, true);
8965
8966 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8967 assert(src_start, "source array is null");
8968 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8969 assert(dest_start, "destination array is null");
8970
8971 Node* base64 = make_runtime_call(RC_LEAF,
8972 OptoRuntime::base64_encodeBlock_Type(),
8973 stubAddr, stubName, TypePtr::BOTTOM,
8974 src_start, offset, len, dest_start, dp, isURL);
8975 return true;
8976 }
8977
8978 bool LibraryCallKit::inline_base64_decodeBlock() {
8979 address stubAddr;
8980 const char *stubName;
8981 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8982 assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8983 stubAddr = StubRoutines::base64_decodeBlock();
8984 stubName = "decodeBlock";
8985
8986 if (!stubAddr) return false;
8987 Node* base64obj = argument(0);
8988 Node* src = argument(1);
8989 Node* src_offset = argument(2);
8990 Node* len = argument(3);
8991 Node* dest = argument(4);
8992 Node* dest_offset = argument(5);
8993 Node* isURL = argument(6);
8994 Node* isMIME = argument(7);
8995
8996 src = must_be_not_null(src, true);
8997 dest = must_be_not_null(dest, true);
8998
8999 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
9000 assert(src_start, "source array is null");
9001 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
9002 assert(dest_start, "destination array is null");
9003
9004 Node* call = make_runtime_call(RC_LEAF,
9005 OptoRuntime::base64_decodeBlock_Type(),
9006 stubAddr, stubName, TypePtr::BOTTOM,
9007 src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
9008 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9009 set_result(result);
9010 return true;
9011 }
9012
9013 bool LibraryCallKit::inline_poly1305_processBlocks() {
9014 address stubAddr;
9015 const char *stubName;
9016 assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
9017 assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
9018 stubAddr = StubRoutines::poly1305_processBlocks();
9019 stubName = "poly1305_processBlocks";
9020
9021 if (!stubAddr) return false;
9022 null_check_receiver(); // null-check receiver
9023 if (stopped()) return true;
9024
9025 Node* input = argument(1);
9026 Node* input_offset = argument(2);
9027 Node* len = argument(3);
9028 Node* alimbs = argument(4);
9029 Node* rlimbs = argument(5);
9030
9031 input = must_be_not_null(input, true);
9032 alimbs = must_be_not_null(alimbs, true);
9033 rlimbs = must_be_not_null(rlimbs, true);
9034
9035 Node* input_start = array_element_address(input, input_offset, T_BYTE);
9036 assert(input_start, "input array is null");
9037 Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
9038 assert(acc_start, "acc array is null");
9039 Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
9040 assert(r_start, "r array is null");
9041
9042 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9043 OptoRuntime::poly1305_processBlocks_Type(),
9044 stubAddr, stubName, TypePtr::BOTTOM,
9045 input_start, len, acc_start, r_start);
9046 return true;
9047 }
9048
9049 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9050 address stubAddr;
9051 const char *stubName;
9052 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9053 assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9054 stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9055 stubName = "intpoly_montgomeryMult_P256";
9056
9057 if (!stubAddr) return false;
9058 null_check_receiver(); // null-check receiver
9059 if (stopped()) return true;
9060
9061 Node* a = argument(1);
9062 Node* b = argument(2);
9063 Node* r = argument(3);
9064
9065 a = must_be_not_null(a, true);
9066 b = must_be_not_null(b, true);
9067 r = must_be_not_null(r, true);
9068
9069 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9070 assert(a_start, "a array is null");
9071 Node* b_start = array_element_address(b, intcon(0), T_LONG);
9072 assert(b_start, "b array is null");
9073 Node* r_start = array_element_address(r, intcon(0), T_LONG);
9074 assert(r_start, "r array is null");
9075
9076 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9077 OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9078 stubAddr, stubName, TypePtr::BOTTOM,
9079 a_start, b_start, r_start);
9080 return true;
9081 }
9082
9083 bool LibraryCallKit::inline_intpoly_assign() {
9084 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9085 assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9086 const char *stubName = "intpoly_assign";
9087 address stubAddr = StubRoutines::intpoly_assign();
9088 if (!stubAddr) return false;
9089
9090 Node* set = argument(0);
9091 Node* a = argument(1);
9092 Node* b = argument(2);
9093 Node* arr_length = load_array_length(a);
9094
9095 a = must_be_not_null(a, true);
9096 b = must_be_not_null(b, true);
9097
9098 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9099 assert(a_start, "a array is null");
9100 Node* b_start = array_element_address(b, intcon(0), T_LONG);
9101 assert(b_start, "b array is null");
9102
9103 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9104 OptoRuntime::intpoly_assign_Type(),
9105 stubAddr, stubName, TypePtr::BOTTOM,
9106 set, a_start, b_start, arr_length);
9107 return true;
9108 }
9109
9110 bool LibraryCallKit::inline_intpoly_mult_25519() {
9111 address stubAddr;
9112 const char *stubName;
9113 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
9114 assert(callee()->signature()->size() == 3, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
9115 stubAddr = StubRoutines::intpoly_mult_25519();
9116 stubName = "intpoly_mult_25519";
9117
9118 if (!stubAddr) return false;
9119 null_check_receiver(); // null-check receiver
9120 if (stopped()) return true;
9121
9122 Node* a = argument(1);
9123 Node* b = argument(2);
9124 Node* r = argument(3);
9125
9126 a = must_be_not_null(a, true);
9127 b = must_be_not_null(b, true);
9128 r = must_be_not_null(r, true);
9129
9130 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9131 assert(a_start, "a array is null");
9132 Node* b_start = array_element_address(b, intcon(0), T_LONG);
9133 assert(b_start, "b array is null");
9134 Node* r_start = array_element_address(r, intcon(0), T_LONG);
9135 assert(r_start, "r array is null");
9136
9137 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9138 OptoRuntime::intpoly_mult_25519_Type(),
9139 stubAddr, stubName, TypePtr::BOTTOM,
9140 a_start, b_start, r_start);
9141 return true;
9142 }
9143
9144 bool LibraryCallKit::inline_intpoly_square_25519() {
9145 address stubAddr;
9146 const char *stubName;
9147 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
9148 assert(callee()->signature()->size() == 2, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
9149 stubAddr = StubRoutines::intpoly_square_25519();
9150 stubName = "intpoly_square_25519";
9151
9152 if (!stubAddr) return false;
9153 null_check_receiver(); // null-check receiver
9154 if (stopped()) return true;
9155
9156 Node* a = argument(1);
9157 Node* r = argument(2);
9158
9159 a = must_be_not_null(a, true);
9160 r = must_be_not_null(r, true);
9161
9162 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9163 assert(a_start, "a array is null");
9164 Node* r_start = array_element_address(r, intcon(0), T_LONG);
9165 assert(r_start, "r array is null");
9166
9167 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9168 OptoRuntime::intpoly_square_25519_Type(),
9169 stubAddr, stubName, TypePtr::BOTTOM,
9170 a_start, r_start);
9171 return true;
9172 }
9173
9174 //------------------------------inline_digestBase_implCompress-----------------------
9175 //
9176 // Calculate MD5 for single-block byte[] array.
9177 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9178 //
9179 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9180 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9181 //
9182 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9183 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9184 //
9185 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9186 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9187 //
9188 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9189 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9190 //
9191 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9192 assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9193
9194 Node* digestBase_obj = argument(0);
9195 Node* src = argument(1); // type oop
9196 Node* ofs = argument(2); // type int
9197
9198 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9199 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9200 // failed array check
9201 return false;
9202 }
9203 // Figure out the size and type of the elements we will be copying.
9204 BasicType src_elem = src_type->elem()->array_element_basic_type();
9205 if (src_elem != T_BYTE) {
9206 return false;
9207 }
9208 // 'src_start' points to src array + offset
9209 src = must_be_not_null(src, true);
9210 Node* src_start = array_element_address(src, ofs, src_elem);
9211 Node* state = nullptr;
9212 Node* block_size = nullptr;
9213 address stubAddr;
9214 const char *stubName;
9215
9216 switch(id) {
9217 case vmIntrinsics::_md5_implCompress:
9218 assert(UseMD5Intrinsics, "need MD5 instruction support");
9219 state = get_state_from_digest_object(digestBase_obj, T_INT);
9220 stubAddr = StubRoutines::md5_implCompress();
9221 stubName = "md5_implCompress";
9222 break;
9223 case vmIntrinsics::_sha_implCompress:
9224 assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9225 state = get_state_from_digest_object(digestBase_obj, T_INT);
9226 stubAddr = StubRoutines::sha1_implCompress();
9227 stubName = "sha1_implCompress";
9228 break;
9229 case vmIntrinsics::_sha2_implCompress:
9230 assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9231 state = get_state_from_digest_object(digestBase_obj, T_INT);
9232 stubAddr = StubRoutines::sha256_implCompress();
9233 stubName = "sha256_implCompress";
9234 break;
9235 case vmIntrinsics::_sha5_implCompress:
9236 assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9237 state = get_state_from_digest_object(digestBase_obj, T_LONG);
9238 stubAddr = StubRoutines::sha512_implCompress();
9239 stubName = "sha512_implCompress";
9240 break;
9241 case vmIntrinsics::_sha3_implCompress:
9242 assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9243 state = get_state_from_digest_object(digestBase_obj, T_LONG);
9244 stubAddr = StubRoutines::sha3_implCompress();
9245 stubName = "sha3_implCompress";
9246 block_size = get_block_size_from_digest_object(digestBase_obj);
9247 if (block_size == nullptr) return false;
9248 break;
9249 default:
9250 fatal_unexpected_iid(id);
9251 return false;
9252 }
9253 if (state == nullptr) return false;
9254
9255 assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9256 if (stubAddr == nullptr) return false;
9257
9258 // Call the stub.
9259 Node* call;
9260 if (block_size == nullptr) {
9261 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9262 stubAddr, stubName, TypePtr::BOTTOM,
9263 src_start, state);
9264 } else {
9265 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9266 stubAddr, stubName, TypePtr::BOTTOM,
9267 src_start, state, block_size);
9268 }
9269
9270 return true;
9271 }
9272
9273 //------------------------------inline_keccak
9274 bool LibraryCallKit::inline_keccak(vmIntrinsics::ID id) {
9275 address stubAddr = nullptr;
9276 const char *stubName;
9277 assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9278 assert((id == vmIntrinsics::_double_keccak && callee()->signature()->size() == 2) ||
9279 (id == vmIntrinsics::_quad_keccak && callee()->signature()->size() == 4),
9280 "double_keccak wrong number of parameters");
9281
9282 int parmCnt = 0;
9283 switch (id) {
9284 case vmIntrinsics::_double_keccak:
9285 stubAddr = StubRoutines::double_keccak();
9286 stubName = "double_keccak";
9287 parmCnt = 2;
9288 break;
9289 case vmIntrinsics::_quad_keccak:
9290 stubAddr = StubRoutines::quad_keccak();
9291 stubName = "quad_keccak";
9292 parmCnt = 4;
9293 break;
9294 default:
9295 ShouldNotReachHere();
9296 }
9297
9298 if (!stubAddr) return false;
9299
9300 Node* state[4];
9301 for (int i = 0; i<parmCnt; i++) {
9302 state[i] = must_be_not_null(argument(i), true);
9303 state[i] = array_element_address(state[i], intcon(0), T_LONG);
9304 assert(state[i], "state[%d] is null", i);
9305 }
9306
9307 Node* keccak;
9308 switch (id) {
9309 case vmIntrinsics::_double_keccak:
9310 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9311 OptoRuntime::double_keccak_Type(),
9312 stubAddr, stubName, TypePtr::BOTTOM,
9313 state[0], state[1]);
9314 break;
9315 case vmIntrinsics::_quad_keccak:
9316 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9317 OptoRuntime::quad_keccak_Type(),
9318 stubAddr, stubName, TypePtr::BOTTOM,
9319 state[0], state[1], state[2], state[3]);
9320 break;
9321 default:
9322 ShouldNotReachHere();
9323 }
9324
9325 // return an int
9326 Node* retvalue = _gvn.transform(new ProjNode(keccak, TypeFunc::Parms));
9327 set_result(retvalue);
9328 return true;
9329 }
9330
9331
9332 //------------------------------inline_digestBase_implCompressMB-----------------------
9333 //
9334 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9335 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9336 //
9337 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9338 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9339 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9340 assert((uint)predicate < 5, "sanity");
9341 assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9342
9343 Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9344 Node* src = argument(1); // byte[] array
9345 Node* ofs = argument(2); // type int
9346 Node* limit = argument(3); // type int
9347
9348 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9349 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9350 // failed array check
9351 return false;
9352 }
9353 // Figure out the size and type of the elements we will be copying.
9354 BasicType src_elem = src_type->elem()->array_element_basic_type();
9355 if (src_elem != T_BYTE) {
9356 return false;
9357 }
9358 // 'src_start' points to src array + offset
9359 src = must_be_not_null(src, false);
9360 Node* src_start = array_element_address(src, ofs, src_elem);
9361
9362 const char* klass_digestBase_name = nullptr;
9363 const char* stub_name = nullptr;
9364 address stub_addr = nullptr;
9365 BasicType elem_type = T_INT;
9366
9367 switch (predicate) {
9368 case 0:
9369 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9370 klass_digestBase_name = "sun/security/provider/MD5";
9371 stub_name = "md5_implCompressMB";
9372 stub_addr = StubRoutines::md5_implCompressMB();
9373 }
9374 break;
9375 case 1:
9376 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9377 klass_digestBase_name = "sun/security/provider/SHA";
9378 stub_name = "sha1_implCompressMB";
9379 stub_addr = StubRoutines::sha1_implCompressMB();
9380 }
9381 break;
9382 case 2:
9383 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9384 klass_digestBase_name = "sun/security/provider/SHA2";
9385 stub_name = "sha256_implCompressMB";
9386 stub_addr = StubRoutines::sha256_implCompressMB();
9387 }
9388 break;
9389 case 3:
9390 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9391 klass_digestBase_name = "sun/security/provider/SHA5";
9392 stub_name = "sha512_implCompressMB";
9393 stub_addr = StubRoutines::sha512_implCompressMB();
9394 elem_type = T_LONG;
9395 }
9396 break;
9397 case 4:
9398 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9399 klass_digestBase_name = "sun/security/provider/SHA3";
9400 stub_name = "sha3_implCompressMB";
9401 stub_addr = StubRoutines::sha3_implCompressMB();
9402 elem_type = T_LONG;
9403 }
9404 break;
9405 default:
9406 fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9407 }
9408 if (klass_digestBase_name != nullptr) {
9409 assert(stub_addr != nullptr, "Stub is generated");
9410 if (stub_addr == nullptr) return false;
9411
9412 // get DigestBase klass to lookup for SHA klass
9413 const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9414 assert(tinst != nullptr, "digestBase_obj is not instance???");
9415 assert(tinst->is_loaded(), "DigestBase is not loaded");
9416
9417 ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9418 assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9419 ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9420 return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9421 }
9422 return false;
9423 }
9424
9425 //------------------------------inline_digestBase_implCompressMB-----------------------
9426 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9427 BasicType elem_type, address stubAddr, const char *stubName,
9428 Node* src_start, Node* ofs, Node* limit) {
9429 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9430 const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9431 Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9432 digest_obj = _gvn.transform(digest_obj);
9433
9434 Node* state = get_state_from_digest_object(digest_obj, elem_type);
9435 if (state == nullptr) return false;
9436
9437 Node* block_size = nullptr;
9438 if (strcmp("sha3_implCompressMB", stubName) == 0) {
9439 block_size = get_block_size_from_digest_object(digest_obj);
9440 if (block_size == nullptr) return false;
9441 }
9442
9443 // Call the stub.
9444 Node* call;
9445 if (block_size == nullptr) {
9446 call = make_runtime_call(RC_LEAF|RC_NO_FP,
9447 OptoRuntime::digestBase_implCompressMB_Type(false),
9448 stubAddr, stubName, TypePtr::BOTTOM,
9449 src_start, state, ofs, limit);
9450 } else {
9451 call = make_runtime_call(RC_LEAF|RC_NO_FP,
9452 OptoRuntime::digestBase_implCompressMB_Type(true),
9453 stubAddr, stubName, TypePtr::BOTTOM,
9454 src_start, state, block_size, ofs, limit);
9455 }
9456
9457 // return ofs (int)
9458 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9459 set_result(result);
9460
9461 return true;
9462 }
9463
9464 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9465 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9466 assert(UseAES, "need AES instruction support");
9467 address stubAddr = nullptr;
9468 const char *stubName = nullptr;
9469 stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9470 stubName = "galoisCounterMode_AESCrypt";
9471
9472 if (stubAddr == nullptr) return false;
9473
9474 Node* in = argument(0);
9475 Node* inOfs = argument(1);
9476 Node* len = argument(2);
9477 Node* ct = argument(3);
9478 Node* ctOfs = argument(4);
9479 Node* out = argument(5);
9480 Node* outOfs = argument(6);
9481 Node* gctr_object = argument(7);
9482 Node* ghash_object = argument(8);
9483
9484 // (1) in, ct and out are arrays.
9485 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9486 const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9487 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9488 assert( in_type != nullptr && in_type->elem() != Type::BOTTOM &&
9489 ct_type != nullptr && ct_type->elem() != Type::BOTTOM &&
9490 out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9491
9492 // checks are the responsibility of the caller
9493 Node* in_start = in;
9494 Node* ct_start = ct;
9495 Node* out_start = out;
9496 if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9497 assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9498 in_start = array_element_address(in, inOfs, T_BYTE);
9499 ct_start = array_element_address(ct, ctOfs, T_BYTE);
9500 out_start = array_element_address(out, outOfs, T_BYTE);
9501 }
9502
9503 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9504 // (because of the predicated logic executed earlier).
9505 // so we cast it here safely.
9506 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9507 Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9508 Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9509 Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9510 Node* state = load_field_from_object(ghash_object, "state", "[J");
9511
9512 if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9513 return false;
9514 }
9515 // cast it to what we know it will be at runtime
9516 const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9517 assert(tinst != nullptr, "GCTR obj is null");
9518 assert(tinst->is_loaded(), "GCTR obj is not loaded");
9519 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9520 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9521 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9522 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9523 const TypeOopPtr* xtype = aklass->as_instance_type();
9524 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9525 aescrypt_object = _gvn.transform(aescrypt_object);
9526 // we need to get the start of the aescrypt_object's expanded key array
9527 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9528 if (k_start == nullptr) return false;
9529 // similarly, get the start address of the r vector
9530 Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9531 Node* state_start = array_element_address(state, intcon(0), T_LONG);
9532 Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9533
9534
9535 // Call the stub, passing params
9536 Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9537 OptoRuntime::galoisCounterMode_aescrypt_Type(),
9538 stubAddr, stubName, TypePtr::BOTTOM,
9539 in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9540
9541 // return cipher length (int)
9542 Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9543 set_result(retvalue);
9544
9545 return true;
9546 }
9547
9548 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9549 // Return node representing slow path of predicate check.
9550 // the pseudo code we want to emulate with this predicate is:
9551 // for encryption:
9552 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9553 // for decryption:
9554 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9555 // note cipher==plain is more conservative than the original java code but that's OK
9556 //
9557
9558 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9559 // The receiver was checked for null already.
9560 Node* objGCTR = argument(7);
9561 // Load embeddedCipher field of GCTR object.
9562 Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9563 assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9564
9565 // get AESCrypt klass for instanceOf check
9566 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9567 // will have same classloader as CipherBlockChaining object
9568 const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9569 assert(tinst != nullptr, "GCTR obj is null");
9570 assert(tinst->is_loaded(), "GCTR obj is not loaded");
9571
9572 // we want to do an instanceof comparison against the AESCrypt class
9573 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9574 if (!klass_AESCrypt->is_loaded()) {
9575 // if AESCrypt is not even loaded, we never take the intrinsic fast path
9576 Node* ctrl = control();
9577 set_control(top()); // no regular fast path
9578 return ctrl;
9579 }
9580
9581 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9582 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9583 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9584 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9585 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9586
9587 return instof_false; // even if it is null
9588 }
9589
9590 //------------------------------get_state_from_digest_object-----------------------
9591 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9592 const char* state_type;
9593 switch (elem_type) {
9594 case T_BYTE: state_type = "[B"; break;
9595 case T_INT: state_type = "[I"; break;
9596 case T_LONG: state_type = "[J"; break;
9597 default: ShouldNotReachHere();
9598 }
9599 Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9600 assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9601 if (digest_state == nullptr) return (Node *) nullptr;
9602
9603 // now have the array, need to get the start address of the state array
9604 Node* state = array_element_address(digest_state, intcon(0), elem_type);
9605 return state;
9606 }
9607
9608 //------------------------------get_block_size_from_sha3_object----------------------------------
9609 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9610 Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9611 assert (block_size != nullptr, "sanity");
9612 return block_size;
9613 }
9614
9615 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9616 // Return node representing slow path of predicate check.
9617 // the pseudo code we want to emulate with this predicate is:
9618 // if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9619 //
9620 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9621 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9622 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9623 assert((uint)predicate < 5, "sanity");
9624
9625 // The receiver was checked for null already.
9626 Node* digestBaseObj = argument(0);
9627
9628 // get DigestBase klass for instanceOf check
9629 const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9630 assert(tinst != nullptr, "digestBaseObj is null");
9631 assert(tinst->is_loaded(), "DigestBase is not loaded");
9632
9633 const char* klass_name = nullptr;
9634 switch (predicate) {
9635 case 0:
9636 if (UseMD5Intrinsics) {
9637 // we want to do an instanceof comparison against the MD5 class
9638 klass_name = "sun/security/provider/MD5";
9639 }
9640 break;
9641 case 1:
9642 if (UseSHA1Intrinsics) {
9643 // we want to do an instanceof comparison against the SHA class
9644 klass_name = "sun/security/provider/SHA";
9645 }
9646 break;
9647 case 2:
9648 if (UseSHA256Intrinsics) {
9649 // we want to do an instanceof comparison against the SHA2 class
9650 klass_name = "sun/security/provider/SHA2";
9651 }
9652 break;
9653 case 3:
9654 if (UseSHA512Intrinsics) {
9655 // we want to do an instanceof comparison against the SHA5 class
9656 klass_name = "sun/security/provider/SHA5";
9657 }
9658 break;
9659 case 4:
9660 if (UseSHA3Intrinsics) {
9661 // we want to do an instanceof comparison against the SHA3 class
9662 klass_name = "sun/security/provider/SHA3";
9663 }
9664 break;
9665 default:
9666 fatal("unknown SHA intrinsic predicate: %d", predicate);
9667 }
9668
9669 ciKlass* klass = nullptr;
9670 if (klass_name != nullptr) {
9671 klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9672 }
9673 if ((klass == nullptr) || !klass->is_loaded()) {
9674 // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9675 Node* ctrl = control();
9676 set_control(top()); // no intrinsic path
9677 return ctrl;
9678 }
9679 ciInstanceKlass* instklass = klass->as_instance_klass();
9680
9681 Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9682 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9683 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9684 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9685
9686 return instof_false; // even if it is null
9687 }
9688
9689 //-------------inline_fma-----------------------------------
9690 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9691 Node *a = nullptr;
9692 Node *b = nullptr;
9693 Node *c = nullptr;
9694 Node* result = nullptr;
9695 switch (id) {
9696 case vmIntrinsics::_fmaD:
9697 assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9698 // no receiver since it is static method
9699 a = argument(0);
9700 b = argument(2);
9701 c = argument(4);
9702 result = _gvn.transform(new FmaDNode(a, b, c));
9703 break;
9704 case vmIntrinsics::_fmaF:
9705 assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9706 a = argument(0);
9707 b = argument(1);
9708 c = argument(2);
9709 result = _gvn.transform(new FmaFNode(a, b, c));
9710 break;
9711 default:
9712 fatal_unexpected_iid(id); break;
9713 }
9714 set_result(result);
9715 return true;
9716 }
9717
9718 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9719 // argument(0) is receiver
9720 Node* codePoint = argument(1);
9721 Node* n = nullptr;
9722
9723 switch (id) {
9724 case vmIntrinsics::_isDigit :
9725 n = new DigitNode(control(), codePoint);
9726 break;
9727 case vmIntrinsics::_isLowerCase :
9728 n = new LowerCaseNode(control(), codePoint);
9729 break;
9730 case vmIntrinsics::_isUpperCase :
9731 n = new UpperCaseNode(control(), codePoint);
9732 break;
9733 case vmIntrinsics::_isWhitespace :
9734 n = new WhitespaceNode(control(), codePoint);
9735 break;
9736 default:
9737 fatal_unexpected_iid(id);
9738 }
9739
9740 set_result(_gvn.transform(n));
9741 return true;
9742 }
9743
9744 bool LibraryCallKit::inline_profileBoolean() {
9745 Node* counts = argument(1);
9746 const TypeAryPtr* ary = nullptr;
9747 ciArray* aobj = nullptr;
9748 if (counts->is_Con()
9749 && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9750 && (aobj = ary->const_oop()->as_array()) != nullptr
9751 && (aobj->length() == 2)) {
9752 // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9753 jint false_cnt = aobj->element_value(0).as_int();
9754 jint true_cnt = aobj->element_value(1).as_int();
9755
9756 if (C->log() != nullptr) {
9757 C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9758 false_cnt, true_cnt);
9759 }
9760
9761 if (false_cnt + true_cnt == 0) {
9762 // According to profile, never executed.
9763 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9764 Deoptimization::Action_reinterpret);
9765 return true;
9766 }
9767
9768 // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9769 // is a number of each value occurrences.
9770 Node* result = argument(0);
9771 if (false_cnt == 0 || true_cnt == 0) {
9772 // According to profile, one value has been never seen.
9773 int expected_val = (false_cnt == 0) ? 1 : 0;
9774
9775 Node* cmp = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9776 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9777
9778 IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9779 Node* fast_path = _gvn.transform(new IfTrueNode(check));
9780 Node* slow_path = _gvn.transform(new IfFalseNode(check));
9781
9782 { // Slow path: uncommon trap for never seen value and then reexecute
9783 // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9784 // the value has been seen at least once.
9785 PreserveJVMState pjvms(this);
9786 PreserveReexecuteState preexecs(this);
9787 jvms()->set_should_reexecute(true);
9788
9789 set_control(slow_path);
9790 set_i_o(i_o());
9791
9792 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9793 Deoptimization::Action_reinterpret);
9794 }
9795 // The guard for never seen value enables sharpening of the result and
9796 // returning a constant. It allows to eliminate branches on the same value
9797 // later on.
9798 set_control(fast_path);
9799 result = intcon(expected_val);
9800 }
9801 // Stop profiling.
9802 // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9803 // By replacing method body with profile data (represented as ProfileBooleanNode
9804 // on IR level) we effectively disable profiling.
9805 // It enables full speed execution once optimized code is generated.
9806 Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9807 C->record_for_igvn(profile);
9808 set_result(profile);
9809 return true;
9810 } else {
9811 // Continue profiling.
9812 // Profile data isn't available at the moment. So, execute method's bytecode version.
9813 // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9814 // is compiled and counters aren't available since corresponding MethodHandle
9815 // isn't a compile-time constant.
9816 return false;
9817 }
9818 }
9819
9820 bool LibraryCallKit::inline_isCompileConstant() {
9821 Node* n = argument(0);
9822 set_result(n->is_Con() ? intcon(1) : intcon(0));
9823 return true;
9824 }
9825
9826 //------------------------------- inline_getObjectSize --------------------------------------
9827 //
9828 // Calculate the runtime size of the object/array.
9829 // native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9830 //
9831 bool LibraryCallKit::inline_getObjectSize() {
9832 Node* obj = argument(3);
9833 Node* klass_node = load_object_klass(obj);
9834
9835 jint layout_con = Klass::_lh_neutral_value;
9836 Node* layout_val = get_layout_helper(klass_node, layout_con);
9837 int layout_is_con = (layout_val == nullptr);
9838
9839 if (layout_is_con) {
9840 // Layout helper is constant, can figure out things at compile time.
9841
9842 if (Klass::layout_helper_is_instance(layout_con)) {
9843 // Instance case: layout_con contains the size itself.
9844 Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9845 set_result(size);
9846 } else {
9847 // Array case: size is round(header + element_size*arraylength).
9848 // Since arraylength is different for every array instance, we have to
9849 // compute the whole thing at runtime.
9850
9851 Node* arr_length = load_array_length(obj);
9852
9853 int round_mask = MinObjAlignmentInBytes - 1;
9854 int hsize = Klass::layout_helper_header_size(layout_con);
9855 int eshift = Klass::layout_helper_log2_element_size(layout_con);
9856
9857 if ((round_mask & ~right_n_bits(eshift)) == 0) {
9858 round_mask = 0; // strength-reduce it if it goes away completely
9859 }
9860 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9861 Node* header_size = intcon(hsize + round_mask);
9862
9863 Node* lengthx = ConvI2X(arr_length);
9864 Node* headerx = ConvI2X(header_size);
9865
9866 Node* abody = lengthx;
9867 if (eshift != 0) {
9868 abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9869 }
9870 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9871 if (round_mask != 0) {
9872 size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9873 }
9874 size = ConvX2L(size);
9875 set_result(size);
9876 }
9877 } else {
9878 // Layout helper is not constant, need to test for array-ness at runtime.
9879
9880 enum { _instance_path = 1, _array_path, PATH_LIMIT };
9881 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9882 PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9883 record_for_igvn(result_reg);
9884
9885 Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9886 if (array_ctl != nullptr) {
9887 // Array case: size is round(header + element_size*arraylength).
9888 // Since arraylength is different for every array instance, we have to
9889 // compute the whole thing at runtime.
9890
9891 PreserveJVMState pjvms(this);
9892 set_control(array_ctl);
9893 Node* arr_length = load_array_length(obj);
9894
9895 int round_mask = MinObjAlignmentInBytes - 1;
9896 Node* mask = intcon(round_mask);
9897
9898 Node* hss = intcon(Klass::_lh_header_size_shift);
9899 Node* hsm = intcon(Klass::_lh_header_size_mask);
9900 Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9901 header_size = _gvn.transform(new AndINode(header_size, hsm));
9902 header_size = _gvn.transform(new AddINode(header_size, mask));
9903
9904 // There is no need to mask or shift this value.
9905 // The semantics of LShiftINode include an implicit mask to 0x1F.
9906 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9907 Node* elem_shift = layout_val;
9908
9909 Node* lengthx = ConvI2X(arr_length);
9910 Node* headerx = ConvI2X(header_size);
9911
9912 Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9913 Node* size = _gvn.transform(new AddXNode(headerx, abody));
9914 if (round_mask != 0) {
9915 size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9916 }
9917 size = ConvX2L(size);
9918
9919 result_reg->init_req(_array_path, control());
9920 result_val->init_req(_array_path, size);
9921 }
9922
9923 if (!stopped()) {
9924 // Instance case: the layout helper gives us instance size almost directly,
9925 // but we need to mask out the _lh_instance_slow_path_bit.
9926 Node* size = ConvI2X(layout_val);
9927 assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9928 Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9929 size = _gvn.transform(new AndXNode(size, mask));
9930 size = ConvX2L(size);
9931
9932 result_reg->init_req(_instance_path, control());
9933 result_val->init_req(_instance_path, size);
9934 }
9935
9936 set_result(result_reg, result_val);
9937 }
9938
9939 return true;
9940 }
9941
9942 //------------------------------- inline_blackhole --------------------------------------
9943 //
9944 // Make sure all arguments to this node are alive.
9945 // This matches methods that were requested to be blackholed through compile commands.
9946 //
9947 bool LibraryCallKit::inline_blackhole() {
9948 assert(callee()->is_static(), "Should have been checked before: only static methods here");
9949 assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9950 assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9951
9952 // Blackhole node pinches only the control, not memory. This allows
9953 // the blackhole to be pinned in the loop that computes blackholed
9954 // values, but have no other side effects, like breaking the optimizations
9955 // across the blackhole.
9956
9957 Node* bh = _gvn.transform(new BlackholeNode(control()));
9958 set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9959
9960 // Bind call arguments as blackhole arguments to keep them alive
9961 uint nargs = callee()->arg_size();
9962 for (uint i = 0; i < nargs; i++) {
9963 bh->add_req(argument(i));
9964 }
9965
9966 return true;
9967 }
9968
9969 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9970 const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9971 if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9972 return nullptr; // box klass is not Float16
9973 }
9974
9975 // Null check; get notnull casted pointer
9976 Node* null_ctl = top();
9977 Node* not_null_box = null_check_oop(box, &null_ctl, true);
9978 // If not_null_box is dead, only null-path is taken
9979 if (stopped()) {
9980 set_control(null_ctl);
9981 return nullptr;
9982 }
9983 assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9984 const TypePtr* adr_type = C->alias_type(field)->adr_type();
9985 Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9986 return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9987 }
9988
9989 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9990 PreserveReexecuteState preexecs(this);
9991 jvms()->set_should_reexecute(true);
9992
9993 const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9994 Node* klass_node = makecon(klass_type);
9995 Node* box = new_instance(klass_node);
9996
9997 Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9998 const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9999
10000 Node* field_store = _gvn.transform(access_store_at(box,
10001 value_field,
10002 value_adr_type,
10003 value,
10004 TypeInt::SHORT,
10005 T_SHORT,
10006 IN_HEAP));
10007 set_memory(field_store, value_adr_type);
10008 return box;
10009 }
10010
10011 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
10012 if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
10013 !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
10014 return false;
10015 }
10016
10017 const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
10018 if (box_type == nullptr || box_type->const_oop() == nullptr) {
10019 return false;
10020 }
10021
10022 ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
10023 const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
10024 ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
10025 ciSymbols::short_signature(),
10026 false);
10027 assert(field != nullptr, "");
10028
10029 // Transformed nodes
10030 Node* fld1 = nullptr;
10031 Node* fld2 = nullptr;
10032 Node* fld3 = nullptr;
10033 switch(num_args) {
10034 case 3:
10035 fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
10036 if (fld3 == nullptr) {
10037 return false;
10038 }
10039 fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
10040 // fall-through
10041 case 2:
10042 fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
10043 if (fld2 == nullptr) {
10044 return false;
10045 }
10046 fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
10047 // fall-through
10048 case 1:
10049 fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
10050 if (fld1 == nullptr) {
10051 return false;
10052 }
10053 fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
10054 break;
10055 default: fatal("Unsupported number of arguments %d", num_args);
10056 }
10057
10058 Node* result = nullptr;
10059 switch (id) {
10060 // Unary operations
10061 case vmIntrinsics::_sqrt_float16:
10062 result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
10063 break;
10064 // Ternary operations
10065 case vmIntrinsics::_fma_float16:
10066 result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
10067 break;
10068 default:
10069 fatal_unexpected_iid(id);
10070 break;
10071 }
10072 result = _gvn.transform(new ReinterpretHF2SNode(result));
10073 set_result(box_fp16_value(float16_box_type, field, result));
10074 return true;
10075 }
10076