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 bool is_non_heap_access = (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR);
2480 if (is_non_heap_access) {
2481 if (type != T_OBJECT) {
2482 decorators |= IN_NATIVE; // off-heap primitive access
2483 } else {
2484 return false; // off-heap oop accesses are not supported
2485 }
2486 } else {
2487 heap_base_oop = base; // on-heap or mixed access
2488 }
2489
2490 // Can base be null? Otherwise, always on-heap access.
2491 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2492
2493 assert(!is_non_heap_access || can_access_non_heap, "sanity"); // is_non_heap_access implies can_access_non_heap
2494
2495 if (!can_access_non_heap) {
2496 decorators |= IN_HEAP;
2497 }
2498
2499 Node* val = is_store ? argument(4) : nullptr;
2500
2501 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2502 if (adr_type == TypePtr::NULL_PTR) {
2503 return false; // off-heap access with zero address
2504 }
2505
2506 // Try to categorize the address.
2507 Compile::AliasType* alias_type = C->alias_type(adr_type);
2508 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2509
2510 assert((alias_type->index() == Compile::AliasIdxRaw) ==
2511 (is_non_heap_access || (can_access_non_heap && alias_type->field() == nullptr)), "wrong alias");
2512
2513 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2514 alias_type->adr_type() == TypeAryPtr::RANGE) {
2515 return false; // not supported
2516 }
2517
2518 bool mismatched = false;
2519 BasicType bt = T_ILLEGAL;
2520 ciField* field = nullptr;
2521 if (adr_type->isa_instptr()) {
2522 const TypeInstPtr* instptr = adr_type->is_instptr();
2523 ciInstanceKlass* k = instptr->instance_klass();
2524 int off = instptr->offset();
2525 if (instptr->const_oop() != nullptr &&
2526 k == ciEnv::current()->Class_klass() &&
2527 instptr->offset() >= (k->size_helper() * wordSize)) {
2528 k = instptr->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
2529 field = k->get_field_by_offset(off, true);
2530 } else {
2531 field = k->get_non_flat_field_by_offset(off);
2532 }
2533 if (field != nullptr) {
2534 bt = type2field[field->type()->basic_type()];
2535 }
2536 if (bt != alias_type->basic_type()) {
2537 // Type mismatch. Is it an access to a nested flat field?
2538 field = k->get_field_by_offset(off, false);
2539 if (field != nullptr) {
2540 bt = type2field[field->type()->basic_type()];
2541 }
2542 }
2543 assert(bt == alias_type->basic_type(), "should match");
2544 } else {
2545 bt = alias_type->basic_type();
2546 }
2547
2548 if (bt != T_ILLEGAL) {
2549 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2550 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2551 // Alias type doesn't differentiate between byte[] and boolean[]).
2552 // Use address type to get the element type.
2553 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2554 }
2555 if (is_reference_type(bt, true)) {
2556 // accessing an array field with getReference is not a mismatch
2557 bt = T_OBJECT;
2558 }
2559 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2560 // Don't intrinsify mismatched object accesses
2561 return false;
2562 }
2563 mismatched = (bt != type);
2564 } else if (alias_type->adr_type()->isa_oopptr()) {
2565 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2566 }
2567
2568 old_state.discard();
2569 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2570
2571 if (mismatched) {
2572 decorators |= C2_MISMATCHED;
2573 }
2574
2575 // First guess at the value type.
2576 const Type *value_type = Type::get_const_basic_type(type);
2577
2578 // Figure out the memory ordering.
2579 decorators |= mo_decorator_for_access_kind(kind);
2580
2581 if (!is_store) {
2582 if (type == T_OBJECT) {
2583 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2584 if (tjp != nullptr) {
2585 value_type = tjp;
2586 }
2587 } else if (type == T_BOOLEAN) {
2588 if (mismatched || alias_type->index() == Compile::AliasIdxRaw) {
2589 value_type = TypeInt::UBYTE;
2590 }
2591 }
2592 }
2593
2594 receiver = null_check(receiver);
2595 if (stopped()) {
2596 return true;
2597 }
2598 // Heap pointers get a null-check from the interpreter,
2599 // as a courtesy. However, this is not guaranteed by Unsafe,
2600 // and it is not possible to fully distinguish unintended nulls
2601 // from intended ones in this API.
2602
2603 if (!is_store) {
2604 Node* p = nullptr;
2605 // Try to constant fold a load from a constant field
2606
2607 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !field->is_flat() && !mismatched) {
2608 // final or stable field
2609 p = make_constant_from_field(field, heap_base_oop);
2610 }
2611
2612 if (p == nullptr) { // Could not constant fold the load
2613 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2614 const TypeOopPtr* ptr = value_type->make_oopptr();
2615 if (ptr != nullptr && ptr->is_inlinetypeptr()) {
2616 // Load a non-flattened inline type from memory
2617 p = InlineTypeNode::make_from_oop(this, p, ptr->inline_klass());
2618 }
2619 }
2620 if (type == T_ADDRESS) {
2621 p = gvn().transform(new CastP2XNode(nullptr, p));
2622 p = ConvX2UL(p);
2623 } else if (type == T_BOOLEAN) {
2624 // Truncate boolean values returned by unsafe operations.
2625 p = gvn().transform(new AndINode(p, gvn().intcon(0x1)));
2626 }
2627 // The load node has the control of the preceding MemBarCPUOrder. All
2628 // following nodes will have the control of the MemBarCPUOrder inserted at
2629 // the end of this method. So, pushing the load onto the stack at a later
2630 // point is fine.
2631 set_result(p);
2632 } else {
2633 if (bt == T_ADDRESS) {
2634 // Repackage the long as a pointer.
2635 val = ConvL2X(val);
2636 val = gvn().transform(new CastX2PNode(val));
2637 }
2638 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2639 }
2640
2641 return true;
2642 }
2643
2644 bool LibraryCallKit::inline_unsafe_flat_access(bool is_store, AccessKind kind) {
2645 #ifdef ASSERT
2646 {
2647 ResourceMark rm;
2648 // Check the signatures.
2649 ciSignature* sig = callee()->signature();
2650 assert(sig->type_at(0)->basic_type() == T_OBJECT, "base should be object, but is %s", type2name(sig->type_at(0)->basic_type()));
2651 assert(sig->type_at(1)->basic_type() == T_LONG, "offset should be long, but is %s", type2name(sig->type_at(1)->basic_type()));
2652 assert(sig->type_at(2)->basic_type() == T_INT, "layout kind should be int, but is %s", type2name(sig->type_at(3)->basic_type()));
2653 assert(sig->type_at(3)->basic_type() == T_OBJECT, "value klass should be object, but is %s", type2name(sig->type_at(4)->basic_type()));
2654 if (is_store) {
2655 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value, but returns %s", type2name(sig->return_type()->basic_type()));
2656 assert(sig->count() == 5, "flat putter should have 5 arguments, but has %d", sig->count());
2657 assert(sig->type_at(4)->basic_type() == T_OBJECT, "put value should be object, but is %s", type2name(sig->type_at(5)->basic_type()));
2658 } else {
2659 assert(sig->return_type()->basic_type() == T_OBJECT, "getter must return an object, but returns %s", type2name(sig->return_type()->basic_type()));
2660 assert(sig->count() == 4, "flat getter should have 4 arguments, but has %d", sig->count());
2661 }
2662 }
2663 #endif // ASSERT
2664
2665 assert(kind == Relaxed, "Only plain accesses for now");
2666 if (callee()->is_static()) {
2667 // caller must have the capability!
2668 return false;
2669 }
2670 C->set_has_unsafe_access(true);
2671
2672 const TypeInstPtr* value_klass_node = _gvn.type(argument(5))->isa_instptr();
2673 if (value_klass_node == nullptr || value_klass_node->const_oop() == nullptr) {
2674 // parameter valueType is not a constant
2675 return false;
2676 }
2677 ciType* mirror_type = value_klass_node->const_oop()->as_instance()->java_mirror_type();
2678 if (!mirror_type->is_inlinetype()) {
2679 // Dead code
2680 return false;
2681 }
2682 ciInlineKlass* value_klass = mirror_type->as_inline_klass();
2683
2684 const TypeInt* layout_type = _gvn.type(argument(4))->isa_int();
2685 if (layout_type == nullptr || !layout_type->is_con()) {
2686 // parameter layoutKind is not a constant
2687 return false;
2688 }
2689 assert(layout_type->get_con() >= static_cast<int>(LayoutKind::REFERENCE) &&
2690 layout_type->get_con() < static_cast<int>(LayoutKind::UNKNOWN),
2691 "invalid layoutKind %d", layout_type->get_con());
2692 LayoutKind layout = static_cast<LayoutKind>(layout_type->get_con());
2693 assert(layout == LayoutKind::REFERENCE || layout == LayoutKind::NULL_FREE_NON_ATOMIC_FLAT ||
2694 layout == LayoutKind::NULL_FREE_ATOMIC_FLAT || layout == LayoutKind::NULLABLE_ATOMIC_FLAT,
2695 "unexpected layoutKind %d", layout_type->get_con());
2696
2697 null_check(argument(0));
2698 if (stopped()) {
2699 return true;
2700 }
2701
2702 Node* base = must_be_not_null(argument(1), true);
2703 Node* offset = argument(2);
2704 const Type* base_type = _gvn.type(base);
2705
2706 Node* ptr;
2707 bool immutable_memory = false;
2708 DecoratorSet decorators = C2_UNSAFE_ACCESS | IN_HEAP | MO_UNORDERED;
2709 if (base_type->isa_instptr()) {
2710 const TypeLong* offset_type = _gvn.type(offset)->isa_long();
2711 if (offset_type == nullptr || !offset_type->is_con()) {
2712 // Offset into a non-array should be a constant
2713 decorators |= C2_MISMATCHED;
2714 } else {
2715 int offset_con = checked_cast<int>(offset_type->get_con());
2716 ciInstanceKlass* base_klass = base_type->is_instptr()->instance_klass();
2717 ciField* field = base_klass->get_non_flat_field_by_offset(offset_con);
2718 if (field == nullptr) {
2719 assert(!base_klass->is_final(), "non-existence field at offset %d of class %s", offset_con, base_klass->name()->as_utf8());
2720 decorators |= C2_MISMATCHED;
2721 } else {
2722 assert(field->type() == value_klass, "field at offset %d of %s is of type %s, but valueType is %s",
2723 offset_con, base_klass->name()->as_utf8(), field->type()->name(), value_klass->name()->as_utf8());
2724 immutable_memory = field->is_strict() && field->is_final();
2725
2726 if (base->is_InlineType()) {
2727 assert(!is_store, "Cannot store into a non-larval value object");
2728 set_result(base->as_InlineType()->field_value_by_offset(offset_con, false));
2729 return true;
2730 }
2731 }
2732 }
2733
2734 if (base->is_InlineType()) {
2735 assert(!is_store, "Cannot store into a non-larval value object");
2736 base = base->as_InlineType()->buffer(this, true);
2737 }
2738 ptr = basic_plus_adr(base, ConvL2X(offset));
2739 } else if (base_type->isa_aryptr()) {
2740 decorators |= IS_ARRAY;
2741 if (layout == LayoutKind::REFERENCE) {
2742 if (!base_type->is_aryptr()->is_not_flat()) {
2743 const TypeAryPtr* array_type = base_type->is_aryptr()->cast_to_not_flat();
2744 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2745 Node* new_base = _gvn.transform(new CastPPNode(control(), base, array_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2746 replace_in_map(base, new_base);
2747 base = new_base;
2748 }
2749 ptr = basic_plus_adr(base, ConvL2X(offset));
2750 } else {
2751 if (UseArrayFlattening) {
2752 // Flat array must have an exact type
2753 bool is_null_free = !LayoutKindHelper::is_nullable_flat(layout);
2754 bool is_atomic = LayoutKindHelper::is_atomic_flat(layout);
2755 Node* new_base = cast_to_flat_array_exact(base, value_klass, is_null_free, is_atomic);
2756 replace_in_map(base, new_base);
2757 base = new_base;
2758 ptr = basic_plus_adr(base, ConvL2X(offset));
2759 const TypeAryPtr* ptr_type = _gvn.type(ptr)->is_aryptr();
2760 if (ptr_type->field_offset().get() != 0) {
2761 // TODO 8350865 This should be a CheckCastPP, can we add a test?
2762 ptr = _gvn.transform(new CastPPNode(control(), ptr, ptr_type->with_field_offset(0), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2763 }
2764 } else {
2765 uncommon_trap(Deoptimization::Reason_intrinsic,
2766 Deoptimization::Action_none);
2767 return true;
2768 }
2769 }
2770 } else {
2771 decorators |= C2_MISMATCHED;
2772 ptr = basic_plus_adr(base, ConvL2X(offset));
2773 }
2774
2775 if (is_store) {
2776 Node* value = argument(6);
2777 const Type* value_type = _gvn.type(value);
2778 if (!value_type->is_inlinetypeptr()) {
2779 value_type = Type::get_const_type(value_klass)->filter_speculative(value_type);
2780 Node* new_value = _gvn.transform(new CheckCastPPNode(control(), value, value_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
2781 new_value = InlineTypeNode::make_from_oop(this, new_value, value_klass);
2782 replace_in_map(value, new_value);
2783 value = new_value;
2784 }
2785
2786 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());
2787 if (layout == LayoutKind::REFERENCE) {
2788 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2789 access_store_at(base, ptr, ptr_type, value, value_type, T_OBJECT, decorators);
2790 } else {
2791 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2792 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2793 value->as_InlineType()->store_flat(this, base, ptr, atomic, immutable_memory, null_free, decorators);
2794 }
2795
2796 return true;
2797 } else {
2798 decorators |= (C2_CONTROL_DEPENDENT_LOAD | C2_UNKNOWN_CONTROL_LOAD);
2799 InlineTypeNode* result;
2800 if (layout == LayoutKind::REFERENCE) {
2801 const TypePtr* ptr_type = (decorators & C2_MISMATCHED) != 0 ? TypeRawPtr::BOTTOM : _gvn.type(ptr)->is_ptr();
2802 Node* oop = access_load_at(base, ptr, ptr_type, Type::get_const_type(value_klass), T_OBJECT, decorators);
2803 result = InlineTypeNode::make_from_oop(this, oop, value_klass);
2804 } else {
2805 bool atomic = LayoutKindHelper::is_atomic_flat(layout);
2806 bool null_free = !LayoutKindHelper::is_nullable_flat(layout);
2807 result = InlineTypeNode::make_from_flat(this, value_klass, base, ptr, atomic, immutable_memory, null_free, decorators);
2808 }
2809
2810 set_result(result);
2811 return true;
2812 }
2813 }
2814
2815 //----------------------------inline_unsafe_load_store----------------------------
2816 // This method serves a couple of different customers (depending on LoadStoreKind):
2817 //
2818 // LS_cmp_swap:
2819 //
2820 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2821 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2822 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2823 //
2824 // LS_cmp_swap_weak:
2825 //
2826 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2827 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2828 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2829 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2830 //
2831 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2832 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2833 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2834 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2835 //
2836 // boolean weakCompareAndSetLong( Object o, long offset, long expected, long x);
2837 // boolean weakCompareAndSetLongPlain( Object o, long offset, long expected, long x);
2838 // boolean weakCompareAndSetLongAcquire( Object o, long offset, long expected, long x);
2839 // boolean weakCompareAndSetLongRelease( Object o, long offset, long expected, long x);
2840 //
2841 // LS_cmp_exchange:
2842 //
2843 // Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2844 // Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2845 // Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2846 //
2847 // Object compareAndExchangeIntVolatile( Object o, long offset, Object expected, Object x);
2848 // Object compareAndExchangeIntAcquire( Object o, long offset, Object expected, Object x);
2849 // Object compareAndExchangeIntRelease( Object o, long offset, Object expected, Object x);
2850 //
2851 // Object compareAndExchangeLongVolatile( Object o, long offset, Object expected, Object x);
2852 // Object compareAndExchangeLongAcquire( Object o, long offset, Object expected, Object x);
2853 // Object compareAndExchangeLongRelease( Object o, long offset, Object expected, Object x);
2854 //
2855 // LS_get_add:
2856 //
2857 // int getAndAddInt( Object o, long offset, int delta)
2858 // long getAndAddLong(Object o, long offset, long delta)
2859 //
2860 // LS_get_set:
2861 //
2862 // int getAndSet(Object o, long offset, int newValue)
2863 // long getAndSet(Object o, long offset, long newValue)
2864 // Object getAndSet(Object o, long offset, Object newValue)
2865 //
2866 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2867 // This basic scheme here is the same as inline_unsafe_access, but
2868 // differs in enough details that combining them would make the code
2869 // overly confusing. (This is a true fact! I originally combined
2870 // them, but even I was confused by it!) As much code/comments as
2871 // possible are retained from inline_unsafe_access though to make
2872 // the correspondences clearer. - dl
2873
2874 if (callee()->is_static()) return false; // caller must have the capability!
2875
2876 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2877 decorators |= mo_decorator_for_access_kind(access_kind);
2878
2879 #ifndef PRODUCT
2880 BasicType rtype;
2881 {
2882 ResourceMark rm;
2883 // Check the signatures.
2884 ciSignature* sig = callee()->signature();
2885 rtype = sig->return_type()->basic_type();
2886 switch(kind) {
2887 case LS_get_add:
2888 case LS_get_set: {
2889 // Check the signatures.
2890 #ifdef ASSERT
2891 assert(rtype == type, "get and set must return the expected type");
2892 assert(sig->count() == 3, "get and set has 3 arguments");
2893 assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2894 assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2895 assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2896 assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2897 #endif // ASSERT
2898 break;
2899 }
2900 case LS_cmp_swap:
2901 case LS_cmp_swap_weak: {
2902 // Check the signatures.
2903 #ifdef ASSERT
2904 assert(rtype == T_BOOLEAN, "CAS must return boolean");
2905 assert(sig->count() == 4, "CAS has 4 arguments");
2906 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2907 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2908 #endif // ASSERT
2909 break;
2910 }
2911 case LS_cmp_exchange: {
2912 // Check the signatures.
2913 #ifdef ASSERT
2914 assert(rtype == type, "CAS must return the expected type");
2915 assert(sig->count() == 4, "CAS has 4 arguments");
2916 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2917 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2918 #endif // ASSERT
2919 break;
2920 }
2921 default:
2922 ShouldNotReachHere();
2923 }
2924 }
2925 #endif //PRODUCT
2926
2927 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2928
2929 // Get arguments:
2930 Node* receiver = nullptr;
2931 Node* base = nullptr;
2932 Node* offset = nullptr;
2933 Node* oldval = nullptr;
2934 Node* newval = nullptr;
2935 switch(kind) {
2936 case LS_cmp_swap:
2937 case LS_cmp_swap_weak:
2938 case LS_cmp_exchange: {
2939 const bool two_slot_type = type2size[type] == 2;
2940 receiver = argument(0); // type: oop
2941 base = argument(1); // type: oop
2942 offset = argument(2); // type: long
2943 oldval = argument(4); // type: oop, int, or long
2944 newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long
2945 break;
2946 }
2947 case LS_get_add:
2948 case LS_get_set: {
2949 receiver = argument(0); // type: oop
2950 base = argument(1); // type: oop
2951 offset = argument(2); // type: long
2952 oldval = nullptr;
2953 newval = argument(4); // type: oop, int, or long
2954 break;
2955 }
2956 default:
2957 ShouldNotReachHere();
2958 }
2959
2960 // Build field offset expression.
2961 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2962 // to be plain byte offsets, which are also the same as those accepted
2963 // by oopDesc::field_addr.
2964 assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2965 // 32-bit machines ignore the high half of long offsets
2966 offset = ConvL2X(offset);
2967 // Save state and restore on bailout
2968 SavedState old_state(this);
2969 Node* adr = make_unsafe_address(base, offset,type, false);
2970 const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2971
2972 Compile::AliasType* alias_type = C->alias_type(adr_type);
2973 BasicType bt = alias_type->basic_type();
2974 if (bt != T_ILLEGAL &&
2975 (is_reference_type(bt) != (type == T_OBJECT))) {
2976 // Don't intrinsify mismatched object accesses.
2977 return false;
2978 }
2979
2980 old_state.discard();
2981
2982 // For CAS, unlike inline_unsafe_access, there seems no point in
2983 // trying to refine types. Just use the coarse types here.
2984 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2985 const Type *value_type = Type::get_const_basic_type(type);
2986
2987 switch (kind) {
2988 case LS_get_set:
2989 case LS_cmp_exchange: {
2990 if (type == T_OBJECT) {
2991 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2992 if (tjp != nullptr) {
2993 value_type = tjp;
2994 }
2995 }
2996 break;
2997 }
2998 case LS_cmp_swap:
2999 case LS_cmp_swap_weak:
3000 case LS_get_add:
3001 break;
3002 default:
3003 ShouldNotReachHere();
3004 }
3005
3006 // Null check receiver.
3007 receiver = null_check(receiver);
3008 if (stopped()) {
3009 return true;
3010 }
3011
3012 int alias_idx = C->get_alias_index(adr_type);
3013
3014 if (is_reference_type(type)) {
3015 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
3016
3017 if (oldval != nullptr && oldval->is_InlineType()) {
3018 // Re-execute the unsafe access if allocation triggers deoptimization.
3019 PreserveReexecuteState preexecs(this);
3020 jvms()->set_should_reexecute(true);
3021 oldval = oldval->as_InlineType()->buffer(this)->get_oop();
3022 }
3023 if (newval != nullptr && newval->is_InlineType()) {
3024 // Re-execute the unsafe access if allocation triggers deoptimization.
3025 PreserveReexecuteState preexecs(this);
3026 jvms()->set_should_reexecute(true);
3027 newval = newval->as_InlineType()->buffer(this)->get_oop();
3028 }
3029
3030 // Transformation of a value which could be null pointer (CastPP #null)
3031 // could be delayed during Parse (for example, in adjust_map_after_if()).
3032 // Execute transformation here to avoid barrier generation in such case.
3033 if (_gvn.type(newval) == TypePtr::NULL_PTR)
3034 newval = _gvn.makecon(TypePtr::NULL_PTR);
3035
3036 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
3037 // Refine the value to a null constant, when it is known to be null
3038 oldval = _gvn.makecon(TypePtr::NULL_PTR);
3039 }
3040 }
3041
3042 Node* result = nullptr;
3043 switch (kind) {
3044 case LS_cmp_exchange: {
3045 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
3046 oldval, newval, value_type, type, decorators);
3047 break;
3048 }
3049 case LS_cmp_swap_weak:
3050 decorators |= C2_WEAK_CMPXCHG;
3051 case LS_cmp_swap: {
3052 result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
3053 oldval, newval, value_type, type, decorators);
3054 break;
3055 }
3056 case LS_get_set: {
3057 result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
3058 newval, value_type, type, decorators);
3059 break;
3060 }
3061 case LS_get_add: {
3062 result = access_atomic_add_at(base, adr, adr_type, alias_idx,
3063 newval, value_type, type, decorators);
3064 break;
3065 }
3066 default:
3067 ShouldNotReachHere();
3068 }
3069
3070 assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
3071 set_result(result);
3072 return true;
3073 }
3074
3075 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
3076 // Regardless of form, don't allow previous ld/st to move down,
3077 // then issue acquire, release, or volatile mem_bar.
3078 insert_mem_bar(Op_MemBarCPUOrder);
3079 switch(id) {
3080 case vmIntrinsics::_loadFence:
3081 insert_mem_bar(Op_LoadFence);
3082 return true;
3083 case vmIntrinsics::_storeFence:
3084 insert_mem_bar(Op_StoreFence);
3085 return true;
3086 case vmIntrinsics::_storeStoreFence:
3087 insert_mem_bar(Op_StoreStoreFence);
3088 return true;
3089 case vmIntrinsics::_fullFence:
3090 insert_mem_bar(Op_MemBarFull);
3091 return true;
3092 default:
3093 fatal_unexpected_iid(id);
3094 return false;
3095 }
3096 }
3097
3098 // private native int arrayInstanceBaseOffset0(Object[] array);
3099 bool LibraryCallKit::inline_arrayInstanceBaseOffset() {
3100 Node* array = argument(1);
3101 Node* klass_node = load_object_klass(array);
3102
3103 jint layout_con = Klass::_lh_neutral_value;
3104 Node* layout_val = get_layout_helper(klass_node, layout_con);
3105 int layout_is_con = (layout_val == nullptr);
3106
3107 Node* header_size = nullptr;
3108 if (layout_is_con) {
3109 int hsize = Klass::layout_helper_header_size(layout_con);
3110 header_size = intcon(hsize);
3111 } else {
3112 Node* hss = intcon(Klass::_lh_header_size_shift);
3113 Node* hsm = intcon(Klass::_lh_header_size_mask);
3114 header_size = _gvn.transform(new URShiftINode(layout_val, hss));
3115 header_size = _gvn.transform(new AndINode(header_size, hsm));
3116 }
3117 set_result(header_size);
3118 return true;
3119 }
3120
3121 // private native int arrayInstanceIndexScale0(Object[] array);
3122 bool LibraryCallKit::inline_arrayInstanceIndexScale() {
3123 Node* array = argument(1);
3124 Node* klass_node = load_object_klass(array);
3125
3126 jint layout_con = Klass::_lh_neutral_value;
3127 Node* layout_val = get_layout_helper(klass_node, layout_con);
3128 int layout_is_con = (layout_val == nullptr);
3129
3130 Node* element_size = nullptr;
3131 if (layout_is_con) {
3132 int log_element_size = Klass::layout_helper_log2_element_size(layout_con);
3133 int elem_size = 1 << log_element_size;
3134 element_size = intcon(elem_size);
3135 } else {
3136 Node* ess = intcon(Klass::_lh_log2_element_size_shift);
3137 Node* esm = intcon(Klass::_lh_log2_element_size_mask);
3138 Node* log_element_size = _gvn.transform(new URShiftINode(layout_val, ess));
3139 log_element_size = _gvn.transform(new AndINode(log_element_size, esm));
3140 element_size = _gvn.transform(new LShiftINode(intcon(1), log_element_size));
3141 }
3142 set_result(element_size);
3143 return true;
3144 }
3145
3146 // private native int arrayLayout0(Object[] array);
3147 bool LibraryCallKit::inline_arrayLayout() {
3148 RegionNode* region = new RegionNode(2);
3149 Node* phi = new PhiNode(region, TypeInt::POS);
3150
3151 Node* array = argument(1);
3152 Node* klass_node = load_object_klass(array);
3153 generate_refArray_guard(klass_node, region);
3154 if (region->req() == 3) {
3155 phi->add_req(intcon((jint)LayoutKind::REFERENCE));
3156 }
3157
3158 int layout_kind_offset = in_bytes(FlatArrayKlass::layout_kind_offset());
3159 Node* layout_kind_addr = basic_plus_adr(top(), klass_node, layout_kind_offset);
3160 Node* layout_kind = make_load(nullptr, layout_kind_addr, TypeInt::POS, T_INT, MemNode::unordered);
3161
3162 region->init_req(1, control());
3163 phi->init_req(1, layout_kind);
3164
3165 set_control(_gvn.transform(region));
3166 set_result(_gvn.transform(phi));
3167 return true;
3168 }
3169
3170 // private native int[] getFieldMap0(Class <?> c);
3171 // int offset = c._klass._acmp_maps_offset;
3172 // return (int[])c.obj_field(offset);
3173 bool LibraryCallKit::inline_getFieldMap() {
3174 Node* mirror = argument(1);
3175 Node* klass = load_klass_from_mirror(mirror, false, nullptr, 0);
3176
3177 int field_map_offset_offset = in_bytes(InstanceKlass::acmp_maps_offset_offset());
3178 Node* field_map_offset_addr = basic_plus_adr(top(), klass, field_map_offset_offset);
3179 Node* field_map_offset = make_load(nullptr, field_map_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
3180 field_map_offset = _gvn.transform(ConvI2L(field_map_offset));
3181
3182 Node* map_addr = basic_plus_adr(mirror, field_map_offset);
3183 const TypeAryPtr* val_type = TypeAryPtr::INTS->cast_to_ptr_type(TypePtr::NotNull)->with_offset(0);
3184 Node* map = access_load_at(mirror, map_addr, TypeAryPtr::INTS, val_type, T_ARRAY, IN_HEAP | MO_UNORDERED);
3185
3186 set_result(map);
3187 return true;
3188 }
3189
3190 bool LibraryCallKit::inline_onspinwait() {
3191 insert_mem_bar(Op_OnSpinWait);
3192 return true;
3193 }
3194
3195 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
3196 if (!kls->is_Con()) {
3197 return true;
3198 }
3199 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
3200 if (klsptr == nullptr) {
3201 return true;
3202 }
3203 ciInstanceKlass* ik = klsptr->instance_klass();
3204 // don't need a guard for a klass that is already initialized
3205 return !ik->is_initialized();
3206 }
3207
3208 //----------------------------inline_unsafe_writeback0-------------------------
3209 // public native void Unsafe.writeback0(long address)
3210 bool LibraryCallKit::inline_unsafe_writeback0() {
3211 if (!Matcher::has_match_rule(Op_CacheWB)) {
3212 return false;
3213 }
3214 #ifndef PRODUCT
3215 assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
3216 assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
3217 ciSignature* sig = callee()->signature();
3218 assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
3219 #endif
3220 null_check_receiver(); // null-check, then ignore
3221 Node *addr = argument(1);
3222 addr = new CastX2PNode(addr);
3223 addr = _gvn.transform(addr);
3224 Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
3225 flush = _gvn.transform(flush);
3226 set_memory(flush, TypeRawPtr::BOTTOM);
3227 return true;
3228 }
3229
3230 //----------------------------inline_unsafe_writeback0-------------------------
3231 // public native void Unsafe.writeback0(long address)
3232 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
3233 if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
3234 return false;
3235 }
3236 if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
3237 return false;
3238 }
3239 #ifndef PRODUCT
3240 assert(Matcher::has_match_rule(Op_CacheWB),
3241 (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
3242 : "found match rule for CacheWBPostSync but not CacheWB"));
3243
3244 #endif
3245 null_check_receiver(); // null-check, then ignore
3246 Node *sync;
3247 if (is_pre) {
3248 sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3249 } else {
3250 sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
3251 }
3252 sync = _gvn.transform(sync);
3253 set_memory(sync, TypeRawPtr::BOTTOM);
3254 return true;
3255 }
3256
3257 //----------------------------inline_unsafe_allocate---------------------------
3258 // public native Object Unsafe.allocateInstance(Class<?> cls);
3259 bool LibraryCallKit::inline_unsafe_allocate() {
3260
3261 #if INCLUDE_JVMTI
3262 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3263 return false;
3264 }
3265 #endif //INCLUDE_JVMTI
3266
3267 if (callee()->is_static()) return false; // caller must have the capability!
3268
3269 null_check_receiver(); // null-check, then ignore
3270 Node* cls = null_check(argument(1));
3271 if (stopped()) return true;
3272
3273 Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
3274 kls = null_check(kls);
3275 if (stopped()) return true; // argument was like int.class
3276
3277 #if INCLUDE_JVMTI
3278 // Don't try to access new allocated obj in the intrinsic.
3279 // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
3280 // Deoptimize and allocate in interpreter instead.
3281 Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
3282 Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
3283 Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
3284 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3285 {
3286 BuildCutout unless(this, tst, PROB_MAX);
3287 uncommon_trap(Deoptimization::Reason_intrinsic,
3288 Deoptimization::Action_make_not_entrant);
3289 }
3290 if (stopped()) {
3291 return true;
3292 }
3293 #endif //INCLUDE_JVMTI
3294
3295 Node* test = nullptr;
3296 if (LibraryCallKit::klass_needs_init_guard(kls)) {
3297 // Note: The argument might still be an illegal value like
3298 // Serializable.class or Object[].class. The runtime will handle it.
3299 // But we must make an explicit check for initialization.
3300 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
3301 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
3302 // can generate code to load it as unsigned byte.
3303 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
3304 Node* bits = intcon(InstanceKlass::fully_initialized);
3305 test = _gvn.transform(new SubINode(inst, bits));
3306 // The 'test' is non-zero if we need to take a slow path.
3307 }
3308 Node* obj = new_instance(kls, test);
3309 set_result(obj);
3310 return true;
3311 }
3312
3313 //------------------------inline_native_time_funcs--------------
3314 // inline code for System.currentTimeMillis() and System.nanoTime()
3315 // these have the same type and signature
3316 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
3317 const TypeFunc* tf = OptoRuntime::void_long_Type();
3318 const TypePtr* no_memory_effects = nullptr;
3319 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
3320 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
3321 #ifdef ASSERT
3322 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
3323 assert(value_top == top(), "second value must be top");
3324 #endif
3325 set_result(value);
3326 return true;
3327 }
3328
3329 //--------------------inline_native_vthread_start_transition--------------------
3330 // inline void startTransition(boolean is_mount);
3331 // inline void startFinalTransition();
3332 // Pseudocode of implementation:
3333 //
3334 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
3335 // carrier->set_is_in_vthread_transition(true);
3336 // OrderAccess::storeload();
3337 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
3338 // + global_vthread_transition_disable_count();
3339 // if (disable_requests > 0) {
3340 // slow path: runtime call
3341 // }
3342 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
3343 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3344 IdealKit ideal(this);
3345
3346 Node* thread = ideal.thread();
3347 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3348 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3349 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3350 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3351 insert_mem_bar(Op_MemBarStoreLoad);
3352 ideal.sync_kit(this);
3353
3354 Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
3355 Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
3356 Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
3357 const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
3358 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*/);
3359 Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
3360
3361 ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
3362 sync_kit(ideal);
3363 Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
3364 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3365 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3366 ideal.sync_kit(this);
3367 }
3368 ideal.end_if();
3369
3370 final_sync(ideal);
3371 return true;
3372 }
3373
3374 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
3375 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
3376 IdealKit ideal(this);
3377
3378 Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3379 Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3380
3381 ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3382 sync_kit(ideal);
3383 Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3384 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3385 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3386 ideal.sync_kit(this);
3387 } ideal.else_(); {
3388 Node* thread = ideal.thread();
3389 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3390 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3391
3392 sync_kit(ideal);
3393 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3394 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3395 ideal.sync_kit(this);
3396 } ideal.end_if();
3397
3398 final_sync(ideal);
3399 return true;
3400 }
3401
3402 #if INCLUDE_JVMTI
3403
3404 // Always update the is_disable_suspend bit.
3405 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3406 if (!DoJVMTIVirtualThreadTransitions) {
3407 return true;
3408 }
3409 IdealKit ideal(this);
3410
3411 {
3412 // unconditionally update the is_disable_suspend bit in current JavaThread
3413 Node* thread = ideal.thread();
3414 Node* arg = argument(0); // argument for notification
3415 Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3416 const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3417
3418 sync_kit(ideal);
3419 access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3420 ideal.sync_kit(this);
3421 }
3422 final_sync(ideal);
3423
3424 return true;
3425 }
3426
3427 #endif // INCLUDE_JVMTI
3428
3429 #ifdef JFR_HAVE_INTRINSICS
3430
3431 /**
3432 * if oop->klass != null
3433 * // normal class
3434 * epoch = _epoch_state ? 2 : 1
3435 * if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3436 * ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3437 * }
3438 * id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3439 * else
3440 * // primitive class
3441 * if oop->array_klass != null
3442 * id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3443 * else
3444 * id = LAST_TYPE_ID + 1 // void class path
3445 * if (!signaled)
3446 * signaled = true
3447 */
3448 bool LibraryCallKit::inline_native_classID() {
3449 Node* cls = argument(0);
3450
3451 IdealKit ideal(this);
3452 #define __ ideal.
3453 IdealVariable result(ideal); __ declarations_done();
3454 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3455 basic_plus_adr(cls, java_lang_Class::klass_offset()),
3456 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3457
3458
3459 __ if_then(kls, BoolTest::ne, null()); {
3460 Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3461 Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3462
3463 Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3464 Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3465 epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3466 Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3467 mask = _gvn.transform(new OrLNode(mask, epoch));
3468 Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3469
3470 float unlikely = PROB_UNLIKELY(0.999);
3471 __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3472 sync_kit(ideal);
3473 make_runtime_call(RC_LEAF,
3474 OptoRuntime::class_id_load_barrier_Type(),
3475 CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3476 "class id load barrier",
3477 TypePtr::BOTTOM,
3478 kls);
3479 ideal.sync_kit(this);
3480 } __ end_if();
3481
3482 ideal.set(result, _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3483 } __ else_(); {
3484 Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3485 basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3486 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3487 __ if_then(array_kls, BoolTest::ne, null()); {
3488 Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3489 Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3490 Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3491 ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3492 } __ else_(); {
3493 // void class case
3494 ideal.set(result, longcon(LAST_TYPE_ID + 1));
3495 } __ end_if();
3496
3497 Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3498 Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3499 __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3500 ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3501 } __ end_if();
3502 } __ end_if();
3503
3504 final_sync(ideal);
3505 set_result(ideal.value(result));
3506 #undef __
3507 return true;
3508 }
3509
3510 //------------------------inline_native_jvm_commit------------------
3511 bool LibraryCallKit::inline_native_jvm_commit() {
3512 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3513
3514 // Save input memory and i_o state.
3515 Node* input_memory_state = reset_memory();
3516 set_all_memory(input_memory_state);
3517 Node* input_io_state = i_o();
3518
3519 // TLS.
3520 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3521 // Jfr java buffer.
3522 Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3523 Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3524 Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3525
3526 // Load the current value of the notified field in the JfrThreadLocal.
3527 Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3528 Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3529
3530 // Test for notification.
3531 Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3532 Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3533 IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3534
3535 // True branch, is notified.
3536 Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3537 set_control(is_notified);
3538
3539 // Reset notified state.
3540 store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3541 Node* notified_reset_memory = reset_memory();
3542
3543 // 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.
3544 Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3545 // Convert the machine-word to a long.
3546 Node* current_pos = ConvX2L(current_pos_X);
3547
3548 // False branch, not notified.
3549 Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3550 set_control(not_notified);
3551 set_all_memory(input_memory_state);
3552
3553 // Arg is the next position as a long.
3554 Node* arg = argument(0);
3555 // Convert long to machine-word.
3556 Node* next_pos_X = ConvL2X(arg);
3557
3558 // Store the next_position to the underlying jfr java buffer.
3559 store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3560
3561 Node* commit_memory = reset_memory();
3562 set_all_memory(commit_memory);
3563
3564 // 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.
3565 Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3566 Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3567 Node* lease_constant = _gvn.intcon(4);
3568
3569 // And flags with lease constant.
3570 Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3571
3572 // Branch on lease to conditionalize returning the leased java buffer.
3573 Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3574 Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3575 IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3576
3577 // False branch, not a lease.
3578 Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3579
3580 // True branch, is lease.
3581 Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3582 set_control(is_lease);
3583
3584 // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3585 Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3586 OptoRuntime::void_void_Type(),
3587 SharedRuntime::jfr_return_lease(),
3588 "return_lease", TypePtr::BOTTOM);
3589 Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3590
3591 RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3592 record_for_igvn(lease_compare_rgn);
3593 PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3594 record_for_igvn(lease_compare_mem);
3595 PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3596 record_for_igvn(lease_compare_io);
3597 PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3598 record_for_igvn(lease_result_value);
3599
3600 // Update control and phi nodes.
3601 lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3602 lease_compare_rgn->init_req(_false_path, not_lease);
3603
3604 lease_compare_mem->init_req(_true_path, reset_memory());
3605 lease_compare_mem->init_req(_false_path, commit_memory);
3606
3607 lease_compare_io->init_req(_true_path, i_o());
3608 lease_compare_io->init_req(_false_path, input_io_state);
3609
3610 lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3611 lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3612
3613 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3614 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3615 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3616 PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3617
3618 // Update control and phi nodes.
3619 result_rgn->init_req(_true_path, is_notified);
3620 result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3621
3622 result_mem->init_req(_true_path, notified_reset_memory);
3623 result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3624
3625 result_io->init_req(_true_path, input_io_state);
3626 result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3627
3628 result_value->init_req(_true_path, current_pos);
3629 result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3630
3631 // Set output state.
3632 set_control(_gvn.transform(result_rgn));
3633 set_all_memory(_gvn.transform(result_mem));
3634 set_i_o(_gvn.transform(result_io));
3635 set_result(result_rgn, result_value);
3636 return true;
3637 }
3638
3639 /*
3640 * The intrinsic is a model of this pseudo-code:
3641 *
3642 * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3643 * jobject h_event_writer = tl->java_event_writer();
3644 * if (h_event_writer == nullptr) {
3645 * return nullptr;
3646 * }
3647 * oop threadObj = Thread::threadObj();
3648 * oop vthread = java_lang_Thread::vthread(threadObj);
3649 * traceid tid;
3650 * bool pinVirtualThread;
3651 * bool excluded;
3652 * if (vthread != threadObj) { // i.e. current thread is virtual
3653 * tid = java_lang_Thread::tid(vthread);
3654 * u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3655 * pinVirtualThread = VMContinuations;
3656 * excluded = vthread_epoch_raw & excluded_mask;
3657 * if (!excluded) {
3658 * traceid current_epoch = JfrTraceIdEpoch::current_generation();
3659 * u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3660 * if (vthread_epoch != current_epoch) {
3661 * write_checkpoint();
3662 * }
3663 * }
3664 * } else {
3665 * tid = java_lang_Thread::tid(threadObj);
3666 * u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3667 * pinVirtualThread = false;
3668 * excluded = thread_epoch_raw & excluded_mask;
3669 * }
3670 * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3671 * traceid tid_in_event_writer = getField(event_writer, "threadID");
3672 * if (tid_in_event_writer != tid) {
3673 * setField(event_writer, "pinVirtualThread", pinVirtualThread);
3674 * setField(event_writer, "excluded", excluded);
3675 * setField(event_writer, "threadID", tid);
3676 * }
3677 * return event_writer
3678 */
3679 bool LibraryCallKit::inline_native_getEventWriter() {
3680 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3681
3682 // Save input memory and i_o state.
3683 Node* input_memory_state = reset_memory();
3684 set_all_memory(input_memory_state);
3685 Node* input_io_state = i_o();
3686
3687 // The most significant bit of the u2 is used to denote thread exclusion
3688 Node* excluded_shift = _gvn.intcon(15);
3689 Node* excluded_mask = _gvn.intcon(1 << 15);
3690 // The epoch generation is the range [1-32767]
3691 Node* epoch_mask = _gvn.intcon(32767);
3692
3693 // TLS
3694 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3695
3696 // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3697 Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3698
3699 // Load the eventwriter jobject handle.
3700 Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3701
3702 // Null check the jobject handle.
3703 Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3704 Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3705 IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3706
3707 // False path, jobj is null.
3708 Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3709
3710 // True path, jobj is not null.
3711 Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3712
3713 set_control(jobj_is_not_null);
3714
3715 // Load the threadObj for the CarrierThread.
3716 Node* threadObj = generate_current_thread(tls_ptr);
3717
3718 // Load the vthread.
3719 Node* vthread = generate_virtual_thread(tls_ptr);
3720
3721 // If vthread != threadObj, this is a virtual thread.
3722 Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3723 Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3724 IfNode* iff_vthread_not_equal_threadObj =
3725 create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3726
3727 // False branch, fallback to threadObj.
3728 Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3729 set_control(vthread_equal_threadObj);
3730
3731 // Load the tid field from the vthread object.
3732 Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3733
3734 // Load the raw epoch value from the threadObj.
3735 Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3736 Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3737 _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3738 TypeInt::CHAR, T_CHAR,
3739 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3740
3741 // Mask off the excluded information from the epoch.
3742 Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3743
3744 // True branch, this is a virtual thread.
3745 Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3746 set_control(vthread_not_equal_threadObj);
3747
3748 // Load the tid field from the vthread object.
3749 Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3750
3751 // Continuation support determines if a virtual thread should be pinned.
3752 Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3753 Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3754
3755 // Load the raw epoch value from the vthread.
3756 Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3757 Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3758 TypeInt::CHAR, T_CHAR,
3759 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3760
3761 // Mask off the excluded information from the epoch.
3762 Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3763
3764 // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3765 Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3766 Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3767 IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3768
3769 // False branch, vthread is excluded, no need to write epoch info.
3770 Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3771
3772 // True branch, vthread is included, update epoch info.
3773 Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3774 set_control(included);
3775
3776 // Get epoch value.
3777 Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3778
3779 // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3780 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3781 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3782
3783 // Compare the epoch in the vthread to the current epoch generation.
3784 Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3785 Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3786 IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3787
3788 // False path, epoch is equal, checkpoint information is valid.
3789 Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3790
3791 // True path, epoch is not equal, write a checkpoint for the vthread.
3792 Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3793
3794 set_control(epoch_is_not_equal);
3795
3796 // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3797 // The call also updates the native thread local thread id and the vthread with the current epoch.
3798 Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3799 OptoRuntime::jfr_write_checkpoint_Type(),
3800 SharedRuntime::jfr_write_checkpoint(),
3801 "write_checkpoint", TypePtr::BOTTOM);
3802 Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3803
3804 // vthread epoch != current epoch
3805 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3806 record_for_igvn(epoch_compare_rgn);
3807 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3808 record_for_igvn(epoch_compare_mem);
3809 PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3810 record_for_igvn(epoch_compare_io);
3811
3812 // Update control and phi nodes.
3813 epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3814 epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3815 epoch_compare_mem->init_req(_true_path, reset_memory());
3816 epoch_compare_mem->init_req(_false_path, input_memory_state);
3817 epoch_compare_io->init_req(_true_path, i_o());
3818 epoch_compare_io->init_req(_false_path, input_io_state);
3819
3820 // excluded != true
3821 RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3822 record_for_igvn(exclude_compare_rgn);
3823 PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3824 record_for_igvn(exclude_compare_mem);
3825 PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3826 record_for_igvn(exclude_compare_io);
3827
3828 // Update control and phi nodes.
3829 exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3830 exclude_compare_rgn->init_req(_false_path, excluded);
3831 exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3832 exclude_compare_mem->init_req(_false_path, input_memory_state);
3833 exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3834 exclude_compare_io->init_req(_false_path, input_io_state);
3835
3836 // vthread != threadObj
3837 RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3838 record_for_igvn(vthread_compare_rgn);
3839 PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3840 PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3841 record_for_igvn(vthread_compare_io);
3842 PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3843 record_for_igvn(tid);
3844 PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3845 record_for_igvn(exclusion);
3846 PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3847 record_for_igvn(pinVirtualThread);
3848
3849 // Update control and phi nodes.
3850 vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3851 vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3852 vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3853 vthread_compare_mem->init_req(_false_path, input_memory_state);
3854 vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3855 vthread_compare_io->init_req(_false_path, input_io_state);
3856 tid->init_req(_true_path, vthread_tid);
3857 tid->init_req(_false_path, thread_obj_tid);
3858 exclusion->init_req(_true_path, vthread_is_excluded);
3859 exclusion->init_req(_false_path, threadObj_is_excluded);
3860 pinVirtualThread->init_req(_true_path, continuation_support);
3861 pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3862
3863 // Update branch state.
3864 set_control(_gvn.transform(vthread_compare_rgn));
3865 set_all_memory(_gvn.transform(vthread_compare_mem));
3866 set_i_o(_gvn.transform(vthread_compare_io));
3867
3868 // Load the event writer oop by dereferencing the jobject handle.
3869 ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3870 assert(klass_EventWriter->is_loaded(), "invariant");
3871 ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3872 const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3873 const TypeOopPtr* const xtype = aklass->as_instance_type();
3874 Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3875 Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3876
3877 // Load the current thread id from the event writer object.
3878 Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3879 // Get the field offset to, conditionally, store an updated tid value later.
3880 Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3881 // Get the field offset to, conditionally, store an updated exclusion value later.
3882 Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3883 // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3884 Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3885
3886 RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3887 record_for_igvn(event_writer_tid_compare_rgn);
3888 PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3889 record_for_igvn(event_writer_tid_compare_mem);
3890 PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3891 record_for_igvn(event_writer_tid_compare_io);
3892
3893 // Compare the current tid from the thread object to what is currently stored in the event writer object.
3894 Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3895 Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3896 IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3897
3898 // False path, tids are the same.
3899 Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3900
3901 // True path, tid is not equal, need to update the tid in the event writer.
3902 Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3903 record_for_igvn(tid_is_not_equal);
3904
3905 // Store the pin state to the event writer.
3906 store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3907
3908 // Store the exclusion state to the event writer.
3909 Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3910 store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3911
3912 // Store the tid to the event writer.
3913 store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3914
3915 // Update control and phi nodes.
3916 event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3917 event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3918 event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3919 event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3920 event_writer_tid_compare_io->init_req(_true_path, i_o());
3921 event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3922
3923 // Result of top level CFG, Memory, IO and Value.
3924 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3925 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3926 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3927 PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3928
3929 // Result control.
3930 result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3931 result_rgn->init_req(_false_path, jobj_is_null);
3932
3933 // Result memory.
3934 result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3935 result_mem->init_req(_false_path, input_memory_state);
3936
3937 // Result IO.
3938 result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3939 result_io->init_req(_false_path, input_io_state);
3940
3941 // Result value.
3942 result_value->init_req(_true_path, event_writer); // return event writer oop
3943 result_value->init_req(_false_path, null()); // return null
3944
3945 // Set output state.
3946 set_control(_gvn.transform(result_rgn));
3947 set_all_memory(_gvn.transform(result_mem));
3948 set_i_o(_gvn.transform(result_io));
3949 set_result(result_rgn, result_value);
3950 return true;
3951 }
3952
3953 /*
3954 * The intrinsic is a model of this pseudo-code:
3955 *
3956 * JfrThreadLocal* const tl = thread->jfr_thread_local();
3957 * if (carrierThread != thread) { // is virtual thread
3958 * const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3959 * bool excluded = vthread_epoch_raw & excluded_mask;
3960 * AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3961 * AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3962 * if (!excluded) {
3963 * const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3964 * AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3965 * }
3966 * AtomicAccess::release_store(&tl->_vthread, true);
3967 * return;
3968 * }
3969 * AtomicAccess::release_store(&tl->_vthread, false);
3970 */
3971 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3972 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3973
3974 Node* input_memory_state = reset_memory();
3975 set_all_memory(input_memory_state);
3976
3977 // The most significant bit of the u2 is used to denote thread exclusion
3978 Node* excluded_mask = _gvn.intcon(1 << 15);
3979 // The epoch generation is the range [1-32767]
3980 Node* epoch_mask = _gvn.intcon(32767);
3981
3982 Node* const carrierThread = generate_current_thread(jt);
3983 // If thread != carrierThread, this is a virtual thread.
3984 Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3985 Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3986 IfNode* iff_thread_not_equal_carrierThread =
3987 create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3988
3989 Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3990
3991 // False branch, is carrierThread.
3992 Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3993 // Store release
3994 Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3995
3996 set_all_memory(input_memory_state);
3997
3998 // True branch, is virtual thread.
3999 Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
4000 set_control(thread_not_equal_carrierThread);
4001
4002 // Load the raw epoch value from the vthread.
4003 Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
4004 Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
4005 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
4006
4007 // Mask off the excluded information from the epoch.
4008 Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
4009
4010 // Load the tid field from the thread.
4011 Node* tid = load_field_from_object(thread, "tid", "J");
4012
4013 // Store the vthread tid to the jfr thread local.
4014 Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
4015 Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
4016
4017 // Branch is_excluded to conditionalize updating the epoch .
4018 Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
4019 Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
4020 IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
4021
4022 // True branch, vthread is excluded, no need to write epoch info.
4023 Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
4024 set_control(excluded);
4025 Node* vthread_is_excluded = _gvn.intcon(1);
4026
4027 // False branch, vthread is included, update epoch info.
4028 Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
4029 set_control(included);
4030 Node* vthread_is_included = _gvn.intcon(0);
4031
4032 // Get epoch value.
4033 Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
4034
4035 // Store the vthread epoch to the jfr thread local.
4036 Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
4037 Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
4038
4039 RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
4040 record_for_igvn(excluded_rgn);
4041 PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
4042 record_for_igvn(excluded_mem);
4043 PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
4044 record_for_igvn(exclusion);
4045
4046 // Merge the excluded control and memory.
4047 excluded_rgn->init_req(_true_path, excluded);
4048 excluded_rgn->init_req(_false_path, included);
4049 excluded_mem->init_req(_true_path, tid_memory);
4050 excluded_mem->init_req(_false_path, included_memory);
4051 exclusion->init_req(_true_path, vthread_is_excluded);
4052 exclusion->init_req(_false_path, vthread_is_included);
4053
4054 // Set intermediate state.
4055 set_control(_gvn.transform(excluded_rgn));
4056 set_all_memory(excluded_mem);
4057
4058 // Store the vthread exclusion state to the jfr thread local.
4059 Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
4060 store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
4061
4062 // Store release
4063 Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
4064
4065 RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
4066 record_for_igvn(thread_compare_rgn);
4067 PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4068 record_for_igvn(thread_compare_mem);
4069 PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
4070 record_for_igvn(vthread);
4071
4072 // Merge the thread_compare control and memory.
4073 thread_compare_rgn->init_req(_true_path, control());
4074 thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
4075 thread_compare_mem->init_req(_true_path, vthread_true_memory);
4076 thread_compare_mem->init_req(_false_path, vthread_false_memory);
4077
4078 // Set output state.
4079 set_control(_gvn.transform(thread_compare_rgn));
4080 set_all_memory(_gvn.transform(thread_compare_mem));
4081 }
4082
4083 //------------------------inline_native_try_update_epoch------------------
4084 //
4085 // The generated code is a function of the argument type.
4086 //
4087 bool LibraryCallKit::inline_native_try_update_epoch() {
4088 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4089
4090 // Save input memory.
4091 Node* input_memory_state = reset_memory();
4092 set_all_memory(input_memory_state);
4093
4094 // Argument is an oop whose class has an injected instance field,
4095 // called 'jfr_epoch' of type T_INT, used for holding a jfr epoch value.
4096 Node* oop = argument(0);
4097 const TypeInstPtr* tinst = _gvn.type(oop)->isa_instptr();
4098 assert(tinst != nullptr, "oop is null");
4099 assert(tinst->is_loaded(), "klass is not loaded");
4100 ciInstanceKlass* const ik = tinst->instance_klass();
4101
4102 ciField* const field = ik->get_injected_instance_field_by_name(ciSymbol::make("jfr_epoch"),
4103 ciSymbol::make("I"));
4104
4105 assert(field != nullptr, "field 'jfr_epoch' of type I not injected in klass %s", ik->name()->as_utf8());
4106
4107 const int jfr_epoch_field_offset = field->offset_in_bytes();
4108 Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset);
4109 const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr();
4110 const int alias_idx = C->get_alias_index(adr_type);
4111 BasicType bt = field->layout_type();
4112 const Type * oop_epoch_field_type = Type::get_const_basic_type(bt);
4113
4114 // Load the epoch value from the oop.
4115 Node* oop_epoch = access_load_at(oop,
4116 oop_epoch_field_offset,
4117 adr_type, oop_epoch_field_type,
4118 bt, IN_HEAP | MO_UNORDERED);
4119
4120 // Load the current JFR epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
4121 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
4122 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
4123
4124 // Compare the epoch in the oop against the current JFR epoch generation.
4125 Node* const epochs_cmp = _gvn.transform(new CmpINode(current_epoch_generation, oop_epoch));
4126 Node* epochs_equal_test = _gvn.transform(new BoolNode(epochs_cmp, BoolTest::eq));
4127 IfNode* iff_epochs_equal = create_and_map_if(control(), epochs_equal_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
4128
4129 // True path.
4130 Node* epochs_are_equal = _gvn.transform(new IfTrueNode(iff_epochs_equal));
4131
4132 // False path.
4133 Node* epochs_are_not_equal = _gvn.transform(new IfFalseNode(iff_epochs_equal));
4134
4135 set_control(_gvn.transform(epochs_are_not_equal));
4136
4137 // Attempt to cas the current JFR epoch generation into the oop epoch field.
4138 DecoratorSet decorators = IN_HEAP;
4139 decorators |= mo_decorator_for_access_kind(Volatile);
4140
4141 Node* result = access_atomic_cmpxchg_val_at(oop,
4142 oop_epoch_field_offset,
4143 adr_type, alias_idx,
4144 oop_epoch, // expected value
4145 current_epoch_generation, // new value
4146 oop_epoch_field_type,
4147 bt,
4148 decorators);
4149
4150 // Compare the result of the cas operation to the expected value.
4151 Node* const cas_cmp_to_expected_value = _gvn.transform(new CmpINode(result, oop_epoch));
4152 Node* cas_operation_test = _gvn.transform(new BoolNode(cas_cmp_to_expected_value, BoolTest::eq));
4153 IfNode* iff_cas_success = create_and_map_if(control(), cas_operation_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
4154
4155 // True path.
4156 Node* cas_success = _gvn.transform(new IfTrueNode(iff_cas_success));
4157
4158 // False path.
4159 Node* cas_failure = _gvn.transform(new IfFalseNode(iff_cas_success));
4160
4161 // Cas result region and phi nodes.
4162 RegionNode* cas_operation_rgn = new RegionNode(PATH_LIMIT);
4163 record_for_igvn(cas_operation_rgn);
4164 PhiNode* cas_operation_mem = new PhiNode(cas_operation_rgn, Type::MEMORY, TypePtr::BOTTOM);
4165 record_for_igvn(cas_operation_mem);
4166 PhiNode* cas_result = new PhiNode(cas_operation_rgn, TypeInt::BOOL);
4167 record_for_igvn(cas_result);
4168
4169 cas_operation_rgn->init_req(_true_path, _gvn.transform(cas_success));
4170 cas_operation_rgn->init_req(_false_path, _gvn.transform(cas_failure));
4171 cas_operation_mem->init_req(_true_path, reset_memory());
4172 cas_operation_mem->init_req(_false_path, input_memory_state);
4173 cas_result->init_req(_true_path, _gvn.intcon(1));
4174 cas_result->init_req(_false_path, _gvn.intcon(0));
4175
4176 // Epoch compare region and phi nodes.
4177 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
4178 record_for_igvn(epoch_compare_rgn);
4179 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
4180 record_for_igvn(epoch_compare_mem);
4181 PhiNode* result_value = new PhiNode(epoch_compare_rgn, TypeInt::BOOL);
4182 record_for_igvn(result_value);
4183
4184 epoch_compare_rgn->init_req(_true_path, _gvn.transform(epochs_are_equal));
4185 epoch_compare_rgn->init_req(_false_path, _gvn.transform(cas_operation_rgn));
4186 epoch_compare_mem->init_req(_true_path, _gvn.transform(input_memory_state));
4187 epoch_compare_mem->init_req(_false_path, _gvn.transform(cas_operation_mem));
4188 result_value->init_req(_true_path, _gvn.intcon(0));
4189 result_value->init_req(_false_path, _gvn.transform(cas_result));
4190
4191 // Set output state.
4192 set_result(epoch_compare_rgn, result_value);
4193 set_all_memory(_gvn.transform(epoch_compare_mem));
4194
4195 return true;
4196 }
4197
4198 #endif // JFR_HAVE_INTRINSICS
4199
4200 //------------------------inline_native_currentCarrierThread------------------
4201 bool LibraryCallKit::inline_native_currentCarrierThread() {
4202 Node* junk = nullptr;
4203 set_result(generate_current_thread(junk));
4204 return true;
4205 }
4206
4207 //------------------------inline_native_currentThread------------------
4208 bool LibraryCallKit::inline_native_currentThread() {
4209 Node* junk = nullptr;
4210 set_result(generate_virtual_thread(junk));
4211 return true;
4212 }
4213
4214 //------------------------inline_native_setVthread------------------
4215 bool LibraryCallKit::inline_native_setCurrentThread() {
4216 assert(C->method()->changes_current_thread(),
4217 "method changes current Thread but is not annotated ChangesCurrentThread");
4218 Node* arr = argument(1);
4219 Node* thread = _gvn.transform(new ThreadLocalNode());
4220 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
4221 Node* thread_obj_handle
4222 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
4223 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
4224 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
4225
4226 // Change the _monitor_owner_id of the JavaThread
4227 Node* tid = load_field_from_object(arr, "tid", "J");
4228 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
4229 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
4230
4231 JFR_ONLY(extend_setCurrentThread(thread, arr);)
4232 return true;
4233 }
4234
4235 const Type* LibraryCallKit::scopedValueCache_type() {
4236 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
4237 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
4238 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS, /* stable= */ false, /* flat= */ false, /* not_flat= */ true, /* not_null_free= */ true, true);
4239
4240 // Because we create the scopedValue cache lazily we have to make the
4241 // type of the result BotPTR.
4242 bool xk = etype->klass_is_exact();
4243 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, TypeAryPtr::Offset(0));
4244 return objects_type;
4245 }
4246
4247 Node* LibraryCallKit::scopedValueCache_helper() {
4248 Node* thread = _gvn.transform(new ThreadLocalNode());
4249 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
4250 // We cannot use immutable_memory() because we might flip onto a
4251 // different carrier thread, at which point we'll need to use that
4252 // carrier thread's cache.
4253 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
4254 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
4255 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
4256 }
4257
4258 //------------------------inline_native_scopedValueCache------------------
4259 bool LibraryCallKit::inline_native_scopedValueCache() {
4260 Node* cache_obj_handle = scopedValueCache_helper();
4261 const Type* objects_type = scopedValueCache_type();
4262 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
4263
4264 return true;
4265 }
4266
4267 //------------------------inline_native_setScopedValueCache------------------
4268 bool LibraryCallKit::inline_native_setScopedValueCache() {
4269 Node* arr = argument(0);
4270 Node* cache_obj_handle = scopedValueCache_helper();
4271 const Type* objects_type = scopedValueCache_type();
4272
4273 const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
4274 access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
4275
4276 return true;
4277 }
4278
4279 //------------------------inline_native_Continuation_pin and unpin-----------
4280
4281 // Shared implementation routine for both pin and unpin.
4282 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
4283 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
4284
4285 // Save input memory.
4286 Node* input_memory_state = reset_memory();
4287 set_all_memory(input_memory_state);
4288
4289 // TLS
4290 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
4291 Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
4292 Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
4293
4294 // Null check the last continuation object.
4295 Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
4296 Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
4297 IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
4298
4299 // False path, last continuation is null.
4300 Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
4301
4302 // True path, last continuation is not null.
4303 Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
4304
4305 set_control(continuation_is_not_null);
4306
4307 // Load the pin count from the last continuation.
4308 Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
4309 Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
4310
4311 // The loaded pin count is compared against a context specific rhs for over/underflow detection.
4312 Node* pin_count_rhs;
4313 if (unpin) {
4314 pin_count_rhs = _gvn.intcon(0);
4315 } else {
4316 pin_count_rhs = _gvn.intcon(UINT32_MAX);
4317 }
4318 Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
4319 Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
4320 IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
4321
4322 // True branch, pin count over/underflow.
4323 Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
4324 {
4325 // Trap (but not deoptimize (Action_none)) and continue in the interpreter
4326 // which will throw IllegalStateException for pin count over/underflow.
4327 // No memory changed so far - we can use memory create by reset_memory()
4328 // at the beginning of this intrinsic. No need to call reset_memory() again.
4329 PreserveJVMState pjvms(this);
4330 set_control(pin_count_over_underflow);
4331 uncommon_trap(Deoptimization::Reason_intrinsic,
4332 Deoptimization::Action_none);
4333 assert(stopped(), "invariant");
4334 }
4335
4336 // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
4337 Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
4338 set_control(valid_pin_count);
4339
4340 Node* next_pin_count;
4341 if (unpin) {
4342 next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
4343 } else {
4344 next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
4345 }
4346
4347 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
4348
4349 // Result of top level CFG and Memory.
4350 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
4351 record_for_igvn(result_rgn);
4352 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
4353 record_for_igvn(result_mem);
4354
4355 result_rgn->init_req(_true_path, valid_pin_count);
4356 result_rgn->init_req(_false_path, continuation_is_null);
4357 result_mem->init_req(_true_path, reset_memory());
4358 result_mem->init_req(_false_path, input_memory_state);
4359
4360 // Set output state.
4361 set_control(_gvn.transform(result_rgn));
4362 set_all_memory(_gvn.transform(result_mem));
4363
4364 return true;
4365 }
4366
4367 //---------------------------load_mirror_from_klass----------------------------
4368 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4369 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
4370 Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
4371 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4372 // mirror = ((OopHandle)mirror)->resolve();
4373 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4374 }
4375
4376 //-----------------------load_klass_from_mirror_common-------------------------
4377 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4378 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4379 // and branch to the given path on the region.
4380 // If never_see_null, take an uncommon trap on null, so we can optimistically
4381 // compile for the non-null case.
4382 // If the region is null, force never_see_null = true.
4383 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4384 bool never_see_null,
4385 RegionNode* region,
4386 int null_path,
4387 int offset) {
4388 if (region == nullptr) never_see_null = true;
4389 Node* p = basic_plus_adr(mirror, offset);
4390 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4391 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4392 Node* null_ctl = top();
4393 kls = null_check_oop(kls, &null_ctl, never_see_null);
4394 if (region != nullptr) {
4395 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4396 region->init_req(null_path, null_ctl);
4397 } else {
4398 assert(null_ctl == top(), "no loose ends");
4399 }
4400 return kls;
4401 }
4402
4403 //--------------------(inline_native_Class_query helpers)---------------------
4404 // Use this for JVM_ACC_INTERFACE.
4405 // Fall through if (mods & mask) == bits, take the guard otherwise.
4406 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4407 ByteSize offset, const Type* type, BasicType bt) {
4408 // Branch around if the given klass has the given modifier bit set.
4409 // Like generate_guard, adds a new path onto the region.
4410 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4411 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4412 Node* mask = intcon(modifier_mask);
4413 Node* bits = intcon(modifier_bits);
4414 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4415 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4416 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4417 return generate_fair_guard(bol, region);
4418 }
4419
4420 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4421 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4422 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4423 }
4424
4425 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4426 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4427 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4428 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4429 }
4430
4431 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4432 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4433 }
4434
4435 //-------------------------inline_native_Class_query-------------------
4436 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4437 const Type* return_type = TypeInt::BOOL;
4438 Node* prim_return_value = top(); // what happens if it's a primitive class?
4439 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4440 bool expect_prim = false; // most of these guys expect to work on refs
4441
4442 enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4443
4444 Node* mirror = argument(0);
4445 Node* obj = top();
4446
4447 switch (id) {
4448 case vmIntrinsics::_isInstance:
4449 // nothing is an instance of a primitive type
4450 prim_return_value = intcon(0);
4451 obj = argument(1);
4452 break;
4453 case vmIntrinsics::_isHidden:
4454 prim_return_value = intcon(0);
4455 break;
4456 case vmIntrinsics::_getSuperclass:
4457 prim_return_value = null();
4458 return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4459 break;
4460 default:
4461 fatal_unexpected_iid(id);
4462 break;
4463 }
4464
4465 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4466 if (mirror_con == nullptr) return false; // cannot happen?
4467
4468 #ifndef PRODUCT
4469 if (C->print_intrinsics() || C->print_inlining()) {
4470 ciType* k = mirror_con->java_mirror_type();
4471 if (k) {
4472 tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4473 k->print_name();
4474 tty->cr();
4475 }
4476 }
4477 #endif
4478
4479 // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4480 RegionNode* region = new RegionNode(PATH_LIMIT);
4481 record_for_igvn(region);
4482 PhiNode* phi = new PhiNode(region, return_type);
4483
4484 // The mirror will never be null of Reflection.getClassAccessFlags, however
4485 // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4486 // if it is. See bug 4774291.
4487
4488 // For Reflection.getClassAccessFlags(), the null check occurs in
4489 // the wrong place; see inline_unsafe_access(), above, for a similar
4490 // situation.
4491 mirror = null_check(mirror);
4492 // If mirror or obj is dead, only null-path is taken.
4493 if (stopped()) return true;
4494
4495 if (expect_prim) never_see_null = false; // expect nulls (meaning prims)
4496
4497 // Now load the mirror's klass metaobject, and null-check it.
4498 // Side-effects region with the control path if the klass is null.
4499 Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4500 // If kls is null, we have a primitive mirror.
4501 phi->init_req(_prim_path, prim_return_value);
4502 if (stopped()) { set_result(region, phi); return true; }
4503 bool safe_for_replace = (region->in(_prim_path) == top());
4504
4505 Node* p; // handy temp
4506 Node* null_ctl;
4507
4508 // Now that we have the non-null klass, we can perform the real query.
4509 // For constant classes, the query will constant-fold in LoadNode::Value.
4510 Node* query_value = top();
4511 switch (id) {
4512 case vmIntrinsics::_isInstance:
4513 // nothing is an instance of a primitive type
4514 query_value = gen_instanceof(obj, kls, safe_for_replace);
4515 break;
4516
4517 case vmIntrinsics::_isHidden:
4518 // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4519 if (generate_hidden_class_guard(kls, region) != nullptr)
4520 // A guard was added. If the guard is taken, it was an hidden class.
4521 phi->add_req(intcon(1));
4522 // If we fall through, it's a plain class.
4523 query_value = intcon(0);
4524 break;
4525
4526
4527 case vmIntrinsics::_getSuperclass:
4528 // The rules here are somewhat unfortunate, but we can still do better
4529 // with random logic than with a JNI call.
4530 // Interfaces store null or Object as _super, but must report null.
4531 // Arrays store an intermediate super as _super, but must report Object.
4532 // Other types can report the actual _super.
4533 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4534 if (generate_array_guard(kls, region) != nullptr) {
4535 // A guard was added. If the guard is taken, it was an array.
4536 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4537 }
4538 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4539 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4540 if (generate_interface_guard(kls, region) != nullptr) {
4541 // A guard was added. If the guard is taken, it was an interface.
4542 phi->add_req(null());
4543 }
4544 // If we fall through, it's a plain class. Get its _super.
4545 if (!stopped()) {
4546 p = basic_plus_adr(top(), kls, in_bytes(Klass::super_offset()));
4547 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4548 null_ctl = top();
4549 kls = null_check_oop(kls, &null_ctl);
4550 if (null_ctl != top()) {
4551 // If the guard is taken, Object.superClass is null (both klass and mirror).
4552 region->add_req(null_ctl);
4553 phi ->add_req(null());
4554 }
4555 if (!stopped()) {
4556 query_value = load_mirror_from_klass(kls);
4557 }
4558 }
4559 break;
4560
4561 default:
4562 fatal_unexpected_iid(id);
4563 break;
4564 }
4565
4566 // Fall-through is the normal case of a query to a real class.
4567 phi->init_req(1, query_value);
4568 region->init_req(1, control());
4569
4570 C->set_has_split_ifs(true); // Has chance for split-if optimization
4571 set_result(region, phi);
4572 return true;
4573 }
4574
4575
4576 //-------------------------inline_Class_cast-------------------
4577 bool LibraryCallKit::inline_Class_cast() {
4578 Node* mirror = argument(0); // Class
4579 Node* obj = argument(1);
4580 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4581 if (mirror_con == nullptr) {
4582 return false; // dead path (mirror->is_top()).
4583 }
4584 if (obj == nullptr || obj->is_top()) {
4585 return false; // dead path
4586 }
4587 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4588
4589 // First, see if Class.cast() can be folded statically.
4590 // java_mirror_type() returns non-null for compile-time Class constants.
4591 ciType* tm = mirror_con->java_mirror_type();
4592 if (tm != nullptr && tm->is_klass() &&
4593 tp != nullptr) {
4594 if (!tp->is_loaded()) {
4595 // Don't use intrinsic when class is not loaded.
4596 return false;
4597 } else {
4598 const TypeKlassPtr* tklass = TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces);
4599 int static_res = C->static_subtype_check(tklass, tp->as_klass_type());
4600 if (static_res == Compile::SSC_always_true) {
4601 // isInstance() is true - fold the code.
4602 set_result(obj);
4603 return true;
4604 } else if (static_res == Compile::SSC_always_false) {
4605 // Don't use intrinsic, have to throw ClassCastException.
4606 // If the reference is null, the non-intrinsic bytecode will
4607 // be optimized appropriately.
4608 return false;
4609 }
4610 }
4611 }
4612
4613 // Bailout intrinsic and do normal inlining if exception path is frequent.
4614 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4615 return false;
4616 }
4617
4618 // Generate dynamic checks.
4619 // Class.cast() is java implementation of _checkcast bytecode.
4620 // Do checkcast (Parse::do_checkcast()) optimizations here.
4621
4622 mirror = null_check(mirror);
4623 // If mirror is dead, only null-path is taken.
4624 if (stopped()) {
4625 return true;
4626 }
4627
4628 // Not-subtype or the mirror's klass ptr is nullptr (in case it is a primitive).
4629 enum { _bad_type_path = 1, _prim_path = 2, _npe_path = 3, PATH_LIMIT };
4630 RegionNode* region = new RegionNode(PATH_LIMIT);
4631 record_for_igvn(region);
4632
4633 // Now load the mirror's klass metaobject, and null-check it.
4634 // If kls is null, we have a primitive mirror and
4635 // nothing is an instance of a primitive type.
4636 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4637
4638 Node* res = top();
4639 Node* io = i_o();
4640 Node* mem = merged_memory();
4641 SafePointNode* new_cast_failure_map = nullptr;
4642
4643 if (!stopped()) {
4644
4645 Node* bad_type_ctrl = top();
4646 // Do checkcast optimizations.
4647 res = gen_checkcast(obj, kls, &bad_type_ctrl, &new_cast_failure_map);
4648 region->init_req(_bad_type_path, bad_type_ctrl);
4649 }
4650 if (region->in(_prim_path) != top() ||
4651 region->in(_bad_type_path) != top() ||
4652 region->in(_npe_path) != top()) {
4653 // Let Interpreter throw ClassCastException.
4654 PreserveJVMState pjvms(this);
4655 if (new_cast_failure_map != nullptr) {
4656 // The current map on the success path could have been modified. Use the dedicated failure path map.
4657 set_map(new_cast_failure_map);
4658 }
4659 set_control(_gvn.transform(region));
4660 // Set IO and memory because gen_checkcast may override them when buffering inline types
4661 set_i_o(io);
4662 set_all_memory(mem);
4663 uncommon_trap(Deoptimization::Reason_intrinsic,
4664 Deoptimization::Action_maybe_recompile);
4665 }
4666 if (!stopped()) {
4667 set_result(res);
4668 }
4669 return true;
4670 }
4671
4672
4673 //--------------------------inline_native_subtype_check------------------------
4674 // This intrinsic takes the JNI calls out of the heart of
4675 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4676 bool LibraryCallKit::inline_native_subtype_check() {
4677 // Pull both arguments off the stack.
4678 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4679 args[0] = argument(0);
4680 args[1] = argument(1);
4681 Node* klasses[2]; // corresponding Klasses: superk, subk
4682 klasses[0] = klasses[1] = top();
4683
4684 enum {
4685 // A full decision tree on {superc is prim, subc is prim}:
4686 _prim_0_path = 1, // {P,N} => false
4687 // {P,P} & superc!=subc => false
4688 _prim_same_path, // {P,P} & superc==subc => true
4689 _prim_1_path, // {N,P} => false
4690 _ref_subtype_path, // {N,N} & subtype check wins => true
4691 _both_ref_path, // {N,N} & subtype check loses => false
4692 PATH_LIMIT
4693 };
4694
4695 RegionNode* region = new RegionNode(PATH_LIMIT);
4696 RegionNode* prim_region = new RegionNode(2);
4697 Node* phi = new PhiNode(region, TypeInt::BOOL);
4698 record_for_igvn(region);
4699 record_for_igvn(prim_region);
4700
4701 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4702 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4703 int class_klass_offset = java_lang_Class::klass_offset();
4704
4705 // First null-check both mirrors and load each mirror's klass metaobject.
4706 int which_arg;
4707 for (which_arg = 0; which_arg <= 1; which_arg++) {
4708 Node* arg = args[which_arg];
4709 arg = null_check(arg);
4710 if (stopped()) break;
4711 args[which_arg] = arg;
4712
4713 Node* p = basic_plus_adr(arg, class_klass_offset);
4714 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4715 klasses[which_arg] = _gvn.transform(kls);
4716 }
4717
4718 // Having loaded both klasses, test each for null.
4719 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4720 for (which_arg = 0; which_arg <= 1; which_arg++) {
4721 Node* kls = klasses[which_arg];
4722 Node* null_ctl = top();
4723 kls = null_check_oop(kls, &null_ctl, never_see_null);
4724 if (which_arg == 0) {
4725 prim_region->init_req(1, null_ctl);
4726 } else {
4727 region->init_req(_prim_1_path, null_ctl);
4728 }
4729 if (stopped()) break;
4730 klasses[which_arg] = kls;
4731 }
4732
4733 if (!stopped()) {
4734 // now we have two reference types, in klasses[0..1]
4735 Node* subk = klasses[1]; // the argument to isAssignableFrom
4736 Node* superk = klasses[0]; // the receiver
4737 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4738 region->set_req(_ref_subtype_path, control());
4739 }
4740
4741 // If both operands are primitive (both klasses null), then
4742 // we must return true when they are identical primitives.
4743 // It is convenient to test this after the first null klass check.
4744 // This path is also used if superc is a value mirror.
4745 set_control(_gvn.transform(prim_region));
4746 if (!stopped()) {
4747 // Since superc is primitive, make a guard for the superc==subc case.
4748 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4749 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4750 generate_fair_guard(bol_eq, region);
4751 if (region->req() == PATH_LIMIT+1) {
4752 // A guard was added. If the added guard is taken, superc==subc.
4753 region->swap_edges(PATH_LIMIT, _prim_same_path);
4754 region->del_req(PATH_LIMIT);
4755 }
4756 region->set_req(_prim_0_path, control()); // Not equal after all.
4757 }
4758
4759 // these are the only paths that produce 'true':
4760 phi->set_req(_prim_same_path, intcon(1));
4761 phi->set_req(_ref_subtype_path, intcon(1));
4762
4763 // pull together the cases:
4764 assert(region->req() == PATH_LIMIT, "sane region");
4765 for (uint i = 1; i < region->req(); i++) {
4766 Node* ctl = region->in(i);
4767 if (ctl == nullptr || ctl == top()) {
4768 region->set_req(i, top());
4769 phi ->set_req(i, top());
4770 } else if (phi->in(i) == nullptr) {
4771 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4772 }
4773 }
4774
4775 set_control(_gvn.transform(region));
4776 set_result(_gvn.transform(phi));
4777 return true;
4778 }
4779
4780 //---------------------generate_array_guard_common------------------------
4781 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ArrayKind kind, Node** obj) {
4782
4783 if (stopped()) {
4784 return nullptr;
4785 }
4786
4787 // Like generate_guard, adds a new path onto the region.
4788 jint layout_con = 0;
4789 Node* layout_val = get_layout_helper(kls, layout_con);
4790 if (layout_val == nullptr) {
4791 bool query = 0;
4792 switch(kind) {
4793 case RefArray: query = Klass::layout_helper_is_refArray(layout_con); break;
4794 case NonRefArray: query = !Klass::layout_helper_is_refArray(layout_con); break;
4795 case TypeArray: query = Klass::layout_helper_is_typeArray(layout_con); break;
4796 case AnyArray: query = Klass::layout_helper_is_array(layout_con); break;
4797 case NonArray: query = !Klass::layout_helper_is_array(layout_con); break;
4798 default:
4799 ShouldNotReachHere();
4800 }
4801 if (!query) {
4802 return nullptr; // never a branch
4803 } else { // always a branch
4804 Node* always_branch = control();
4805 if (region != nullptr)
4806 region->add_req(always_branch);
4807 set_control(top());
4808 return always_branch;
4809 }
4810 }
4811 unsigned int value = 0;
4812 BoolTest::mask btest = BoolTest::illegal;
4813 switch(kind) {
4814 case RefArray:
4815 case NonRefArray: {
4816 value = Klass::_lh_array_tag_ref_value;
4817 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4818 btest = (kind == RefArray) ? BoolTest::eq : BoolTest::ne;
4819 break;
4820 }
4821 case TypeArray: {
4822 value = Klass::_lh_array_tag_type_value;
4823 layout_val = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
4824 btest = BoolTest::eq;
4825 break;
4826 }
4827 case AnyArray: value = Klass::_lh_neutral_value; btest = BoolTest::lt; break;
4828 case NonArray: value = Klass::_lh_neutral_value; btest = BoolTest::gt; break;
4829 default:
4830 ShouldNotReachHere();
4831 }
4832 // Now test the correct condition.
4833 jint nval = (jint)value;
4834 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4835 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4836 Node* ctrl = generate_fair_guard(bol, region);
4837 Node* is_array_ctrl = kind == NonArray ? control() : ctrl;
4838 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4839 // Keep track of the fact that 'obj' is an array to prevent
4840 // array specific accesses from floating above the guard.
4841 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4842 }
4843 return ctrl;
4844 }
4845
4846 // public static native Object[] ValueClass::newNullRestrictedAtomicArray(Class<?> componentType, int length, Object initVal);
4847 // public static native Object[] ValueClass::newNullRestrictedNonAtomicArray(Class<?> componentType, int length, Object initVal);
4848 // public static native Object[] ValueClass::newNullableAtomicArray(Class<?> componentType, int length);
4849 bool LibraryCallKit::inline_newArray(bool null_free, bool atomic) {
4850 assert(null_free || atomic, "nullable implies atomic");
4851 Node* componentType = argument(0);
4852 Node* length = argument(1);
4853 Node* init_val = null_free ? argument(2) : nullptr;
4854
4855 const TypeInstPtr* tp = _gvn.type(componentType)->isa_instptr();
4856 if (tp != nullptr) {
4857 ciInstanceKlass* ik = tp->instance_klass();
4858 if (ik == C->env()->Class_klass()) {
4859 ciType* t = tp->java_mirror_type();
4860 if (t != nullptr && t->is_inlinetype()) {
4861
4862 ciArrayKlass* array_klass = ciArrayKlass::make(t, null_free, atomic, true);
4863 assert(array_klass->is_elem_null_free() == null_free, "inconsistency");
4864
4865 // TODO 8350865 ZGC needs card marks on initializing oop stores
4866 if ((UseZGC || UseShenandoahGC) && null_free && !array_klass->is_flat_array_klass()) {
4867 return false;
4868 }
4869
4870 if (array_klass->is_loaded() && array_klass->element_klass()->as_inline_klass()->is_initialized()) {
4871 const TypeAryKlassPtr* array_klass_type = TypeAryKlassPtr::make(array_klass, Type::trust_interfaces);
4872 if (null_free) {
4873 if (init_val->is_InlineType()) {
4874 if (array_klass_type->is_flat() && init_val->as_InlineType()->is_all_zero(&gvn(), /* flat */ true)) {
4875 // Zeroing is enough because the init value is the all-zero value
4876 init_val = nullptr;
4877 } else {
4878 init_val = init_val->as_InlineType()->buffer(this);
4879 }
4880 }
4881 if (init_val != nullptr) {
4882 #ifdef ASSERT
4883 init_val = null_check(init_val);
4884 Node* wrong_type_ctl = gen_subtype_check(init_val, makecon(TypeKlassPtr::make(array_klass->element_klass())));
4885 {
4886 PreserveJVMState pjvms(this);
4887 set_control(wrong_type_ctl);
4888 halt(control(), frameptr(), "incompatible type for initVal in newArray");
4889 stop_and_kill_map();
4890 }
4891 #endif
4892 init_val = _gvn.transform(new CheckCastPPNode(control(), init_val, TypeOopPtr::make_from_klass(array_klass->element_klass()), ConstraintCastNode::DependencyType::NonFloatingNarrowing));
4893 }
4894 }
4895 Node* obj = new_array(makecon(array_klass_type), length, 0, nullptr, false, init_val);
4896 const TypeAryPtr* arytype = gvn().type(obj)->is_aryptr();
4897 assert(arytype->is_null_free() == null_free, "inconsistency");
4898 assert(arytype->is_not_null_free() == !null_free, "inconsistency");
4899 set_result(obj);
4900 return true;
4901 }
4902 }
4903 }
4904 }
4905 return false;
4906 }
4907
4908 // public static native boolean ValueClass::isFlatArray(Object array);
4909 // public static native boolean ValueClass::isNullRestrictedArray(Object array);
4910 // public static native boolean ValueClass::isAtomicArray(Object array);
4911 bool LibraryCallKit::inline_getArrayProperties(ArrayPropertiesCheck check) {
4912 Node* array = argument(0);
4913
4914 Node* bol;
4915 switch(check) {
4916 case IsFlat:
4917 bol = flat_array_test(load_object_klass(array));
4918 break;
4919 case IsNullRestricted:
4920 bol = null_free_array_test(array);
4921 break;
4922 case IsAtomic: {
4923 // See conditions in JVM_IsAtomicArray
4924 // 1. If not flat, then atomic, or else...
4925 RegionNode* atomic_region = new RegionNode(1);
4926 RegionNode* non_atomic_region = new RegionNode(1);
4927 Node* array_klass = load_object_klass(array);
4928 Node* is_flat_bol = flat_array_test(array_klass);
4929 IfNode* iff_is_flat = create_and_xform_if(control(), is_flat_bol, PROB_FAIR, COUNT_UNKNOWN);
4930 atomic_region->add_req(_gvn.transform(new IfFalseNode(iff_is_flat)));
4931 set_control(_gvn.transform(new IfTrueNode(iff_is_flat)));
4932
4933 // 2. ...if the layout is atomic, then atomic, or else...
4934 Node* layout_kind = atomic_layout_array_test_and_get_layout_kind(array, atomic_region);
4935
4936 // 3. ...if the element type is naturally atomic and null-free OR empty and nullable, then atomic, or else...
4937 int element_klass_offset = in_bytes(ObjArrayKlass::element_klass_offset());
4938 Node* array_element_klass_addr = off_heap_plus_addr(array_klass, element_klass_offset);
4939 Node* array_element_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), array_element_klass_addr, _gvn.type(array_klass)->is_klassptr()));
4940 int klass_flags_offset = in_bytes(InstanceKlass::misc_flags_offset() + InstanceKlassFlags::flags_offset());
4941 Node* array_element_klass_flags_addr = off_heap_plus_addr(array_element_klass, klass_flags_offset);
4942 Node* array_element_klass_flags = make_load(control(), array_element_klass_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
4943
4944 // Here, layout can only be non-atomic, otherwise atomic_layout_array_test_and_get_layout_kind already decides the array to be atomic.
4945 Node* is_null_free_cmp = _gvn.transform(new CmpINode(layout_kind, intcon(static_cast<jint>(LayoutKind::NULL_FREE_NON_ATOMIC_FLAT))));
4946 Node* is_null_free_bol = _gvn.transform(new BoolNode(is_null_free_cmp, BoolTest::eq));
4947 IfNode* iff_is_null_free_bol = create_and_xform_if(control(), is_null_free_bol, PROB_FAIR, COUNT_UNKNOWN);
4948 Node* is_null_free_ctl = _gvn.transform(new IfTrueNode(iff_is_null_free_bol));
4949 Node* is_nullable_ctl = _gvn.transform(new IfFalseNode(iff_is_null_free_bol));
4950
4951 Node* is_naturally_atomic_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_naturally_atomic)));
4952 Node* is_naturally_atomic_cmp = _gvn.transform(new CmpINode(is_naturally_atomic_flag, intcon(0)));
4953 Node* is_naturally_atomic_bol = _gvn.transform(new BoolNode(is_naturally_atomic_cmp, BoolTest::ne));
4954 IfNode* iff_is_naturally_atomic = create_and_xform_if(is_null_free_ctl, is_naturally_atomic_bol, PROB_FAIR, COUNT_UNKNOWN);
4955 Node* is_naturally_atomic_ctl = _gvn.transform(new IfTrueNode(iff_is_naturally_atomic));
4956 Node* is_not_naturally_atomic_ctl = _gvn.transform(new IfFalseNode(iff_is_naturally_atomic));
4957 atomic_region->add_req(is_naturally_atomic_ctl);
4958 non_atomic_region->add_req(is_not_naturally_atomic_ctl);
4959
4960 Node* is_empty_inline_type_flag = _gvn.transform(new AndINode(array_element_klass_flags, intcon(InstanceKlassFlags::_misc_is_empty_inline_type)));
4961 Node* is_empty_inline_type_cmp = _gvn.transform(new CmpINode(is_empty_inline_type_flag, intcon(0)));
4962 Node* is_empty_inline_type_bol = _gvn.transform(new BoolNode(is_empty_inline_type_cmp, BoolTest::ne));
4963 IfNode* iff_is_empty_inline_type = create_and_xform_if(is_nullable_ctl, is_empty_inline_type_bol, PROB_FAIR, COUNT_UNKNOWN);
4964 Node* is_empty_inline_type_ctl = _gvn.transform(new IfTrueNode(iff_is_empty_inline_type));
4965 Node* is_nonempty_inline_type_ctl = _gvn.transform(new IfFalseNode(iff_is_empty_inline_type));
4966 atomic_region->add_req(is_empty_inline_type_ctl);
4967 non_atomic_region->add_req(is_nonempty_inline_type_ctl);
4968
4969 // ...non-atomic, but we tried everything.
4970 RegionNode* decision = new RegionNode(3);
4971 decision->set_req(1, _gvn.transform(atomic_region));
4972 decision->set_req(2, _gvn.transform(non_atomic_region));
4973 PhiNode* result = PhiNode::make(decision, intcon(1), TypeInt::BOOL);
4974 result->set_req(2, intcon(0));
4975 set_control(_gvn.transform(decision));
4976 set_result(_gvn.transform(result));
4977 return true;
4978 }
4979 default:
4980 ShouldNotReachHere();
4981 }
4982
4983 Node* res = gvn().transform(new CMoveINode(bol, intcon(0), intcon(1), TypeInt::BOOL));
4984 set_result(res);
4985 return true;
4986 }
4987
4988 // Load the default refined array klass from an ObjArrayKlass. This relies on the first entry in the
4989 // '_next_refined_array_klass' linked list being the default (see ObjArrayKlass::klass_with_properties).
4990 Node* LibraryCallKit::load_default_refined_array_klass(Node* klass_node, bool type_array_guard) {
4991 RegionNode* region = new RegionNode(2);
4992 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT_OR_NULL);
4993
4994 if (type_array_guard) {
4995 generate_typeArray_guard(klass_node, region);
4996 if (region->req() == 3) {
4997 phi->add_req(klass_node);
4998 }
4999 }
5000 Node* adr_refined_klass = basic_plus_adr(top(), klass_node, in_bytes(ObjArrayKlass::next_refined_array_klass_offset()));
5001 Node* refined_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), adr_refined_klass, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
5002
5003 // Can be null if not initialized yet, just deopt
5004 Node* null_ctl = top();
5005 refined_klass = null_check_oop(refined_klass, &null_ctl, /* never_see_null= */ true);
5006
5007 region->init_req(1, control());
5008 phi->init_req(1, refined_klass);
5009
5010 set_control(_gvn.transform(region));
5011 return _gvn.transform(phi);
5012 }
5013
5014 // Load the non-refined array klass from an ObjArrayKlass.
5015 Node* LibraryCallKit::load_non_refined_array_klass(Node* klass_node) {
5016 const TypeAryKlassPtr* ary_klass_ptr = _gvn.type(klass_node)->isa_aryklassptr();
5017 if (ary_klass_ptr != nullptr && ary_klass_ptr->klass_is_exact()) {
5018 return _gvn.makecon(ary_klass_ptr->cast_to_refined_array_klass_ptr(false));
5019 }
5020
5021 RegionNode* region = new RegionNode(2);
5022 Node* phi = new PhiNode(region, TypeInstKlassPtr::OBJECT);
5023
5024 generate_typeArray_guard(klass_node, region);
5025 if (region->req() == 3) {
5026 phi->add_req(klass_node);
5027 }
5028 Node* super_adr = basic_plus_adr(top(), klass_node, in_bytes(Klass::super_offset()));
5029 Node* super_klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), super_adr, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT));
5030
5031 region->init_req(1, control());
5032 phi->init_req(1, super_klass);
5033
5034 set_control(_gvn.transform(region));
5035 return _gvn.transform(phi);
5036 }
5037
5038 //-----------------------inline_native_newArray--------------------------
5039 // private static native Object java.lang.reflect.Array.newArray(Class<?> componentType, int length);
5040 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
5041 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
5042 Node* mirror;
5043 Node* count_val;
5044 if (uninitialized) {
5045 null_check_receiver();
5046 mirror = argument(1);
5047 count_val = argument(2);
5048 } else {
5049 mirror = argument(0);
5050 count_val = argument(1);
5051 }
5052
5053 mirror = null_check(mirror);
5054 // If mirror or obj is dead, only null-path is taken.
5055 if (stopped()) return true;
5056
5057 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
5058 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5059 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5060 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5061 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5062
5063 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
5064 Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
5065 result_reg, _slow_path);
5066 Node* normal_ctl = control();
5067 Node* no_array_ctl = result_reg->in(_slow_path);
5068
5069 // Generate code for the slow case. We make a call to newArray().
5070 set_control(no_array_ctl);
5071 if (!stopped()) {
5072 // Either the input type is void.class, or else the
5073 // array klass has not yet been cached. Either the
5074 // ensuing call will throw an exception, or else it
5075 // will cache the array klass for next time.
5076 PreserveJVMState pjvms(this);
5077 CallJavaNode* slow_call = nullptr;
5078 if (uninitialized) {
5079 // Generate optimized virtual call (holder class 'Unsafe' is final)
5080 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
5081 } else {
5082 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
5083 }
5084 Node* slow_result = set_results_for_java_call(slow_call);
5085 // this->control() comes from set_results_for_java_call
5086 result_reg->set_req(_slow_path, control());
5087 result_val->set_req(_slow_path, slow_result);
5088 result_io ->set_req(_slow_path, i_o());
5089 result_mem->set_req(_slow_path, reset_memory());
5090 }
5091
5092 set_control(normal_ctl);
5093 if (!stopped()) {
5094 // Normal case: The array type has been cached in the java.lang.Class.
5095 // The following call works fine even if the array type is polymorphic.
5096 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5097
5098 klass_node = load_default_refined_array_klass(klass_node);
5099
5100 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
5101 result_reg->init_req(_normal_path, control());
5102 result_val->init_req(_normal_path, obj);
5103 result_io ->init_req(_normal_path, i_o());
5104 result_mem->init_req(_normal_path, reset_memory());
5105
5106 if (uninitialized) {
5107 // Mark the allocation so that zeroing is skipped
5108 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
5109 alloc->maybe_set_complete(&_gvn);
5110 }
5111 }
5112
5113 // Return the combined state.
5114 set_i_o( _gvn.transform(result_io) );
5115 set_all_memory( _gvn.transform(result_mem));
5116
5117 C->set_has_split_ifs(true); // Has chance for split-if optimization
5118 set_result(result_reg, result_val);
5119 return true;
5120 }
5121
5122 //----------------------inline_native_getLength--------------------------
5123 // public static native int java.lang.reflect.Array.getLength(Object array);
5124 bool LibraryCallKit::inline_native_getLength() {
5125 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
5126
5127 Node* array = null_check(argument(0));
5128 // If array is dead, only null-path is taken.
5129 if (stopped()) return true;
5130
5131 // Deoptimize if it is a non-array.
5132 Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
5133
5134 if (non_array != nullptr) {
5135 PreserveJVMState pjvms(this);
5136 set_control(non_array);
5137 uncommon_trap(Deoptimization::Reason_intrinsic,
5138 Deoptimization::Action_maybe_recompile);
5139 }
5140
5141 // If control is dead, only non-array-path is taken.
5142 if (stopped()) return true;
5143
5144 // The works fine even if the array type is polymorphic.
5145 // It could be a dynamic mix of int[], boolean[], Object[], etc.
5146 Node* result = load_array_length(array);
5147
5148 C->set_has_split_ifs(true); // Has chance for split-if optimization
5149 set_result(result);
5150 return true;
5151 }
5152
5153 //------------------------inline_array_copyOf----------------------------
5154 // public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);
5155 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);
5156 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
5157 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
5158
5159 // Get the arguments.
5160 Node* original = argument(0);
5161 Node* start = is_copyOfRange? argument(1): intcon(0);
5162 Node* end = is_copyOfRange? argument(2): argument(1);
5163 Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
5164
5165 Node* newcopy = nullptr;
5166
5167 // Set the original stack and the reexecute bit for the interpreter to reexecute
5168 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
5169 { PreserveReexecuteState preexecs(this);
5170 jvms()->set_should_reexecute(true);
5171
5172 array_type_mirror = null_check(array_type_mirror);
5173 original = null_check(original);
5174
5175 // Check if a null path was taken unconditionally.
5176 if (stopped()) return true;
5177
5178 Node* orig_length = load_array_length(original);
5179
5180 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
5181 klass_node = null_check(klass_node);
5182
5183 RegionNode* bailout = new RegionNode(1);
5184 record_for_igvn(bailout);
5185
5186 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
5187 // Bail out if that is so.
5188 // Inline type array may have object field that would require a
5189 // write barrier. Conservatively, go to slow path.
5190 // TODO 8251971: Optimize for the case when flat src/dst are later found
5191 // to not contain oops (i.e., move this check to the macro expansion phase).
5192 // TODO 8382226: Revisit for flat abstract value class arrays
5193 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5194 const TypeAryPtr* orig_t = _gvn.type(original)->isa_aryptr();
5195 const TypeKlassPtr* tklass = _gvn.type(klass_node)->is_klassptr();
5196 bool exclude_flat = UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, false, false, BarrierSetC2::Parsing) &&
5197 // Can src array be flat and contain oops?
5198 (orig_t == nullptr || (!orig_t->is_not_flat() && (!orig_t->is_flat() || orig_t->elem()->inline_klass()->contains_oops()))) &&
5199 // Can dest array be flat and contain oops?
5200 tklass->can_be_inline_array() && (!tklass->is_flat() || tklass->is_aryklassptr()->elem()->is_instklassptr()->instance_klass()->as_inline_klass()->contains_oops());
5201 Node* not_objArray = exclude_flat ? generate_non_refArray_guard(klass_node, bailout) : generate_typeArray_guard(klass_node, bailout);
5202
5203 Node* refined_klass_node = load_default_refined_array_klass(klass_node, /* type_array_guard= */ false);
5204
5205 if (not_objArray != nullptr) {
5206 // Improve the klass node's type from the new optimistic assumption:
5207 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
5208 bool not_flat = !UseArrayFlattening;
5209 bool not_null_free = !Arguments::is_valhalla_enabled();
5210 const Type* akls = TypeAryKlassPtr::make(TypePtr::NotNull, ak, Type::Offset(0), Type::trust_interfaces, not_flat, not_null_free, false, false, not_flat, true);
5211 Node* cast = new CastPPNode(control(), refined_klass_node, akls);
5212 refined_klass_node = _gvn.transform(cast);
5213 }
5214
5215 // Bail out if either start or end is negative.
5216 generate_negative_guard(start, bailout, &start);
5217 generate_negative_guard(end, bailout, &end);
5218
5219 Node* length = end;
5220 if (_gvn.type(start) != TypeInt::ZERO) {
5221 length = _gvn.transform(new SubINode(end, start));
5222 }
5223
5224 // Bail out if length is negative (i.e., if start > end).
5225 // Without this the new_array would throw
5226 // NegativeArraySizeException but IllegalArgumentException is what
5227 // should be thrown
5228 generate_negative_guard(length, bailout, &length);
5229
5230 // Handle inline type arrays
5231 // TODO 8251971 This is too strong
5232 generate_fair_guard(flat_array_test(load_object_klass(original)), bailout);
5233 generate_fair_guard(flat_array_test(refined_klass_node), bailout);
5234 generate_fair_guard(null_free_array_test(original), bailout);
5235
5236 // Bail out if start is larger than the original length
5237 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
5238 generate_negative_guard(orig_tail, bailout, &orig_tail);
5239
5240 if (bailout->req() > 1) {
5241 PreserveJVMState pjvms(this);
5242 set_control(_gvn.transform(bailout));
5243 uncommon_trap(Deoptimization::Reason_intrinsic,
5244 Deoptimization::Action_maybe_recompile);
5245 }
5246
5247 if (!stopped()) {
5248 // How many elements will we copy from the original?
5249 // The answer is MinI(orig_tail, length).
5250 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
5251
5252 // Generate a direct call to the right arraycopy function(s).
5253 // We know the copy is disjoint but we might not know if the
5254 // oop stores need checking.
5255 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
5256 // This will fail a store-check if x contains any non-nulls.
5257
5258 // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
5259 // loads/stores but it is legal only if we're sure the
5260 // Arrays.copyOf would succeed. So we need all input arguments
5261 // to the copyOf to be validated, including that the copy to the
5262 // new array won't trigger an ArrayStoreException. That subtype
5263 // check can be optimized if we know something on the type of
5264 // the input array from type speculation.
5265 if (_gvn.type(klass_node)->singleton()) {
5266 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
5267 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
5268
5269 int test = C->static_subtype_check(superk, subk);
5270 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
5271 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
5272 if (t_original->speculative_type() != nullptr) {
5273 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
5274 }
5275 }
5276 }
5277
5278 bool validated = false;
5279 // Reason_class_check rather than Reason_intrinsic because we
5280 // want to intrinsify even if this traps.
5281 if (!too_many_traps(Deoptimization::Reason_class_check)) {
5282 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
5283
5284 if (not_subtype_ctrl != top()) {
5285 PreserveJVMState pjvms(this);
5286 set_control(not_subtype_ctrl);
5287 uncommon_trap(Deoptimization::Reason_class_check,
5288 Deoptimization::Action_make_not_entrant);
5289 assert(stopped(), "Should be stopped");
5290 }
5291 validated = true;
5292 }
5293
5294 if (!stopped()) {
5295 newcopy = new_array(refined_klass_node, length, 0); // no arguments to push
5296
5297 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
5298 load_object_klass(original), klass_node);
5299 if (!is_copyOfRange) {
5300 ac->set_copyof(validated);
5301 } else {
5302 ac->set_copyofrange(validated);
5303 }
5304 Node* n = _gvn.transform(ac);
5305 if (n == ac) {
5306 ac->connect_outputs(this);
5307 } else {
5308 assert(validated, "shouldn't transform if all arguments not validated");
5309 set_all_memory(n);
5310 }
5311 }
5312 }
5313 } // original reexecute is set back here
5314
5315 C->set_has_split_ifs(true); // Has chance for split-if optimization
5316 if (!stopped()) {
5317 set_result(newcopy);
5318 }
5319 return true;
5320 }
5321
5322
5323 //----------------------generate_virtual_guard---------------------------
5324 // Helper for hashCode and clone. Peeks inside the vtable to avoid a call.
5325 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
5326 RegionNode* slow_region) {
5327 ciMethod* method = callee();
5328 int vtable_index = method->vtable_index();
5329 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5330 "bad index %d", vtable_index);
5331 // Get the Method* out of the appropriate vtable entry.
5332 int entry_offset = in_bytes(Klass::vtable_start_offset()) +
5333 vtable_index*vtableEntry::size_in_bytes() +
5334 in_bytes(vtableEntry::method_offset());
5335 Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
5336 Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
5337
5338 // Compare the target method with the expected method (e.g., Object.hashCode).
5339 const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
5340
5341 Node* native_call = makecon(native_call_addr);
5342 Node* chk_native = _gvn.transform(new CmpPNode(target_call, native_call));
5343 Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
5344
5345 return generate_slow_guard(test_native, slow_region);
5346 }
5347
5348 //-----------------------generate_method_call----------------------------
5349 // Use generate_method_call to make a slow-call to the real
5350 // method if the fast path fails. An alternative would be to
5351 // use a stub like OptoRuntime::slow_arraycopy_Java.
5352 // This only works for expanding the current library call,
5353 // not another intrinsic. (E.g., don't use this for making an
5354 // arraycopy call inside of the copyOf intrinsic.)
5355 CallJavaNode*
5356 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
5357 // When compiling the intrinsic method itself, do not use this technique.
5358 guarantee(callee() != C->method(), "cannot make slow-call to self");
5359
5360 ciMethod* method = callee();
5361 // ensure the JVMS we have will be correct for this call
5362 guarantee(method_id == method->intrinsic_id(), "must match");
5363
5364 const TypeFunc* tf = TypeFunc::make(method);
5365 if (res_not_null) {
5366 assert(tf->return_type() == T_OBJECT, "");
5367 const TypeTuple* range = tf->range_cc();
5368 const Type** fields = TypeTuple::fields(range->cnt());
5369 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
5370 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
5371 tf = TypeFunc::make(tf->domain_cc(), new_range);
5372 }
5373 CallJavaNode* slow_call;
5374 if (is_static) {
5375 assert(!is_virtual, "");
5376 slow_call = new CallStaticJavaNode(C, tf,
5377 SharedRuntime::get_resolve_static_call_stub(), method);
5378 } else if (is_virtual) {
5379 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5380 int vtable_index = Method::invalid_vtable_index;
5381 if (UseInlineCaches) {
5382 // Suppress the vtable call
5383 } else {
5384 // hashCode and clone are not a miranda methods,
5385 // so the vtable index is fixed.
5386 // No need to use the linkResolver to get it.
5387 vtable_index = method->vtable_index();
5388 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
5389 "bad index %d", vtable_index);
5390 }
5391 slow_call = new CallDynamicJavaNode(tf,
5392 SharedRuntime::get_resolve_virtual_call_stub(),
5393 method, vtable_index);
5394 } else { // neither virtual nor static: opt_virtual
5395 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
5396 slow_call = new CallStaticJavaNode(C, tf,
5397 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
5398 slow_call->set_optimized_virtual(true);
5399 }
5400 if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
5401 // To be able to issue a direct call (optimized virtual or virtual)
5402 // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
5403 // about the method being invoked should be attached to the call site to
5404 // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
5405 slow_call->set_override_symbolic_info(true);
5406 }
5407 set_arguments_for_java_call(slow_call);
5408 set_edges_for_java_call(slow_call);
5409 return slow_call;
5410 }
5411
5412
5413 /**
5414 * Build special case code for calls to hashCode on an object. This call may
5415 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
5416 * slightly different code.
5417 */
5418 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
5419 assert(is_static == callee()->is_static(), "correct intrinsic selection");
5420 assert(!(is_virtual && is_static), "either virtual, special, or static");
5421
5422 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
5423
5424 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5425 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
5426 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
5427 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5428 Node* obj = argument(0);
5429
5430 // Don't intrinsify hashcode on inline types for now.
5431 // The "is locked" runtime check also subsumes the inline type check (as inline types cannot be locked) and goes to the slow path.
5432 if (gvn().type(obj)->is_inlinetypeptr()) {
5433 return false;
5434 }
5435
5436 if (!is_static) {
5437 // Check for hashing null object
5438 obj = null_check_receiver();
5439 if (stopped()) return true; // unconditionally null
5440 result_reg->init_req(_null_path, top());
5441 result_val->init_req(_null_path, top());
5442 } else {
5443 // Do a null check, and return zero if null.
5444 // System.identityHashCode(null) == 0
5445 Node* null_ctl = top();
5446 obj = null_check_oop(obj, &null_ctl);
5447 result_reg->init_req(_null_path, null_ctl);
5448 result_val->init_req(_null_path, _gvn.intcon(0));
5449 }
5450
5451 // Unconditionally null? Then return right away.
5452 if (stopped()) {
5453 set_control( result_reg->in(_null_path));
5454 if (!stopped())
5455 set_result(result_val->in(_null_path));
5456 return true;
5457 }
5458
5459 // We only go to the fast case code if we pass a number of guards. The
5460 // paths which do not pass are accumulated in the slow_region.
5461 RegionNode* slow_region = new RegionNode(1);
5462 record_for_igvn(slow_region);
5463
5464 // If this is a virtual call, we generate a funny guard. We pull out
5465 // the vtable entry corresponding to hashCode() from the target object.
5466 // If the target method which we are calling happens to be the native
5467 // Object hashCode() method, we pass the guard. We do not need this
5468 // guard for non-virtual calls -- the caller is known to be the native
5469 // Object hashCode().
5470 if (is_virtual) {
5471 // After null check, get the object's klass.
5472 Node* obj_klass = load_object_klass(obj);
5473 generate_virtual_guard(obj_klass, slow_region);
5474 }
5475
5476 // Get the header out of the object, use LoadMarkNode when available
5477 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
5478 // The control of the load must be null. Otherwise, the load can move before
5479 // the null check after castPP removal.
5480 Node* no_ctrl = nullptr;
5481 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
5482
5483 if (!UseObjectMonitorTable) {
5484 // Test the header to see if it is safe to read w.r.t. locking.
5485 // We cannot use the inline type mask as this may check bits that are overridden
5486 // by an object monitor's pointer when inflating locking.
5487 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
5488 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
5489 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
5490 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
5491 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
5492
5493 generate_slow_guard(test_monitor, slow_region);
5494 }
5495
5496 // Get the hash value and check to see that it has been properly assigned.
5497 // We depend on hash_mask being at most 32 bits and avoid the use of
5498 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
5499 // vm: see markWord.hpp.
5500 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
5501 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
5502 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
5503 // This hack lets the hash bits live anywhere in the mark object now, as long
5504 // as the shift drops the relevant bits into the low 32 bits. Note that
5505 // Java spec says that HashCode is an int so there's no point in capturing
5506 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
5507 hshifted_header = ConvX2I(hshifted_header);
5508 Node *hash_val = _gvn.transform(new AndINode(hshifted_header, hash_mask));
5509
5510 Node *no_hash_val = _gvn.intcon(markWord::no_hash);
5511 Node *chk_assigned = _gvn.transform(new CmpINode( hash_val, no_hash_val));
5512 Node *test_assigned = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
5513
5514 generate_slow_guard(test_assigned, slow_region);
5515
5516 Node* init_mem = reset_memory();
5517 // fill in the rest of the null path:
5518 result_io ->init_req(_null_path, i_o());
5519 result_mem->init_req(_null_path, init_mem);
5520
5521 result_val->init_req(_fast_path, hash_val);
5522 result_reg->init_req(_fast_path, control());
5523 result_io ->init_req(_fast_path, i_o());
5524 result_mem->init_req(_fast_path, init_mem);
5525
5526 // Generate code for the slow case. We make a call to hashCode().
5527 set_control(_gvn.transform(slow_region));
5528 if (!stopped()) {
5529 // No need for PreserveJVMState, because we're using up the present state.
5530 set_all_memory(init_mem);
5531 vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
5532 CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
5533 Node* slow_result = set_results_for_java_call(slow_call);
5534 // this->control() comes from set_results_for_java_call
5535 result_reg->init_req(_slow_path, control());
5536 result_val->init_req(_slow_path, slow_result);
5537 result_io ->set_req(_slow_path, i_o());
5538 result_mem ->set_req(_slow_path, reset_memory());
5539 }
5540
5541 // Return the combined state.
5542 set_i_o( _gvn.transform(result_io) );
5543 set_all_memory( _gvn.transform(result_mem));
5544
5545 set_result(result_reg, result_val);
5546 return true;
5547 }
5548
5549 //---------------------------inline_native_getClass----------------------------
5550 // public final native Class<?> java.lang.Object.getClass();
5551 //
5552 // Build special case code for calls to getClass on an object.
5553 bool LibraryCallKit::inline_native_getClass() {
5554 Node* obj = argument(0);
5555 if (obj->is_InlineType()) {
5556 const Type* t = _gvn.type(obj);
5557 if (t->maybe_null()) {
5558 null_check(obj);
5559 }
5560 set_result(makecon(TypeInstPtr::make(t->inline_klass()->java_mirror())));
5561 return true;
5562 }
5563 obj = null_check_receiver();
5564 if (stopped()) return true;
5565 set_result(load_mirror_from_klass(load_object_klass(obj)));
5566 return true;
5567 }
5568
5569 //-----------------inline_native_Reflection_getCallerClass---------------------
5570 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
5571 //
5572 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
5573 //
5574 // NOTE: This code must perform the same logic as JVM_GetCallerClass
5575 // in that it must skip particular security frames and checks for
5576 // caller sensitive methods.
5577 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
5578 #ifndef PRODUCT
5579 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5580 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
5581 }
5582 #endif
5583
5584 if (!jvms()->has_method()) {
5585 #ifndef PRODUCT
5586 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5587 tty->print_cr(" Bailing out because intrinsic was inlined at top level");
5588 }
5589 #endif
5590 return false;
5591 }
5592
5593 // Walk back up the JVM state to find the caller at the required
5594 // depth.
5595 JVMState* caller_jvms = jvms();
5596
5597 // Cf. JVM_GetCallerClass
5598 // NOTE: Start the loop at depth 1 because the current JVM state does
5599 // not include the Reflection.getCallerClass() frame.
5600 for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
5601 ciMethod* m = caller_jvms->method();
5602 switch (n) {
5603 case 0:
5604 fatal("current JVM state does not include the Reflection.getCallerClass frame");
5605 break;
5606 case 1:
5607 // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
5608 if (!m->caller_sensitive()) {
5609 #ifndef PRODUCT
5610 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5611 tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);
5612 }
5613 #endif
5614 return false; // bail-out; let JVM_GetCallerClass do the work
5615 }
5616 break;
5617 default:
5618 if (!m->is_ignored_by_security_stack_walk()) {
5619 // We have reached the desired frame; return the holder class.
5620 // Acquire method holder as java.lang.Class and push as constant.
5621 ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
5622 ciInstance* caller_mirror = caller_klass->java_mirror();
5623 set_result(makecon(TypeInstPtr::make(caller_mirror)));
5624
5625 #ifndef PRODUCT
5626 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5627 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());
5628 tty->print_cr(" JVM state at this point:");
5629 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5630 ciMethod* m = jvms()->of_depth(i)->method();
5631 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5632 }
5633 }
5634 #endif
5635 return true;
5636 }
5637 break;
5638 }
5639 }
5640
5641 #ifndef PRODUCT
5642 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
5643 tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
5644 tty->print_cr(" JVM state at this point:");
5645 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
5646 ciMethod* m = jvms()->of_depth(i)->method();
5647 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5648 }
5649 }
5650 #endif
5651
5652 return false; // bail-out; let JVM_GetCallerClass do the work
5653 }
5654
5655 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5656 Node* arg = argument(0);
5657 Node* result = nullptr;
5658
5659 switch (id) {
5660 case vmIntrinsics::_floatToRawIntBits: result = new MoveF2INode(arg); break;
5661 case vmIntrinsics::_intBitsToFloat: result = new MoveI2FNode(arg); break;
5662 case vmIntrinsics::_doubleToRawLongBits: result = new MoveD2LNode(arg); break;
5663 case vmIntrinsics::_longBitsToDouble: result = new MoveL2DNode(arg); break;
5664 case vmIntrinsics::_floatToFloat16: result = new ConvF2HFNode(arg); break;
5665 case vmIntrinsics::_float16ToFloat: result = new ConvHF2FNode(arg); break;
5666
5667 case vmIntrinsics::_doubleToLongBits: {
5668 // two paths (plus control) merge in a wood
5669 RegionNode *r = new RegionNode(3);
5670 Node *phi = new PhiNode(r, TypeLong::LONG);
5671
5672 Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5673 // Build the boolean node
5674 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5675
5676 // Branch either way.
5677 // NaN case is less traveled, which makes all the difference.
5678 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5679 Node *opt_isnan = _gvn.transform(ifisnan);
5680 assert( opt_isnan->is_If(), "Expect an IfNode");
5681 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5682 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5683
5684 set_control(iftrue);
5685
5686 static const jlong nan_bits = CONST64(0x7ff8000000000000);
5687 Node *slow_result = longcon(nan_bits); // return NaN
5688 phi->init_req(1, _gvn.transform( slow_result ));
5689 r->init_req(1, iftrue);
5690
5691 // Else fall through
5692 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5693 set_control(iffalse);
5694
5695 phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5696 r->init_req(2, iffalse);
5697
5698 // Post merge
5699 set_control(_gvn.transform(r));
5700 record_for_igvn(r);
5701
5702 C->set_has_split_ifs(true); // Has chance for split-if optimization
5703 result = phi;
5704 assert(result->bottom_type()->isa_long(), "must be");
5705 break;
5706 }
5707
5708 case vmIntrinsics::_floatToIntBits: {
5709 // two paths (plus control) merge in a wood
5710 RegionNode *r = new RegionNode(3);
5711 Node *phi = new PhiNode(r, TypeInt::INT);
5712
5713 Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5714 // Build the boolean node
5715 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5716
5717 // Branch either way.
5718 // NaN case is less traveled, which makes all the difference.
5719 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5720 Node *opt_isnan = _gvn.transform(ifisnan);
5721 assert( opt_isnan->is_If(), "Expect an IfNode");
5722 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5723 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5724
5725 set_control(iftrue);
5726
5727 static const jint nan_bits = 0x7fc00000;
5728 Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5729 phi->init_req(1, _gvn.transform( slow_result ));
5730 r->init_req(1, iftrue);
5731
5732 // Else fall through
5733 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5734 set_control(iffalse);
5735
5736 phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5737 r->init_req(2, iffalse);
5738
5739 // Post merge
5740 set_control(_gvn.transform(r));
5741 record_for_igvn(r);
5742
5743 C->set_has_split_ifs(true); // Has chance for split-if optimization
5744 result = phi;
5745 assert(result->bottom_type()->isa_int(), "must be");
5746 break;
5747 }
5748
5749 default:
5750 fatal_unexpected_iid(id);
5751 break;
5752 }
5753 set_result(_gvn.transform(result));
5754 return true;
5755 }
5756
5757 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5758 Node* arg = argument(0);
5759 Node* result = nullptr;
5760
5761 switch (id) {
5762 case vmIntrinsics::_floatIsInfinite:
5763 result = new IsInfiniteFNode(arg);
5764 break;
5765 case vmIntrinsics::_floatIsFinite:
5766 result = new IsFiniteFNode(arg);
5767 break;
5768 case vmIntrinsics::_doubleIsInfinite:
5769 result = new IsInfiniteDNode(arg);
5770 break;
5771 case vmIntrinsics::_doubleIsFinite:
5772 result = new IsFiniteDNode(arg);
5773 break;
5774 default:
5775 fatal_unexpected_iid(id);
5776 break;
5777 }
5778 set_result(_gvn.transform(result));
5779 return true;
5780 }
5781
5782 //----------------------inline_unsafe_copyMemory-------------------------
5783 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5784
5785 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5786 const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5787 const Type* base_t = gvn.type(base);
5788
5789 bool in_native = (base_t == TypePtr::NULL_PTR);
5790 bool in_heap = !TypePtr::NULL_PTR->higher_equal(base_t);
5791 bool is_mixed = !in_heap && !in_native;
5792
5793 if (is_mixed) {
5794 return true; // mixed accesses can touch both on-heap and off-heap memory
5795 }
5796 if (in_heap) {
5797 bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5798 if (!is_prim_array) {
5799 // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5800 // there's not enough type information available to determine proper memory slice for it.
5801 return true;
5802 }
5803 }
5804 return false;
5805 }
5806
5807 bool LibraryCallKit::inline_unsafe_copyMemory() {
5808 if (callee()->is_static()) return false; // caller must have the capability!
5809 null_check_receiver(); // null-check receiver
5810 if (stopped()) return true;
5811
5812 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5813
5814 Node* src_base = argument(1); // type: oop
5815 Node* src_off = ConvL2X(argument(2)); // type: long
5816 Node* dst_base = argument(4); // type: oop
5817 Node* dst_off = ConvL2X(argument(5)); // type: long
5818 Node* size = ConvL2X(argument(7)); // type: long
5819
5820 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5821 "fieldOffset must be byte-scaled");
5822
5823 Node* src_addr = make_unsafe_address(src_base, src_off);
5824 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5825
5826 Node* thread = _gvn.transform(new ThreadLocalNode());
5827 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5828 BasicType doing_unsafe_access_bt = T_BYTE;
5829 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5830
5831 // update volatile field
5832 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5833
5834 int flags = RC_LEAF | RC_NO_FP;
5835
5836 const TypePtr* dst_type = TypePtr::BOTTOM;
5837
5838 // Adjust memory effects of the runtime call based on input values.
5839 if (!has_wide_mem(_gvn, src_addr, src_base) &&
5840 !has_wide_mem(_gvn, dst_addr, dst_base)) {
5841 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5842
5843 const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5844 if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5845 flags |= RC_NARROW_MEM; // narrow in memory
5846 }
5847 }
5848
5849 // Call it. Note that the length argument is not scaled.
5850 make_runtime_call(flags,
5851 OptoRuntime::fast_arraycopy_Type(),
5852 StubRoutines::unsafe_arraycopy(),
5853 "unsafe_arraycopy",
5854 dst_type,
5855 src_addr, dst_addr, size XTOP);
5856
5857 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5858
5859 return true;
5860 }
5861
5862 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5863 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5864 bool LibraryCallKit::inline_unsafe_setMemory() {
5865 if (callee()->is_static()) return false; // caller must have the capability!
5866 null_check_receiver(); // null-check receiver
5867 if (stopped()) return true;
5868
5869 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5870
5871 Node* dst_base = argument(1); // type: oop
5872 Node* dst_off = ConvL2X(argument(2)); // type: long
5873 Node* size = ConvL2X(argument(4)); // type: long
5874 Node* byte = argument(6); // type: byte
5875
5876 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5877 "fieldOffset must be byte-scaled");
5878
5879 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5880
5881 Node* thread = _gvn.transform(new ThreadLocalNode());
5882 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5883 BasicType doing_unsafe_access_bt = T_BYTE;
5884 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5885
5886 // update volatile field
5887 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5888
5889 int flags = RC_LEAF | RC_NO_FP;
5890
5891 const TypePtr* dst_type = TypePtr::BOTTOM;
5892
5893 // Adjust memory effects of the runtime call based on input values.
5894 if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5895 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5896
5897 flags |= RC_NARROW_MEM; // narrow in memory
5898 }
5899
5900 // Call it. Note that the length argument is not scaled.
5901 make_runtime_call(flags,
5902 OptoRuntime::unsafe_setmemory_Type(),
5903 StubRoutines::unsafe_setmemory(),
5904 "unsafe_setmemory",
5905 dst_type,
5906 dst_addr, size XTOP, byte);
5907
5908 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5909
5910 return true;
5911 }
5912
5913 #undef XTOP
5914
5915 //------------------------clone_coping-----------------------------------
5916 // Helper function for inline_native_clone.
5917 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5918 assert(obj_size != nullptr, "");
5919 Node* raw_obj = alloc_obj->in(1);
5920 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5921
5922 AllocateNode* alloc = nullptr;
5923 if (ReduceBulkZeroing &&
5924 // If we are implementing an array clone without knowing its source type
5925 // (can happen when compiling the array-guarded branch of a reflective
5926 // Object.clone() invocation), initialize the array within the allocation.
5927 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5928 // to a runtime clone call that assumes fully initialized source arrays.
5929 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5930 // We will be completely responsible for initializing this object -
5931 // mark Initialize node as complete.
5932 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5933 // The object was just allocated - there should be no any stores!
5934 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5935 // Mark as complete_with_arraycopy so that on AllocateNode
5936 // expansion, we know this AllocateNode is initialized by an array
5937 // copy and a StoreStore barrier exists after the array copy.
5938 alloc->initialization()->set_complete_with_arraycopy();
5939 }
5940
5941 Node* size = _gvn.transform(obj_size);
5942 access_clone(obj, alloc_obj, size, is_array);
5943
5944 // Do not let reads from the cloned object float above the arraycopy.
5945 if (alloc != nullptr) {
5946 // Do not let stores that initialize this object be reordered with
5947 // a subsequent store that would make this object accessible by
5948 // other threads.
5949 // Record what AllocateNode this StoreStore protects so that
5950 // escape analysis can go from the MemBarStoreStoreNode to the
5951 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5952 // based on the escape status of the AllocateNode.
5953 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5954 } else {
5955 insert_mem_bar(Op_MemBarCPUOrder);
5956 }
5957 }
5958
5959 //------------------------inline_native_clone----------------------------
5960 // protected native Object java.lang.Object.clone();
5961 //
5962 // Here are the simple edge cases:
5963 // null receiver => normal trap
5964 // virtual and clone was overridden => slow path to out-of-line clone
5965 // not cloneable or finalizer => slow path to out-of-line Object.clone
5966 //
5967 // The general case has two steps, allocation and copying.
5968 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5969 //
5970 // Copying also has two cases, oop arrays and everything else.
5971 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5972 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5973 //
5974 // These steps fold up nicely if and when the cloned object's klass
5975 // can be sharply typed as an object array, a type array, or an instance.
5976 //
5977 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5978 PhiNode* result_val;
5979
5980 // Set the reexecute bit for the interpreter to reexecute
5981 // the bytecode that invokes Object.clone if deoptimization happens.
5982 { PreserveReexecuteState preexecs(this);
5983 jvms()->set_should_reexecute(true);
5984
5985 Node* obj = argument(0);
5986 obj = null_check_receiver();
5987 if (stopped()) return true;
5988
5989 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5990 if (obj_type->is_inlinetypeptr()) {
5991 // If the object to clone is an inline type, we can simply return it (i.e. a nop) since inline types have
5992 // no identity.
5993 set_result(obj);
5994 return true;
5995 }
5996
5997 // If we are going to clone an instance, we need its exact type to
5998 // know the number and types of fields to convert the clone to
5999 // loads/stores. Maybe a speculative type can help us.
6000 if (!obj_type->klass_is_exact() &&
6001 obj_type->speculative_type() != nullptr &&
6002 obj_type->speculative_type()->is_instance_klass() &&
6003 !obj_type->speculative_type()->is_inlinetype()) {
6004 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
6005 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
6006 !spec_ik->has_injected_fields()) {
6007 if (!obj_type->isa_instptr() ||
6008 obj_type->is_instptr()->instance_klass()->has_subklass()) {
6009 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
6010 }
6011 }
6012 }
6013
6014 // Conservatively insert a memory barrier on all memory slices.
6015 // Do not let writes into the original float below the clone.
6016 insert_mem_bar(Op_MemBarCPUOrder);
6017
6018 // paths into result_reg:
6019 enum {
6020 _slow_path = 1, // out-of-line call to clone method (virtual or not)
6021 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
6022 _array_path, // plain array allocation, plus arrayof_long_arraycopy
6023 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
6024 PATH_LIMIT
6025 };
6026 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6027 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
6028 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
6029 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
6030 record_for_igvn(result_reg);
6031
6032 Node* obj_klass = load_object_klass(obj);
6033 // We only go to the fast case code if we pass a number of guards.
6034 // The paths which do not pass are accumulated in the slow_region.
6035 RegionNode* slow_region = new RegionNode(1);
6036 record_for_igvn(slow_region);
6037
6038 Node* array_obj = obj;
6039 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
6040 if (array_ctl != nullptr) {
6041 // It's an array.
6042 PreserveJVMState pjvms(this);
6043 set_control(array_ctl);
6044
6045 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6046 const TypeAryPtr* ary_ptr = obj_type->isa_aryptr();
6047 if (UseArrayFlattening && bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Expansion) &&
6048 obj_type->can_be_inline_array() &&
6049 (ary_ptr == nullptr || (!ary_ptr->is_not_flat() && (!ary_ptr->is_flat() || ary_ptr->elem()->inline_klass()->contains_oops())))) {
6050 // Flat inline type array may have object field that would require a
6051 // write barrier. Conservatively, go to slow path.
6052 generate_fair_guard(flat_array_test(obj_klass), slow_region);
6053 }
6054
6055 if (!stopped()) {
6056 Node* obj_length = load_array_length(array_obj);
6057 Node* array_size = nullptr; // Size of the array without object alignment padding.
6058 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
6059
6060 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
6061 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
6062 // If it is an oop array, it requires very special treatment,
6063 // because gc barriers are required when accessing the array.
6064 Node* is_obja = generate_refArray_guard(obj_klass, (RegionNode*)nullptr);
6065 if (is_obja != nullptr) {
6066 PreserveJVMState pjvms2(this);
6067 set_control(is_obja);
6068 // Generate a direct call to the right arraycopy function(s).
6069 // Clones are always tightly coupled.
6070 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
6071 ac->set_clone_oop_array();
6072 Node* n = _gvn.transform(ac);
6073 assert(n == ac, "cannot disappear");
6074 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
6075
6076 result_reg->init_req(_objArray_path, control());
6077 result_val->init_req(_objArray_path, alloc_obj);
6078 result_i_o ->set_req(_objArray_path, i_o());
6079 result_mem ->set_req(_objArray_path, reset_memory());
6080 }
6081 }
6082 // Otherwise, there are no barriers to worry about.
6083 // (We can dispense with card marks if we know the allocation
6084 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
6085 // causes the non-eden paths to take compensating steps to
6086 // simulate a fresh allocation, so that no further
6087 // card marks are required in compiled code to initialize
6088 // the object.)
6089
6090 if (!stopped()) {
6091 copy_to_clone(obj, alloc_obj, array_size, true);
6092
6093 // Present the results of the copy.
6094 result_reg->init_req(_array_path, control());
6095 result_val->init_req(_array_path, alloc_obj);
6096 result_i_o ->set_req(_array_path, i_o());
6097 result_mem ->set_req(_array_path, reset_memory());
6098 }
6099 }
6100 }
6101
6102 if (!stopped()) {
6103 // It's an instance (we did array above). Make the slow-path tests.
6104 // If this is a virtual call, we generate a funny guard. We grab
6105 // the vtable entry corresponding to clone() from the target object.
6106 // If the target method which we are calling happens to be the
6107 // Object clone() method, we pass the guard. We do not need this
6108 // guard for non-virtual calls; the caller is known to be the native
6109 // Object clone().
6110 if (is_virtual) {
6111 generate_virtual_guard(obj_klass, slow_region);
6112 }
6113
6114 // The object must be easily cloneable and must not have a finalizer.
6115 // Both of these conditions may be checked in a single test.
6116 // We could optimize the test further, but we don't care.
6117 generate_misc_flags_guard(obj_klass,
6118 // Test both conditions:
6119 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
6120 // Must be cloneable but not finalizer:
6121 KlassFlags::_misc_is_cloneable_fast,
6122 slow_region);
6123 }
6124
6125 if (!stopped()) {
6126 // It's an instance, and it passed the slow-path tests.
6127 PreserveJVMState pjvms(this);
6128 Node* obj_size = nullptr; // Total object size, including object alignment padding.
6129 // Need to deoptimize on exception from allocation since Object.clone intrinsic
6130 // is reexecuted if deoptimization occurs and there could be problems when merging
6131 // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
6132 Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
6133
6134 copy_to_clone(obj, alloc_obj, obj_size, false);
6135
6136 // Present the results of the slow call.
6137 result_reg->init_req(_instance_path, control());
6138 result_val->init_req(_instance_path, alloc_obj);
6139 result_i_o ->set_req(_instance_path, i_o());
6140 result_mem ->set_req(_instance_path, reset_memory());
6141 }
6142
6143 // Generate code for the slow case. We make a call to clone().
6144 set_control(_gvn.transform(slow_region));
6145 if (!stopped()) {
6146 PreserveJVMState pjvms(this);
6147 CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
6148 // We need to deoptimize on exception (see comment above)
6149 Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
6150 // this->control() comes from set_results_for_java_call
6151 result_reg->init_req(_slow_path, control());
6152 result_val->init_req(_slow_path, slow_result);
6153 result_i_o ->set_req(_slow_path, i_o());
6154 result_mem ->set_req(_slow_path, reset_memory());
6155 }
6156
6157 // Return the combined state.
6158 set_control( _gvn.transform(result_reg));
6159 set_i_o( _gvn.transform(result_i_o));
6160 set_all_memory( _gvn.transform(result_mem));
6161 } // original reexecute is set back here
6162
6163 set_result(_gvn.transform(result_val));
6164 return true;
6165 }
6166
6167 // If we have a tightly coupled allocation, the arraycopy may take care
6168 // of the array initialization. If one of the guards we insert between
6169 // the allocation and the arraycopy causes a deoptimization, an
6170 // uninitialized array will escape the compiled method. To prevent that
6171 // we set the JVM state for uncommon traps between the allocation and
6172 // the arraycopy to the state before the allocation so, in case of
6173 // deoptimization, we'll reexecute the allocation and the
6174 // initialization.
6175 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
6176 if (alloc != nullptr) {
6177 ciMethod* trap_method = alloc->jvms()->method();
6178 int trap_bci = alloc->jvms()->bci();
6179
6180 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6181 !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
6182 // Make sure there's no store between the allocation and the
6183 // arraycopy otherwise visible side effects could be rexecuted
6184 // in case of deoptimization and cause incorrect execution.
6185 bool no_interfering_store = true;
6186 Node* mem = alloc->in(TypeFunc::Memory);
6187 if (mem->is_MergeMem()) {
6188 for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
6189 Node* n = mms.memory();
6190 if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6191 assert(n->is_Store(), "what else?");
6192 no_interfering_store = false;
6193 break;
6194 }
6195 }
6196 } else {
6197 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
6198 Node* n = mms.memory();
6199 if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
6200 assert(n->is_Store(), "what else?");
6201 no_interfering_store = false;
6202 break;
6203 }
6204 }
6205 }
6206
6207 if (no_interfering_store) {
6208 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6209
6210 JVMState* saved_jvms = jvms();
6211 saved_reexecute_sp = _reexecute_sp;
6212
6213 set_jvms(sfpt->jvms());
6214 _reexecute_sp = jvms()->sp();
6215
6216 return saved_jvms;
6217 }
6218 }
6219 }
6220 return nullptr;
6221 }
6222
6223 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
6224 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
6225 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
6226 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
6227 uint size = alloc->req();
6228 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
6229 old_jvms->set_map(sfpt);
6230 for (uint i = 0; i < size; i++) {
6231 sfpt->init_req(i, alloc->in(i));
6232 }
6233 int adjustment = 1;
6234 const TypeAryKlassPtr* ary_klass_ptr = alloc->in(AllocateNode::KlassNode)->bottom_type()->is_aryklassptr();
6235 if (ary_klass_ptr->is_null_free()) {
6236 // A null-free, tightly coupled array allocation can only come from LibraryCallKit::inline_newArray which
6237 // also requires the componentType and initVal on stack for re-execution.
6238 // Re-create and push the componentType.
6239 ciArrayKlass* klass = ary_klass_ptr->exact_klass()->as_array_klass();
6240 ciInstance* instance = klass->component_mirror_instance();
6241 const TypeInstPtr* t_instance = TypeInstPtr::make(instance);
6242 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), makecon(t_instance));
6243 adjustment++;
6244 }
6245 // re-push array length for deoptimization
6246 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment - 1, alloc->in(AllocateNode::ALength));
6247 if (ary_klass_ptr->is_null_free()) {
6248 // Re-create and push the initVal.
6249 Node* init_val = alloc->in(AllocateNode::InitValue);
6250 if (init_val == nullptr) {
6251 init_val = InlineTypeNode::make_all_zero(_gvn, ary_klass_ptr->elem()->is_instklassptr()->instance_klass()->as_inline_klass());
6252 } else if (UseCompressedOops) {
6253 init_val = _gvn.transform(new DecodeNNode(init_val, init_val->bottom_type()->make_ptr()));
6254 }
6255 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp() + adjustment, init_val);
6256 adjustment++;
6257 }
6258 old_jvms->set_sp(old_jvms->sp() + adjustment);
6259 old_jvms->set_monoff(old_jvms->monoff() + adjustment);
6260 old_jvms->set_scloff(old_jvms->scloff() + adjustment);
6261 old_jvms->set_endoff(old_jvms->endoff() + adjustment);
6262 old_jvms->set_should_reexecute(true);
6263
6264 sfpt->set_i_o(map()->i_o());
6265 sfpt->set_memory(map()->memory());
6266 sfpt->set_control(map()->control());
6267 return sfpt;
6268 }
6269
6270 // In case of a deoptimization, we restart execution at the
6271 // allocation, allocating a new array. We would leave an uninitialized
6272 // array in the heap that GCs wouldn't expect. Move the allocation
6273 // after the traps so we don't allocate the array if we
6274 // deoptimize. This is possible because tightly_coupled_allocation()
6275 // guarantees there's no observer of the allocated array at this point
6276 // and the control flow is simple enough.
6277 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
6278 int saved_reexecute_sp, uint new_idx) {
6279 if (saved_jvms_before_guards != nullptr && !stopped()) {
6280 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
6281
6282 assert(alloc != nullptr, "only with a tightly coupled allocation");
6283 // restore JVM state to the state at the arraycopy
6284 saved_jvms_before_guards->map()->set_control(map()->control());
6285 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
6286 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
6287 // If we've improved the types of some nodes (null check) while
6288 // emitting the guards, propagate them to the current state
6289 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
6290 set_jvms(saved_jvms_before_guards);
6291 _reexecute_sp = saved_reexecute_sp;
6292
6293 // Remove the allocation from above the guards
6294 CallProjections* callprojs = alloc->extract_projections(true);
6295 InitializeNode* init = alloc->initialization();
6296 Node* alloc_mem = alloc->in(TypeFunc::Memory);
6297 C->gvn_replace_by(callprojs->fallthrough_ioproj, alloc->in(TypeFunc::I_O));
6298 init->replace_mem_projs_by(alloc_mem, C);
6299
6300 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
6301 // the allocation (i.e. is only valid if the allocation succeeds):
6302 // 1) replace CastIINode with AllocateArrayNode's length here
6303 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
6304 //
6305 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
6306 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
6307 Node* init_control = init->proj_out(TypeFunc::Control);
6308 Node* alloc_length = alloc->Ideal_length();
6309 #ifdef ASSERT
6310 Node* prev_cast = nullptr;
6311 #endif
6312 for (uint i = 0; i < init_control->outcnt(); i++) {
6313 Node* init_out = init_control->raw_out(i);
6314 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
6315 #ifdef ASSERT
6316 if (prev_cast == nullptr) {
6317 prev_cast = init_out;
6318 } else {
6319 if (prev_cast->cmp(*init_out) == false) {
6320 prev_cast->dump();
6321 init_out->dump();
6322 assert(false, "not equal CastIINode");
6323 }
6324 }
6325 #endif
6326 C->gvn_replace_by(init_out, alloc_length);
6327 }
6328 }
6329 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
6330
6331 // move the allocation here (after the guards)
6332 _gvn.hash_delete(alloc);
6333 alloc->set_req(TypeFunc::Control, control());
6334 alloc->set_req(TypeFunc::I_O, i_o());
6335 Node *mem = reset_memory();
6336 set_all_memory(mem);
6337 alloc->set_req(TypeFunc::Memory, mem);
6338 set_control(init->proj_out_or_null(TypeFunc::Control));
6339 set_i_o(callprojs->fallthrough_ioproj);
6340
6341 // Update memory as done in GraphKit::set_output_for_allocation()
6342 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
6343 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
6344 if (ary_type->isa_aryptr() && length_type != nullptr) {
6345 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
6346 }
6347 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
6348 int elemidx = C->get_alias_index(telemref);
6349 // Need to properly move every memory projection for the Initialize
6350 #ifdef ASSERT
6351 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
6352 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
6353 #endif
6354 auto move_proj = [&](ProjNode* proj) {
6355 int alias_idx = C->get_alias_index(proj->adr_type());
6356 assert(alias_idx == Compile::AliasIdxRaw ||
6357 alias_idx == elemidx ||
6358 alias_idx == mark_idx ||
6359 alias_idx == klass_idx, "should be raw memory or array element type");
6360 set_memory(proj, alias_idx);
6361 };
6362 init->for_each_proj(move_proj, TypeFunc::Memory);
6363
6364 Node* allocx = _gvn.transform(alloc);
6365 assert(allocx == alloc, "where has the allocation gone?");
6366 assert(dest->is_CheckCastPP(), "not an allocation result?");
6367
6368 _gvn.hash_delete(dest);
6369 dest->set_req(0, control());
6370 Node* destx = _gvn.transform(dest);
6371 assert(destx == dest, "where has the allocation result gone?");
6372
6373 array_ideal_length(alloc, ary_type, true);
6374 }
6375 }
6376
6377 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
6378 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
6379 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
6380 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
6381 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
6382 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
6383 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
6384 JVMState* saved_jvms_before_guards) {
6385 if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
6386 // There is at least one unrelated uncommon trap which needs to be replaced.
6387 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
6388
6389 JVMState* saved_jvms = jvms();
6390 const int saved_reexecute_sp = _reexecute_sp;
6391 set_jvms(sfpt->jvms());
6392 _reexecute_sp = jvms()->sp();
6393
6394 replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
6395
6396 // Restore state
6397 set_jvms(saved_jvms);
6398 _reexecute_sp = saved_reexecute_sp;
6399 }
6400 }
6401
6402 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
6403 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
6404 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
6405 Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
6406 while (if_proj->is_IfProj()) {
6407 CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
6408 if (uncommon_trap != nullptr) {
6409 create_new_uncommon_trap(uncommon_trap);
6410 }
6411 assert(if_proj->in(0)->is_If(), "must be If");
6412 if_proj = if_proj->in(0)->in(0);
6413 }
6414 assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
6415 "must have reached control projection of init node");
6416 }
6417
6418 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
6419 const int trap_request = uncommon_trap_call->uncommon_trap_request();
6420 assert(trap_request != 0, "no valid UCT trap request");
6421 PreserveJVMState pjvms(this);
6422 set_control(uncommon_trap_call->in(0));
6423 uncommon_trap(Deoptimization::trap_request_reason(trap_request),
6424 Deoptimization::trap_request_action(trap_request));
6425 assert(stopped(), "Should be stopped");
6426 _gvn.hash_delete(uncommon_trap_call);
6427 uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
6428 }
6429
6430 // Common checks for array sorting intrinsics arguments.
6431 // Returns `true` if checks passed.
6432 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
6433 // check address of the class
6434 if (elementType == nullptr || elementType->is_top()) {
6435 return false; // dead path
6436 }
6437 const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
6438 if (elem_klass == nullptr) {
6439 return false; // dead path
6440 }
6441 // java_mirror_type() returns non-null for compile-time Class constants only
6442 ciType* elem_type = elem_klass->java_mirror_type();
6443 if (elem_type == nullptr) {
6444 return false;
6445 }
6446 bt = elem_type->basic_type();
6447 // Disable the intrinsic if the CPU does not support SIMD sort
6448 if (!Matcher::supports_simd_sort(bt)) {
6449 return false;
6450 }
6451 // check address of the array
6452 if (obj == nullptr || obj->is_top()) {
6453 return false; // dead path
6454 }
6455 const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
6456 if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
6457 return false; // failed input validation
6458 }
6459 return true;
6460 }
6461
6462 //------------------------------inline_array_partition-----------------------
6463 bool LibraryCallKit::inline_array_partition() {
6464 address stubAddr = StubRoutines::select_array_partition_function();
6465 if (stubAddr == nullptr) {
6466 return false; // Intrinsic's stub is not implemented on this platform
6467 }
6468 assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
6469
6470 // no receiver because it is a static method
6471 Node* elementType = argument(0);
6472 Node* obj = argument(1);
6473 Node* offset = argument(2); // long
6474 Node* fromIndex = argument(4);
6475 Node* toIndex = argument(5);
6476 Node* indexPivot1 = argument(6);
6477 Node* indexPivot2 = argument(7);
6478 // PartitionOperation: argument(8) is ignored
6479
6480 Node* pivotIndices = nullptr;
6481 BasicType bt = T_ILLEGAL;
6482
6483 if (!check_array_sort_arguments(elementType, obj, bt)) {
6484 return false;
6485 }
6486 null_check(obj);
6487 // If obj is dead, only null-path is taken.
6488 if (stopped()) {
6489 return true;
6490 }
6491 // Set the original stack and the reexecute bit for the interpreter to reexecute
6492 // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
6493 { PreserveReexecuteState preexecs(this);
6494 jvms()->set_should_reexecute(true);
6495
6496 Node* obj_adr = make_unsafe_address(obj, offset);
6497
6498 // create the pivotIndices array of type int and size = 2
6499 Node* size = intcon(2);
6500 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
6501 pivotIndices = new_array(klass_node, size, 0); // no arguments to push
6502 AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
6503 guarantee(alloc != nullptr, "created above");
6504 Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
6505
6506 // pass the basic type enum to the stub
6507 Node* elemType = intcon(bt);
6508
6509 // Call the stub
6510 const char *stubName = "array_partition_stub";
6511 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
6512 stubAddr, stubName, TypePtr::BOTTOM,
6513 obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
6514 indexPivot1, indexPivot2);
6515
6516 } // original reexecute is set back here
6517
6518 if (!stopped()) {
6519 set_result(pivotIndices);
6520 }
6521
6522 return true;
6523 }
6524
6525
6526 //------------------------------inline_array_sort-----------------------
6527 bool LibraryCallKit::inline_array_sort() {
6528 address stubAddr = StubRoutines::select_arraysort_function();
6529 if (stubAddr == nullptr) {
6530 return false; // Intrinsic's stub is not implemented on this platform
6531 }
6532 assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
6533
6534 // no receiver because it is a static method
6535 Node* elementType = argument(0);
6536 Node* obj = argument(1);
6537 Node* offset = argument(2); // long
6538 Node* fromIndex = argument(4);
6539 Node* toIndex = argument(5);
6540 // SortOperation: argument(6) is ignored
6541
6542 BasicType bt = T_ILLEGAL;
6543
6544 if (!check_array_sort_arguments(elementType, obj, bt)) {
6545 return false;
6546 }
6547 null_check(obj);
6548 // If obj is dead, only null-path is taken.
6549 if (stopped()) {
6550 return true;
6551 }
6552 Node* obj_adr = make_unsafe_address(obj, offset);
6553
6554 // pass the basic type enum to the stub
6555 Node* elemType = intcon(bt);
6556
6557 // Call the stub.
6558 const char *stubName = "arraysort_stub";
6559 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
6560 stubAddr, stubName, TypePtr::BOTTOM,
6561 obj_adr, elemType, fromIndex, toIndex);
6562
6563 return true;
6564 }
6565
6566
6567 //------------------------------inline_arraycopy-----------------------
6568 // public static native void java.lang.System.arraycopy(Object src, int srcPos,
6569 // Object dest, int destPos,
6570 // int length);
6571 bool LibraryCallKit::inline_arraycopy() {
6572 // Get the arguments.
6573 Node* src = argument(0); // type: oop
6574 Node* src_offset = argument(1); // type: int
6575 Node* dest = argument(2); // type: oop
6576 Node* dest_offset = argument(3); // type: int
6577 Node* length = argument(4); // type: int
6578
6579 uint new_idx = C->unique();
6580
6581 // Check for allocation before we add nodes that would confuse
6582 // tightly_coupled_allocation()
6583 AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
6584
6585 int saved_reexecute_sp = -1;
6586 JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
6587 // See arraycopy_restore_alloc_state() comment
6588 // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
6589 // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
6590 // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
6591 bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
6592
6593 // The following tests must be performed
6594 // (1) src and dest are arrays.
6595 // (2) src and dest arrays must have elements of the same BasicType
6596 // (3) src and dest must not be null.
6597 // (4) src_offset must not be negative.
6598 // (5) dest_offset must not be negative.
6599 // (6) length must not be negative.
6600 // (7) src_offset + length must not exceed length of src.
6601 // (8) dest_offset + length must not exceed length of dest.
6602 // (9) each element of an oop array must be assignable
6603
6604 // (3) src and dest must not be null.
6605 // always do this here because we need the JVM state for uncommon traps
6606 Node* null_ctl = top();
6607 src = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
6608 assert(null_ctl->is_top(), "no null control here");
6609 dest = null_check(dest, T_ARRAY);
6610
6611 if (!can_emit_guards) {
6612 // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
6613 // guards but the arraycopy node could still take advantage of a
6614 // tightly allocated allocation. tightly_coupled_allocation() is
6615 // called again to make sure it takes the null check above into
6616 // account: the null check is mandatory and if it caused an
6617 // uncommon trap to be emitted then the allocation can't be
6618 // considered tightly coupled in this context.
6619 alloc = tightly_coupled_allocation(dest);
6620 }
6621
6622 bool validated = false;
6623
6624 const Type* src_type = _gvn.type(src);
6625 const Type* dest_type = _gvn.type(dest);
6626 const TypeAryPtr* top_src = src_type->isa_aryptr();
6627 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
6628
6629 // Do we have the type of src?
6630 bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6631 // Do we have the type of dest?
6632 bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6633 // Is the type for src from speculation?
6634 bool src_spec = false;
6635 // Is the type for dest from speculation?
6636 bool dest_spec = false;
6637
6638 if ((!has_src || !has_dest) && can_emit_guards) {
6639 // We don't have sufficient type information, let's see if
6640 // speculative types can help. We need to have types for both src
6641 // and dest so that it pays off.
6642
6643 // Do we already have or could we have type information for src
6644 bool could_have_src = has_src;
6645 // Do we already have or could we have type information for dest
6646 bool could_have_dest = has_dest;
6647
6648 ciKlass* src_k = nullptr;
6649 if (!has_src) {
6650 src_k = src_type->speculative_type_not_null();
6651 if (src_k != nullptr && src_k->is_array_klass()) {
6652 could_have_src = true;
6653 }
6654 }
6655
6656 ciKlass* dest_k = nullptr;
6657 if (!has_dest) {
6658 dest_k = dest_type->speculative_type_not_null();
6659 if (dest_k != nullptr && dest_k->is_array_klass()) {
6660 could_have_dest = true;
6661 }
6662 }
6663
6664 if (could_have_src && could_have_dest) {
6665 // This is going to pay off so emit the required guards
6666 if (!has_src) {
6667 src = maybe_cast_profiled_obj(src, src_k, true);
6668 src_type = _gvn.type(src);
6669 top_src = src_type->isa_aryptr();
6670 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
6671 src_spec = true;
6672 }
6673 if (!has_dest) {
6674 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6675 dest_type = _gvn.type(dest);
6676 top_dest = dest_type->isa_aryptr();
6677 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
6678 dest_spec = true;
6679 }
6680 }
6681 }
6682
6683 if (has_src && has_dest && can_emit_guards) {
6684 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
6685 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
6686 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
6687 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
6688
6689 if (src_elem == dest_elem && top_src->is_flat() == top_dest->is_flat() && src_elem == T_OBJECT) {
6690 // If both arrays are object arrays then having the exact types
6691 // for both will remove the need for a subtype check at runtime
6692 // before the call and may make it possible to pick a faster copy
6693 // routine (without a subtype check on every element)
6694 // Do we have the exact type of src?
6695 bool could_have_src = src_spec;
6696 // Do we have the exact type of dest?
6697 bool could_have_dest = dest_spec;
6698 ciKlass* src_k = nullptr;
6699 ciKlass* dest_k = nullptr;
6700 if (!src_spec) {
6701 src_k = src_type->speculative_type_not_null();
6702 if (src_k != nullptr && src_k->is_array_klass()) {
6703 could_have_src = true;
6704 }
6705 }
6706 if (!dest_spec) {
6707 dest_k = dest_type->speculative_type_not_null();
6708 if (dest_k != nullptr && dest_k->is_array_klass()) {
6709 could_have_dest = true;
6710 }
6711 }
6712 if (could_have_src && could_have_dest) {
6713 // If we can have both exact types, emit the missing guards
6714 if (could_have_src && !src_spec) {
6715 src = maybe_cast_profiled_obj(src, src_k, true);
6716 src_type = _gvn.type(src);
6717 top_src = src_type->isa_aryptr();
6718 }
6719 if (could_have_dest && !dest_spec) {
6720 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6721 dest_type = _gvn.type(dest);
6722 top_dest = dest_type->isa_aryptr();
6723 }
6724 }
6725 }
6726 }
6727
6728 ciMethod* trap_method = method();
6729 int trap_bci = bci();
6730 if (saved_jvms_before_guards != nullptr) {
6731 trap_method = alloc->jvms()->method();
6732 trap_bci = alloc->jvms()->bci();
6733 }
6734
6735 bool negative_length_guard_generated = false;
6736
6737 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6738 can_emit_guards && !src->is_top() && !dest->is_top()) {
6739 // validate arguments: enables transformation the ArrayCopyNode
6740 validated = true;
6741
6742 RegionNode* slow_region = new RegionNode(1);
6743 record_for_igvn(slow_region);
6744
6745 // (1) src and dest are arrays.
6746 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6747 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6748
6749 // (2) src and dest arrays must have elements of the same BasicType
6750 // done at macro expansion or at Ideal transformation time
6751
6752 // (4) src_offset must not be negative.
6753 generate_negative_guard(src_offset, slow_region);
6754
6755 // (5) dest_offset must not be negative.
6756 generate_negative_guard(dest_offset, slow_region);
6757
6758 // (7) src_offset + length must not exceed length of src.
6759 generate_limit_guard(src_offset, length,
6760 load_array_length(src),
6761 slow_region);
6762
6763 // (8) dest_offset + length must not exceed length of dest.
6764 generate_limit_guard(dest_offset, length,
6765 load_array_length(dest),
6766 slow_region);
6767
6768 // (6) length must not be negative.
6769 // This is also checked in generate_arraycopy() during macro expansion, but
6770 // we also have to check it here for the case where the ArrayCopyNode will
6771 // be eliminated by Escape Analysis.
6772 if (EliminateAllocations) {
6773 generate_negative_guard(length, slow_region);
6774 negative_length_guard_generated = true;
6775 }
6776
6777 // (9) each element of an oop array must be assignable
6778 Node* dest_klass = load_object_klass(dest);
6779 Node* refined_dest_klass = dest_klass;
6780 if (src != dest) {
6781 dest_klass = load_non_refined_array_klass(refined_dest_klass);
6782 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6783 slow_region->add_req(not_subtype_ctrl);
6784 }
6785
6786 // TODO 8251971 Improve this. What about atomicity? Make sure this is always folded for type arrays.
6787 // If destination is null-restricted, source must be null-restricted as well: src_null_restricted || !dst_null_restricted
6788 Node* src_klass = load_object_klass(src);
6789 Node* adr_prop_src = basic_plus_adr(top(), src_klass, in_bytes(ArrayKlass::properties_offset()));
6790 Node* prop_src = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_src,
6791 _gvn.type(adr_prop_src)->is_ptr(), TypeInt::INT, T_INT,
6792 MemNode::unordered));
6793 Node* adr_prop_dest = basic_plus_adr(top(), refined_dest_klass, in_bytes(ArrayKlass::properties_offset()));
6794 Node* prop_dest = _gvn.transform(LoadNode::make(_gvn, control(), immutable_memory(), adr_prop_dest,
6795 _gvn.type(adr_prop_dest)->is_ptr(), TypeInt::INT, T_INT,
6796 MemNode::unordered));
6797
6798 const ArrayProperties props_null_restricted = ArrayProperties::Default().with_null_restricted();
6799 jint props_value = (jint)props_null_restricted.value();
6800
6801 prop_dest = _gvn.transform(new XorINode(prop_dest, intcon(props_value)));
6802 prop_src = _gvn.transform(new OrINode(prop_dest, prop_src));
6803 prop_src = _gvn.transform(new AndINode(prop_src, intcon(props_value)));
6804
6805 Node* chk = _gvn.transform(new CmpINode(prop_src, intcon(props_value)));
6806 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
6807 generate_fair_guard(tst, slow_region);
6808
6809 // TODO 8251971 This is too strong
6810 generate_fair_guard(flat_array_test(src), slow_region);
6811 generate_fair_guard(flat_array_test(dest), slow_region);
6812
6813 {
6814 PreserveJVMState pjvms(this);
6815 set_control(_gvn.transform(slow_region));
6816 uncommon_trap(Deoptimization::Reason_intrinsic,
6817 Deoptimization::Action_make_not_entrant);
6818 assert(stopped(), "Should be stopped");
6819 }
6820
6821 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->isa_klassptr();
6822 if (dest_klass_t == nullptr) {
6823 // refined_dest_klass may not be an array, which leads to dest_klass being top. This means we
6824 // are in a dead path.
6825 uncommon_trap(Deoptimization::Reason_intrinsic,
6826 Deoptimization::Action_make_not_entrant);
6827 return true;
6828 }
6829
6830 const Type* toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6831 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6832 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6833 }
6834
6835 if (stopped()) {
6836 return true;
6837 }
6838
6839 Node* dest_klass = load_object_klass(dest);
6840 dest_klass = load_non_refined_array_klass(dest_klass);
6841
6842 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6843 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6844 // so the compiler has a chance to eliminate them: during macro expansion,
6845 // we have to set their control (CastPP nodes are eliminated).
6846 load_object_klass(src), dest_klass,
6847 load_array_length(src), load_array_length(dest));
6848
6849 ac->set_arraycopy(validated);
6850
6851 Node* n = _gvn.transform(ac);
6852 if (n == ac) {
6853 ac->connect_outputs(this);
6854 } else {
6855 assert(validated, "shouldn't transform if all arguments not validated");
6856 set_all_memory(n);
6857 }
6858 clear_upper_avx();
6859
6860
6861 return true;
6862 }
6863
6864
6865 // Helper function which determines if an arraycopy immediately follows
6866 // an allocation, with no intervening tests or other escapes for the object.
6867 AllocateArrayNode*
6868 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6869 if (stopped()) return nullptr; // no fast path
6870 if (!C->do_aliasing()) return nullptr; // no MergeMems around
6871
6872 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6873 if (alloc == nullptr) return nullptr;
6874
6875 Node* rawmem = memory(Compile::AliasIdxRaw);
6876 // Is the allocation's memory state untouched?
6877 if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6878 // Bail out if there have been raw-memory effects since the allocation.
6879 // (Example: There might have been a call or safepoint.)
6880 return nullptr;
6881 }
6882 rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6883 if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6884 return nullptr;
6885 }
6886
6887 // There must be no unexpected observers of this allocation.
6888 for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6889 Node* obs = ptr->fast_out(i);
6890 if (obs != this->map()) {
6891 return nullptr;
6892 }
6893 }
6894
6895 // This arraycopy must unconditionally follow the allocation of the ptr.
6896 Node* alloc_ctl = ptr->in(0);
6897 Node* ctl = control();
6898 while (ctl != alloc_ctl) {
6899 // There may be guards which feed into the slow_region.
6900 // Any other control flow means that we might not get a chance
6901 // to finish initializing the allocated object.
6902 // Various low-level checks bottom out in uncommon traps. These
6903 // are considered safe since we've already checked above that
6904 // there is no unexpected observer of this allocation.
6905 if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6906 assert(ctl->in(0)->is_If(), "must be If");
6907 ctl = ctl->in(0)->in(0);
6908 } else {
6909 return nullptr;
6910 }
6911 }
6912
6913 // If we get this far, we have an allocation which immediately
6914 // precedes the arraycopy, and we can take over zeroing the new object.
6915 // The arraycopy will finish the initialization, and provide
6916 // a new control state to which we will anchor the destination pointer.
6917
6918 return alloc;
6919 }
6920
6921 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6922 if (node->is_IfProj()) {
6923 IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6924 for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6925 Node* obs = other_proj->fast_out(j);
6926 if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6927 (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6928 return obs->as_CallStaticJava();
6929 }
6930 }
6931 }
6932 return nullptr;
6933 }
6934
6935 //-------------inline_encodeISOArray-----------------------------------
6936 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6937 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6938 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6939 // encode char[] to byte[] in ISO_8859_1 or ASCII
6940 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6941 assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6942 // no receiver since it is static method
6943 Node *src = argument(0);
6944 Node *src_offset = argument(1);
6945 Node *dst = argument(2);
6946 Node *dst_offset = argument(3);
6947 Node *length = argument(4);
6948
6949 // Cast source & target arrays to not-null
6950 src = must_be_not_null(src, true);
6951 dst = must_be_not_null(dst, true);
6952 if (stopped()) {
6953 return true;
6954 }
6955
6956 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6957 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6958 if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6959 dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6960 // failed array check
6961 return false;
6962 }
6963
6964 // Figure out the size and type of the elements we will be copying.
6965 BasicType src_elem = src_type->elem()->array_element_basic_type();
6966 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6967 if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6968 return false;
6969 }
6970
6971 // Check source & target bounds
6972 RegionNode* bailout = create_bailout();
6973 generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6974 generate_string_range_check(dst, dst_offset, length, false, bailout);
6975 if (check_bailout(bailout)) {
6976 return true;
6977 }
6978
6979 Node* src_start = array_element_address(src, src_offset, T_CHAR);
6980 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6981 // 'src_start' points to src array + scaled offset
6982 // 'dst_start' points to dst array + scaled offset
6983
6984 // See GraphKit::compress_string
6985 const TypePtr* adr_type;
6986 Node* mem = capture_memory(adr_type, src_type, dst_type);
6987 Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii);
6988 enc = _gvn.transform(enc);
6989 Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6990 memory_effect(res_mem, src_type, dst_type);
6991
6992 set_result(enc);
6993 clear_upper_avx();
6994
6995 return true;
6996 }
6997
6998 //-------------inline_multiplyToLen-----------------------------------
6999 bool LibraryCallKit::inline_multiplyToLen() {
7000 assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
7001
7002 address stubAddr = StubRoutines::multiplyToLen();
7003 if (stubAddr == nullptr) {
7004 return false; // Intrinsic's stub is not implemented on this platform
7005 }
7006 const char* stubName = "multiplyToLen";
7007
7008 assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
7009
7010 // no receiver because it is a static method
7011 Node* x = argument(0);
7012 Node* xlen = argument(1);
7013 Node* y = argument(2);
7014 Node* ylen = argument(3);
7015 Node* z = argument(4);
7016
7017 x = must_be_not_null(x, true);
7018 y = must_be_not_null(y, true);
7019
7020 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7021 const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
7022 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7023 y_type == nullptr || y_type->elem() == Type::BOTTOM) {
7024 // failed array check
7025 return false;
7026 }
7027
7028 BasicType x_elem = x_type->elem()->array_element_basic_type();
7029 BasicType y_elem = y_type->elem()->array_element_basic_type();
7030 if (x_elem != T_INT || y_elem != T_INT) {
7031 return false;
7032 }
7033
7034 Node* x_start = array_element_address(x, intcon(0), x_elem);
7035 Node* y_start = array_element_address(y, intcon(0), y_elem);
7036 // 'x_start' points to x array + scaled xlen
7037 // 'y_start' points to y array + scaled ylen
7038
7039 Node* z_start = array_element_address(z, intcon(0), T_INT);
7040
7041 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7042 OptoRuntime::multiplyToLen_Type(),
7043 stubAddr, stubName, TypePtr::BOTTOM,
7044 x_start, xlen, y_start, ylen, z_start);
7045
7046 C->set_has_split_ifs(true); // Has chance for split-if optimization
7047 set_result(z);
7048 return true;
7049 }
7050
7051 //-------------inline_squareToLen------------------------------------
7052 bool LibraryCallKit::inline_squareToLen() {
7053 assert(UseSquareToLenIntrinsic, "not implemented on this platform");
7054
7055 address stubAddr = StubRoutines::squareToLen();
7056 if (stubAddr == nullptr) {
7057 return false; // Intrinsic's stub is not implemented on this platform
7058 }
7059 const char* stubName = "squareToLen";
7060
7061 assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
7062
7063 Node* x = argument(0);
7064 Node* len = argument(1);
7065 Node* z = argument(2);
7066 Node* zlen = argument(3);
7067
7068 x = must_be_not_null(x, true);
7069 z = must_be_not_null(z, true);
7070
7071 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
7072 const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
7073 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
7074 z_type == nullptr || z_type->elem() == Type::BOTTOM) {
7075 // failed array check
7076 return false;
7077 }
7078
7079 BasicType x_elem = x_type->elem()->array_element_basic_type();
7080 BasicType z_elem = z_type->elem()->array_element_basic_type();
7081 if (x_elem != T_INT || z_elem != T_INT) {
7082 return false;
7083 }
7084
7085
7086 Node* x_start = array_element_address(x, intcon(0), x_elem);
7087 Node* z_start = array_element_address(z, intcon(0), z_elem);
7088
7089 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7090 OptoRuntime::squareToLen_Type(),
7091 stubAddr, stubName, TypePtr::BOTTOM,
7092 x_start, len, z_start, zlen);
7093
7094 set_result(z);
7095 return true;
7096 }
7097
7098 //-------------inline_mulAdd------------------------------------------
7099 bool LibraryCallKit::inline_mulAdd() {
7100 assert(UseMulAddIntrinsic, "not implemented on this platform");
7101
7102 address stubAddr = StubRoutines::mulAdd();
7103 if (stubAddr == nullptr) {
7104 return false; // Intrinsic's stub is not implemented on this platform
7105 }
7106 const char* stubName = "mulAdd";
7107
7108 assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
7109
7110 Node* out = argument(0);
7111 Node* in = argument(1);
7112 Node* offset = argument(2);
7113 Node* len = argument(3);
7114 Node* k = argument(4);
7115
7116 in = must_be_not_null(in, true);
7117 out = must_be_not_null(out, true);
7118
7119 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
7120 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
7121 if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
7122 in_type == nullptr || in_type->elem() == Type::BOTTOM) {
7123 // failed array check
7124 return false;
7125 }
7126
7127 BasicType out_elem = out_type->elem()->array_element_basic_type();
7128 BasicType in_elem = in_type->elem()->array_element_basic_type();
7129 if (out_elem != T_INT || in_elem != T_INT) {
7130 return false;
7131 }
7132
7133 Node* outlen = load_array_length(out);
7134 Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
7135 Node* out_start = array_element_address(out, intcon(0), out_elem);
7136 Node* in_start = array_element_address(in, intcon(0), in_elem);
7137
7138 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
7139 OptoRuntime::mulAdd_Type(),
7140 stubAddr, stubName, TypePtr::BOTTOM,
7141 out_start,in_start, new_offset, len, k);
7142 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7143 set_result(result);
7144 return true;
7145 }
7146
7147 //-------------inline_montgomeryMultiply-----------------------------------
7148 bool LibraryCallKit::inline_montgomeryMultiply() {
7149 address stubAddr = StubRoutines::montgomeryMultiply();
7150 if (stubAddr == nullptr) {
7151 return false; // Intrinsic's stub is not implemented on this platform
7152 }
7153
7154 assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
7155 const char* stubName = "montgomery_multiply";
7156
7157 assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
7158
7159 Node* a = argument(0);
7160 Node* b = argument(1);
7161 Node* n = argument(2);
7162 Node* len = argument(3);
7163 Node* inv = argument(4);
7164 Node* m = argument(6);
7165
7166 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7167 const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
7168 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7169 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7170 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7171 b_type == nullptr || b_type->elem() == Type::BOTTOM ||
7172 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7173 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7174 // failed array check
7175 return false;
7176 }
7177
7178 BasicType a_elem = a_type->elem()->array_element_basic_type();
7179 BasicType b_elem = b_type->elem()->array_element_basic_type();
7180 BasicType n_elem = n_type->elem()->array_element_basic_type();
7181 BasicType m_elem = m_type->elem()->array_element_basic_type();
7182 if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7183 return false;
7184 }
7185
7186 // Make the call
7187 {
7188 Node* a_start = array_element_address(a, intcon(0), a_elem);
7189 Node* b_start = array_element_address(b, intcon(0), b_elem);
7190 Node* n_start = array_element_address(n, intcon(0), n_elem);
7191 Node* m_start = array_element_address(m, intcon(0), m_elem);
7192
7193 Node* call = make_runtime_call(RC_LEAF,
7194 OptoRuntime::montgomeryMultiply_Type(),
7195 stubAddr, stubName, TypePtr::BOTTOM,
7196 a_start, b_start, n_start, len, inv, top(),
7197 m_start);
7198 set_result(m);
7199 }
7200
7201 return true;
7202 }
7203
7204 bool LibraryCallKit::inline_montgomerySquare() {
7205 address stubAddr = StubRoutines::montgomerySquare();
7206 if (stubAddr == nullptr) {
7207 return false; // Intrinsic's stub is not implemented on this platform
7208 }
7209
7210 assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
7211 const char* stubName = "montgomery_square";
7212
7213 assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
7214
7215 Node* a = argument(0);
7216 Node* n = argument(1);
7217 Node* len = argument(2);
7218 Node* inv = argument(3);
7219 Node* m = argument(5);
7220
7221 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
7222 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
7223 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
7224 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
7225 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
7226 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
7227 // failed array check
7228 return false;
7229 }
7230
7231 BasicType a_elem = a_type->elem()->array_element_basic_type();
7232 BasicType n_elem = n_type->elem()->array_element_basic_type();
7233 BasicType m_elem = m_type->elem()->array_element_basic_type();
7234 if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
7235 return false;
7236 }
7237
7238 // Make the call
7239 {
7240 Node* a_start = array_element_address(a, intcon(0), a_elem);
7241 Node* n_start = array_element_address(n, intcon(0), n_elem);
7242 Node* m_start = array_element_address(m, intcon(0), m_elem);
7243
7244 Node* call = make_runtime_call(RC_LEAF,
7245 OptoRuntime::montgomerySquare_Type(),
7246 stubAddr, stubName, TypePtr::BOTTOM,
7247 a_start, n_start, len, inv, top(),
7248 m_start);
7249 set_result(m);
7250 }
7251
7252 return true;
7253 }
7254
7255 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
7256 address stubAddr = nullptr;
7257 const char* stubName = nullptr;
7258
7259 stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
7260 if (stubAddr == nullptr) {
7261 return false; // Intrinsic's stub is not implemented on this platform
7262 }
7263
7264 stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
7265
7266 assert(callee()->signature()->size() == 5, "expected 5 arguments");
7267
7268 Node* newArr = argument(0);
7269 Node* oldArr = argument(1);
7270 Node* newIdx = argument(2);
7271 Node* shiftCount = argument(3);
7272 Node* numIter = argument(4);
7273
7274 const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
7275 const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
7276 if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
7277 oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
7278 return false;
7279 }
7280
7281 BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
7282 BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
7283 if (newArr_elem != T_INT || oldArr_elem != T_INT) {
7284 return false;
7285 }
7286
7287 // Make the call
7288 {
7289 Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
7290 Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
7291
7292 Node* call = make_runtime_call(RC_LEAF,
7293 OptoRuntime::bigIntegerShift_Type(),
7294 stubAddr,
7295 stubName,
7296 TypePtr::BOTTOM,
7297 newArr_start,
7298 oldArr_start,
7299 newIdx,
7300 shiftCount,
7301 numIter);
7302 }
7303
7304 return true;
7305 }
7306
7307 //-------------inline_vectorizedMismatch------------------------------
7308 bool LibraryCallKit::inline_vectorizedMismatch() {
7309 assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
7310
7311 assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
7312 Node* obja = argument(0); // Object
7313 Node* aoffset = argument(1); // long
7314 Node* objb = argument(3); // Object
7315 Node* boffset = argument(4); // long
7316 Node* length = argument(6); // int
7317 Node* scale = argument(7); // int
7318
7319 const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
7320 const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
7321 if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
7322 objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
7323 scale == top()) {
7324 return false; // failed input validation
7325 }
7326
7327 Node* obja_adr = make_unsafe_address(obja, aoffset);
7328 Node* objb_adr = make_unsafe_address(objb, boffset);
7329
7330 // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
7331 //
7332 // inline_limit = ArrayOperationPartialInlineSize / element_size;
7333 // if (length <= inline_limit) {
7334 // inline_path:
7335 // vmask = VectorMaskGen length
7336 // vload1 = LoadVectorMasked obja, vmask
7337 // vload2 = LoadVectorMasked objb, vmask
7338 // result1 = VectorCmpMasked vload1, vload2, vmask
7339 // } else {
7340 // call_stub_path:
7341 // result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
7342 // }
7343 // exit_block:
7344 // return Phi(result1, result2);
7345 //
7346 enum { inline_path = 1, // input is small enough to process it all at once
7347 stub_path = 2, // input is too large; call into the VM
7348 PATH_LIMIT = 3
7349 };
7350
7351 Node* exit_block = new RegionNode(PATH_LIMIT);
7352 Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
7353 Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
7354
7355 Node* call_stub_path = control();
7356
7357 BasicType elem_bt = T_ILLEGAL;
7358
7359 const TypeInt* scale_t = _gvn.type(scale)->is_int();
7360 if (scale_t->is_con()) {
7361 switch (scale_t->get_con()) {
7362 case 0: elem_bt = T_BYTE; break;
7363 case 1: elem_bt = T_SHORT; break;
7364 case 2: elem_bt = T_INT; break;
7365 case 3: elem_bt = T_LONG; break;
7366
7367 default: elem_bt = T_ILLEGAL; break; // not supported
7368 }
7369 }
7370
7371 int inline_limit = 0;
7372 bool do_partial_inline = false;
7373
7374 if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
7375 inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
7376 do_partial_inline = inline_limit >= 16;
7377 }
7378
7379 if (do_partial_inline) {
7380 assert(elem_bt != T_ILLEGAL, "sanity");
7381
7382 if (Matcher::match_rule_supported_vector(Op_VectorMaskGen, inline_limit, elem_bt) &&
7383 Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
7384 Matcher::match_rule_supported_vector(Op_VectorCmpMasked, inline_limit, elem_bt)) {
7385
7386 const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
7387 Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
7388 Node* bol_gt = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
7389
7390 call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
7391
7392 if (!stopped()) {
7393 Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
7394
7395 const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
7396 const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
7397 Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
7398 Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
7399
7400 Node* vmask = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
7401 Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
7402 Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
7403 Node* result = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
7404
7405 exit_block->init_req(inline_path, control());
7406 memory_phi->init_req(inline_path, map()->memory());
7407 result_phi->init_req(inline_path, result);
7408
7409 C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
7410 clear_upper_avx();
7411 }
7412 }
7413 }
7414
7415 if (call_stub_path != nullptr) {
7416 set_control(call_stub_path);
7417
7418 Node* call = make_runtime_call(RC_LEAF,
7419 OptoRuntime::vectorizedMismatch_Type(),
7420 StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
7421 obja_adr, objb_adr, length, scale);
7422
7423 exit_block->init_req(stub_path, control());
7424 memory_phi->init_req(stub_path, map()->memory());
7425 result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
7426 }
7427
7428 exit_block = _gvn.transform(exit_block);
7429 memory_phi = _gvn.transform(memory_phi);
7430 result_phi = _gvn.transform(result_phi);
7431
7432 record_for_igvn(exit_block);
7433 record_for_igvn(memory_phi);
7434 record_for_igvn(result_phi);
7435
7436 set_control(exit_block);
7437 set_all_memory(memory_phi);
7438 set_result(result_phi);
7439
7440 return true;
7441 }
7442
7443 //------------------------------inline_vectorizedHashcode----------------------------
7444 bool LibraryCallKit::inline_vectorizedHashCode() {
7445 assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
7446
7447 assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
7448 Node* array = argument(0);
7449 Node* offset = argument(1);
7450 Node* length = argument(2);
7451 Node* initialValue = argument(3);
7452 Node* basic_type = argument(4);
7453
7454 if (basic_type == top()) {
7455 return false; // failed input validation
7456 }
7457
7458 const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
7459 if (!basic_type_t->is_con()) {
7460 return false; // Only intrinsify if mode argument is constant
7461 }
7462
7463 array = must_be_not_null(array, true);
7464
7465 BasicType bt = (BasicType)basic_type_t->get_con();
7466
7467 // Resolve address of first element
7468 Node* array_start = array_element_address(array, offset, bt);
7469
7470 const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt);
7471 set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type,
7472 array_start, length, initialValue, basic_type)));
7473 clear_upper_avx();
7474
7475 return true;
7476 }
7477
7478 /**
7479 * Calculate CRC32 for byte.
7480 * int java.util.zip.CRC32.update(int crc, int b)
7481 */
7482 bool LibraryCallKit::inline_updateCRC32() {
7483 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7484 assert(callee()->signature()->size() == 2, "update has 2 parameters");
7485 // no receiver since it is static method
7486 Node* crc = argument(0); // type: int
7487 Node* b = argument(1); // type: int
7488
7489 /*
7490 * int c = ~ crc;
7491 * b = timesXtoThe32[(b ^ c) & 0xFF];
7492 * b = b ^ (c >>> 8);
7493 * crc = ~b;
7494 */
7495
7496 Node* M1 = intcon(-1);
7497 crc = _gvn.transform(new XorINode(crc, M1));
7498 Node* result = _gvn.transform(new XorINode(crc, b));
7499 result = _gvn.transform(new AndINode(result, intcon(0xFF)));
7500
7501 Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
7502 Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
7503 Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
7504 result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
7505
7506 crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
7507 result = _gvn.transform(new XorINode(crc, result));
7508 result = _gvn.transform(new XorINode(result, M1));
7509 set_result(result);
7510 return true;
7511 }
7512
7513 /**
7514 * Calculate CRC32 for byte[] array.
7515 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
7516 */
7517 bool LibraryCallKit::inline_updateBytesCRC32() {
7518 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7519 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7520 // no receiver since it is static method
7521 Node* crc = argument(0); // type: int
7522 Node* src = argument(1); // type: oop
7523 Node* offset = argument(2); // type: int
7524 Node* length = argument(3); // type: int
7525
7526 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7527 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7528 // failed array check
7529 return false;
7530 }
7531
7532 // Figure out the size and type of the elements we will be copying.
7533 BasicType src_elem = src_type->elem()->array_element_basic_type();
7534 if (src_elem != T_BYTE) {
7535 return false;
7536 }
7537
7538 // 'src_start' points to src array + scaled offset
7539 src = must_be_not_null(src, true);
7540 Node* src_start = array_element_address(src, offset, src_elem);
7541
7542 // We assume that range check is done by caller.
7543 // TODO: generate range check (offset+length < src.length) in debug VM.
7544
7545 // Call the stub.
7546 address stubAddr = StubRoutines::updateBytesCRC32();
7547 const char *stubName = "updateBytesCRC32";
7548
7549 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7550 stubAddr, stubName, TypePtr::BOTTOM,
7551 crc, src_start, length);
7552 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7553 set_result(result);
7554 return true;
7555 }
7556
7557 /**
7558 * Calculate CRC32 for ByteBuffer.
7559 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
7560 */
7561 bool LibraryCallKit::inline_updateByteBufferCRC32() {
7562 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
7563 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7564 // no receiver since it is static method
7565 Node* crc = argument(0); // type: int
7566 Node* src = argument(1); // type: long
7567 Node* offset = argument(3); // type: int
7568 Node* length = argument(4); // type: int
7569
7570 src = ConvL2X(src); // adjust Java long to machine word
7571 Node* base = _gvn.transform(new CastX2PNode(src));
7572 offset = ConvI2X(offset);
7573
7574 // 'src_start' points to src array + scaled offset
7575 Node* src_start = off_heap_plus_addr(base, offset);
7576
7577 // Call the stub.
7578 address stubAddr = StubRoutines::updateBytesCRC32();
7579 const char *stubName = "updateBytesCRC32";
7580
7581 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
7582 stubAddr, stubName, TypePtr::BOTTOM,
7583 crc, src_start, length);
7584 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7585 set_result(result);
7586 return true;
7587 }
7588
7589 //------------------------------get_table_from_crc32c_class-----------------------
7590 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
7591 Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
7592 assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
7593
7594 return table;
7595 }
7596
7597 //------------------------------inline_updateBytesCRC32C-----------------------
7598 //
7599 // Calculate CRC32C for byte[] array.
7600 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
7601 //
7602 bool LibraryCallKit::inline_updateBytesCRC32C() {
7603 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7604 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7605 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7606 // no receiver since it is a static method
7607 Node* crc = argument(0); // type: int
7608 Node* src = argument(1); // type: oop
7609 Node* offset = argument(2); // type: int
7610 Node* end = argument(3); // type: int
7611
7612 Node* length = _gvn.transform(new SubINode(end, offset));
7613
7614 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7615 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7616 // failed array check
7617 return false;
7618 }
7619
7620 // Figure out the size and type of the elements we will be copying.
7621 BasicType src_elem = src_type->elem()->array_element_basic_type();
7622 if (src_elem != T_BYTE) {
7623 return false;
7624 }
7625
7626 // 'src_start' points to src array + scaled offset
7627 src = must_be_not_null(src, true);
7628 Node* src_start = array_element_address(src, offset, src_elem);
7629
7630 // static final int[] byteTable in class CRC32C
7631 Node* table = get_table_from_crc32c_class(callee()->holder());
7632 table = must_be_not_null(table, true);
7633 Node* table_start = array_element_address(table, intcon(0), T_INT);
7634
7635 // We assume that range check is done by caller.
7636 // TODO: generate range check (offset+length < src.length) in debug VM.
7637
7638 // Call the stub.
7639 address stubAddr = StubRoutines::updateBytesCRC32C();
7640 const char *stubName = "updateBytesCRC32C";
7641
7642 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7643 stubAddr, stubName, TypePtr::BOTTOM,
7644 crc, src_start, length, table_start);
7645 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7646 set_result(result);
7647 return true;
7648 }
7649
7650 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
7651 //
7652 // Calculate CRC32C for DirectByteBuffer.
7653 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
7654 //
7655 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
7656 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
7657 assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
7658 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
7659 // no receiver since it is a static method
7660 Node* crc = argument(0); // type: int
7661 Node* src = argument(1); // type: long
7662 Node* offset = argument(3); // type: int
7663 Node* end = argument(4); // type: int
7664
7665 Node* length = _gvn.transform(new SubINode(end, offset));
7666
7667 src = ConvL2X(src); // adjust Java long to machine word
7668 Node* base = _gvn.transform(new CastX2PNode(src));
7669 offset = ConvI2X(offset);
7670
7671 // 'src_start' points to src array + scaled offset
7672 Node* src_start = off_heap_plus_addr(base, offset);
7673
7674 // static final int[] byteTable in class CRC32C
7675 Node* table = get_table_from_crc32c_class(callee()->holder());
7676 table = must_be_not_null(table, true);
7677 Node* table_start = array_element_address(table, intcon(0), T_INT);
7678
7679 // Call the stub.
7680 address stubAddr = StubRoutines::updateBytesCRC32C();
7681 const char *stubName = "updateBytesCRC32C";
7682
7683 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
7684 stubAddr, stubName, TypePtr::BOTTOM,
7685 crc, src_start, length, table_start);
7686 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7687 set_result(result);
7688 return true;
7689 }
7690
7691 //------------------------------inline_updateBytesAdler32----------------------
7692 //
7693 // Calculate Adler32 checksum for byte[] array.
7694 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
7695 //
7696 bool LibraryCallKit::inline_updateBytesAdler32() {
7697 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7698 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
7699 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7700 // no receiver since it is static method
7701 Node* crc = argument(0); // type: int
7702 Node* src = argument(1); // type: oop
7703 Node* offset = argument(2); // type: int
7704 Node* length = argument(3); // type: int
7705
7706 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7707 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
7708 // failed array check
7709 return false;
7710 }
7711
7712 // Figure out the size and type of the elements we will be copying.
7713 BasicType src_elem = src_type->elem()->array_element_basic_type();
7714 if (src_elem != T_BYTE) {
7715 return false;
7716 }
7717
7718 // 'src_start' points to src array + scaled offset
7719 Node* src_start = array_element_address(src, offset, src_elem);
7720
7721 // We assume that range check is done by caller.
7722 // TODO: generate range check (offset+length < src.length) in debug VM.
7723
7724 // Call the stub.
7725 address stubAddr = StubRoutines::updateBytesAdler32();
7726 const char *stubName = "updateBytesAdler32";
7727
7728 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7729 stubAddr, stubName, TypePtr::BOTTOM,
7730 crc, src_start, length);
7731 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7732 set_result(result);
7733 return true;
7734 }
7735
7736 //------------------------------inline_updateByteBufferAdler32---------------
7737 //
7738 // Calculate Adler32 checksum for DirectByteBuffer.
7739 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7740 //
7741 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7742 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7743 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7744 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7745 // no receiver since it is static method
7746 Node* crc = argument(0); // type: int
7747 Node* src = argument(1); // type: long
7748 Node* offset = argument(3); // type: int
7749 Node* length = argument(4); // type: int
7750
7751 src = ConvL2X(src); // adjust Java long to machine word
7752 Node* base = _gvn.transform(new CastX2PNode(src));
7753 offset = ConvI2X(offset);
7754
7755 // 'src_start' points to src array + scaled offset
7756 Node* src_start = off_heap_plus_addr(base, offset);
7757
7758 // Call the stub.
7759 address stubAddr = StubRoutines::updateBytesAdler32();
7760 const char *stubName = "updateBytesAdler32";
7761
7762 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7763 stubAddr, stubName, TypePtr::BOTTOM,
7764 crc, src_start, length);
7765
7766 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7767 set_result(result);
7768 return true;
7769 }
7770
7771 //----------------------------inline_reference_get0----------------------------
7772 // public T java.lang.ref.Reference.get();
7773 bool LibraryCallKit::inline_reference_get0() {
7774 const int referent_offset = java_lang_ref_Reference::referent_offset();
7775
7776 // Get the argument:
7777 Node* reference_obj = null_check_receiver();
7778 if (stopped()) return true;
7779
7780 DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7781 Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7782 decorators, /*is_static*/ false,
7783 env()->Reference_klass());
7784 if (result == nullptr) return false;
7785
7786 // Add memory barrier to prevent commoning reads from this field
7787 // across safepoint since GC can change its value.
7788 insert_mem_bar(Op_MemBarCPUOrder);
7789
7790 set_result(result);
7791 return true;
7792 }
7793
7794 //----------------------------inline_reference_refersTo0----------------------------
7795 // bool java.lang.ref.Reference.refersTo0();
7796 // bool java.lang.ref.PhantomReference.refersTo0();
7797 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7798 // Get arguments:
7799 Node* reference_obj = null_check_receiver();
7800 Node* other_obj = argument(1);
7801 if (stopped()) return true;
7802
7803 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7804 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7805 Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7806 decorators, /*is_static*/ false,
7807 env()->Reference_klass());
7808 if (referent == nullptr) return false;
7809
7810 // Add memory barrier to prevent commoning reads from this field
7811 // across safepoint since GC can change its value.
7812 insert_mem_bar(Op_MemBarCPUOrder);
7813
7814 Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7815 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7816 IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7817
7818 RegionNode* region = new RegionNode(3);
7819 PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7820
7821 Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7822 region->init_req(1, if_true);
7823 phi->init_req(1, intcon(1));
7824
7825 Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7826 region->init_req(2, if_false);
7827 phi->init_req(2, intcon(0));
7828
7829 set_control(_gvn.transform(region));
7830 record_for_igvn(region);
7831 set_result(_gvn.transform(phi));
7832 return true;
7833 }
7834
7835 //----------------------------inline_reference_clear0----------------------------
7836 // void java.lang.ref.Reference.clear0();
7837 // void java.lang.ref.PhantomReference.clear0();
7838 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7839 // This matches the implementation in JVM_ReferenceClear, see the comments there.
7840
7841 // Get arguments
7842 Node* reference_obj = null_check_receiver();
7843 if (stopped()) return true;
7844
7845 // Common access parameters
7846 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7847 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7848 Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7849 const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7850 const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7851
7852 Node* referent = access_load_at(reference_obj,
7853 referent_field_addr,
7854 referent_field_addr_type,
7855 val_type,
7856 T_OBJECT,
7857 decorators);
7858
7859 IdealKit ideal(this);
7860 #define __ ideal.
7861 __ if_then(referent, BoolTest::ne, null());
7862 sync_kit(ideal);
7863 access_store_at(reference_obj,
7864 referent_field_addr,
7865 referent_field_addr_type,
7866 null(),
7867 val_type,
7868 T_OBJECT,
7869 decorators);
7870 __ sync_kit(this);
7871 __ end_if();
7872 final_sync(ideal);
7873 #undef __
7874
7875 return true;
7876 }
7877
7878 //-----------------------inline_reference_reachabilityFence-----------------
7879 // bool java.lang.ref.Reference.reachabilityFence();
7880 bool LibraryCallKit::inline_reference_reachabilityFence() {
7881 Node* referent = argument(0);
7882 insert_reachability_fence(referent);
7883 return true;
7884 }
7885
7886 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7887 DecoratorSet decorators, bool is_static,
7888 ciInstanceKlass* fromKls) {
7889 if (fromKls == nullptr) {
7890 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7891 assert(tinst != nullptr, "obj is null");
7892 assert(tinst->is_loaded(), "obj is not loaded");
7893 fromKls = tinst->instance_klass();
7894 }
7895 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7896 ciSymbol::make(fieldTypeString),
7897 is_static);
7898
7899 assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7900 if (field == nullptr) return (Node *) nullptr;
7901
7902 if (is_static) {
7903 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7904 fromObj = makecon(tip);
7905 }
7906
7907 // Next code copied from Parse::do_get_xxx():
7908
7909 // Compute address and memory type.
7910 int offset = field->offset_in_bytes();
7911 bool is_vol = field->is_volatile();
7912 ciType* field_klass = field->type();
7913 assert(field_klass->is_loaded(), "should be loaded");
7914 const TypePtr* adr_type = C->alias_type(field)->adr_type();
7915 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7916 assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7917 "slice of address and input slice don't match");
7918 BasicType bt = field->layout_type();
7919
7920 // Build the resultant type of the load
7921 const Type *type;
7922 if (bt == T_OBJECT) {
7923 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7924 } else {
7925 type = Type::get_const_basic_type(bt);
7926 }
7927
7928 if (is_vol) {
7929 decorators |= MO_SEQ_CST;
7930 }
7931
7932 return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7933 }
7934
7935 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7936 bool is_exact /* true */, bool is_static /* false */,
7937 ciInstanceKlass * fromKls /* nullptr */) {
7938 if (fromKls == nullptr) {
7939 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7940 assert(tinst != nullptr, "obj is null");
7941 assert(tinst->is_loaded(), "obj is not loaded");
7942 assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7943 fromKls = tinst->instance_klass();
7944 }
7945 else {
7946 assert(is_static, "only for static field access");
7947 }
7948 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7949 ciSymbol::make(fieldTypeString),
7950 is_static);
7951
7952 assert(field != nullptr, "undefined field");
7953 assert(!field->is_volatile(), "not defined for volatile fields");
7954
7955 if (is_static) {
7956 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7957 fromObj = makecon(tip);
7958 }
7959
7960 // Next code copied from Parse::do_get_xxx():
7961
7962 // Compute address and memory type.
7963 int offset = field->offset_in_bytes();
7964 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7965
7966 return adr;
7967 }
7968
7969 //------------------------------inline_aescrypt_Block-----------------------
7970 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7971 address stubAddr = nullptr;
7972 const char *stubName;
7973 bool is_decrypt = false;
7974 assert(UseAES, "need AES instruction support");
7975
7976 switch(id) {
7977 case vmIntrinsics::_aescrypt_encryptBlock:
7978 stubAddr = StubRoutines::aescrypt_encryptBlock();
7979 stubName = "aescrypt_encryptBlock";
7980 break;
7981 case vmIntrinsics::_aescrypt_decryptBlock:
7982 stubAddr = StubRoutines::aescrypt_decryptBlock();
7983 stubName = "aescrypt_decryptBlock";
7984 is_decrypt = true;
7985 break;
7986 default:
7987 break;
7988 }
7989 if (stubAddr == nullptr) return false;
7990
7991 Node* aescrypt_object = argument(0);
7992 Node* src = argument(1);
7993 Node* src_offset = argument(2);
7994 Node* dest = argument(3);
7995 Node* dest_offset = argument(4);
7996
7997 src = must_be_not_null(src, true);
7998 dest = must_be_not_null(dest, true);
7999
8000 // (1) src and dest are arrays.
8001 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8002 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8003 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8004 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8005
8006 // for the quick and dirty code we will skip all the checks.
8007 // we are just trying to get the call to be generated.
8008 Node* src_start = src;
8009 Node* dest_start = dest;
8010 if (src_offset != nullptr || dest_offset != nullptr) {
8011 assert(src_offset != nullptr && dest_offset != nullptr, "");
8012 src_start = array_element_address(src, src_offset, T_BYTE);
8013 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8014 }
8015
8016 // now need to get the start of its expanded key array
8017 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8018 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8019 if (k_start == nullptr) return false;
8020
8021 // Call the stub.
8022 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
8023 stubAddr, stubName, TypePtr::BOTTOM,
8024 src_start, dest_start, k_start);
8025
8026 return true;
8027 }
8028
8029 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
8030 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
8031 address stubAddr = nullptr;
8032 const char *stubName = nullptr;
8033 bool is_decrypt = false;
8034 assert(UseAES, "need AES instruction support");
8035
8036 switch(id) {
8037 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
8038 stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
8039 stubName = "cipherBlockChaining_encryptAESCrypt";
8040 break;
8041 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
8042 stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
8043 stubName = "cipherBlockChaining_decryptAESCrypt";
8044 is_decrypt = true;
8045 break;
8046 default:
8047 break;
8048 }
8049 if (stubAddr == nullptr) return false;
8050
8051 Node* cipherBlockChaining_object = argument(0);
8052 Node* src = argument(1);
8053 Node* src_offset = argument(2);
8054 Node* len = argument(3);
8055 Node* dest = argument(4);
8056 Node* dest_offset = argument(5);
8057
8058 src = must_be_not_null(src, false);
8059 dest = must_be_not_null(dest, false);
8060
8061 // (1) src and dest are arrays.
8062 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8063 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8064 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8065 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8066
8067 // checks are the responsibility of the caller
8068 Node* src_start = src;
8069 Node* dest_start = dest;
8070 if (src_offset != nullptr || dest_offset != nullptr) {
8071 assert(src_offset != nullptr && dest_offset != nullptr, "");
8072 src_start = array_element_address(src, src_offset, T_BYTE);
8073 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8074 }
8075
8076 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8077 // (because of the predicated logic executed earlier).
8078 // so we cast it here safely.
8079 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8080
8081 Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8082 if (embeddedCipherObj == nullptr) return false;
8083
8084 // cast it to what we know it will be at runtime
8085 const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
8086 assert(tinst != nullptr, "CBC obj is null");
8087 assert(tinst->is_loaded(), "CBC obj is not loaded");
8088 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8089 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8090
8091 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8092 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8093 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8094 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8095 aescrypt_object = _gvn.transform(aescrypt_object);
8096
8097 // we need to get the start of the aescrypt_object's expanded key array
8098 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8099 if (k_start == nullptr) return false;
8100
8101 // similarly, get the start address of the r vector
8102 Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
8103 if (objRvec == nullptr) return false;
8104 Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
8105
8106 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8107 Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8108 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
8109 stubAddr, stubName, TypePtr::BOTTOM,
8110 src_start, dest_start, k_start, r_start, len);
8111
8112 // return cipher length (int)
8113 Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
8114 set_result(retvalue);
8115 return true;
8116 }
8117
8118 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
8119 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
8120 address stubAddr = nullptr;
8121 const char *stubName = nullptr;
8122 bool is_decrypt = false;
8123 assert(UseAES, "need AES instruction support");
8124
8125 switch (id) {
8126 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
8127 stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
8128 stubName = "electronicCodeBook_encryptAESCrypt";
8129 break;
8130 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
8131 stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
8132 stubName = "electronicCodeBook_decryptAESCrypt";
8133 is_decrypt = true;
8134 break;
8135 default:
8136 break;
8137 }
8138
8139 if (stubAddr == nullptr) return false;
8140
8141 Node* electronicCodeBook_object = argument(0);
8142 Node* src = argument(1);
8143 Node* src_offset = argument(2);
8144 Node* len = argument(3);
8145 Node* dest = argument(4);
8146 Node* dest_offset = argument(5);
8147
8148 // (1) src and dest are arrays.
8149 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8150 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8151 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8152 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8153
8154 // checks are the responsibility of the caller
8155 Node* src_start = src;
8156 Node* dest_start = dest;
8157 if (src_offset != nullptr || dest_offset != nullptr) {
8158 assert(src_offset != nullptr && dest_offset != nullptr, "");
8159 src_start = array_element_address(src, src_offset, T_BYTE);
8160 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8161 }
8162
8163 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8164 // (because of the predicated logic executed earlier).
8165 // so we cast it here safely.
8166 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8167
8168 Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8169 if (embeddedCipherObj == nullptr) return false;
8170
8171 // cast it to what we know it will be at runtime
8172 const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
8173 assert(tinst != nullptr, "ECB obj is null");
8174 assert(tinst->is_loaded(), "ECB obj is not loaded");
8175 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8176 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8177
8178 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8179 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8180 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8181 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8182 aescrypt_object = _gvn.transform(aescrypt_object);
8183
8184 // we need to get the start of the aescrypt_object's expanded key array
8185 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
8186 if (k_start == nullptr) return false;
8187
8188 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8189 Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
8190 OptoRuntime::electronicCodeBook_aescrypt_Type(),
8191 stubAddr, stubName, TypePtr::BOTTOM,
8192 src_start, dest_start, k_start, len);
8193
8194 // return cipher length (int)
8195 Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
8196 set_result(retvalue);
8197 return true;
8198 }
8199
8200 //------------------------------inline_counterMode_AESCrypt-----------------------
8201 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
8202 assert(UseAES, "need AES instruction support");
8203 if (!UseAESCTRIntrinsics) return false;
8204
8205 address stubAddr = nullptr;
8206 const char *stubName = nullptr;
8207 if (id == vmIntrinsics::_counterMode_AESCrypt) {
8208 stubAddr = StubRoutines::counterMode_AESCrypt();
8209 stubName = "counterMode_AESCrypt";
8210 }
8211 if (stubAddr == nullptr) return false;
8212
8213 Node* counterMode_object = argument(0);
8214 Node* src = argument(1);
8215 Node* src_offset = argument(2);
8216 Node* len = argument(3);
8217 Node* dest = argument(4);
8218 Node* dest_offset = argument(5);
8219
8220 // (1) src and dest are arrays.
8221 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8222 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
8223 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
8224 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
8225
8226 // checks are the responsibility of the caller
8227 Node* src_start = src;
8228 Node* dest_start = dest;
8229 if (src_offset != nullptr || dest_offset != nullptr) {
8230 assert(src_offset != nullptr && dest_offset != nullptr, "");
8231 src_start = array_element_address(src, src_offset, T_BYTE);
8232 dest_start = array_element_address(dest, dest_offset, T_BYTE);
8233 }
8234
8235 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8236 // (because of the predicated logic executed earlier).
8237 // so we cast it here safely.
8238 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8239 Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8240 if (embeddedCipherObj == nullptr) return false;
8241 // cast it to what we know it will be at runtime
8242 const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
8243 assert(tinst != nullptr, "CTR obj is null");
8244 assert(tinst->is_loaded(), "CTR obj is not loaded");
8245 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8246 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8247 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8248 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8249 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8250 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8251 aescrypt_object = _gvn.transform(aescrypt_object);
8252 // we need to get the start of the aescrypt_object's expanded key array
8253 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8254 if (k_start == nullptr) return false;
8255 // similarly, get the start address of the r vector
8256 Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
8257 if (obj_counter == nullptr) return false;
8258 Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
8259
8260 Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
8261 if (saved_encCounter == nullptr) return false;
8262 Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
8263 Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
8264
8265 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
8266 Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8267 OptoRuntime::counterMode_aescrypt_Type(),
8268 stubAddr, stubName, TypePtr::BOTTOM,
8269 src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
8270
8271 // return cipher length (int)
8272 Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
8273 set_result(retvalue);
8274 return true;
8275 }
8276
8277 //------------------------------get_key_start_from_aescrypt_object-----------------------
8278 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
8279 // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
8280 // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
8281 // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
8282 // The following platform specific stubs of encryption and decryption use the same round keys.
8283 #if defined(PPC64) || defined(S390) || defined(RISCV64)
8284 bool use_decryption_key = false;
8285 #else
8286 bool use_decryption_key = is_decrypt;
8287 #endif
8288 Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
8289 assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
8290 if (objAESCryptKey == nullptr) return (Node *) nullptr;
8291
8292 // now have the array, need to get the start address of the selected key array
8293 Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
8294 return k_start;
8295 }
8296
8297 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
8298 // Return node representing slow path of predicate check.
8299 // the pseudo code we want to emulate with this predicate is:
8300 // for encryption:
8301 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8302 // for decryption:
8303 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8304 // note cipher==plain is more conservative than the original java code but that's OK
8305 //
8306 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
8307 // The receiver was checked for null already.
8308 Node* objCBC = argument(0);
8309
8310 Node* src = argument(1);
8311 Node* dest = argument(4);
8312
8313 // Load embeddedCipher field of CipherBlockChaining object.
8314 Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8315
8316 // get AESCrypt klass for instanceOf check
8317 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8318 // will have same classloader as CipherBlockChaining object
8319 const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
8320 assert(tinst != nullptr, "CBCobj is null");
8321 assert(tinst->is_loaded(), "CBCobj is not loaded");
8322
8323 // we want to do an instanceof comparison against the AESCrypt class
8324 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8325 if (!klass_AESCrypt->is_loaded()) {
8326 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8327 Node* ctrl = control();
8328 set_control(top()); // no regular fast path
8329 return ctrl;
8330 }
8331
8332 src = must_be_not_null(src, true);
8333 dest = must_be_not_null(dest, true);
8334
8335 // Resolve oops to stable for CmpP below.
8336 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8337
8338 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8339 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8340 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8341
8342 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8343
8344 // for encryption, we are done
8345 if (!decrypting)
8346 return instof_false; // even if it is null
8347
8348 // for decryption, we need to add a further check to avoid
8349 // taking the intrinsic path when cipher and plain are the same
8350 // see the original java code for why.
8351 RegionNode* region = new RegionNode(3);
8352 region->init_req(1, instof_false);
8353
8354 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8355 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8356 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8357 region->init_req(2, src_dest_conjoint);
8358
8359 record_for_igvn(region);
8360 return _gvn.transform(region);
8361 }
8362
8363 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
8364 // Return node representing slow path of predicate check.
8365 // the pseudo code we want to emulate with this predicate is:
8366 // for encryption:
8367 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8368 // for decryption:
8369 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8370 // note cipher==plain is more conservative than the original java code but that's OK
8371 //
8372 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
8373 // The receiver was checked for null already.
8374 Node* objECB = argument(0);
8375
8376 // Load embeddedCipher field of ElectronicCodeBook object.
8377 Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8378
8379 // get AESCrypt klass for instanceOf check
8380 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8381 // will have same classloader as ElectronicCodeBook object
8382 const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
8383 assert(tinst != nullptr, "ECBobj is null");
8384 assert(tinst->is_loaded(), "ECBobj is not loaded");
8385
8386 // we want to do an instanceof comparison against the AESCrypt class
8387 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8388 if (!klass_AESCrypt->is_loaded()) {
8389 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8390 Node* ctrl = control();
8391 set_control(top()); // no regular fast path
8392 return ctrl;
8393 }
8394 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8395
8396 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8397 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8398 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8399
8400 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8401
8402 // for encryption, we are done
8403 if (!decrypting)
8404 return instof_false; // even if it is null
8405
8406 // for decryption, we need to add a further check to avoid
8407 // taking the intrinsic path when cipher and plain are the same
8408 // see the original java code for why.
8409 RegionNode* region = new RegionNode(3);
8410 region->init_req(1, instof_false);
8411 Node* src = argument(1);
8412 Node* dest = argument(4);
8413 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
8414 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
8415 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
8416 region->init_req(2, src_dest_conjoint);
8417
8418 record_for_igvn(region);
8419 return _gvn.transform(region);
8420 }
8421
8422 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
8423 // Return node representing slow path of predicate check.
8424 // the pseudo code we want to emulate with this predicate is:
8425 // for encryption:
8426 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8427 // for decryption:
8428 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8429 // note cipher==plain is more conservative than the original java code but that's OK
8430 //
8431
8432 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
8433 // The receiver was checked for null already.
8434 Node* objCTR = argument(0);
8435
8436 // Load embeddedCipher field of CipherBlockChaining object.
8437 Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8438
8439 // get AESCrypt klass for instanceOf check
8440 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8441 // will have same classloader as CipherBlockChaining object
8442 const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
8443 assert(tinst != nullptr, "CTRobj is null");
8444 assert(tinst->is_loaded(), "CTRobj is not loaded");
8445
8446 // we want to do an instanceof comparison against the AESCrypt class
8447 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8448 if (!klass_AESCrypt->is_loaded()) {
8449 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8450 Node* ctrl = control();
8451 set_control(top()); // no regular fast path
8452 return ctrl;
8453 }
8454
8455 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8456 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8457 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8458 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8459 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8460
8461 return instof_false; // even if it is null
8462 }
8463
8464 //------------------------------inline_ghash_processBlocks
8465 bool LibraryCallKit::inline_ghash_processBlocks() {
8466 address stubAddr;
8467 const char *stubName;
8468 assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
8469
8470 stubAddr = StubRoutines::ghash_processBlocks();
8471 stubName = "ghash_processBlocks";
8472
8473 Node* data = argument(0);
8474 Node* offset = argument(1);
8475 Node* len = argument(2);
8476 Node* state = argument(3);
8477 Node* subkeyH = argument(4);
8478
8479 state = must_be_not_null(state, true);
8480 subkeyH = must_be_not_null(subkeyH, true);
8481 data = must_be_not_null(data, true);
8482
8483 Node* state_start = array_element_address(state, intcon(0), T_LONG);
8484 assert(state_start, "state is null");
8485 Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);
8486 assert(subkeyH_start, "subkeyH is null");
8487 Node* data_start = array_element_address(data, offset, T_BYTE);
8488 assert(data_start, "data is null");
8489
8490 Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
8491 OptoRuntime::ghash_processBlocks_Type(),
8492 stubAddr, stubName, TypePtr::BOTTOM,
8493 state_start, subkeyH_start, data_start, len);
8494 return true;
8495 }
8496
8497 //------------------------------inline_chacha20Block
8498 bool LibraryCallKit::inline_chacha20Block() {
8499 address stubAddr;
8500 const char *stubName;
8501 assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
8502
8503 stubAddr = StubRoutines::chacha20Block();
8504 stubName = "chacha20Block";
8505
8506 Node* state = argument(0);
8507 Node* result = argument(1);
8508
8509 state = must_be_not_null(state, true);
8510 result = must_be_not_null(result, true);
8511
8512 Node* state_start = array_element_address(state, intcon(0), T_INT);
8513 assert(state_start, "state is null");
8514 Node* result_start = array_element_address(result, intcon(0), T_BYTE);
8515 assert(result_start, "result is null");
8516
8517 Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
8518 OptoRuntime::chacha20Block_Type(),
8519 stubAddr, stubName, TypePtr::BOTTOM,
8520 state_start, result_start);
8521 // return key stream length (int)
8522 Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
8523 set_result(retvalue);
8524 return true;
8525 }
8526
8527 //------------------------------inline_kyberNtt
8528 bool LibraryCallKit::inline_kyberNtt() {
8529 address stubAddr;
8530 const char *stubName;
8531 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8532 assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
8533
8534 stubAddr = StubRoutines::kyberNtt();
8535 stubName = "kyberNtt";
8536 if (!stubAddr) return false;
8537
8538 Node* coeffs = argument(0);
8539 Node* ntt_zetas = argument(1);
8540
8541 coeffs = must_be_not_null(coeffs, true);
8542 ntt_zetas = must_be_not_null(ntt_zetas, true);
8543
8544 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8545 assert(coeffs_start, "coeffs is null");
8546 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_SHORT);
8547 assert(ntt_zetas_start, "ntt_zetas is null");
8548 Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8549 OptoRuntime::kyberNtt_Type(),
8550 stubAddr, stubName, TypePtr::BOTTOM,
8551 coeffs_start, ntt_zetas_start);
8552 // return an int
8553 Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
8554 set_result(retvalue);
8555 return true;
8556 }
8557
8558 //------------------------------inline_kyberInverseNtt
8559 bool LibraryCallKit::inline_kyberInverseNtt() {
8560 address stubAddr;
8561 const char *stubName;
8562 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8563 assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
8564
8565 stubAddr = StubRoutines::kyberInverseNtt();
8566 stubName = "kyberInverseNtt";
8567 if (!stubAddr) return false;
8568
8569 Node* coeffs = argument(0);
8570 Node* zetas = argument(1);
8571
8572 coeffs = must_be_not_null(coeffs, true);
8573 zetas = must_be_not_null(zetas, true);
8574
8575 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8576 assert(coeffs_start, "coeffs is null");
8577 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
8578 assert(zetas_start, "inverseNtt_zetas is null");
8579 Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8580 OptoRuntime::kyberInverseNtt_Type(),
8581 stubAddr, stubName, TypePtr::BOTTOM,
8582 coeffs_start, zetas_start);
8583
8584 // return an int
8585 Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
8586 set_result(retvalue);
8587 return true;
8588 }
8589
8590 //------------------------------inline_kyberNttMult
8591 bool LibraryCallKit::inline_kyberNttMult() {
8592 address stubAddr;
8593 const char *stubName;
8594 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8595 assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
8596
8597 stubAddr = StubRoutines::kyberNttMult();
8598 stubName = "kyberNttMult";
8599 if (!stubAddr) return false;
8600
8601 Node* result = argument(0);
8602 Node* ntta = argument(1);
8603 Node* nttb = argument(2);
8604 Node* zetas = argument(3);
8605
8606 result = must_be_not_null(result, true);
8607 ntta = must_be_not_null(ntta, true);
8608 nttb = must_be_not_null(nttb, true);
8609 zetas = must_be_not_null(zetas, true);
8610
8611 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8612 assert(result_start, "result is null");
8613 Node* ntta_start = array_element_address(ntta, intcon(0), T_SHORT);
8614 assert(ntta_start, "ntta is null");
8615 Node* nttb_start = array_element_address(nttb, intcon(0), T_SHORT);
8616 assert(nttb_start, "nttb is null");
8617 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
8618 assert(zetas_start, "nttMult_zetas is null");
8619 Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8620 OptoRuntime::kyberNttMult_Type(),
8621 stubAddr, stubName, TypePtr::BOTTOM,
8622 result_start, ntta_start, nttb_start,
8623 zetas_start);
8624
8625 // return an int
8626 Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
8627 set_result(retvalue);
8628
8629 return true;
8630 }
8631
8632 //------------------------------inline_kyberAddPoly_2
8633 bool LibraryCallKit::inline_kyberAddPoly_2() {
8634 address stubAddr;
8635 const char *stubName;
8636 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8637 assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
8638
8639 stubAddr = StubRoutines::kyberAddPoly_2();
8640 stubName = "kyberAddPoly_2";
8641 if (!stubAddr) return false;
8642
8643 Node* result = argument(0);
8644 Node* a = argument(1);
8645 Node* b = argument(2);
8646
8647 result = must_be_not_null(result, true);
8648 a = must_be_not_null(a, true);
8649 b = must_be_not_null(b, true);
8650
8651 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8652 assert(result_start, "result is null");
8653 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
8654 assert(a_start, "a is null");
8655 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
8656 assert(b_start, "b is null");
8657 Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
8658 OptoRuntime::kyberAddPoly_2_Type(),
8659 stubAddr, stubName, TypePtr::BOTTOM,
8660 result_start, a_start, b_start);
8661 // return an int
8662 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
8663 set_result(retvalue);
8664 return true;
8665 }
8666
8667 //------------------------------inline_kyberAddPoly_3
8668 bool LibraryCallKit::inline_kyberAddPoly_3() {
8669 address stubAddr;
8670 const char *stubName;
8671 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8672 assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
8673
8674 stubAddr = StubRoutines::kyberAddPoly_3();
8675 stubName = "kyberAddPoly_3";
8676 if (!stubAddr) return false;
8677
8678 Node* result = argument(0);
8679 Node* a = argument(1);
8680 Node* b = argument(2);
8681 Node* c = argument(3);
8682
8683 result = must_be_not_null(result, true);
8684 a = must_be_not_null(a, true);
8685 b = must_be_not_null(b, true);
8686 c = must_be_not_null(c, true);
8687
8688 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
8689 assert(result_start, "result is null");
8690 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
8691 assert(a_start, "a is null");
8692 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
8693 assert(b_start, "b is null");
8694 Node* c_start = array_element_address(c, intcon(0), T_SHORT);
8695 assert(c_start, "c is null");
8696 Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
8697 OptoRuntime::kyberAddPoly_3_Type(),
8698 stubAddr, stubName, TypePtr::BOTTOM,
8699 result_start, a_start, b_start, c_start);
8700 // return an int
8701 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
8702 set_result(retvalue);
8703 return true;
8704 }
8705
8706 //------------------------------inline_kyber12To16
8707 bool LibraryCallKit::inline_kyber12To16() {
8708 address stubAddr;
8709 const char *stubName;
8710 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8711 assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
8712
8713 stubAddr = StubRoutines::kyber12To16();
8714 stubName = "kyber12To16";
8715 if (!stubAddr) return false;
8716
8717 Node* condensed = argument(0);
8718 Node* condensedOffs = argument(1);
8719 Node* parsed = argument(2);
8720 Node* parsedLength = argument(3);
8721
8722 condensed = must_be_not_null(condensed, true);
8723 parsed = must_be_not_null(parsed, true);
8724
8725 Node* condensed_start = array_element_address(condensed, intcon(0), T_BYTE);
8726 assert(condensed_start, "condensed is null");
8727 Node* parsed_start = array_element_address(parsed, intcon(0), T_SHORT);
8728 assert(parsed_start, "parsed is null");
8729 Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8730 OptoRuntime::kyber12To16_Type(),
8731 stubAddr, stubName, TypePtr::BOTTOM,
8732 condensed_start, condensedOffs, parsed_start, parsedLength);
8733 // return an int
8734 Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8735 set_result(retvalue);
8736 return true;
8737
8738 }
8739
8740 //------------------------------inline_kyberBarrettReduce
8741 bool LibraryCallKit::inline_kyberBarrettReduce() {
8742 address stubAddr;
8743 const char *stubName;
8744 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8745 assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8746
8747 stubAddr = StubRoutines::kyberBarrettReduce();
8748 stubName = "kyberBarrettReduce";
8749 if (!stubAddr) return false;
8750
8751 Node* coeffs = argument(0);
8752
8753 coeffs = must_be_not_null(coeffs, true);
8754
8755 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8756 assert(coeffs_start, "coeffs is null");
8757 Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8758 OptoRuntime::kyberBarrettReduce_Type(),
8759 stubAddr, stubName, TypePtr::BOTTOM,
8760 coeffs_start);
8761 // return an int
8762 Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8763 set_result(retvalue);
8764 return true;
8765 }
8766
8767 //------------------------------inline_dilithiumAlmostNtt
8768 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8769 address stubAddr;
8770 const char *stubName;
8771 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8772 assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8773
8774 stubAddr = StubRoutines::dilithiumAlmostNtt();
8775 stubName = "dilithiumAlmostNtt";
8776 if (!stubAddr) return false;
8777
8778 Node* coeffs = argument(0);
8779 Node* ntt_zetas = argument(1);
8780
8781 coeffs = must_be_not_null(coeffs, true);
8782 ntt_zetas = must_be_not_null(ntt_zetas, true);
8783
8784 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8785 assert(coeffs_start, "coeffs is null");
8786 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_INT);
8787 assert(ntt_zetas_start, "ntt_zetas is null");
8788 Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8789 OptoRuntime::dilithiumAlmostNtt_Type(),
8790 stubAddr, stubName, TypePtr::BOTTOM,
8791 coeffs_start, ntt_zetas_start);
8792 // return an int
8793 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8794 set_result(retvalue);
8795 return true;
8796 }
8797
8798 //------------------------------inline_dilithiumAlmostInverseNtt
8799 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8800 address stubAddr;
8801 const char *stubName;
8802 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8803 assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8804
8805 stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8806 stubName = "dilithiumAlmostInverseNtt";
8807 if (!stubAddr) return false;
8808
8809 Node* coeffs = argument(0);
8810 Node* zetas = argument(1);
8811
8812 coeffs = must_be_not_null(coeffs, true);
8813 zetas = must_be_not_null(zetas, true);
8814
8815 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8816 assert(coeffs_start, "coeffs is null");
8817 Node* zetas_start = array_element_address(zetas, intcon(0), T_INT);
8818 assert(zetas_start, "inverseNtt_zetas is null");
8819 Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8820 OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8821 stubAddr, stubName, TypePtr::BOTTOM,
8822 coeffs_start, zetas_start);
8823 // return an int
8824 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8825 set_result(retvalue);
8826 return true;
8827 }
8828
8829 //------------------------------inline_dilithiumNttMult
8830 bool LibraryCallKit::inline_dilithiumNttMult() {
8831 address stubAddr;
8832 const char *stubName;
8833 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8834 assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8835
8836 stubAddr = StubRoutines::dilithiumNttMult();
8837 stubName = "dilithiumNttMult";
8838 if (!stubAddr) return false;
8839
8840 Node* result = argument(0);
8841 Node* ntta = argument(1);
8842 Node* nttb = argument(2);
8843 Node* zetas = argument(3);
8844
8845 result = must_be_not_null(result, true);
8846 ntta = must_be_not_null(ntta, true);
8847 nttb = must_be_not_null(nttb, true);
8848 zetas = must_be_not_null(zetas, true);
8849
8850 Node* result_start = array_element_address(result, intcon(0), T_INT);
8851 assert(result_start, "result is null");
8852 Node* ntta_start = array_element_address(ntta, intcon(0), T_INT);
8853 assert(ntta_start, "ntta is null");
8854 Node* nttb_start = array_element_address(nttb, intcon(0), T_INT);
8855 assert(nttb_start, "nttb is null");
8856 Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8857 OptoRuntime::dilithiumNttMult_Type(),
8858 stubAddr, stubName, TypePtr::BOTTOM,
8859 result_start, ntta_start, nttb_start);
8860
8861 // return an int
8862 Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8863 set_result(retvalue);
8864
8865 return true;
8866 }
8867
8868 //------------------------------inline_dilithiumMontMulByConstant
8869 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8870 address stubAddr;
8871 const char *stubName;
8872 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8873 assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8874
8875 stubAddr = StubRoutines::dilithiumMontMulByConstant();
8876 stubName = "dilithiumMontMulByConstant";
8877 if (!stubAddr) return false;
8878
8879 Node* coeffs = argument(0);
8880 Node* constant = argument(1);
8881
8882 coeffs = must_be_not_null(coeffs, true);
8883
8884 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8885 assert(coeffs_start, "coeffs is null");
8886 Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8887 OptoRuntime::dilithiumMontMulByConstant_Type(),
8888 stubAddr, stubName, TypePtr::BOTTOM,
8889 coeffs_start, constant);
8890
8891 // return an int
8892 Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8893 set_result(retvalue);
8894 return true;
8895 }
8896
8897
8898 //------------------------------inline_dilithiumDecomposePoly
8899 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8900 address stubAddr;
8901 const char *stubName;
8902 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8903 assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8904
8905 stubAddr = StubRoutines::dilithiumDecomposePoly();
8906 stubName = "dilithiumDecomposePoly";
8907 if (!stubAddr) return false;
8908
8909 Node* input = argument(0);
8910 Node* lowPart = argument(1);
8911 Node* highPart = argument(2);
8912 Node* twoGamma2 = argument(3);
8913 Node* multiplier = argument(4);
8914
8915 input = must_be_not_null(input, true);
8916 lowPart = must_be_not_null(lowPart, true);
8917 highPart = must_be_not_null(highPart, true);
8918
8919 Node* input_start = array_element_address(input, intcon(0), T_INT);
8920 assert(input_start, "input is null");
8921 Node* lowPart_start = array_element_address(lowPart, intcon(0), T_INT);
8922 assert(lowPart_start, "lowPart is null");
8923 Node* highPart_start = array_element_address(highPart, intcon(0), T_INT);
8924 assert(highPart_start, "highPart is null");
8925
8926 Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8927 OptoRuntime::dilithiumDecomposePoly_Type(),
8928 stubAddr, stubName, TypePtr::BOTTOM,
8929 input_start, lowPart_start, highPart_start,
8930 twoGamma2, multiplier);
8931
8932 // return an int
8933 Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8934 set_result(retvalue);
8935 return true;
8936 }
8937
8938 bool LibraryCallKit::inline_base64_encodeBlock() {
8939 address stubAddr;
8940 const char *stubName;
8941 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8942 assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8943 stubAddr = StubRoutines::base64_encodeBlock();
8944 stubName = "encodeBlock";
8945
8946 if (!stubAddr) return false;
8947 Node* base64obj = argument(0);
8948 Node* src = argument(1);
8949 Node* offset = argument(2);
8950 Node* len = argument(3);
8951 Node* dest = argument(4);
8952 Node* dp = argument(5);
8953 Node* isURL = argument(6);
8954
8955 src = must_be_not_null(src, true);
8956 dest = must_be_not_null(dest, true);
8957
8958 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8959 assert(src_start, "source array is null");
8960 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8961 assert(dest_start, "destination array is null");
8962
8963 Node* base64 = make_runtime_call(RC_LEAF,
8964 OptoRuntime::base64_encodeBlock_Type(),
8965 stubAddr, stubName, TypePtr::BOTTOM,
8966 src_start, offset, len, dest_start, dp, isURL);
8967 return true;
8968 }
8969
8970 bool LibraryCallKit::inline_base64_decodeBlock() {
8971 address stubAddr;
8972 const char *stubName;
8973 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8974 assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8975 stubAddr = StubRoutines::base64_decodeBlock();
8976 stubName = "decodeBlock";
8977
8978 if (!stubAddr) return false;
8979 Node* base64obj = argument(0);
8980 Node* src = argument(1);
8981 Node* src_offset = argument(2);
8982 Node* len = argument(3);
8983 Node* dest = argument(4);
8984 Node* dest_offset = argument(5);
8985 Node* isURL = argument(6);
8986 Node* isMIME = argument(7);
8987
8988 src = must_be_not_null(src, true);
8989 dest = must_be_not_null(dest, true);
8990
8991 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8992 assert(src_start, "source array is null");
8993 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8994 assert(dest_start, "destination array is null");
8995
8996 Node* call = make_runtime_call(RC_LEAF,
8997 OptoRuntime::base64_decodeBlock_Type(),
8998 stubAddr, stubName, TypePtr::BOTTOM,
8999 src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
9000 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9001 set_result(result);
9002 return true;
9003 }
9004
9005 bool LibraryCallKit::inline_poly1305_processBlocks() {
9006 address stubAddr;
9007 const char *stubName;
9008 assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
9009 assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
9010 stubAddr = StubRoutines::poly1305_processBlocks();
9011 stubName = "poly1305_processBlocks";
9012
9013 if (!stubAddr) return false;
9014 null_check_receiver(); // null-check receiver
9015 if (stopped()) return true;
9016
9017 Node* input = argument(1);
9018 Node* input_offset = argument(2);
9019 Node* len = argument(3);
9020 Node* alimbs = argument(4);
9021 Node* rlimbs = argument(5);
9022
9023 input = must_be_not_null(input, true);
9024 alimbs = must_be_not_null(alimbs, true);
9025 rlimbs = must_be_not_null(rlimbs, true);
9026
9027 Node* input_start = array_element_address(input, input_offset, T_BYTE);
9028 assert(input_start, "input array is null");
9029 Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
9030 assert(acc_start, "acc array is null");
9031 Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
9032 assert(r_start, "r array is null");
9033
9034 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9035 OptoRuntime::poly1305_processBlocks_Type(),
9036 stubAddr, stubName, TypePtr::BOTTOM,
9037 input_start, len, acc_start, r_start);
9038 return true;
9039 }
9040
9041 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
9042 address stubAddr;
9043 const char *stubName;
9044 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9045 assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
9046 stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
9047 stubName = "intpoly_montgomeryMult_P256";
9048
9049 if (!stubAddr) return false;
9050 null_check_receiver(); // null-check receiver
9051 if (stopped()) return true;
9052
9053 Node* a = argument(1);
9054 Node* b = argument(2);
9055 Node* r = argument(3);
9056
9057 a = must_be_not_null(a, true);
9058 b = must_be_not_null(b, true);
9059 r = must_be_not_null(r, true);
9060
9061 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9062 assert(a_start, "a array is null");
9063 Node* b_start = array_element_address(b, intcon(0), T_LONG);
9064 assert(b_start, "b array is null");
9065 Node* r_start = array_element_address(r, intcon(0), T_LONG);
9066 assert(r_start, "r array is null");
9067
9068 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9069 OptoRuntime::intpoly_montgomeryMult_P256_Type(),
9070 stubAddr, stubName, TypePtr::BOTTOM,
9071 a_start, b_start, r_start);
9072 return true;
9073 }
9074
9075 bool LibraryCallKit::inline_intpoly_assign() {
9076 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
9077 assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
9078 const char *stubName = "intpoly_assign";
9079 address stubAddr = StubRoutines::intpoly_assign();
9080 if (!stubAddr) return false;
9081
9082 Node* set = argument(0);
9083 Node* a = argument(1);
9084 Node* b = argument(2);
9085 Node* arr_length = load_array_length(a);
9086
9087 a = must_be_not_null(a, true);
9088 b = must_be_not_null(b, true);
9089
9090 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9091 assert(a_start, "a array is null");
9092 Node* b_start = array_element_address(b, intcon(0), T_LONG);
9093 assert(b_start, "b array is null");
9094
9095 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9096 OptoRuntime::intpoly_assign_Type(),
9097 stubAddr, stubName, TypePtr::BOTTOM,
9098 set, a_start, b_start, arr_length);
9099 return true;
9100 }
9101
9102 bool LibraryCallKit::inline_intpoly_mult_25519() {
9103 address stubAddr;
9104 const char *stubName;
9105 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
9106 assert(callee()->signature()->size() == 3, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
9107 stubAddr = StubRoutines::intpoly_mult_25519();
9108 stubName = "intpoly_mult_25519";
9109
9110 if (!stubAddr) return false;
9111 null_check_receiver(); // null-check receiver
9112 if (stopped()) return true;
9113
9114 Node* a = argument(1);
9115 Node* b = argument(2);
9116 Node* r = argument(3);
9117
9118 a = must_be_not_null(a, true);
9119 b = must_be_not_null(b, true);
9120 r = must_be_not_null(r, true);
9121
9122 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9123 assert(a_start, "a array is null");
9124 Node* b_start = array_element_address(b, intcon(0), T_LONG);
9125 assert(b_start, "b array is null");
9126 Node* r_start = array_element_address(r, intcon(0), T_LONG);
9127 assert(r_start, "r array is null");
9128
9129 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9130 OptoRuntime::intpoly_mult_25519_Type(),
9131 stubAddr, stubName, TypePtr::BOTTOM,
9132 a_start, b_start, r_start);
9133 return true;
9134 }
9135
9136 bool LibraryCallKit::inline_intpoly_square_25519() {
9137 address stubAddr;
9138 const char *stubName;
9139 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
9140 assert(callee()->signature()->size() == 2, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
9141 stubAddr = StubRoutines::intpoly_square_25519();
9142 stubName = "intpoly_square_25519";
9143
9144 if (!stubAddr) return false;
9145 null_check_receiver(); // null-check receiver
9146 if (stopped()) return true;
9147
9148 Node* a = argument(1);
9149 Node* r = argument(2);
9150
9151 a = must_be_not_null(a, true);
9152 r = must_be_not_null(r, true);
9153
9154 Node* a_start = array_element_address(a, intcon(0), T_LONG);
9155 assert(a_start, "a array is null");
9156 Node* r_start = array_element_address(r, intcon(0), T_LONG);
9157 assert(r_start, "r array is null");
9158
9159 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
9160 OptoRuntime::intpoly_square_25519_Type(),
9161 stubAddr, stubName, TypePtr::BOTTOM,
9162 a_start, r_start);
9163 return true;
9164 }
9165
9166 //------------------------------inline_digestBase_implCompress-----------------------
9167 //
9168 // Calculate MD5 for single-block byte[] array.
9169 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
9170 //
9171 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
9172 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
9173 //
9174 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
9175 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
9176 //
9177 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
9178 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
9179 //
9180 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
9181 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
9182 //
9183 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
9184 assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
9185
9186 Node* digestBase_obj = argument(0);
9187 Node* src = argument(1); // type oop
9188 Node* ofs = argument(2); // type int
9189
9190 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9191 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9192 // failed array check
9193 return false;
9194 }
9195 // Figure out the size and type of the elements we will be copying.
9196 BasicType src_elem = src_type->elem()->array_element_basic_type();
9197 if (src_elem != T_BYTE) {
9198 return false;
9199 }
9200 // 'src_start' points to src array + offset
9201 src = must_be_not_null(src, true);
9202 Node* src_start = array_element_address(src, ofs, src_elem);
9203 Node* state = nullptr;
9204 Node* block_size = nullptr;
9205 address stubAddr;
9206 const char *stubName;
9207
9208 switch(id) {
9209 case vmIntrinsics::_md5_implCompress:
9210 assert(UseMD5Intrinsics, "need MD5 instruction support");
9211 state = get_state_from_digest_object(digestBase_obj, T_INT);
9212 stubAddr = StubRoutines::md5_implCompress();
9213 stubName = "md5_implCompress";
9214 break;
9215 case vmIntrinsics::_sha_implCompress:
9216 assert(UseSHA1Intrinsics, "need SHA1 instruction support");
9217 state = get_state_from_digest_object(digestBase_obj, T_INT);
9218 stubAddr = StubRoutines::sha1_implCompress();
9219 stubName = "sha1_implCompress";
9220 break;
9221 case vmIntrinsics::_sha2_implCompress:
9222 assert(UseSHA256Intrinsics, "need SHA256 instruction support");
9223 state = get_state_from_digest_object(digestBase_obj, T_INT);
9224 stubAddr = StubRoutines::sha256_implCompress();
9225 stubName = "sha256_implCompress";
9226 break;
9227 case vmIntrinsics::_sha5_implCompress:
9228 assert(UseSHA512Intrinsics, "need SHA512 instruction support");
9229 state = get_state_from_digest_object(digestBase_obj, T_LONG);
9230 stubAddr = StubRoutines::sha512_implCompress();
9231 stubName = "sha512_implCompress";
9232 break;
9233 case vmIntrinsics::_sha3_implCompress:
9234 assert(UseSHA3Intrinsics, "need SHA3 instruction support");
9235 state = get_state_from_digest_object(digestBase_obj, T_LONG);
9236 stubAddr = StubRoutines::sha3_implCompress();
9237 stubName = "sha3_implCompress";
9238 block_size = get_block_size_from_digest_object(digestBase_obj);
9239 if (block_size == nullptr) return false;
9240 break;
9241 default:
9242 fatal_unexpected_iid(id);
9243 return false;
9244 }
9245 if (state == nullptr) return false;
9246
9247 assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
9248 if (stubAddr == nullptr) return false;
9249
9250 // Call the stub.
9251 Node* call;
9252 if (block_size == nullptr) {
9253 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
9254 stubAddr, stubName, TypePtr::BOTTOM,
9255 src_start, state);
9256 } else {
9257 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
9258 stubAddr, stubName, TypePtr::BOTTOM,
9259 src_start, state, block_size);
9260 }
9261
9262 return true;
9263 }
9264
9265 //------------------------------inline_keccak
9266 bool LibraryCallKit::inline_keccak(vmIntrinsics::ID id) {
9267 address stubAddr = nullptr;
9268 const char *stubName;
9269 assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
9270 assert((id == vmIntrinsics::_double_keccak && callee()->signature()->size() == 2) ||
9271 (id == vmIntrinsics::_quad_keccak && callee()->signature()->size() == 4),
9272 "double_keccak wrong number of parameters");
9273
9274 int parmCnt = 0;
9275 switch (id) {
9276 case vmIntrinsics::_double_keccak:
9277 stubAddr = StubRoutines::double_keccak();
9278 stubName = "double_keccak";
9279 parmCnt = 2;
9280 break;
9281 case vmIntrinsics::_quad_keccak:
9282 stubAddr = StubRoutines::quad_keccak();
9283 stubName = "quad_keccak";
9284 parmCnt = 4;
9285 break;
9286 default:
9287 ShouldNotReachHere();
9288 }
9289
9290 if (!stubAddr) return false;
9291
9292 Node* state[4];
9293 for (int i = 0; i<parmCnt; i++) {
9294 state[i] = must_be_not_null(argument(i), true);
9295 state[i] = array_element_address(state[i], intcon(0), T_LONG);
9296 assert(state[i], "state[%d] is null", i);
9297 }
9298
9299 Node* keccak;
9300 switch (id) {
9301 case vmIntrinsics::_double_keccak:
9302 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9303 OptoRuntime::double_keccak_Type(),
9304 stubAddr, stubName, TypePtr::BOTTOM,
9305 state[0], state[1]);
9306 break;
9307 case vmIntrinsics::_quad_keccak:
9308 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
9309 OptoRuntime::quad_keccak_Type(),
9310 stubAddr, stubName, TypePtr::BOTTOM,
9311 state[0], state[1], state[2], state[3]);
9312 break;
9313 default:
9314 ShouldNotReachHere();
9315 }
9316
9317 // return an int
9318 Node* retvalue = _gvn.transform(new ProjNode(keccak, TypeFunc::Parms));
9319 set_result(retvalue);
9320 return true;
9321 }
9322
9323
9324 //------------------------------inline_digestBase_implCompressMB-----------------------
9325 //
9326 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
9327 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
9328 //
9329 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
9330 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9331 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9332 assert((uint)predicate < 5, "sanity");
9333 assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
9334
9335 Node* digestBase_obj = argument(0); // The receiver was checked for null already.
9336 Node* src = argument(1); // byte[] array
9337 Node* ofs = argument(2); // type int
9338 Node* limit = argument(3); // type int
9339
9340 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
9341 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
9342 // failed array check
9343 return false;
9344 }
9345 // Figure out the size and type of the elements we will be copying.
9346 BasicType src_elem = src_type->elem()->array_element_basic_type();
9347 if (src_elem != T_BYTE) {
9348 return false;
9349 }
9350 // 'src_start' points to src array + offset
9351 src = must_be_not_null(src, false);
9352 Node* src_start = array_element_address(src, ofs, src_elem);
9353
9354 const char* klass_digestBase_name = nullptr;
9355 const char* stub_name = nullptr;
9356 address stub_addr = nullptr;
9357 BasicType elem_type = T_INT;
9358
9359 switch (predicate) {
9360 case 0:
9361 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
9362 klass_digestBase_name = "sun/security/provider/MD5";
9363 stub_name = "md5_implCompressMB";
9364 stub_addr = StubRoutines::md5_implCompressMB();
9365 }
9366 break;
9367 case 1:
9368 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
9369 klass_digestBase_name = "sun/security/provider/SHA";
9370 stub_name = "sha1_implCompressMB";
9371 stub_addr = StubRoutines::sha1_implCompressMB();
9372 }
9373 break;
9374 case 2:
9375 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
9376 klass_digestBase_name = "sun/security/provider/SHA2";
9377 stub_name = "sha256_implCompressMB";
9378 stub_addr = StubRoutines::sha256_implCompressMB();
9379 }
9380 break;
9381 case 3:
9382 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
9383 klass_digestBase_name = "sun/security/provider/SHA5";
9384 stub_name = "sha512_implCompressMB";
9385 stub_addr = StubRoutines::sha512_implCompressMB();
9386 elem_type = T_LONG;
9387 }
9388 break;
9389 case 4:
9390 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
9391 klass_digestBase_name = "sun/security/provider/SHA3";
9392 stub_name = "sha3_implCompressMB";
9393 stub_addr = StubRoutines::sha3_implCompressMB();
9394 elem_type = T_LONG;
9395 }
9396 break;
9397 default:
9398 fatal("unknown DigestBase intrinsic predicate: %d", predicate);
9399 }
9400 if (klass_digestBase_name != nullptr) {
9401 assert(stub_addr != nullptr, "Stub is generated");
9402 if (stub_addr == nullptr) return false;
9403
9404 // get DigestBase klass to lookup for SHA klass
9405 const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
9406 assert(tinst != nullptr, "digestBase_obj is not instance???");
9407 assert(tinst->is_loaded(), "DigestBase is not loaded");
9408
9409 ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
9410 assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
9411 ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
9412 return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
9413 }
9414 return false;
9415 }
9416
9417 //------------------------------inline_digestBase_implCompressMB-----------------------
9418 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
9419 BasicType elem_type, address stubAddr, const char *stubName,
9420 Node* src_start, Node* ofs, Node* limit) {
9421 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
9422 const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
9423 Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
9424 digest_obj = _gvn.transform(digest_obj);
9425
9426 Node* state = get_state_from_digest_object(digest_obj, elem_type);
9427 if (state == nullptr) return false;
9428
9429 Node* block_size = nullptr;
9430 if (strcmp("sha3_implCompressMB", stubName) == 0) {
9431 block_size = get_block_size_from_digest_object(digest_obj);
9432 if (block_size == nullptr) return false;
9433 }
9434
9435 // Call the stub.
9436 Node* call;
9437 if (block_size == nullptr) {
9438 call = make_runtime_call(RC_LEAF|RC_NO_FP,
9439 OptoRuntime::digestBase_implCompressMB_Type(false),
9440 stubAddr, stubName, TypePtr::BOTTOM,
9441 src_start, state, ofs, limit);
9442 } else {
9443 call = make_runtime_call(RC_LEAF|RC_NO_FP,
9444 OptoRuntime::digestBase_implCompressMB_Type(true),
9445 stubAddr, stubName, TypePtr::BOTTOM,
9446 src_start, state, block_size, ofs, limit);
9447 }
9448
9449 // return ofs (int)
9450 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
9451 set_result(result);
9452
9453 return true;
9454 }
9455
9456 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
9457 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
9458 assert(UseAES, "need AES instruction support");
9459 address stubAddr = nullptr;
9460 const char *stubName = nullptr;
9461 stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
9462 stubName = "galoisCounterMode_AESCrypt";
9463
9464 if (stubAddr == nullptr) return false;
9465
9466 Node* in = argument(0);
9467 Node* inOfs = argument(1);
9468 Node* len = argument(2);
9469 Node* ct = argument(3);
9470 Node* ctOfs = argument(4);
9471 Node* out = argument(5);
9472 Node* outOfs = argument(6);
9473 Node* gctr_object = argument(7);
9474 Node* ghash_object = argument(8);
9475
9476 // (1) in, ct and out are arrays.
9477 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
9478 const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
9479 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
9480 assert( in_type != nullptr && in_type->elem() != Type::BOTTOM &&
9481 ct_type != nullptr && ct_type->elem() != Type::BOTTOM &&
9482 out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
9483
9484 // checks are the responsibility of the caller
9485 Node* in_start = in;
9486 Node* ct_start = ct;
9487 Node* out_start = out;
9488 if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
9489 assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
9490 in_start = array_element_address(in, inOfs, T_BYTE);
9491 ct_start = array_element_address(ct, ctOfs, T_BYTE);
9492 out_start = array_element_address(out, outOfs, T_BYTE);
9493 }
9494
9495 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
9496 // (because of the predicated logic executed earlier).
9497 // so we cast it here safely.
9498 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
9499 Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9500 Node* counter = load_field_from_object(gctr_object, "counter", "[B");
9501 Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
9502 Node* state = load_field_from_object(ghash_object, "state", "[J");
9503
9504 if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
9505 return false;
9506 }
9507 // cast it to what we know it will be at runtime
9508 const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
9509 assert(tinst != nullptr, "GCTR obj is null");
9510 assert(tinst->is_loaded(), "GCTR obj is not loaded");
9511 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9512 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
9513 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9514 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
9515 const TypeOopPtr* xtype = aklass->as_instance_type();
9516 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
9517 aescrypt_object = _gvn.transform(aescrypt_object);
9518 // we need to get the start of the aescrypt_object's expanded key array
9519 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
9520 if (k_start == nullptr) return false;
9521 // similarly, get the start address of the r vector
9522 Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
9523 Node* state_start = array_element_address(state, intcon(0), T_LONG);
9524 Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
9525
9526
9527 // Call the stub, passing params
9528 Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
9529 OptoRuntime::galoisCounterMode_aescrypt_Type(),
9530 stubAddr, stubName, TypePtr::BOTTOM,
9531 in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
9532
9533 // return cipher length (int)
9534 Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
9535 set_result(retvalue);
9536
9537 return true;
9538 }
9539
9540 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
9541 // Return node representing slow path of predicate check.
9542 // the pseudo code we want to emulate with this predicate is:
9543 // for encryption:
9544 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
9545 // for decryption:
9546 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
9547 // note cipher==plain is more conservative than the original java code but that's OK
9548 //
9549
9550 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
9551 // The receiver was checked for null already.
9552 Node* objGCTR = argument(7);
9553 // Load embeddedCipher field of GCTR object.
9554 Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
9555 assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
9556
9557 // get AESCrypt klass for instanceOf check
9558 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
9559 // will have same classloader as CipherBlockChaining object
9560 const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
9561 assert(tinst != nullptr, "GCTR obj is null");
9562 assert(tinst->is_loaded(), "GCTR obj is not loaded");
9563
9564 // we want to do an instanceof comparison against the AESCrypt class
9565 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
9566 if (!klass_AESCrypt->is_loaded()) {
9567 // if AESCrypt is not even loaded, we never take the intrinsic fast path
9568 Node* ctrl = control();
9569 set_control(top()); // no regular fast path
9570 return ctrl;
9571 }
9572
9573 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
9574 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
9575 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9576 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9577 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9578
9579 return instof_false; // even if it is null
9580 }
9581
9582 //------------------------------get_state_from_digest_object-----------------------
9583 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
9584 const char* state_type;
9585 switch (elem_type) {
9586 case T_BYTE: state_type = "[B"; break;
9587 case T_INT: state_type = "[I"; break;
9588 case T_LONG: state_type = "[J"; break;
9589 default: ShouldNotReachHere();
9590 }
9591 Node* digest_state = load_field_from_object(digest_object, "state", state_type);
9592 assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
9593 if (digest_state == nullptr) return (Node *) nullptr;
9594
9595 // now have the array, need to get the start address of the state array
9596 Node* state = array_element_address(digest_state, intcon(0), elem_type);
9597 return state;
9598 }
9599
9600 //------------------------------get_block_size_from_sha3_object----------------------------------
9601 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
9602 Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
9603 assert (block_size != nullptr, "sanity");
9604 return block_size;
9605 }
9606
9607 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
9608 // Return node representing slow path of predicate check.
9609 // the pseudo code we want to emulate with this predicate is:
9610 // if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
9611 //
9612 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
9613 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
9614 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
9615 assert((uint)predicate < 5, "sanity");
9616
9617 // The receiver was checked for null already.
9618 Node* digestBaseObj = argument(0);
9619
9620 // get DigestBase klass for instanceOf check
9621 const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
9622 assert(tinst != nullptr, "digestBaseObj is null");
9623 assert(tinst->is_loaded(), "DigestBase is not loaded");
9624
9625 const char* klass_name = nullptr;
9626 switch (predicate) {
9627 case 0:
9628 if (UseMD5Intrinsics) {
9629 // we want to do an instanceof comparison against the MD5 class
9630 klass_name = "sun/security/provider/MD5";
9631 }
9632 break;
9633 case 1:
9634 if (UseSHA1Intrinsics) {
9635 // we want to do an instanceof comparison against the SHA class
9636 klass_name = "sun/security/provider/SHA";
9637 }
9638 break;
9639 case 2:
9640 if (UseSHA256Intrinsics) {
9641 // we want to do an instanceof comparison against the SHA2 class
9642 klass_name = "sun/security/provider/SHA2";
9643 }
9644 break;
9645 case 3:
9646 if (UseSHA512Intrinsics) {
9647 // we want to do an instanceof comparison against the SHA5 class
9648 klass_name = "sun/security/provider/SHA5";
9649 }
9650 break;
9651 case 4:
9652 if (UseSHA3Intrinsics) {
9653 // we want to do an instanceof comparison against the SHA3 class
9654 klass_name = "sun/security/provider/SHA3";
9655 }
9656 break;
9657 default:
9658 fatal("unknown SHA intrinsic predicate: %d", predicate);
9659 }
9660
9661 ciKlass* klass = nullptr;
9662 if (klass_name != nullptr) {
9663 klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
9664 }
9665 if ((klass == nullptr) || !klass->is_loaded()) {
9666 // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
9667 Node* ctrl = control();
9668 set_control(top()); // no intrinsic path
9669 return ctrl;
9670 }
9671 ciInstanceKlass* instklass = klass->as_instance_klass();
9672
9673 Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
9674 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
9675 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
9676 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
9677
9678 return instof_false; // even if it is null
9679 }
9680
9681 //-------------inline_fma-----------------------------------
9682 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
9683 Node *a = nullptr;
9684 Node *b = nullptr;
9685 Node *c = nullptr;
9686 Node* result = nullptr;
9687 switch (id) {
9688 case vmIntrinsics::_fmaD:
9689 assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
9690 // no receiver since it is static method
9691 a = argument(0);
9692 b = argument(2);
9693 c = argument(4);
9694 result = _gvn.transform(new FmaDNode(a, b, c));
9695 break;
9696 case vmIntrinsics::_fmaF:
9697 assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
9698 a = argument(0);
9699 b = argument(1);
9700 c = argument(2);
9701 result = _gvn.transform(new FmaFNode(a, b, c));
9702 break;
9703 default:
9704 fatal_unexpected_iid(id); break;
9705 }
9706 set_result(result);
9707 return true;
9708 }
9709
9710 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
9711 // argument(0) is receiver
9712 Node* codePoint = argument(1);
9713 Node* n = nullptr;
9714
9715 switch (id) {
9716 case vmIntrinsics::_isDigit :
9717 n = new DigitNode(control(), codePoint);
9718 break;
9719 case vmIntrinsics::_isLowerCase :
9720 n = new LowerCaseNode(control(), codePoint);
9721 break;
9722 case vmIntrinsics::_isUpperCase :
9723 n = new UpperCaseNode(control(), codePoint);
9724 break;
9725 case vmIntrinsics::_isWhitespace :
9726 n = new WhitespaceNode(control(), codePoint);
9727 break;
9728 default:
9729 fatal_unexpected_iid(id);
9730 }
9731
9732 set_result(_gvn.transform(n));
9733 return true;
9734 }
9735
9736 bool LibraryCallKit::inline_profileBoolean() {
9737 Node* counts = argument(1);
9738 const TypeAryPtr* ary = nullptr;
9739 ciArray* aobj = nullptr;
9740 if (counts->is_Con()
9741 && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9742 && (aobj = ary->const_oop()->as_array()) != nullptr
9743 && (aobj->length() == 2)) {
9744 // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9745 jint false_cnt = aobj->element_value(0).as_int();
9746 jint true_cnt = aobj->element_value(1).as_int();
9747
9748 if (C->log() != nullptr) {
9749 C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9750 false_cnt, true_cnt);
9751 }
9752
9753 if (false_cnt + true_cnt == 0) {
9754 // According to profile, never executed.
9755 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9756 Deoptimization::Action_reinterpret);
9757 return true;
9758 }
9759
9760 // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9761 // is a number of each value occurrences.
9762 Node* result = argument(0);
9763 if (false_cnt == 0 || true_cnt == 0) {
9764 // According to profile, one value has been never seen.
9765 int expected_val = (false_cnt == 0) ? 1 : 0;
9766
9767 Node* cmp = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9768 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9769
9770 IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9771 Node* fast_path = _gvn.transform(new IfTrueNode(check));
9772 Node* slow_path = _gvn.transform(new IfFalseNode(check));
9773
9774 { // Slow path: uncommon trap for never seen value and then reexecute
9775 // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9776 // the value has been seen at least once.
9777 PreserveJVMState pjvms(this);
9778 PreserveReexecuteState preexecs(this);
9779 jvms()->set_should_reexecute(true);
9780
9781 set_control(slow_path);
9782 set_i_o(i_o());
9783
9784 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9785 Deoptimization::Action_reinterpret);
9786 }
9787 // The guard for never seen value enables sharpening of the result and
9788 // returning a constant. It allows to eliminate branches on the same value
9789 // later on.
9790 set_control(fast_path);
9791 result = intcon(expected_val);
9792 }
9793 // Stop profiling.
9794 // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9795 // By replacing method body with profile data (represented as ProfileBooleanNode
9796 // on IR level) we effectively disable profiling.
9797 // It enables full speed execution once optimized code is generated.
9798 Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9799 C->record_for_igvn(profile);
9800 set_result(profile);
9801 return true;
9802 } else {
9803 // Continue profiling.
9804 // Profile data isn't available at the moment. So, execute method's bytecode version.
9805 // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9806 // is compiled and counters aren't available since corresponding MethodHandle
9807 // isn't a compile-time constant.
9808 return false;
9809 }
9810 }
9811
9812 bool LibraryCallKit::inline_isCompileConstant() {
9813 Node* n = argument(0);
9814 set_result(n->is_Con() ? intcon(1) : intcon(0));
9815 return true;
9816 }
9817
9818 //------------------------------- inline_getObjectSize --------------------------------------
9819 //
9820 // Calculate the runtime size of the object/array.
9821 // native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9822 //
9823 bool LibraryCallKit::inline_getObjectSize() {
9824 Node* obj = argument(3);
9825 Node* klass_node = load_object_klass(obj);
9826
9827 jint layout_con = Klass::_lh_neutral_value;
9828 Node* layout_val = get_layout_helper(klass_node, layout_con);
9829 int layout_is_con = (layout_val == nullptr);
9830
9831 if (layout_is_con) {
9832 // Layout helper is constant, can figure out things at compile time.
9833
9834 if (Klass::layout_helper_is_instance(layout_con)) {
9835 // Instance case: layout_con contains the size itself.
9836 Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9837 set_result(size);
9838 } else {
9839 // Array case: size is round(header + element_size*arraylength).
9840 // Since arraylength is different for every array instance, we have to
9841 // compute the whole thing at runtime.
9842
9843 Node* arr_length = load_array_length(obj);
9844
9845 int round_mask = MinObjAlignmentInBytes - 1;
9846 int hsize = Klass::layout_helper_header_size(layout_con);
9847 int eshift = Klass::layout_helper_log2_element_size(layout_con);
9848
9849 if ((round_mask & ~right_n_bits(eshift)) == 0) {
9850 round_mask = 0; // strength-reduce it if it goes away completely
9851 }
9852 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9853 Node* header_size = intcon(hsize + round_mask);
9854
9855 Node* lengthx = ConvI2X(arr_length);
9856 Node* headerx = ConvI2X(header_size);
9857
9858 Node* abody = lengthx;
9859 if (eshift != 0) {
9860 abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9861 }
9862 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9863 if (round_mask != 0) {
9864 size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9865 }
9866 size = ConvX2L(size);
9867 set_result(size);
9868 }
9869 } else {
9870 // Layout helper is not constant, need to test for array-ness at runtime.
9871
9872 enum { _instance_path = 1, _array_path, PATH_LIMIT };
9873 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9874 PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9875 record_for_igvn(result_reg);
9876
9877 Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9878 if (array_ctl != nullptr) {
9879 // Array case: size is round(header + element_size*arraylength).
9880 // Since arraylength is different for every array instance, we have to
9881 // compute the whole thing at runtime.
9882
9883 PreserveJVMState pjvms(this);
9884 set_control(array_ctl);
9885 Node* arr_length = load_array_length(obj);
9886
9887 int round_mask = MinObjAlignmentInBytes - 1;
9888 Node* mask = intcon(round_mask);
9889
9890 Node* hss = intcon(Klass::_lh_header_size_shift);
9891 Node* hsm = intcon(Klass::_lh_header_size_mask);
9892 Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9893 header_size = _gvn.transform(new AndINode(header_size, hsm));
9894 header_size = _gvn.transform(new AddINode(header_size, mask));
9895
9896 // There is no need to mask or shift this value.
9897 // The semantics of LShiftINode include an implicit mask to 0x1F.
9898 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9899 Node* elem_shift = layout_val;
9900
9901 Node* lengthx = ConvI2X(arr_length);
9902 Node* headerx = ConvI2X(header_size);
9903
9904 Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9905 Node* size = _gvn.transform(new AddXNode(headerx, abody));
9906 if (round_mask != 0) {
9907 size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9908 }
9909 size = ConvX2L(size);
9910
9911 result_reg->init_req(_array_path, control());
9912 result_val->init_req(_array_path, size);
9913 }
9914
9915 if (!stopped()) {
9916 // Instance case: the layout helper gives us instance size almost directly,
9917 // but we need to mask out the _lh_instance_slow_path_bit.
9918 Node* size = ConvI2X(layout_val);
9919 assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9920 Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9921 size = _gvn.transform(new AndXNode(size, mask));
9922 size = ConvX2L(size);
9923
9924 result_reg->init_req(_instance_path, control());
9925 result_val->init_req(_instance_path, size);
9926 }
9927
9928 set_result(result_reg, result_val);
9929 }
9930
9931 return true;
9932 }
9933
9934 //------------------------------- inline_blackhole --------------------------------------
9935 //
9936 // Make sure all arguments to this node are alive.
9937 // This matches methods that were requested to be blackholed through compile commands.
9938 //
9939 bool LibraryCallKit::inline_blackhole() {
9940 assert(callee()->is_static(), "Should have been checked before: only static methods here");
9941 assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9942 assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9943
9944 // Blackhole node pinches only the control, not memory. This allows
9945 // the blackhole to be pinned in the loop that computes blackholed
9946 // values, but have no other side effects, like breaking the optimizations
9947 // across the blackhole.
9948
9949 Node* bh = _gvn.transform(new BlackholeNode(control()));
9950 set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9951
9952 // Bind call arguments as blackhole arguments to keep them alive
9953 uint nargs = callee()->arg_size();
9954 for (uint i = 0; i < nargs; i++) {
9955 bh->add_req(argument(i));
9956 }
9957
9958 return true;
9959 }
9960
9961 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9962 const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9963 if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9964 return nullptr; // box klass is not Float16
9965 }
9966
9967 // Null check; get notnull casted pointer
9968 Node* null_ctl = top();
9969 Node* not_null_box = null_check_oop(box, &null_ctl, true);
9970 // If not_null_box is dead, only null-path is taken
9971 if (stopped()) {
9972 set_control(null_ctl);
9973 return nullptr;
9974 }
9975 assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9976 const TypePtr* adr_type = C->alias_type(field)->adr_type();
9977 Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9978 return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9979 }
9980
9981 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9982 PreserveReexecuteState preexecs(this);
9983 jvms()->set_should_reexecute(true);
9984
9985 const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9986 Node* klass_node = makecon(klass_type);
9987 Node* box = new_instance(klass_node);
9988
9989 Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9990 const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9991
9992 Node* field_store = _gvn.transform(access_store_at(box,
9993 value_field,
9994 value_adr_type,
9995 value,
9996 TypeInt::SHORT,
9997 T_SHORT,
9998 IN_HEAP));
9999 set_memory(field_store, value_adr_type);
10000 return box;
10001 }
10002
10003 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
10004 if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
10005 !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
10006 return false;
10007 }
10008
10009 const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
10010 if (box_type == nullptr || box_type->const_oop() == nullptr) {
10011 return false;
10012 }
10013
10014 ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
10015 const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
10016 ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
10017 ciSymbols::short_signature(),
10018 false);
10019 assert(field != nullptr, "");
10020
10021 // Transformed nodes
10022 Node* fld1 = nullptr;
10023 Node* fld2 = nullptr;
10024 Node* fld3 = nullptr;
10025 switch(num_args) {
10026 case 3:
10027 fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
10028 if (fld3 == nullptr) {
10029 return false;
10030 }
10031 fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
10032 // fall-through
10033 case 2:
10034 fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
10035 if (fld2 == nullptr) {
10036 return false;
10037 }
10038 fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
10039 // fall-through
10040 case 1:
10041 fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
10042 if (fld1 == nullptr) {
10043 return false;
10044 }
10045 fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
10046 break;
10047 default: fatal("Unsupported number of arguments %d", num_args);
10048 }
10049
10050 Node* result = nullptr;
10051 switch (id) {
10052 // Unary operations
10053 case vmIntrinsics::_sqrt_float16:
10054 result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
10055 break;
10056 // Ternary operations
10057 case vmIntrinsics::_fma_float16:
10058 result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
10059 break;
10060 default:
10061 fatal_unexpected_iid(id);
10062 break;
10063 }
10064 result = _gvn.transform(new ReinterpretHF2SNode(result));
10065 set_result(box_fp16_value(float16_box_type, field, result));
10066 return true;
10067 }
10068