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/ciSymbols.hpp"
27 #include "ci/ciUtilities.inline.hpp"
28 #include "classfile/vmIntrinsics.hpp"
29 #include "compiler/compileBroker.hpp"
30 #include "compiler/compileLog.hpp"
31 #include "gc/shared/barrierSet.hpp"
32 #include "jfr/support/jfrIntrinsics.hpp"
33 #include "memory/resourceArea.hpp"
34 #include "oops/klass.inline.hpp"
35 #include "oops/objArrayKlass.hpp"
36 #include "opto/addnode.hpp"
37 #include "opto/arraycopynode.hpp"
38 #include "opto/c2compiler.hpp"
39 #include "opto/castnode.hpp"
40 #include "opto/cfgnode.hpp"
41 #include "opto/convertnode.hpp"
42 #include "opto/countbitsnode.hpp"
43 #include "opto/idealKit.hpp"
44 #include "opto/library_call.hpp"
45 #include "opto/mathexactnode.hpp"
46 #include "opto/mulnode.hpp"
47 #include "opto/narrowptrnode.hpp"
48 #include "opto/opaquenode.hpp"
49 #include "opto/parse.hpp"
50 #include "opto/rootnode.hpp"
51 #include "opto/runtime.hpp"
52 #include "opto/subnode.hpp"
53 #include "opto/vectornode.hpp"
54 #include "prims/jvmtiExport.hpp"
55 #include "prims/jvmtiThreadState.hpp"
56 #include "prims/unsafe.hpp"
57 #include "runtime/jniHandles.inline.hpp"
58 #include "runtime/mountUnmountDisabler.hpp"
59 #include "runtime/objectMonitor.hpp"
60 #include "runtime/sharedRuntime.hpp"
61 #include "runtime/stubRoutines.hpp"
62 #include "utilities/macros.hpp"
63 #include "utilities/powerOfTwo.hpp"
64
65 //---------------------------make_vm_intrinsic----------------------------
66 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
67 vmIntrinsicID id = m->intrinsic_id();
68 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
69
70 if (!m->is_loaded()) {
71 // Do not attempt to inline unloaded methods.
72 return nullptr;
73 }
74
75 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
76 bool is_available = false;
77
78 {
79 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
80 // the compiler must transition to '_thread_in_vm' state because both
81 // methods access VM-internal data.
82 VM_ENTRY_MARK;
83 methodHandle mh(THREAD, m->get_Method());
84 is_available = compiler != nullptr && compiler->is_intrinsic_available(mh, C->directive());
85 if (is_available && is_virtual) {
86 is_available = vmIntrinsics::does_virtual_dispatch(id);
87 }
88 }
89
90 if (is_available) {
91 assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
92 assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
93 return new LibraryIntrinsic(m, is_virtual,
94 vmIntrinsics::predicates_needed(id),
95 vmIntrinsics::does_virtual_dispatch(id),
96 id);
97 } else {
98 return nullptr;
99 }
100 }
101
102 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
103 LibraryCallKit kit(jvms, this);
104 Compile* C = kit.C;
105 int nodes = C->unique();
106 #ifndef PRODUCT
107 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
108 char buf[1000];
109 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
110 tty->print_cr("Intrinsic %s", str);
111 }
112 #endif
113 ciMethod* callee = kit.callee();
114 const int bci = kit.bci();
115 #ifdef ASSERT
116 Node* ctrl = kit.control();
117 #endif
118 // Try to inline the intrinsic.
119 if (callee->check_intrinsic_candidate() &&
120 kit.try_to_inline(_last_predicate)) {
121 const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
122 : "(intrinsic)";
123 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
124 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
125 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
126 if (C->log()) {
127 C->log()->elem("intrinsic id='%s'%s nodes='%d'",
128 vmIntrinsics::name_at(intrinsic_id()),
129 (is_virtual() ? " virtual='1'" : ""),
130 C->unique() - nodes);
131 }
132 // Push the result from the inlined method onto the stack.
133 kit.push_result();
134 return kit.transfer_exceptions_into_jvms();
135 }
136
137 // The intrinsic bailed out
138 assert(ctrl == kit.control(), "Control flow was added although the intrinsic bailed out");
139 assert(jvms->map() == kit.map(), "Out of sync JVM state");
140 if (jvms->has_method()) {
141 // Not a root compile.
142 const char* msg;
143 if (callee->intrinsic_candidate()) {
144 msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
145 } else {
146 msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
147 : "failed to inline (intrinsic), method not annotated";
148 }
149 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
150 C->inline_printer()->record(callee, jvms, InliningResult::FAILURE, msg);
151 } else {
152 // Root compile
153 ResourceMark rm;
154 stringStream msg_stream;
155 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
156 vmIntrinsics::name_at(intrinsic_id()),
157 is_virtual() ? " (virtual)" : "", bci);
158 const char *msg = msg_stream.freeze();
159 log_debug(jit, inlining)("%s", msg);
160 if (C->print_intrinsics() || C->print_inlining()) {
161 tty->print("%s", msg);
162 }
163 }
164 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
165
166 return nullptr;
167 }
168
169 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
170 LibraryCallKit kit(jvms, this);
171 Compile* C = kit.C;
172 int nodes = C->unique();
173 _last_predicate = predicate;
174 #ifndef PRODUCT
175 assert(is_predicated() && predicate < predicates_count(), "sanity");
176 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
177 char buf[1000];
178 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
179 tty->print_cr("Predicate for intrinsic %s", str);
180 }
181 #endif
182 ciMethod* callee = kit.callee();
183 const int bci = kit.bci();
184
185 Node* slow_ctl = kit.try_to_predicate(predicate);
186 if (!kit.failing()) {
187 const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
188 : "(intrinsic, predicate)";
189 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, InliningResult::SUCCESS, inline_msg);
190 C->inline_printer()->record(callee, jvms, InliningResult::SUCCESS, inline_msg);
191
192 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
193 if (C->log()) {
194 C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
195 vmIntrinsics::name_at(intrinsic_id()),
196 (is_virtual() ? " virtual='1'" : ""),
197 C->unique() - nodes);
198 }
199 return slow_ctl; // Could be null if the check folds.
200 }
201
202 // The intrinsic bailed out
203 if (jvms->has_method()) {
204 // Not a root compile.
205 const char* msg = "failed to generate predicate for intrinsic";
206 CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, InliningResult::FAILURE, msg);
207 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
208 } else {
209 // Root compile
210 ResourceMark rm;
211 stringStream msg_stream;
212 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
213 vmIntrinsics::name_at(intrinsic_id()),
214 is_virtual() ? " (virtual)" : "", bci);
215 const char *msg = msg_stream.freeze();
216 log_debug(jit, inlining)("%s", msg);
217 C->inline_printer()->record(kit.callee(), jvms, InliningResult::FAILURE, msg);
218 }
219 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
220 return nullptr;
221 }
222
223 bool LibraryCallKit::try_to_inline(int predicate) {
224 // Handle symbolic names for otherwise undistinguished boolean switches:
225 const bool is_store = true;
226 const bool is_compress = true;
227 const bool is_static = true;
228 const bool is_volatile = true;
229
230 if (!jvms()->has_method()) {
231 // Root JVMState has a null method.
232 assert(map()->memory()->Opcode() == Op_Parm, "");
233 // Insert the memory aliasing node
234 set_all_memory(reset_memory());
235 }
236 assert(merged_memory(), "");
237
238 switch (intrinsic_id()) {
239 case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
240 case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);
241 case vmIntrinsics::_getClass: return inline_native_getClass();
242
243 case vmIntrinsics::_ceil:
244 case vmIntrinsics::_floor:
245 case vmIntrinsics::_rint:
246 case vmIntrinsics::_dsin:
247 case vmIntrinsics::_dcos:
248 case vmIntrinsics::_dtan:
249 case vmIntrinsics::_dsinh:
250 case vmIntrinsics::_dtanh:
251 case vmIntrinsics::_dcbrt:
252 case vmIntrinsics::_dabs:
253 case vmIntrinsics::_fabs:
254 case vmIntrinsics::_iabs:
255 case vmIntrinsics::_labs:
256 case vmIntrinsics::_datan2:
257 case vmIntrinsics::_dsqrt:
258 case vmIntrinsics::_dsqrt_strict:
259 case vmIntrinsics::_dexp:
260 case vmIntrinsics::_dlog:
261 case vmIntrinsics::_dlog10:
262 case vmIntrinsics::_dpow:
263 case vmIntrinsics::_dcopySign:
264 case vmIntrinsics::_fcopySign:
265 case vmIntrinsics::_dsignum:
266 case vmIntrinsics::_roundF:
267 case vmIntrinsics::_roundD:
268 case vmIntrinsics::_fsignum: return inline_math_native(intrinsic_id());
269
270 case vmIntrinsics::_notify:
271 case vmIntrinsics::_notifyAll:
272 return inline_notify(intrinsic_id());
273
274 case vmIntrinsics::_addExactI: return inline_math_addExactI(false /* add */);
275 case vmIntrinsics::_addExactL: return inline_math_addExactL(false /* add */);
276 case vmIntrinsics::_decrementExactI: return inline_math_subtractExactI(true /* decrement */);
277 case vmIntrinsics::_decrementExactL: return inline_math_subtractExactL(true /* decrement */);
278 case vmIntrinsics::_incrementExactI: return inline_math_addExactI(true /* increment */);
279 case vmIntrinsics::_incrementExactL: return inline_math_addExactL(true /* increment */);
280 case vmIntrinsics::_multiplyExactI: return inline_math_multiplyExactI();
281 case vmIntrinsics::_multiplyExactL: return inline_math_multiplyExactL();
282 case vmIntrinsics::_multiplyHigh: return inline_math_multiplyHigh();
283 case vmIntrinsics::_unsignedMultiplyHigh: return inline_math_unsignedMultiplyHigh();
284 case vmIntrinsics::_negateExactI: return inline_math_negateExactI();
285 case vmIntrinsics::_negateExactL: return inline_math_negateExactL();
286 case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);
287 case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);
288
289 case vmIntrinsics::_arraycopy: return inline_arraycopy();
290
291 case vmIntrinsics::_arraySort: return inline_array_sort();
292 case vmIntrinsics::_arrayPartition: return inline_array_partition();
293
294 case vmIntrinsics::_compareToL: return inline_string_compareTo(StrIntrinsicNode::LL);
295 case vmIntrinsics::_compareToU: return inline_string_compareTo(StrIntrinsicNode::UU);
296 case vmIntrinsics::_compareToLU: return inline_string_compareTo(StrIntrinsicNode::LU);
297 case vmIntrinsics::_compareToUL: return inline_string_compareTo(StrIntrinsicNode::UL);
298
299 case vmIntrinsics::_indexOfL: return inline_string_indexOf(StrIntrinsicNode::LL);
300 case vmIntrinsics::_indexOfU: return inline_string_indexOf(StrIntrinsicNode::UU);
301 case vmIntrinsics::_indexOfUL: return inline_string_indexOf(StrIntrinsicNode::UL);
302 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
303 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
304 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
305 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
306 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
307
308 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
309
310 case vmIntrinsics::_vectorizedHashCode: return inline_vectorizedHashCode();
311
312 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
313 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
314 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
315 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
316
317 case vmIntrinsics::_compressStringC:
318 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
319 case vmIntrinsics::_inflateStringC:
320 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
321
322 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
323 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
324 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
325 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
326 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
327 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
328 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
329 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
330 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
331
332 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
333 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
334 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
335 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
336 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
337 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
338 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
339 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
340 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
341
342 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
343 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
344 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
345 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
346 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
347 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
348 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
349 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
350 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
351
352 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
353 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
354 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
355 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
356 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
357 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
358 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
359 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
360 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
361
362 case vmIntrinsics::_getShortUnaligned: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, true);
363 case vmIntrinsics::_getCharUnaligned: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, true);
364 case vmIntrinsics::_getIntUnaligned: return inline_unsafe_access(!is_store, T_INT, Relaxed, true);
365 case vmIntrinsics::_getLongUnaligned: return inline_unsafe_access(!is_store, T_LONG, Relaxed, true);
366
367 case vmIntrinsics::_putShortUnaligned: return inline_unsafe_access( is_store, T_SHORT, Relaxed, true);
368 case vmIntrinsics::_putCharUnaligned: return inline_unsafe_access( is_store, T_CHAR, Relaxed, true);
369 case vmIntrinsics::_putIntUnaligned: return inline_unsafe_access( is_store, T_INT, Relaxed, true);
370 case vmIntrinsics::_putLongUnaligned: return inline_unsafe_access( is_store, T_LONG, Relaxed, true);
371
372 case vmIntrinsics::_getReferenceAcquire: return inline_unsafe_access(!is_store, T_OBJECT, Acquire, false);
373 case vmIntrinsics::_getBooleanAcquire: return inline_unsafe_access(!is_store, T_BOOLEAN, Acquire, false);
374 case vmIntrinsics::_getByteAcquire: return inline_unsafe_access(!is_store, T_BYTE, Acquire, false);
375 case vmIntrinsics::_getShortAcquire: return inline_unsafe_access(!is_store, T_SHORT, Acquire, false);
376 case vmIntrinsics::_getCharAcquire: return inline_unsafe_access(!is_store, T_CHAR, Acquire, false);
377 case vmIntrinsics::_getIntAcquire: return inline_unsafe_access(!is_store, T_INT, Acquire, false);
378 case vmIntrinsics::_getLongAcquire: return inline_unsafe_access(!is_store, T_LONG, Acquire, false);
379 case vmIntrinsics::_getFloatAcquire: return inline_unsafe_access(!is_store, T_FLOAT, Acquire, false);
380 case vmIntrinsics::_getDoubleAcquire: return inline_unsafe_access(!is_store, T_DOUBLE, Acquire, false);
381
382 case vmIntrinsics::_putReferenceRelease: return inline_unsafe_access( is_store, T_OBJECT, Release, false);
383 case vmIntrinsics::_putBooleanRelease: return inline_unsafe_access( is_store, T_BOOLEAN, Release, false);
384 case vmIntrinsics::_putByteRelease: return inline_unsafe_access( is_store, T_BYTE, Release, false);
385 case vmIntrinsics::_putShortRelease: return inline_unsafe_access( is_store, T_SHORT, Release, false);
386 case vmIntrinsics::_putCharRelease: return inline_unsafe_access( is_store, T_CHAR, Release, false);
387 case vmIntrinsics::_putIntRelease: return inline_unsafe_access( is_store, T_INT, Release, false);
388 case vmIntrinsics::_putLongRelease: return inline_unsafe_access( is_store, T_LONG, Release, false);
389 case vmIntrinsics::_putFloatRelease: return inline_unsafe_access( is_store, T_FLOAT, Release, false);
390 case vmIntrinsics::_putDoubleRelease: return inline_unsafe_access( is_store, T_DOUBLE, Release, false);
391
392 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
393 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
394 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
395 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
396 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
397 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
398 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
399 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
400 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
401
402 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
403 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
404 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
405 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
406 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
407 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
408 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
409 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
410 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
411
412 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
413 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
414 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
415 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
416 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
417
418 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
419 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
420 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
421 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
422 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
423 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
424 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
425 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
426 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
427 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
428 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
429 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
430 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
431 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
432 case vmIntrinsics::_weakCompareAndSetIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Release);
433 case vmIntrinsics::_weakCompareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Volatile);
434 case vmIntrinsics::_weakCompareAndSetLongPlain: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Relaxed);
435 case vmIntrinsics::_weakCompareAndSetLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Acquire);
436 case vmIntrinsics::_weakCompareAndSetLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Release);
437 case vmIntrinsics::_weakCompareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Volatile);
438
439 case vmIntrinsics::_compareAndExchangeReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Volatile);
440 case vmIntrinsics::_compareAndExchangeReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Acquire);
441 case vmIntrinsics::_compareAndExchangeReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Release);
442 case vmIntrinsics::_compareAndExchangeByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Volatile);
443 case vmIntrinsics::_compareAndExchangeByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Acquire);
444 case vmIntrinsics::_compareAndExchangeByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Release);
445 case vmIntrinsics::_compareAndExchangeShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Volatile);
446 case vmIntrinsics::_compareAndExchangeShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Acquire);
447 case vmIntrinsics::_compareAndExchangeShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Release);
448 case vmIntrinsics::_compareAndExchangeInt: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Volatile);
449 case vmIntrinsics::_compareAndExchangeIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Acquire);
450 case vmIntrinsics::_compareAndExchangeIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Release);
451 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
452 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
453 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
454
455 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
456 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
457 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
458 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
459
460 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
461 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
462 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
463 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
464 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
465
466 case vmIntrinsics::_loadFence:
467 case vmIntrinsics::_storeFence:
468 case vmIntrinsics::_storeStoreFence:
469 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
470
471 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
472
473 case vmIntrinsics::_currentCarrierThread: return inline_native_currentCarrierThread();
474 case vmIntrinsics::_currentThread: return inline_native_currentThread();
475 case vmIntrinsics::_setCurrentThread: return inline_native_setCurrentThread();
476
477 case vmIntrinsics::_scopedValueCache: return inline_native_scopedValueCache();
478 case vmIntrinsics::_setScopedValueCache: return inline_native_setScopedValueCache();
479
480 case vmIntrinsics::_Continuation_pin: return inline_native_Continuation_pinning(false);
481 case vmIntrinsics::_Continuation_unpin: return inline_native_Continuation_pinning(true);
482
483 case vmIntrinsics::_vthreadEndFirstTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_first_transition_Java()),
484 "endFirstTransition", true);
485 case vmIntrinsics::_vthreadStartFinalTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_final_transition_Java()),
486 "startFinalTransition", true);
487 case vmIntrinsics::_vthreadStartTransition: return inline_native_vthread_start_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_start_transition_Java()),
488 "startTransition", false);
489 case vmIntrinsics::_vthreadEndTransition: return inline_native_vthread_end_transition(CAST_FROM_FN_PTR(address, OptoRuntime::vthread_end_transition_Java()),
490 "endTransition", false);
491 #if INCLUDE_JVMTI
492 case vmIntrinsics::_notifyJvmtiVThreadDisableSuspend: return inline_native_notify_jvmti_sync();
493 #endif
494
495 #ifdef JFR_HAVE_INTRINSICS
496 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JfrTime::time_function()), "counterTime");
497 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
498 case vmIntrinsics::_jvm_commit: return inline_native_jvm_commit();
499 case vmIntrinsics::_tryUpdateEpochField: return inline_native_try_update_epoch();
500 #endif
501 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
502 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
503 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
504 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
505 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
506 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
507 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
508 case vmIntrinsics::_setMemory: return inline_unsafe_setMemory();
509 case vmIntrinsics::_getLength: return inline_native_getLength();
510 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
511 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
512 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
513 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
514 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
515 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
516 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
517
518 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
519 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
520
521 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
522
523 case vmIntrinsics::_isInstance:
524 case vmIntrinsics::_isHidden:
525 case vmIntrinsics::_getSuperclass: return inline_native_Class_query(intrinsic_id());
526
527 case vmIntrinsics::_floatToRawIntBits:
528 case vmIntrinsics::_floatToIntBits:
529 case vmIntrinsics::_intBitsToFloat:
530 case vmIntrinsics::_doubleToRawLongBits:
531 case vmIntrinsics::_doubleToLongBits:
532 case vmIntrinsics::_longBitsToDouble:
533 case vmIntrinsics::_floatToFloat16:
534 case vmIntrinsics::_float16ToFloat: return inline_fp_conversions(intrinsic_id());
535 case vmIntrinsics::_sqrt_float16: return inline_fp16_operations(intrinsic_id(), 1);
536 case vmIntrinsics::_fma_float16: return inline_fp16_operations(intrinsic_id(), 3);
537 case vmIntrinsics::_floatIsFinite:
538 case vmIntrinsics::_floatIsInfinite:
539 case vmIntrinsics::_doubleIsFinite:
540 case vmIntrinsics::_doubleIsInfinite: return inline_fp_range_check(intrinsic_id());
541
542 case vmIntrinsics::_numberOfLeadingZeros_i:
543 case vmIntrinsics::_numberOfLeadingZeros_l:
544 case vmIntrinsics::_numberOfTrailingZeros_i:
545 case vmIntrinsics::_numberOfTrailingZeros_l:
546 case vmIntrinsics::_bitCount_i:
547 case vmIntrinsics::_bitCount_l:
548 case vmIntrinsics::_reverse_i:
549 case vmIntrinsics::_reverse_l:
550 case vmIntrinsics::_reverseBytes_i:
551 case vmIntrinsics::_reverseBytes_l:
552 case vmIntrinsics::_reverseBytes_s:
553 case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());
554
555 case vmIntrinsics::_compress_i:
556 case vmIntrinsics::_compress_l:
557 case vmIntrinsics::_expand_i:
558 case vmIntrinsics::_expand_l: return inline_bitshuffle_methods(intrinsic_id());
559
560 case vmIntrinsics::_compareUnsigned_i:
561 case vmIntrinsics::_compareUnsigned_l: return inline_compare_unsigned(intrinsic_id());
562
563 case vmIntrinsics::_divideUnsigned_i:
564 case vmIntrinsics::_divideUnsigned_l:
565 case vmIntrinsics::_remainderUnsigned_i:
566 case vmIntrinsics::_remainderUnsigned_l: return inline_divmod_methods(intrinsic_id());
567
568 case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();
569
570 case vmIntrinsics::_Reference_get0: return inline_reference_get0();
571 case vmIntrinsics::_Reference_refersTo0: return inline_reference_refersTo0(false);
572 case vmIntrinsics::_Reference_reachabilityFence: return inline_reference_reachabilityFence();
573 case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
574 case vmIntrinsics::_Reference_clear0: return inline_reference_clear0(false);
575 case vmIntrinsics::_PhantomReference_clear0: return inline_reference_clear0(true);
576
577 case vmIntrinsics::_Class_cast: return inline_Class_cast();
578
579 case vmIntrinsics::_aescrypt_encryptBlock:
580 case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());
581
582 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
583 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
584 return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
585
586 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
587 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
588 return inline_electronicCodeBook_AESCrypt(intrinsic_id());
589
590 case vmIntrinsics::_counterMode_AESCrypt:
591 return inline_counterMode_AESCrypt(intrinsic_id());
592
593 case vmIntrinsics::_galoisCounterMode_AESCrypt:
594 return inline_galoisCounterMode_AESCrypt();
595
596 case vmIntrinsics::_md5_implCompress:
597 case vmIntrinsics::_sha_implCompress:
598 case vmIntrinsics::_sha2_implCompress:
599 case vmIntrinsics::_sha5_implCompress:
600 case vmIntrinsics::_sha3_implCompress:
601 return inline_digestBase_implCompress(intrinsic_id());
602 case vmIntrinsics::_double_keccak:
603 case vmIntrinsics::_quad_keccak:
604 return inline_keccak(intrinsic_id());
605
606 case vmIntrinsics::_digestBase_implCompressMB:
607 return inline_digestBase_implCompressMB(predicate);
608
609 case vmIntrinsics::_multiplyToLen:
610 return inline_multiplyToLen();
611
612 case vmIntrinsics::_squareToLen:
613 return inline_squareToLen();
614
615 case vmIntrinsics::_mulAdd:
616 return inline_mulAdd();
617
618 case vmIntrinsics::_montgomeryMultiply:
619 return inline_montgomeryMultiply();
620 case vmIntrinsics::_montgomerySquare:
621 return inline_montgomerySquare();
622
623 case vmIntrinsics::_bigIntegerRightShiftWorker:
624 return inline_bigIntegerShift(true);
625 case vmIntrinsics::_bigIntegerLeftShiftWorker:
626 return inline_bigIntegerShift(false);
627
628 case vmIntrinsics::_vectorizedMismatch:
629 return inline_vectorizedMismatch();
630
631 case vmIntrinsics::_ghash_processBlocks:
632 return inline_ghash_processBlocks();
633 case vmIntrinsics::_chacha20Block:
634 return inline_chacha20Block();
635 case vmIntrinsics::_kyberNtt:
636 return inline_kyberNtt();
637 case vmIntrinsics::_kyberInverseNtt:
638 return inline_kyberInverseNtt();
639 case vmIntrinsics::_kyberNttMult:
640 return inline_kyberNttMult();
641 case vmIntrinsics::_kyberAddPoly_2:
642 return inline_kyberAddPoly_2();
643 case vmIntrinsics::_kyberAddPoly_3:
644 return inline_kyberAddPoly_3();
645 case vmIntrinsics::_kyber12To16:
646 return inline_kyber12To16();
647 case vmIntrinsics::_kyberBarrettReduce:
648 return inline_kyberBarrettReduce();
649 case vmIntrinsics::_dilithiumAlmostNtt:
650 return inline_dilithiumAlmostNtt();
651 case vmIntrinsics::_dilithiumAlmostInverseNtt:
652 return inline_dilithiumAlmostInverseNtt();
653 case vmIntrinsics::_dilithiumNttMult:
654 return inline_dilithiumNttMult();
655 case vmIntrinsics::_dilithiumMontMulByConstant:
656 return inline_dilithiumMontMulByConstant();
657 case vmIntrinsics::_dilithiumDecomposePoly:
658 return inline_dilithiumDecomposePoly();
659 case vmIntrinsics::_base64_encodeBlock:
660 return inline_base64_encodeBlock();
661 case vmIntrinsics::_base64_decodeBlock:
662 return inline_base64_decodeBlock();
663 case vmIntrinsics::_poly1305_processBlocks:
664 return inline_poly1305_processBlocks();
665 case vmIntrinsics::_intpoly_montgomeryMult_P256:
666 return inline_intpoly_montgomeryMult_P256();
667 case vmIntrinsics::_intpoly_assign:
668 return inline_intpoly_assign();
669 case vmIntrinsics::_intpoly_mult_25519:
670 return inline_intpoly_mult_25519();
671 case vmIntrinsics::_intpoly_square_25519:
672 return inline_intpoly_square_25519();
673 case vmIntrinsics::_encodeISOArray:
674 case vmIntrinsics::_encodeByteISOArray:
675 return inline_encodeISOArray(false);
676 case vmIntrinsics::_encodeAsciiArray:
677 return inline_encodeISOArray(true);
678
679 case vmIntrinsics::_updateCRC32:
680 return inline_updateCRC32();
681 case vmIntrinsics::_updateBytesCRC32:
682 return inline_updateBytesCRC32();
683 case vmIntrinsics::_updateByteBufferCRC32:
684 return inline_updateByteBufferCRC32();
685
686 case vmIntrinsics::_updateBytesCRC32C:
687 return inline_updateBytesCRC32C();
688 case vmIntrinsics::_updateDirectByteBufferCRC32C:
689 return inline_updateDirectByteBufferCRC32C();
690
691 case vmIntrinsics::_updateBytesAdler32:
692 return inline_updateBytesAdler32();
693 case vmIntrinsics::_updateByteBufferAdler32:
694 return inline_updateByteBufferAdler32();
695
696 case vmIntrinsics::_profileBoolean:
697 return inline_profileBoolean();
698 case vmIntrinsics::_isCompileConstant:
699 return inline_isCompileConstant();
700
701 case vmIntrinsics::_countPositives:
702 return inline_countPositives();
703
704 case vmIntrinsics::_fmaD:
705 case vmIntrinsics::_fmaF:
706 return inline_fma(intrinsic_id());
707
708 case vmIntrinsics::_isDigit:
709 case vmIntrinsics::_isLowerCase:
710 case vmIntrinsics::_isUpperCase:
711 case vmIntrinsics::_isWhitespace:
712 return inline_character_compare(intrinsic_id());
713
714 case vmIntrinsics::_min:
715 case vmIntrinsics::_max:
716 case vmIntrinsics::_min_strict:
717 case vmIntrinsics::_max_strict:
718 case vmIntrinsics::_minL:
719 case vmIntrinsics::_maxL:
720 case vmIntrinsics::_minF:
721 case vmIntrinsics::_maxF:
722 case vmIntrinsics::_minD:
723 case vmIntrinsics::_maxD:
724 case vmIntrinsics::_minF_strict:
725 case vmIntrinsics::_maxF_strict:
726 case vmIntrinsics::_minD_strict:
727 case vmIntrinsics::_maxD_strict:
728 return inline_min_max(intrinsic_id());
729
730 case vmIntrinsics::_VectorUnaryOp:
731 return inline_vector_nary_operation(1);
732 case vmIntrinsics::_VectorBinaryOp:
733 return inline_vector_nary_operation(2);
734 case vmIntrinsics::_VectorUnaryLibOp:
735 return inline_vector_call(1);
736 case vmIntrinsics::_VectorBinaryLibOp:
737 return inline_vector_call(2);
738 case vmIntrinsics::_VectorTernaryOp:
739 return inline_vector_nary_operation(3);
740 case vmIntrinsics::_VectorFromBitsCoerced:
741 return inline_vector_frombits_coerced();
742 case vmIntrinsics::_VectorMaskOp:
743 return inline_vector_mask_operation();
744 case vmIntrinsics::_VectorLoadOp:
745 return inline_vector_mem_operation(/*is_store=*/false);
746 case vmIntrinsics::_VectorLoadMaskedOp:
747 return inline_vector_mem_masked_operation(/*is_store*/false);
748 case vmIntrinsics::_VectorStoreOp:
749 return inline_vector_mem_operation(/*is_store=*/true);
750 case vmIntrinsics::_VectorStoreMaskedOp:
751 return inline_vector_mem_masked_operation(/*is_store=*/true);
752 case vmIntrinsics::_VectorGatherOp:
753 return inline_vector_gather_scatter(/*is_scatter*/ false);
754 case vmIntrinsics::_VectorScatterOp:
755 return inline_vector_gather_scatter(/*is_scatter*/ true);
756 case vmIntrinsics::_VectorReductionCoerced:
757 return inline_vector_reduction();
758 case vmIntrinsics::_VectorTest:
759 return inline_vector_test();
760 case vmIntrinsics::_VectorBlend:
761 return inline_vector_blend();
762 case vmIntrinsics::_VectorRearrange:
763 return inline_vector_rearrange();
764 case vmIntrinsics::_VectorSelectFrom:
765 return inline_vector_select_from();
766 case vmIntrinsics::_VectorCompare:
767 return inline_vector_compare();
768 case vmIntrinsics::_VectorBroadcastInt:
769 return inline_vector_broadcast_int();
770 case vmIntrinsics::_VectorConvert:
771 return inline_vector_convert();
772 case vmIntrinsics::_VectorInsert:
773 return inline_vector_insert();
774 case vmIntrinsics::_VectorExtract:
775 return inline_vector_extract();
776 case vmIntrinsics::_VectorCompressExpand:
777 return inline_vector_compress_expand();
778 case vmIntrinsics::_VectorSelectFromTwoVectorOp:
779 return inline_vector_select_from_two_vectors();
780 case vmIntrinsics::_IndexVector:
781 return inline_index_vector();
782 case vmIntrinsics::_IndexPartiallyInUpperRange:
783 return inline_index_partially_in_upper_range();
784
785 case vmIntrinsics::_getObjectSize:
786 return inline_getObjectSize();
787
788 case vmIntrinsics::_blackhole:
789 return inline_blackhole();
790
791 default:
792 // If you get here, it may be that someone has added a new intrinsic
793 // to the list in vmIntrinsics.hpp without implementing it here.
794 #ifndef PRODUCT
795 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
796 tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
797 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
798 }
799 #endif
800 return false;
801 }
802 }
803
804 Node* LibraryCallKit::try_to_predicate(int predicate) {
805 if (!jvms()->has_method()) {
806 // Root JVMState has a null method.
807 assert(map()->memory()->Opcode() == Op_Parm, "");
808 // Insert the memory aliasing node
809 set_all_memory(reset_memory());
810 }
811 assert(merged_memory(), "");
812
813 switch (intrinsic_id()) {
814 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
815 return inline_cipherBlockChaining_AESCrypt_predicate(false);
816 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
817 return inline_cipherBlockChaining_AESCrypt_predicate(true);
818 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
819 return inline_electronicCodeBook_AESCrypt_predicate(false);
820 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
821 return inline_electronicCodeBook_AESCrypt_predicate(true);
822 case vmIntrinsics::_counterMode_AESCrypt:
823 return inline_counterMode_AESCrypt_predicate();
824 case vmIntrinsics::_digestBase_implCompressMB:
825 return inline_digestBase_implCompressMB_predicate(predicate);
826 case vmIntrinsics::_galoisCounterMode_AESCrypt:
827 return inline_galoisCounterMode_AESCrypt_predicate();
828
829 default:
830 // If you get here, it may be that someone has added a new intrinsic
831 // to the list in vmIntrinsics.hpp without implementing it here.
832 #ifndef PRODUCT
833 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
834 tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
835 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
836 }
837 #endif
838 Node* slow_ctl = control();
839 set_control(top()); // No fast path intrinsic
840 return slow_ctl;
841 }
842 }
843
844 //------------------------------set_result-------------------------------
845 // Helper function for finishing intrinsics.
846 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
847 record_for_igvn(region);
848 set_control(_gvn.transform(region));
849 set_result( _gvn.transform(value));
850 assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
851 }
852
853 RegionNode* LibraryCallKit::create_bailout() {
854 RegionNode* bailout = new RegionNode(1);
855 record_for_igvn(bailout);
856 return bailout;
857 }
858
859 bool LibraryCallKit::check_bailout(RegionNode* bailout) {
860 if (bailout->req() > 1) {
861 bailout = _gvn.transform(bailout)->as_Region();
862 Node* frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
863 Node* halt = _gvn.transform(new HaltNode(bailout, frame, "unexpected guard failure in intrinsic"));
864 C->root()->add_req(halt);
865 }
866 return stopped();
867 }
868
869 //------------------------------generate_guard---------------------------
870 // Helper function for generating guarded fast-slow graph structures.
871 // The given 'test', if true, guards a slow path. If the test fails
872 // then a fast path can be taken. (We generally hope it fails.)
873 // In all cases, GraphKit::control() is updated to the fast path.
874 // The returned value represents the control for the slow path.
875 // The return value is never 'top'; it is either a valid control
876 // or null if it is obvious that the slow path can never be taken.
877 // Also, if region and the slow control are not null, the slow edge
878 // is appended to the region.
879 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
880 if (stopped()) {
881 // Already short circuited.
882 return nullptr;
883 }
884
885 // Build an if node and its projections.
886 // If test is true we take the slow path, which we assume is uncommon.
887 if (_gvn.type(test) == TypeInt::ZERO) {
888 // The slow branch is never taken. No need to build this guard.
889 return nullptr;
890 }
891
892 IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
893
894 Node* if_slow = _gvn.transform(new IfTrueNode(iff));
895 if (if_slow == top()) {
896 // The slow branch is never taken. No need to build this guard.
897 return nullptr;
898 }
899
900 if (region != nullptr)
901 region->add_req(if_slow);
902
903 Node* if_fast = _gvn.transform(new IfFalseNode(iff));
904 set_control(if_fast);
905
906 return if_slow;
907 }
908
909 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
910 return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
911 }
912 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
913 return generate_guard(test, region, PROB_FAIR);
914 }
915
916 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
917 Node** pos_index, bool with_opaque) {
918 if (stopped())
919 return nullptr; // already stopped
920 if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
921 return nullptr; // index is already adequately typed
922 Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
923 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
924 if (with_opaque) {
925 bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
926 }
927 Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
928 if (is_neg != nullptr && pos_index != nullptr) {
929 // Emulate effect of Parse::adjust_map_after_if.
930 Node* ccast = new CastIINode(control(), index, TypeInt::POS);
931 (*pos_index) = _gvn.transform(ccast);
932 }
933 return is_neg;
934 }
935
936 // Make sure that 'position' is a valid limit index, in [0..length].
937 // There are two equivalent plans for checking this:
938 // A. (offset + copyLength) unsigned<= arrayLength
939 // B. offset <= (arrayLength - copyLength)
940 // We require that all of the values above, except for the sum and
941 // difference, are already known to be non-negative.
942 // Plan A is robust in the face of overflow, if offset and copyLength
943 // are both hugely positive.
944 //
945 // Plan B is less direct and intuitive, but it does not overflow at
946 // all, since the difference of two non-negatives is always
947 // representable. Whenever Java methods must perform the equivalent
948 // check they generally use Plan B instead of Plan A.
949 // For the moment we use Plan A.
950 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
951 Node* subseq_length,
952 Node* array_length,
953 RegionNode* region,
954 bool with_opaque) {
955 if (stopped())
956 return nullptr; // already stopped
957 bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
958 if (zero_offset && subseq_length->eqv_uncast(array_length))
959 return nullptr; // common case of whole-array copy
960 Node* last = subseq_length;
961 if (!zero_offset) // last += offset
962 last = _gvn.transform(new AddINode(last, offset));
963 Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
964 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
965 if (with_opaque) {
966 bol_lt = _gvn.transform(new OpaqueConstantBoolNode(C, bol_lt, false));
967 }
968 Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
969 return is_over;
970 }
971
972 // Emit range checks for the given String.value byte array
973 void LibraryCallKit::generate_string_range_check(Node* array,
974 Node* offset,
975 Node* count,
976 bool char_count,
977 RegionNode* region) {
978 if (stopped()) {
979 return; // already stopped
980 }
981 if (char_count) {
982 // Convert char count to byte count
983 count = _gvn.transform(new LShiftINode(count, intcon(1)));
984 }
985 // Offset and count must not be negative
986 generate_negative_guard(offset, region, nullptr, true);
987 generate_negative_guard(count, region, nullptr, true);
988 // Offset + count must not exceed length of array
989 generate_limit_guard(offset, count, load_array_length(array), region, true);
990 }
991
992 Node* LibraryCallKit::current_thread_helper(Node*& tls_output, ByteSize handle_offset,
993 bool is_immutable) {
994 ciKlass* thread_klass = env()->Thread_klass();
995 const Type* thread_type
996 = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
997
998 Node* thread = _gvn.transform(new ThreadLocalNode());
999 Node* p = off_heap_plus_addr(thread, in_bytes(handle_offset));
1000 tls_output = thread;
1001
1002 Node* thread_obj_handle
1003 = (is_immutable
1004 ? LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
1005 TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered)
1006 : make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered));
1007 thread_obj_handle = _gvn.transform(thread_obj_handle);
1008
1009 DecoratorSet decorators = IN_NATIVE;
1010 if (is_immutable) {
1011 decorators |= C2_IMMUTABLE_MEMORY;
1012 }
1013 return access_load(thread_obj_handle, thread_type, T_OBJECT, decorators);
1014 }
1015
1016 //--------------------------generate_current_thread--------------------
1017 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
1018 return current_thread_helper(tls_output, JavaThread::threadObj_offset(),
1019 /*is_immutable*/false);
1020 }
1021
1022 //--------------------------generate_virtual_thread--------------------
1023 Node* LibraryCallKit::generate_virtual_thread(Node* tls_output) {
1024 return current_thread_helper(tls_output, JavaThread::vthread_offset(),
1025 !C->method()->changes_current_thread());
1026 }
1027
1028 //------------------------------make_string_method_node------------------------
1029 // Helper method for String intrinsic functions. This version is called with
1030 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
1031 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
1032 // containing the lengths of str1 and str2.
1033 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
1034 Node* result = nullptr;
1035 switch (opcode) {
1036 case Op_StrIndexOf:
1037 result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
1038 str1_start, cnt1, str2_start, cnt2, ae);
1039 break;
1040 case Op_StrComp:
1041 result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
1042 str1_start, cnt1, str2_start, cnt2, ae);
1043 break;
1044 case Op_StrEquals:
1045 // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
1046 // Use the constant length if there is one because optimized match rule may exist.
1047 result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
1048 str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
1049 break;
1050 default:
1051 ShouldNotReachHere();
1052 return nullptr;
1053 }
1054
1055 // All these intrinsics have checks.
1056 C->set_has_split_ifs(true); // Has chance for split-if optimization
1057 clear_upper_avx();
1058
1059 return _gvn.transform(result);
1060 }
1061
1062 //------------------------------inline_string_compareTo------------------------
1063 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
1064 Node* arg1 = argument(0);
1065 Node* arg2 = argument(1);
1066
1067 arg1 = must_be_not_null(arg1, true);
1068 arg2 = must_be_not_null(arg2, true);
1069
1070 // Get start addr and length of first argument
1071 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1072 Node* arg1_cnt = load_array_length(arg1);
1073
1074 // Get start addr and length of second argument
1075 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1076 Node* arg2_cnt = load_array_length(arg2);
1077
1078 Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1079 set_result(result);
1080 return true;
1081 }
1082
1083 //------------------------------inline_string_equals------------------------
1084 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
1085 Node* arg1 = argument(0);
1086 Node* arg2 = argument(1);
1087
1088 // paths (plus control) merge
1089 RegionNode* region = new RegionNode(3);
1090 Node* phi = new PhiNode(region, TypeInt::BOOL);
1091
1092 if (!stopped()) {
1093
1094 arg1 = must_be_not_null(arg1, true);
1095 arg2 = must_be_not_null(arg2, true);
1096
1097 // Get start addr and length of first argument
1098 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
1099 Node* arg1_cnt = load_array_length(arg1);
1100
1101 // Get start addr and length of second argument
1102 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
1103 Node* arg2_cnt = load_array_length(arg2);
1104
1105 // Check for arg1_cnt != arg2_cnt
1106 Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
1107 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
1108 Node* if_ne = generate_slow_guard(bol, nullptr);
1109 if (if_ne != nullptr) {
1110 phi->init_req(2, intcon(0));
1111 region->init_req(2, if_ne);
1112 }
1113
1114 // Check for count == 0 is done by assembler code for StrEquals.
1115
1116 if (!stopped()) {
1117 Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
1118 phi->init_req(1, equals);
1119 region->init_req(1, control());
1120 }
1121 }
1122
1123 // post merge
1124 set_control(_gvn.transform(region));
1125 record_for_igvn(region);
1126
1127 set_result(_gvn.transform(phi));
1128 return true;
1129 }
1130
1131 //------------------------------inline_array_equals----------------------------
1132 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
1133 assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
1134 Node* arg1 = argument(0);
1135 Node* arg2 = argument(1);
1136
1137 const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
1138 set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), mtype, arg1, arg2, ae)));
1139 clear_upper_avx();
1140
1141 return true;
1142 }
1143
1144
1145 //------------------------------inline_countPositives------------------------------
1146 // int java.lang.StringCoding#countPositives0(byte[] ba, int off, int len)
1147 bool LibraryCallKit::inline_countPositives() {
1148 assert(callee()->signature()->size() == 3, "countPositives has 3 parameters");
1149 // no receiver since it is static method
1150 Node* ba = argument(0);
1151 Node* offset = argument(1);
1152 Node* len = argument(2);
1153
1154 ba = must_be_not_null(ba, true);
1155 RegionNode* bailout = create_bailout();
1156 generate_string_range_check(ba, offset, len, false, bailout);
1157 if (check_bailout(bailout)) {
1158 return true;
1159 }
1160
1161 Node* ba_start = array_element_address(ba, offset, T_BYTE);
1162 Node* result = new CountPositivesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1163 set_result(_gvn.transform(result));
1164 clear_upper_avx();
1165 return true;
1166 }
1167
1168 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1169 Node* index = argument(0);
1170 Node* length = bt == T_INT ? argument(1) : argument(2);
1171 if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1172 return false;
1173 }
1174
1175 // check that length is positive
1176 Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1177 Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1178
1179 {
1180 BuildCutout unless(this, len_pos_bol, PROB_MAX);
1181 uncommon_trap(Deoptimization::Reason_intrinsic,
1182 Deoptimization::Action_make_not_entrant);
1183 }
1184
1185 if (stopped()) {
1186 // Length is known to be always negative during compilation and the IR graph so far constructed is good so return success
1187 return true;
1188 }
1189
1190 // length is now known positive, add a cast node to make this explicit
1191 jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1192 Node* casted_length = ConstraintCastNode::make_cast_for_basic_type(
1193 control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1194 ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1195 casted_length = _gvn.transform(casted_length);
1196 replace_in_map(length, casted_length);
1197 length = casted_length;
1198
1199 // Use an unsigned comparison for the range check itself
1200 Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1201 BoolTest::mask btest = BoolTest::lt;
1202 Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1203 RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1204 _gvn.set_type(rc, rc->Value(&_gvn));
1205 if (!rc_bool->is_Con()) {
1206 record_for_igvn(rc);
1207 }
1208 set_control(_gvn.transform(new IfTrueNode(rc)));
1209 {
1210 PreserveJVMState pjvms(this);
1211 set_control(_gvn.transform(new IfFalseNode(rc)));
1212 uncommon_trap(Deoptimization::Reason_range_check,
1213 Deoptimization::Action_make_not_entrant);
1214 }
1215
1216 if (stopped()) {
1217 // Range check is known to always fail during compilation and the IR graph so far constructed is good so return success
1218 return true;
1219 }
1220
1221 // index is now known to be >= 0 and < length, cast it
1222 Node* result = ConstraintCastNode::make_cast_for_basic_type(
1223 control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt),
1224 ConstraintCastNode::DependencyType::FloatingNarrowing, bt);
1225 result = _gvn.transform(result);
1226 set_result(result);
1227 replace_in_map(index, result);
1228 return true;
1229 }
1230
1231 //------------------------------inline_string_indexOf------------------------
1232 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1233 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1234 return false;
1235 }
1236 Node* src = argument(0);
1237 Node* tgt = argument(1);
1238
1239 // Make the merge point
1240 RegionNode* result_rgn = new RegionNode(4);
1241 Node* result_phi = new PhiNode(result_rgn, TypeInt::INT);
1242
1243 src = must_be_not_null(src, true);
1244 tgt = must_be_not_null(tgt, true);
1245
1246 // Get start addr and length of source string
1247 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1248 Node* src_count = load_array_length(src);
1249
1250 // Get start addr and length of substring
1251 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1252 Node* tgt_count = load_array_length(tgt);
1253
1254 Node* result = nullptr;
1255 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1256
1257 if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1258 // Divide src size by 2 if String is UTF16 encoded
1259 src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1260 }
1261 if (ae == StrIntrinsicNode::UU) {
1262 // Divide substring size by 2 if String is UTF16 encoded
1263 tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1264 }
1265
1266 if (call_opt_stub) {
1267 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1268 StubRoutines::_string_indexof_array[ae],
1269 "stringIndexOf", TypePtr::BOTTOM, src_start,
1270 src_count, tgt_start, tgt_count);
1271 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1272 } else {
1273 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1274 result_rgn, result_phi, ae);
1275 }
1276 if (result != nullptr) {
1277 result_phi->init_req(3, result);
1278 result_rgn->init_req(3, control());
1279 }
1280 set_control(_gvn.transform(result_rgn));
1281 record_for_igvn(result_rgn);
1282 set_result(_gvn.transform(result_phi));
1283
1284 return true;
1285 }
1286
1287 //-----------------------------inline_string_indexOfI-----------------------
1288 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1289 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1290 return false;
1291 }
1292
1293 assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1294 Node* src = argument(0); // byte[]
1295 Node* src_count = argument(1); // char count
1296 Node* tgt = argument(2); // byte[]
1297 Node* tgt_count = argument(3); // char count
1298 Node* from_index = argument(4); // char index
1299
1300 src = must_be_not_null(src, true);
1301 tgt = must_be_not_null(tgt, true);
1302
1303 // Multiply byte array index by 2 if String is UTF16 encoded
1304 Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1305 src_count = _gvn.transform(new SubINode(src_count, from_index));
1306 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1307 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1308
1309 // Range checks
1310 RegionNode* bailout = create_bailout();
1311 generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL, bailout);
1312 generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU, bailout);
1313 if (check_bailout(bailout)) {
1314 return true;
1315 }
1316
1317 RegionNode* region = new RegionNode(5);
1318 Node* phi = new PhiNode(region, TypeInt::INT);
1319 Node* result = nullptr;
1320
1321 bool call_opt_stub = (StubRoutines::_string_indexof_array[ae] != nullptr);
1322
1323 if (call_opt_stub) {
1324 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::string_IndexOf_Type(),
1325 StubRoutines::_string_indexof_array[ae],
1326 "stringIndexOf", TypePtr::BOTTOM, src_start,
1327 src_count, tgt_start, tgt_count);
1328 result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1329 } else {
1330 result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count,
1331 region, phi, ae);
1332 }
1333 if (result != nullptr) {
1334 // The result is index relative to from_index if substring was found, -1 otherwise.
1335 // Generate code which will fold into cmove.
1336 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1337 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1338
1339 Node* if_lt = generate_slow_guard(bol, nullptr);
1340 if (if_lt != nullptr) {
1341 // result == -1
1342 phi->init_req(3, result);
1343 region->init_req(3, if_lt);
1344 }
1345 if (!stopped()) {
1346 result = _gvn.transform(new AddINode(result, from_index));
1347 phi->init_req(4, result);
1348 region->init_req(4, control());
1349 }
1350 }
1351
1352 set_control(_gvn.transform(region));
1353 record_for_igvn(region);
1354 set_result(_gvn.transform(phi));
1355 clear_upper_avx();
1356
1357 return true;
1358 }
1359
1360 // Create StrIndexOfNode with fast path checks
1361 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1362 RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1363 // Check for substr count > string count
1364 Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1365 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1366 Node* if_gt = generate_slow_guard(bol, nullptr);
1367 if (if_gt != nullptr) {
1368 phi->init_req(1, intcon(-1));
1369 region->init_req(1, if_gt);
1370 }
1371 if (!stopped()) {
1372 // Check for substr count == 0
1373 cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1374 bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1375 Node* if_zero = generate_slow_guard(bol, nullptr);
1376 if (if_zero != nullptr) {
1377 phi->init_req(2, intcon(0));
1378 region->init_req(2, if_zero);
1379 }
1380 }
1381 if (!stopped()) {
1382 return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1383 }
1384 return nullptr;
1385 }
1386
1387 //-----------------------------inline_string_indexOfChar-----------------------
1388 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1389 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1390 return false;
1391 }
1392 if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1393 return false;
1394 }
1395 assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1396 Node* src = argument(0); // byte[]
1397 Node* int_ch = argument(1);
1398 Node* from_index = argument(2);
1399 Node* max = argument(3);
1400
1401 src = must_be_not_null(src, true);
1402
1403 Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1404 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1405 Node* src_count = _gvn.transform(new SubINode(max, from_index));
1406
1407 // Range checks
1408 RegionNode* bailout = create_bailout();
1409 generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U, bailout);
1410 if (check_bailout(bailout)) {
1411 return true;
1412 }
1413
1414 // Check for int_ch >= 0
1415 Node* int_ch_cmp = _gvn.transform(new CmpINode(int_ch, intcon(0)));
1416 Node* int_ch_bol = _gvn.transform(new BoolNode(int_ch_cmp, BoolTest::ge));
1417 {
1418 BuildCutout unless(this, int_ch_bol, PROB_MAX);
1419 uncommon_trap(Deoptimization::Reason_intrinsic,
1420 Deoptimization::Action_maybe_recompile);
1421 }
1422 if (stopped()) {
1423 return true;
1424 }
1425
1426 RegionNode* region = new RegionNode(3);
1427 Node* phi = new PhiNode(region, TypeInt::INT);
1428
1429 Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, int_ch, ae);
1430 C->set_has_split_ifs(true); // Has chance for split-if optimization
1431 _gvn.transform(result);
1432
1433 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1434 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1435
1436 Node* if_lt = generate_slow_guard(bol, nullptr);
1437 if (if_lt != nullptr) {
1438 // result == -1
1439 phi->init_req(2, result);
1440 region->init_req(2, if_lt);
1441 }
1442 if (!stopped()) {
1443 result = _gvn.transform(new AddINode(result, from_index));
1444 phi->init_req(1, result);
1445 region->init_req(1, control());
1446 }
1447 set_control(_gvn.transform(region));
1448 record_for_igvn(region);
1449 set_result(_gvn.transform(phi));
1450 clear_upper_avx();
1451
1452 return true;
1453 }
1454 //---------------------------inline_string_copy---------------------
1455 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1456 // int StringUTF16.compress0(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1457 // int StringUTF16.compress0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1458 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1459 // void StringLatin1.inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1460 // void StringLatin1.inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1461 bool LibraryCallKit::inline_string_copy(bool compress) {
1462 int nargs = 5; // 2 oops, 3 ints
1463 assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1464
1465 Node* src = argument(0);
1466 Node* src_offset = argument(1);
1467 Node* dst = argument(2);
1468 Node* dst_offset = argument(3);
1469 Node* length = argument(4);
1470
1471 // Check for allocation before we add nodes that would confuse
1472 // tightly_coupled_allocation()
1473 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1474
1475 // Figure out the size and type of the elements we will be copying.
1476 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
1477 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
1478 if (src_type == nullptr || dst_type == nullptr) {
1479 return false;
1480 }
1481 BasicType src_elem = src_type->elem()->array_element_basic_type();
1482 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
1483 assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1484 (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1485 "Unsupported array types for inline_string_copy");
1486
1487 src = must_be_not_null(src, true);
1488 dst = must_be_not_null(dst, true);
1489
1490 // Convert char[] offsets to byte[] offsets
1491 bool convert_src = (compress && src_elem == T_BYTE);
1492 bool convert_dst = (!compress && dst_elem == T_BYTE);
1493 if (convert_src) {
1494 src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1495 } else if (convert_dst) {
1496 dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1497 }
1498
1499 // Range checks
1500 RegionNode* bailout = create_bailout();
1501 generate_string_range_check(src, src_offset, length, convert_src, bailout);
1502 generate_string_range_check(dst, dst_offset, length, convert_dst, bailout);
1503 if (check_bailout(bailout)) {
1504 return true;
1505 }
1506
1507 Node* src_start = array_element_address(src, src_offset, src_elem);
1508 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1509 // 'src_start' points to src array + scaled offset
1510 // 'dst_start' points to dst array + scaled offset
1511 Node* count = nullptr;
1512 if (compress) {
1513 count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1514 } else {
1515 inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1516 }
1517
1518 if (alloc != nullptr) {
1519 if (alloc->maybe_set_complete(&_gvn)) {
1520 // "You break it, you buy it."
1521 InitializeNode* init = alloc->initialization();
1522 assert(init->is_complete(), "we just did this");
1523 init->set_complete_with_arraycopy();
1524 assert(dst->is_CheckCastPP(), "sanity");
1525 assert(dst->in(0)->in(0) == init, "dest pinned");
1526 }
1527 // Do not let stores that initialize this object be reordered with
1528 // a subsequent store that would make this object accessible by
1529 // other threads.
1530 // Record what AllocateNode this StoreStore protects so that
1531 // escape analysis can go from the MemBarStoreStoreNode to the
1532 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1533 // based on the escape status of the AllocateNode.
1534 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1535 }
1536 if (compress) {
1537 set_result(_gvn.transform(count));
1538 }
1539 clear_upper_avx();
1540
1541 return true;
1542 }
1543
1544 #ifdef _LP64
1545 #define XTOP ,top() /*additional argument*/
1546 #else //_LP64
1547 #define XTOP /*no additional argument*/
1548 #endif //_LP64
1549
1550 //------------------------inline_string_toBytesU--------------------------
1551 // public static byte[] StringUTF16.toBytes0(char[] value, int off, int len)
1552 bool LibraryCallKit::inline_string_toBytesU() {
1553 // Get the arguments.
1554 assert(callee()->signature()->size() == 3, "character array encoder requires 3 arguments");
1555 Node* value = argument(0);
1556 Node* offset = argument(1);
1557 Node* length = argument(2);
1558
1559 Node* newcopy = nullptr;
1560
1561 // Set the original stack and the reexecute bit for the interpreter to reexecute
1562 // the bytecode that invokes StringUTF16.toBytes0() if deoptimization happens.
1563 { PreserveReexecuteState preexecs(this);
1564 jvms()->set_should_reexecute(true);
1565
1566 value = must_be_not_null(value, true);
1567 RegionNode* bailout = create_bailout();
1568 generate_negative_guard(offset, bailout, nullptr, true);
1569 generate_negative_guard(length, bailout, nullptr, true);
1570 generate_limit_guard(offset, length, load_array_length(value), bailout, true);
1571 // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1572 generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout, true);
1573 if (check_bailout(bailout)) {
1574 return true;
1575 }
1576
1577 Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1578 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1579 newcopy = new_array(klass_node, size, 0); // no arguments to push
1580 AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy);
1581 guarantee(alloc != nullptr, "created above");
1582
1583 // Calculate starting addresses.
1584 Node* src_start = array_element_address(value, offset, T_CHAR);
1585 Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1586
1587 // Check if dst array address is aligned to HeapWordSize
1588 bool aligned = (arrayOopDesc::base_offset_in_bytes(T_BYTE) % HeapWordSize == 0);
1589 // If true, then check if src array address is aligned to HeapWordSize
1590 if (aligned) {
1591 const TypeInt* toffset = gvn().type(offset)->is_int();
1592 aligned = toffset->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) +
1593 toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1594 }
1595
1596 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1597 const char* copyfunc_name = "arraycopy";
1598 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1599 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1600 OptoRuntime::fast_arraycopy_Type(),
1601 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1602 src_start, dst_start, ConvI2X(length) XTOP);
1603 // Do not let reads from the cloned object float above the arraycopy.
1604 if (alloc->maybe_set_complete(&_gvn)) {
1605 // "You break it, you buy it."
1606 InitializeNode* init = alloc->initialization();
1607 assert(init->is_complete(), "we just did this");
1608 init->set_complete_with_arraycopy();
1609 assert(newcopy->is_CheckCastPP(), "sanity");
1610 assert(newcopy->in(0)->in(0) == init, "dest pinned");
1611 }
1612 // Do not let stores that initialize this object be reordered with
1613 // a subsequent store that would make this object accessible by
1614 // other threads.
1615 // Record what AllocateNode this StoreStore protects so that
1616 // escape analysis can go from the MemBarStoreStoreNode to the
1617 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1618 // based on the escape status of the AllocateNode.
1619 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1620 } // original reexecute is set back here
1621
1622 C->set_has_split_ifs(true); // Has chance for split-if optimization
1623 if (!stopped()) {
1624 set_result(newcopy);
1625 }
1626 clear_upper_avx();
1627
1628 return true;
1629 }
1630
1631 //------------------------inline_string_getCharsU--------------------------
1632 // public void StringUTF16.getChars0(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
1633 bool LibraryCallKit::inline_string_getCharsU() {
1634 assert(callee()->signature()->size() == 5, "StringUTF16.getChars0() has 5 arguments");
1635 // Get the arguments.
1636 Node* src = argument(0);
1637 Node* src_begin = argument(1);
1638 Node* src_end = argument(2); // exclusive offset (i < src_end)
1639 Node* dst = argument(3);
1640 Node* dst_begin = argument(4);
1641
1642 // Check for allocation before we add nodes that would confuse
1643 // tightly_coupled_allocation()
1644 AllocateArrayNode* alloc = tightly_coupled_allocation(dst);
1645
1646 // Check if a null path was taken unconditionally.
1647 src = must_be_not_null(src, true);
1648 dst = must_be_not_null(dst, true);
1649 if (stopped()) {
1650 return true;
1651 }
1652
1653 // Get length and convert char[] offset to byte[] offset
1654 Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1655 src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1656
1657 // Range checks
1658 RegionNode* bailout = create_bailout();
1659 generate_string_range_check(src, src_begin, length, true, bailout);
1660 generate_string_range_check(dst, dst_begin, length, false, bailout);
1661 if (check_bailout(bailout)) {
1662 return true;
1663 }
1664
1665 // Calculate starting addresses.
1666 Node* src_start = array_element_address(src, src_begin, T_BYTE);
1667 Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1668
1669 // Check if array addresses are aligned to HeapWordSize
1670 const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1671 const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1672 bool aligned = tsrc->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_BYTE) + tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1673 tdst->is_con() && ((arrayOopDesc::base_offset_in_bytes(T_CHAR) + tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1674
1675 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1676 const char* copyfunc_name = "arraycopy";
1677 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1678 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1679 OptoRuntime::fast_arraycopy_Type(),
1680 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1681 src_start, dst_start, ConvI2X(length) XTOP);
1682 // Do not let reads from the cloned object float above the arraycopy.
1683 if (alloc != nullptr) {
1684 if (alloc->maybe_set_complete(&_gvn)) {
1685 // "You break it, you buy it."
1686 InitializeNode* init = alloc->initialization();
1687 assert(init->is_complete(), "we just did this");
1688 init->set_complete_with_arraycopy();
1689 assert(dst->is_CheckCastPP(), "sanity");
1690 assert(dst->in(0)->in(0) == init, "dest pinned");
1691 }
1692 // Do not let stores that initialize this object be reordered with
1693 // a subsequent store that would make this object accessible by
1694 // other threads.
1695 // Record what AllocateNode this StoreStore protects so that
1696 // escape analysis can go from the MemBarStoreStoreNode to the
1697 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1698 // based on the escape status of the AllocateNode.
1699 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1700 } else {
1701 insert_mem_bar(Op_MemBarCPUOrder);
1702 }
1703
1704 C->set_has_split_ifs(true); // Has chance for split-if optimization
1705 return true;
1706 }
1707
1708 //----------------------inline_string_char_access----------------------------
1709 // Store/Load char to/from byte[] array.
1710 // static void StringUTF16.putChar(byte[] val, int index, int c)
1711 // static char StringUTF16.getChar(byte[] val, int index)
1712 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1713 Node* ch;
1714 if (is_store) {
1715 assert(callee()->signature()->size() == 3, "StringUTF16.putChar() has 3 arguments");
1716 ch = argument(2);
1717 } else {
1718 assert(callee()->signature()->size() == 2, "StringUTF16.getChar() has 2 arguments");
1719 ch = nullptr;
1720 }
1721 Node* value = argument(0);
1722 Node* index = argument(1);
1723
1724 // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1725 // correctly requires matched array shapes.
1726 assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1727 "sanity: byte[] and char[] bases agree");
1728 assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1729 "sanity: byte[] and char[] scales agree");
1730
1731 // Bail when getChar over constants is requested: constant folding would
1732 // reject folding mismatched char access over byte[]. A normal inlining for getChar
1733 // Java method would constant fold nicely instead.
1734 if (!is_store && value->is_Con() && index->is_Con()) {
1735 return false;
1736 }
1737
1738 // Save state and restore on bailout
1739 SavedState old_state(this);
1740
1741 value = must_be_not_null(value, true);
1742
1743 Node* adr = array_element_address(value, index, T_CHAR);
1744 if (adr->is_top()) {
1745 return false;
1746 }
1747 old_state.discard();
1748 if (is_store) {
1749 access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1750 } else {
1751 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);
1752 set_result(ch);
1753 }
1754 return true;
1755 }
1756
1757
1758 //------------------------------inline_math-----------------------------------
1759 // public static double Math.abs(double)
1760 // public static double Math.sqrt(double)
1761 // public static double Math.log(double)
1762 // public static double Math.log10(double)
1763 // public static double Math.round(double)
1764 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1765 Node* arg = argument(0);
1766 Node* n = nullptr;
1767 switch (id) {
1768 case vmIntrinsics::_dabs: n = new AbsDNode( arg); break;
1769 case vmIntrinsics::_dsqrt:
1770 case vmIntrinsics::_dsqrt_strict:
1771 n = new SqrtDNode(C, control(), arg); break;
1772 case vmIntrinsics::_ceil: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1773 case vmIntrinsics::_floor: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1774 case vmIntrinsics::_rint: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1775 case vmIntrinsics::_roundD: n = new RoundDNode(arg); break;
1776 case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, argument(2)); break;
1777 case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1778 default: fatal_unexpected_iid(id); break;
1779 }
1780 set_result(_gvn.transform(n));
1781 return true;
1782 }
1783
1784 //------------------------------inline_math-----------------------------------
1785 // public static float Math.abs(float)
1786 // public static int Math.abs(int)
1787 // public static long Math.abs(long)
1788 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1789 Node* arg = argument(0);
1790 Node* n = nullptr;
1791 switch (id) {
1792 case vmIntrinsics::_fabs: n = new AbsFNode( arg); break;
1793 case vmIntrinsics::_iabs: n = new AbsINode( arg); break;
1794 case vmIntrinsics::_labs: n = new AbsLNode( arg); break;
1795 case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1796 case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1797 case vmIntrinsics::_roundF: n = new RoundFNode(arg); break;
1798 default: fatal_unexpected_iid(id); break;
1799 }
1800 set_result(_gvn.transform(n));
1801 return true;
1802 }
1803
1804 //------------------------------runtime_math-----------------------------
1805 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1806 assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1807 "must be (DD)D or (D)D type");
1808
1809 // Inputs
1810 Node* a = argument(0);
1811 Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? argument(2) : nullptr;
1812
1813 const TypePtr* no_memory_effects = nullptr;
1814 Node* trig = make_runtime_call(RC_LEAF | RC_PURE, call_type, funcAddr, funcName,
1815 no_memory_effects,
1816 a, top(), b, b ? top() : nullptr);
1817 Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1818 #ifdef ASSERT
1819 Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1820 assert(value_top == top(), "second value must be top");
1821 #endif
1822
1823 set_result(value);
1824 return true;
1825 }
1826
1827 //------------------------------inline_math_pow-----------------------------
1828 bool LibraryCallKit::inline_math_pow() {
1829 Node* base = argument(0);
1830 Node* exp = argument(2);
1831
1832 CallNode* pow = new PowDNode(C, base, exp);
1833 set_predefined_input_for_runtime_call(pow);
1834 pow = _gvn.transform(pow)->as_CallLeafPure();
1835 set_predefined_output_for_runtime_call(pow);
1836 Node* result = _gvn.transform(new ProjNode(pow, TypeFunc::Parms + 0));
1837 record_for_igvn(pow);
1838 set_result(result);
1839 return true;
1840 }
1841
1842 //------------------------------inline_math_native-----------------------------
1843 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1844 switch (id) {
1845 case vmIntrinsics::_dsin:
1846 return StubRoutines::dsin() != nullptr ?
1847 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1848 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dsin), "SIN");
1849 case vmIntrinsics::_dcos:
1850 return StubRoutines::dcos() != nullptr ?
1851 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1852 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dcos), "COS");
1853 case vmIntrinsics::_dtan:
1854 return StubRoutines::dtan() != nullptr ?
1855 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1856 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dtan), "TAN");
1857 case vmIntrinsics::_dsinh:
1858 return StubRoutines::dsinh() != nullptr ?
1859 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsinh(), "dsinh") : false;
1860 case vmIntrinsics::_dtanh:
1861 return StubRoutines::dtanh() != nullptr ?
1862 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtanh(), "dtanh") : false;
1863 case vmIntrinsics::_dcbrt:
1864 return StubRoutines::dcbrt() != nullptr ?
1865 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcbrt(), "dcbrt") : false;
1866 case vmIntrinsics::_dexp:
1867 return StubRoutines::dexp() != nullptr ?
1868 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(), "dexp") :
1869 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
1870 case vmIntrinsics::_dlog:
1871 return StubRoutines::dlog() != nullptr ?
1872 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1873 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog), "LOG");
1874 case vmIntrinsics::_dlog10:
1875 return StubRoutines::dlog10() != nullptr ?
1876 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1877 runtime_math(OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dlog10), "LOG10");
1878
1879 case vmIntrinsics::_roundD: return Matcher::match_rule_supported(Op_RoundD) ? inline_double_math(id) : false;
1880 case vmIntrinsics::_ceil:
1881 case vmIntrinsics::_floor:
1882 case vmIntrinsics::_rint: return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1883
1884 case vmIntrinsics::_dsqrt:
1885 case vmIntrinsics::_dsqrt_strict:
1886 return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1887 case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_double_math(id) : false;
1888 case vmIntrinsics::_fabs: return Matcher::match_rule_supported(Op_AbsF) ? inline_math(id) : false;
1889 case vmIntrinsics::_iabs: return Matcher::match_rule_supported(Op_AbsI) ? inline_math(id) : false;
1890 case vmIntrinsics::_labs: return Matcher::match_rule_supported(Op_AbsL) ? inline_math(id) : false;
1891
1892 case vmIntrinsics::_dpow: return inline_math_pow();
1893 case vmIntrinsics::_dcopySign: return inline_double_math(id);
1894 case vmIntrinsics::_fcopySign: return inline_math(id);
1895 case vmIntrinsics::_dsignum: return Matcher::match_rule_supported(Op_SignumD) ? inline_double_math(id) : false;
1896 case vmIntrinsics::_fsignum: return Matcher::match_rule_supported(Op_SignumF) ? inline_math(id) : false;
1897 case vmIntrinsics::_roundF: return Matcher::match_rule_supported(Op_RoundF) ? inline_math(id) : false;
1898
1899 // These intrinsics are not yet correctly implemented
1900 case vmIntrinsics::_datan2:
1901 return false;
1902
1903 default:
1904 fatal_unexpected_iid(id);
1905 return false;
1906 }
1907 }
1908
1909 //----------------------------inline_notify-----------------------------------*
1910 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1911 const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1912 address func;
1913 if (id == vmIntrinsics::_notify) {
1914 func = OptoRuntime::monitor_notify_Java();
1915 } else {
1916 func = OptoRuntime::monitor_notifyAll_Java();
1917 }
1918 Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, nullptr, TypeRawPtr::BOTTOM, argument(0));
1919 make_slow_call_ex(call, env()->Throwable_klass(), false);
1920 return true;
1921 }
1922
1923
1924 //----------------------------inline_min_max-----------------------------------
1925 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1926 Node* a = nullptr;
1927 Node* b = nullptr;
1928 Node* n = nullptr;
1929 switch (id) {
1930 case vmIntrinsics::_min:
1931 case vmIntrinsics::_max:
1932 case vmIntrinsics::_minF:
1933 case vmIntrinsics::_maxF:
1934 case vmIntrinsics::_minF_strict:
1935 case vmIntrinsics::_maxF_strict:
1936 case vmIntrinsics::_min_strict:
1937 case vmIntrinsics::_max_strict:
1938 assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
1939 a = argument(0);
1940 b = argument(1);
1941 break;
1942 case vmIntrinsics::_minD:
1943 case vmIntrinsics::_maxD:
1944 case vmIntrinsics::_minD_strict:
1945 case vmIntrinsics::_maxD_strict:
1946 assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
1947 a = argument(0);
1948 b = argument(2);
1949 break;
1950 case vmIntrinsics::_minL:
1951 case vmIntrinsics::_maxL:
1952 assert(callee()->signature()->size() == 4, "minL/maxL has 2 parameters of size 2 each.");
1953 a = argument(0);
1954 b = argument(2);
1955 break;
1956 default:
1957 fatal_unexpected_iid(id);
1958 break;
1959 }
1960
1961 switch (id) {
1962 case vmIntrinsics::_min:
1963 case vmIntrinsics::_min_strict:
1964 n = new MinINode(a, b);
1965 break;
1966 case vmIntrinsics::_max:
1967 case vmIntrinsics::_max_strict:
1968 n = new MaxINode(a, b);
1969 break;
1970 case vmIntrinsics::_minF:
1971 case vmIntrinsics::_minF_strict:
1972 n = new MinFNode(a, b);
1973 break;
1974 case vmIntrinsics::_maxF:
1975 case vmIntrinsics::_maxF_strict:
1976 n = new MaxFNode(a, b);
1977 break;
1978 case vmIntrinsics::_minD:
1979 case vmIntrinsics::_minD_strict:
1980 n = new MinDNode(a, b);
1981 break;
1982 case vmIntrinsics::_maxD:
1983 case vmIntrinsics::_maxD_strict:
1984 n = new MaxDNode(a, b);
1985 break;
1986 case vmIntrinsics::_minL:
1987 n = new MinLNode(_gvn.C, a, b);
1988 break;
1989 case vmIntrinsics::_maxL:
1990 n = new MaxLNode(_gvn.C, a, b);
1991 break;
1992 default:
1993 fatal_unexpected_iid(id);
1994 break;
1995 }
1996
1997 set_result(_gvn.transform(n));
1998 return true;
1999 }
2000
2001 bool LibraryCallKit::inline_math_mathExact(Node* math, Node* test) {
2002 if (builtin_throw_too_many_traps(Deoptimization::Reason_intrinsic,
2003 env()->ArithmeticException_instance())) {
2004 // It has been already too many times, but we cannot use builtin_throw (e.g. we care about backtraces),
2005 // so let's bail out intrinsic rather than risking deopting again.
2006 return false;
2007 }
2008
2009 Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
2010 IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
2011 Node* fast_path = _gvn.transform( new IfFalseNode(check));
2012 Node* slow_path = _gvn.transform( new IfTrueNode(check) );
2013
2014 {
2015 PreserveJVMState pjvms(this);
2016 PreserveReexecuteState preexecs(this);
2017 jvms()->set_should_reexecute(true);
2018
2019 set_control(slow_path);
2020 set_i_o(i_o());
2021
2022 builtin_throw(Deoptimization::Reason_intrinsic,
2023 env()->ArithmeticException_instance(),
2024 /*allow_too_many_traps*/ false);
2025 }
2026
2027 set_control(fast_path);
2028 set_result(math);
2029 return true;
2030 }
2031
2032 template <typename OverflowOp>
2033 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
2034 typedef typename OverflowOp::MathOp MathOp;
2035
2036 MathOp* mathOp = new MathOp(arg1, arg2);
2037 Node* operation = _gvn.transform( mathOp );
2038 Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
2039 return inline_math_mathExact(operation, ofcheck);
2040 }
2041
2042 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
2043 return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
2044 }
2045
2046 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
2047 return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
2048 }
2049
2050 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
2051 return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
2052 }
2053
2054 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
2055 return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
2056 }
2057
2058 bool LibraryCallKit::inline_math_negateExactI() {
2059 return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
2060 }
2061
2062 bool LibraryCallKit::inline_math_negateExactL() {
2063 return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
2064 }
2065
2066 bool LibraryCallKit::inline_math_multiplyExactI() {
2067 return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
2068 }
2069
2070 bool LibraryCallKit::inline_math_multiplyExactL() {
2071 return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
2072 }
2073
2074 bool LibraryCallKit::inline_math_multiplyHigh() {
2075 set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
2076 return true;
2077 }
2078
2079 bool LibraryCallKit::inline_math_unsignedMultiplyHigh() {
2080 set_result(_gvn.transform(new UMulHiLNode(argument(0), argument(2))));
2081 return true;
2082 }
2083
2084 inline int
2085 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
2086 const TypePtr* base_type = TypePtr::NULL_PTR;
2087 if (base != nullptr) base_type = _gvn.type(base)->isa_ptr();
2088 if (base_type == nullptr) {
2089 // Unknown type.
2090 return Type::AnyPtr;
2091 } else if (_gvn.type(base->uncast()) == TypePtr::NULL_PTR) {
2092 // Since this is a null+long form, we have to switch to a rawptr.
2093 base = _gvn.transform(new CastX2PNode(offset));
2094 offset = MakeConX(0);
2095 return Type::RawPtr;
2096 } else if (base_type->base() == Type::RawPtr) {
2097 return Type::RawPtr;
2098 } else if (base_type->isa_oopptr()) {
2099 // Base is never null => always a heap address.
2100 if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2101 return Type::OopPtr;
2102 }
2103 // Offset is small => always a heap address.
2104 const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2105 if (offset_type != nullptr &&
2106 base_type->offset() == 0 && // (should always be?)
2107 offset_type->_lo >= 0 &&
2108 !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2109 return Type::OopPtr;
2110 } else if (type == T_OBJECT) {
2111 // off heap access to an oop doesn't make any sense. Has to be on
2112 // heap.
2113 return Type::OopPtr;
2114 }
2115 // Otherwise, it might either be oop+off or null+addr.
2116 return Type::AnyPtr;
2117 } else {
2118 // No information:
2119 return Type::AnyPtr;
2120 }
2121 }
2122
2123 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, BasicType type, bool can_cast) {
2124 Node* uncasted_base = base;
2125 int kind = classify_unsafe_addr(uncasted_base, offset, type);
2126 if (kind == Type::RawPtr) {
2127 return off_heap_plus_addr(uncasted_base, offset);
2128 } else if (kind == Type::AnyPtr) {
2129 assert(base == uncasted_base, "unexpected base change");
2130 if (can_cast) {
2131 if (!_gvn.type(base)->speculative_maybe_null() &&
2132 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2133 // According to profiling, this access is always on
2134 // heap. Casting the base to not null and thus avoiding membars
2135 // around the access should allow better optimizations
2136 Node* null_ctl = top();
2137 base = null_check_oop(base, &null_ctl, true, true, true);
2138 assert(null_ctl->is_top(), "no null control here");
2139 return basic_plus_adr(base, offset);
2140 } else if (_gvn.type(base)->speculative_always_null() &&
2141 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2142 // According to profiling, this access is always off
2143 // heap.
2144 base = null_assert(base);
2145 Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2146 offset = MakeConX(0);
2147 return off_heap_plus_addr(raw_base, offset);
2148 }
2149 }
2150 // We don't know if it's an on heap or off heap access. Fall back
2151 // to raw memory access.
2152 Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2153 return off_heap_plus_addr(raw, offset);
2154 } else {
2155 assert(base == uncasted_base, "unexpected base change");
2156 // We know it's an on heap access so base can't be null
2157 if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2158 base = must_be_not_null(base, true);
2159 }
2160 return basic_plus_adr(base, offset);
2161 }
2162 }
2163
2164 //--------------------------inline_number_methods-----------------------------
2165 // inline int Integer.numberOfLeadingZeros(int)
2166 // inline int Long.numberOfLeadingZeros(long)
2167 //
2168 // inline int Integer.numberOfTrailingZeros(int)
2169 // inline int Long.numberOfTrailingZeros(long)
2170 //
2171 // inline int Integer.bitCount(int)
2172 // inline int Long.bitCount(long)
2173 //
2174 // inline char Character.reverseBytes(char)
2175 // inline short Short.reverseBytes(short)
2176 // inline int Integer.reverseBytes(int)
2177 // inline long Long.reverseBytes(long)
2178 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2179 Node* arg = argument(0);
2180 Node* n = nullptr;
2181 switch (id) {
2182 case vmIntrinsics::_numberOfLeadingZeros_i: n = new CountLeadingZerosINode( arg); break;
2183 case vmIntrinsics::_numberOfLeadingZeros_l: n = new CountLeadingZerosLNode( arg); break;
2184 case vmIntrinsics::_numberOfTrailingZeros_i: n = new CountTrailingZerosINode(arg); break;
2185 case vmIntrinsics::_numberOfTrailingZeros_l: n = new CountTrailingZerosLNode(arg); break;
2186 case vmIntrinsics::_bitCount_i: n = new PopCountINode( arg); break;
2187 case vmIntrinsics::_bitCount_l: n = new PopCountLNode( arg); break;
2188 case vmIntrinsics::_reverseBytes_c: n = new ReverseBytesUSNode( arg); break;
2189 case vmIntrinsics::_reverseBytes_s: n = new ReverseBytesSNode( arg); break;
2190 case vmIntrinsics::_reverseBytes_i: n = new ReverseBytesINode( arg); break;
2191 case vmIntrinsics::_reverseBytes_l: n = new ReverseBytesLNode( arg); break;
2192 case vmIntrinsics::_reverse_i: n = new ReverseINode( arg); break;
2193 case vmIntrinsics::_reverse_l: n = new ReverseLNode( arg); break;
2194 default: fatal_unexpected_iid(id); break;
2195 }
2196 set_result(_gvn.transform(n));
2197 return true;
2198 }
2199
2200 //--------------------------inline_bitshuffle_methods-----------------------------
2201 // inline int Integer.compress(int, int)
2202 // inline int Integer.expand(int, int)
2203 // inline long Long.compress(long, long)
2204 // inline long Long.expand(long, long)
2205 bool LibraryCallKit::inline_bitshuffle_methods(vmIntrinsics::ID id) {
2206 Node* n = nullptr;
2207 switch (id) {
2208 case vmIntrinsics::_compress_i: n = new CompressBitsNode(argument(0), argument(1), TypeInt::INT); break;
2209 case vmIntrinsics::_expand_i: n = new ExpandBitsNode(argument(0), argument(1), TypeInt::INT); break;
2210 case vmIntrinsics::_compress_l: n = new CompressBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2211 case vmIntrinsics::_expand_l: n = new ExpandBitsNode(argument(0), argument(2), TypeLong::LONG); break;
2212 default: fatal_unexpected_iid(id); break;
2213 }
2214 set_result(_gvn.transform(n));
2215 return true;
2216 }
2217
2218 //--------------------------inline_number_methods-----------------------------
2219 // inline int Integer.compareUnsigned(int, int)
2220 // inline int Long.compareUnsigned(long, long)
2221 bool LibraryCallKit::inline_compare_unsigned(vmIntrinsics::ID id) {
2222 Node* arg1 = argument(0);
2223 Node* arg2 = (id == vmIntrinsics::_compareUnsigned_l) ? argument(2) : argument(1);
2224 Node* n = nullptr;
2225 switch (id) {
2226 case vmIntrinsics::_compareUnsigned_i: n = new CmpU3Node(arg1, arg2); break;
2227 case vmIntrinsics::_compareUnsigned_l: n = new CmpUL3Node(arg1, arg2); break;
2228 default: fatal_unexpected_iid(id); break;
2229 }
2230 set_result(_gvn.transform(n));
2231 return true;
2232 }
2233
2234 //--------------------------inline_unsigned_divmod_methods-----------------------------
2235 // inline int Integer.divideUnsigned(int, int)
2236 // inline int Integer.remainderUnsigned(int, int)
2237 // inline long Long.divideUnsigned(long, long)
2238 // inline long Long.remainderUnsigned(long, long)
2239 bool LibraryCallKit::inline_divmod_methods(vmIntrinsics::ID id) {
2240 Node* n = nullptr;
2241 switch (id) {
2242 case vmIntrinsics::_divideUnsigned_i: {
2243 zero_check_int(argument(1));
2244 // Compile-time detect of null-exception
2245 if (stopped()) {
2246 return true; // keep the graph constructed so far
2247 }
2248 n = new UDivINode(control(), argument(0), argument(1));
2249 break;
2250 }
2251 case vmIntrinsics::_divideUnsigned_l: {
2252 zero_check_long(argument(2));
2253 // Compile-time detect of null-exception
2254 if (stopped()) {
2255 return true; // keep the graph constructed so far
2256 }
2257 n = new UDivLNode(control(), argument(0), argument(2));
2258 break;
2259 }
2260 case vmIntrinsics::_remainderUnsigned_i: {
2261 zero_check_int(argument(1));
2262 // Compile-time detect of null-exception
2263 if (stopped()) {
2264 return true; // keep the graph constructed so far
2265 }
2266 n = new UModINode(control(), argument(0), argument(1));
2267 break;
2268 }
2269 case vmIntrinsics::_remainderUnsigned_l: {
2270 zero_check_long(argument(2));
2271 // Compile-time detect of null-exception
2272 if (stopped()) {
2273 return true; // keep the graph constructed so far
2274 }
2275 n = new UModLNode(control(), argument(0), argument(2));
2276 break;
2277 }
2278 default: fatal_unexpected_iid(id); break;
2279 }
2280 set_result(_gvn.transform(n));
2281 return true;
2282 }
2283
2284 //----------------------------inline_unsafe_access----------------------------
2285
2286 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2287 // Attempt to infer a sharper value type from the offset and base type.
2288 ciKlass* sharpened_klass = nullptr;
2289
2290 // See if it is an instance field, with an object type.
2291 if (alias_type->field() != nullptr) {
2292 if (alias_type->field()->type()->is_klass()) {
2293 sharpened_klass = alias_type->field()->type()->as_klass();
2294 }
2295 }
2296
2297 const TypeOopPtr* result = nullptr;
2298 // See if it is a narrow oop array.
2299 if (adr_type->isa_aryptr()) {
2300 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2301 const TypeOopPtr* elem_type = adr_type->is_aryptr()->elem()->make_oopptr();
2302 if (elem_type != nullptr && elem_type->is_loaded()) {
2303 // Sharpen the value type.
2304 result = elem_type;
2305 }
2306 }
2307 }
2308
2309 // The sharpened class might be unloaded if there is no class loader
2310 // contraint in place.
2311 if (result == nullptr && sharpened_klass != nullptr && sharpened_klass->is_loaded()) {
2312 // Sharpen the value type.
2313 result = TypeOopPtr::make_from_klass(sharpened_klass);
2314 }
2315 if (result != nullptr) {
2316 #ifndef PRODUCT
2317 if (C->print_intrinsics() || C->print_inlining()) {
2318 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2319 tty->print(" sharpened value: "); result->dump(); tty->cr();
2320 }
2321 #endif
2322 }
2323 return result;
2324 }
2325
2326 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2327 switch (kind) {
2328 case Relaxed:
2329 return MO_UNORDERED;
2330 case Opaque:
2331 return MO_RELAXED;
2332 case Acquire:
2333 return MO_ACQUIRE;
2334 case Release:
2335 return MO_RELEASE;
2336 case Volatile:
2337 return MO_SEQ_CST;
2338 default:
2339 ShouldNotReachHere();
2340 return 0;
2341 }
2342 }
2343
2344 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2345 if (callee()->is_static()) return false; // caller must have the capability!
2346 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2347 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2348 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2349 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2350
2351 if (is_reference_type(type)) {
2352 decorators |= ON_UNKNOWN_OOP_REF;
2353 }
2354
2355 if (unaligned) {
2356 decorators |= C2_UNALIGNED;
2357 }
2358
2359 #ifndef PRODUCT
2360 {
2361 ResourceMark rm;
2362 // Check the signatures.
2363 ciSignature* sig = callee()->signature();
2364 #ifdef ASSERT
2365 if (!is_store) {
2366 // Object getReference(Object base, int/long offset), etc.
2367 BasicType rtype = sig->return_type()->basic_type();
2368 assert(rtype == type, "getter must return the expected value");
2369 assert(sig->count() == 2, "oop getter has 2 arguments");
2370 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2371 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2372 } else {
2373 // void putReference(Object base, int/long offset, Object x), etc.
2374 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2375 assert(sig->count() == 3, "oop putter has 3 arguments");
2376 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2377 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2378 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2379 assert(vtype == type, "putter must accept the expected value");
2380 }
2381 #endif // ASSERT
2382 }
2383 #endif //PRODUCT
2384
2385 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2386
2387 Node* receiver = argument(0); // type: oop
2388
2389 // Build address expression.
2390 Node* heap_base_oop = top();
2391
2392 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2393 Node* base = argument(1); // type: oop
2394 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2395 Node* offset = argument(2); // type: long
2396 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2397 // to be plain byte offsets, which are also the same as those accepted
2398 // by oopDesc::field_addr.
2399 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2400 "fieldOffset must be byte-scaled");
2401 // 32-bit machines ignore the high half!
2402 offset = ConvL2X(offset);
2403
2404 // Save state and restore on bailout
2405 SavedState old_state(this);
2406
2407 Node* adr = make_unsafe_address(base, offset, type, kind == Relaxed);
2408 assert(!stopped(), "Inlining of unsafe access failed: address construction stopped unexpectedly");
2409
2410 bool is_non_heap_access = (_gvn.type(base->uncast())->isa_ptr() == TypePtr::NULL_PTR);
2411 if (is_non_heap_access) {
2412 if (type != T_OBJECT) {
2413 decorators |= IN_NATIVE; // off-heap primitive access
2414 } else {
2415 return false; // off-heap oop accesses are not supported
2416 }
2417 } else {
2418 heap_base_oop = base; // on-heap or mixed access
2419 }
2420
2421 // Can base be null? Otherwise, always on-heap access.
2422 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2423
2424 assert(!is_non_heap_access || can_access_non_heap, "sanity"); // is_non_heap_access implies can_access_non_heap
2425
2426 if (!can_access_non_heap) {
2427 decorators |= IN_HEAP;
2428 }
2429
2430 Node* val = is_store ? argument(4) : nullptr;
2431
2432 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2433 if (adr_type == TypePtr::NULL_PTR) {
2434 return false; // off-heap access with zero address
2435 }
2436
2437 // Try to categorize the address.
2438 Compile::AliasType* alias_type = C->alias_type(adr_type);
2439 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2440
2441 assert((alias_type->index() == Compile::AliasIdxRaw) ==
2442 (is_non_heap_access || (can_access_non_heap && alias_type->field() == nullptr)), "wrong alias");
2443
2444 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2445 alias_type->adr_type() == TypeAryPtr::RANGE) {
2446 return false; // not supported
2447 }
2448
2449 bool mismatched = false;
2450 BasicType bt = alias_type->basic_type();
2451 if (bt != T_ILLEGAL) {
2452 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2453 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2454 // Alias type doesn't differentiate between byte[] and boolean[]).
2455 // Use address type to get the element type.
2456 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2457 }
2458 if (is_reference_type(bt, true)) {
2459 // accessing an array field with getReference is not a mismatch
2460 bt = T_OBJECT;
2461 }
2462 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2463 // Don't intrinsify mismatched object accesses
2464 return false;
2465 }
2466 mismatched = (bt != type);
2467 } else if (alias_type->adr_type()->isa_oopptr()) {
2468 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2469 }
2470
2471 old_state.discard();
2472 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2473
2474 if (mismatched) {
2475 decorators |= C2_MISMATCHED;
2476 }
2477
2478 // First guess at the value type.
2479 const Type *value_type = Type::get_const_basic_type(type);
2480
2481 // Figure out the memory ordering.
2482 decorators |= mo_decorator_for_access_kind(kind);
2483
2484 if (!is_store) {
2485 if (type == T_OBJECT) {
2486 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2487 if (tjp != nullptr) {
2488 value_type = tjp;
2489 }
2490 } else if (type == T_BOOLEAN) {
2491 if (mismatched || alias_type->index() == Compile::AliasIdxRaw) {
2492 value_type = TypeInt::UBYTE;
2493 }
2494 }
2495 }
2496
2497 receiver = null_check(receiver);
2498 if (stopped()) {
2499 return true;
2500 }
2501 // Heap pointers get a null-check from the interpreter,
2502 // as a courtesy. However, this is not guaranteed by Unsafe,
2503 // and it is not possible to fully distinguish unintended nulls
2504 // from intended ones in this API.
2505
2506 if (!is_store) {
2507 Node* p = nullptr;
2508 // Try to constant fold a load from a constant field
2509 ciField* field = alias_type->field();
2510 if (heap_base_oop != top() && field != nullptr && field->is_constant() && !mismatched) {
2511 // final or stable field
2512 p = make_constant_from_field(field, heap_base_oop);
2513 }
2514
2515 if (p == nullptr) { // Could not constant fold the load
2516 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2517 }
2518 if (type == T_ADDRESS) {
2519 p = gvn().transform(new CastP2XNode(nullptr, p));
2520 p = ConvX2UL(p);
2521 } else if (type == T_BOOLEAN) {
2522 // Truncate boolean values returned by unsafe operations.
2523 p = gvn().transform(new AndINode(p, gvn().intcon(0x1)));
2524 }
2525 // The load node has the control of the preceding MemBarCPUOrder. All
2526 // following nodes will have the control of the MemBarCPUOrder inserted at
2527 // the end of this method. So, pushing the load onto the stack at a later
2528 // point is fine.
2529 set_result(p);
2530 } else {
2531 if (bt == T_ADDRESS) {
2532 // Repackage the long as a pointer.
2533 val = ConvL2X(val);
2534 val = gvn().transform(new CastX2PNode(val));
2535 }
2536 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2537 }
2538
2539 return true;
2540 }
2541
2542 //----------------------------inline_unsafe_load_store----------------------------
2543 // This method serves a couple of different customers (depending on LoadStoreKind):
2544 //
2545 // LS_cmp_swap:
2546 //
2547 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2548 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2549 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2550 //
2551 // LS_cmp_swap_weak:
2552 //
2553 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2554 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2555 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2556 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2557 //
2558 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2559 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2560 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2561 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2562 //
2563 // boolean weakCompareAndSetLong( Object o, long offset, long expected, long x);
2564 // boolean weakCompareAndSetLongPlain( Object o, long offset, long expected, long x);
2565 // boolean weakCompareAndSetLongAcquire( Object o, long offset, long expected, long x);
2566 // boolean weakCompareAndSetLongRelease( Object o, long offset, long expected, long x);
2567 //
2568 // LS_cmp_exchange:
2569 //
2570 // Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2571 // Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2572 // Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2573 //
2574 // Object compareAndExchangeIntVolatile( Object o, long offset, Object expected, Object x);
2575 // Object compareAndExchangeIntAcquire( Object o, long offset, Object expected, Object x);
2576 // Object compareAndExchangeIntRelease( Object o, long offset, Object expected, Object x);
2577 //
2578 // Object compareAndExchangeLongVolatile( Object o, long offset, Object expected, Object x);
2579 // Object compareAndExchangeLongAcquire( Object o, long offset, Object expected, Object x);
2580 // Object compareAndExchangeLongRelease( Object o, long offset, Object expected, Object x);
2581 //
2582 // LS_get_add:
2583 //
2584 // int getAndAddInt( Object o, long offset, int delta)
2585 // long getAndAddLong(Object o, long offset, long delta)
2586 //
2587 // LS_get_set:
2588 //
2589 // int getAndSet(Object o, long offset, int newValue)
2590 // long getAndSet(Object o, long offset, long newValue)
2591 // Object getAndSet(Object o, long offset, Object newValue)
2592 //
2593 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2594 // This basic scheme here is the same as inline_unsafe_access, but
2595 // differs in enough details that combining them would make the code
2596 // overly confusing. (This is a true fact! I originally combined
2597 // them, but even I was confused by it!) As much code/comments as
2598 // possible are retained from inline_unsafe_access though to make
2599 // the correspondences clearer. - dl
2600
2601 if (callee()->is_static()) return false; // caller must have the capability!
2602
2603 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2604 decorators |= mo_decorator_for_access_kind(access_kind);
2605
2606 #ifndef PRODUCT
2607 BasicType rtype;
2608 {
2609 ResourceMark rm;
2610 // Check the signatures.
2611 ciSignature* sig = callee()->signature();
2612 rtype = sig->return_type()->basic_type();
2613 switch(kind) {
2614 case LS_get_add:
2615 case LS_get_set: {
2616 // Check the signatures.
2617 #ifdef ASSERT
2618 assert(rtype == type, "get and set must return the expected type");
2619 assert(sig->count() == 3, "get and set has 3 arguments");
2620 assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2621 assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2622 assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2623 assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2624 #endif // ASSERT
2625 break;
2626 }
2627 case LS_cmp_swap:
2628 case LS_cmp_swap_weak: {
2629 // Check the signatures.
2630 #ifdef ASSERT
2631 assert(rtype == T_BOOLEAN, "CAS must return boolean");
2632 assert(sig->count() == 4, "CAS has 4 arguments");
2633 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2634 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2635 #endif // ASSERT
2636 break;
2637 }
2638 case LS_cmp_exchange: {
2639 // Check the signatures.
2640 #ifdef ASSERT
2641 assert(rtype == type, "CAS must return the expected type");
2642 assert(sig->count() == 4, "CAS has 4 arguments");
2643 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2644 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2645 #endif // ASSERT
2646 break;
2647 }
2648 default:
2649 ShouldNotReachHere();
2650 }
2651 }
2652 #endif //PRODUCT
2653
2654 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2655
2656 // Get arguments:
2657 Node* receiver = nullptr;
2658 Node* base = nullptr;
2659 Node* offset = nullptr;
2660 Node* oldval = nullptr;
2661 Node* newval = nullptr;
2662 switch(kind) {
2663 case LS_cmp_swap:
2664 case LS_cmp_swap_weak:
2665 case LS_cmp_exchange: {
2666 const bool two_slot_type = type2size[type] == 2;
2667 receiver = argument(0); // type: oop
2668 base = argument(1); // type: oop
2669 offset = argument(2); // type: long
2670 oldval = argument(4); // type: oop, int, or long
2671 newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long
2672 break;
2673 }
2674 case LS_get_add:
2675 case LS_get_set: {
2676 receiver = argument(0); // type: oop
2677 base = argument(1); // type: oop
2678 offset = argument(2); // type: long
2679 oldval = nullptr;
2680 newval = argument(4); // type: oop, int, or long
2681 break;
2682 }
2683 default:
2684 ShouldNotReachHere();
2685 }
2686
2687 // Build field offset expression.
2688 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2689 // to be plain byte offsets, which are also the same as those accepted
2690 // by oopDesc::field_addr.
2691 assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2692 // 32-bit machines ignore the high half of long offsets
2693 offset = ConvL2X(offset);
2694 // Save state and restore on bailout
2695 SavedState old_state(this);
2696 Node* adr = make_unsafe_address(base, offset,type, false);
2697 const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2698
2699 Compile::AliasType* alias_type = C->alias_type(adr_type);
2700 BasicType bt = alias_type->basic_type();
2701 if (bt != T_ILLEGAL &&
2702 (is_reference_type(bt) != (type == T_OBJECT))) {
2703 // Don't intrinsify mismatched object accesses.
2704 return false;
2705 }
2706
2707 old_state.discard();
2708
2709 // For CAS, unlike inline_unsafe_access, there seems no point in
2710 // trying to refine types. Just use the coarse types here.
2711 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2712 const Type *value_type = Type::get_const_basic_type(type);
2713
2714 switch (kind) {
2715 case LS_get_set:
2716 case LS_cmp_exchange: {
2717 if (type == T_OBJECT) {
2718 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2719 if (tjp != nullptr) {
2720 value_type = tjp;
2721 }
2722 }
2723 break;
2724 }
2725 case LS_cmp_swap:
2726 case LS_cmp_swap_weak:
2727 case LS_get_add:
2728 break;
2729 default:
2730 ShouldNotReachHere();
2731 }
2732
2733 // Null check receiver.
2734 receiver = null_check(receiver);
2735 if (stopped()) {
2736 return true;
2737 }
2738
2739 int alias_idx = C->get_alias_index(adr_type);
2740
2741 if (is_reference_type(type)) {
2742 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2743
2744 // Transformation of a value which could be null pointer (CastPP #null)
2745 // could be delayed during Parse (for example, in adjust_map_after_if()).
2746 // Execute transformation here to avoid barrier generation in such case.
2747 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2748 newval = _gvn.makecon(TypePtr::NULL_PTR);
2749
2750 if (oldval != nullptr && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2751 // Refine the value to a null constant, when it is known to be null
2752 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2753 }
2754 }
2755
2756 Node* result = nullptr;
2757 switch (kind) {
2758 case LS_cmp_exchange: {
2759 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2760 oldval, newval, value_type, type, decorators);
2761 break;
2762 }
2763 case LS_cmp_swap_weak:
2764 decorators |= C2_WEAK_CMPXCHG;
2765 case LS_cmp_swap: {
2766 result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
2767 oldval, newval, value_type, type, decorators);
2768 break;
2769 }
2770 case LS_get_set: {
2771 result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
2772 newval, value_type, type, decorators);
2773 break;
2774 }
2775 case LS_get_add: {
2776 result = access_atomic_add_at(base, adr, adr_type, alias_idx,
2777 newval, value_type, type, decorators);
2778 break;
2779 }
2780 default:
2781 ShouldNotReachHere();
2782 }
2783
2784 assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2785 set_result(result);
2786 return true;
2787 }
2788
2789 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
2790 // Regardless of form, don't allow previous ld/st to move down,
2791 // then issue acquire, release, or volatile mem_bar.
2792 insert_mem_bar(Op_MemBarCPUOrder);
2793 switch(id) {
2794 case vmIntrinsics::_loadFence:
2795 insert_mem_bar(Op_LoadFence);
2796 return true;
2797 case vmIntrinsics::_storeFence:
2798 insert_mem_bar(Op_StoreFence);
2799 return true;
2800 case vmIntrinsics::_storeStoreFence:
2801 insert_mem_bar(Op_StoreStoreFence);
2802 return true;
2803 case vmIntrinsics::_fullFence:
2804 insert_mem_bar(Op_MemBarFull);
2805 return true;
2806 default:
2807 fatal_unexpected_iid(id);
2808 return false;
2809 }
2810 }
2811
2812 bool LibraryCallKit::inline_onspinwait() {
2813 insert_mem_bar(Op_OnSpinWait);
2814 return true;
2815 }
2816
2817 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2818 if (!kls->is_Con()) {
2819 return true;
2820 }
2821 const TypeInstKlassPtr* klsptr = kls->bottom_type()->isa_instklassptr();
2822 if (klsptr == nullptr) {
2823 return true;
2824 }
2825 ciInstanceKlass* ik = klsptr->instance_klass();
2826 // don't need a guard for a klass that is already initialized
2827 return !ik->is_initialized();
2828 }
2829
2830 //----------------------------inline_unsafe_writeback0-------------------------
2831 // public native void Unsafe.writeback0(long address)
2832 bool LibraryCallKit::inline_unsafe_writeback0() {
2833 if (!Matcher::has_match_rule(Op_CacheWB)) {
2834 return false;
2835 }
2836 #ifndef PRODUCT
2837 assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
2838 assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
2839 ciSignature* sig = callee()->signature();
2840 assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
2841 #endif
2842 null_check_receiver(); // null-check, then ignore
2843 Node *addr = argument(1);
2844 addr = new CastX2PNode(addr);
2845 addr = _gvn.transform(addr);
2846 Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
2847 flush = _gvn.transform(flush);
2848 set_memory(flush, TypeRawPtr::BOTTOM);
2849 return true;
2850 }
2851
2852 //----------------------------inline_unsafe_writeback0-------------------------
2853 // public native void Unsafe.writeback0(long address)
2854 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
2855 if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
2856 return false;
2857 }
2858 if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
2859 return false;
2860 }
2861 #ifndef PRODUCT
2862 assert(Matcher::has_match_rule(Op_CacheWB),
2863 (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
2864 : "found match rule for CacheWBPostSync but not CacheWB"));
2865
2866 #endif
2867 null_check_receiver(); // null-check, then ignore
2868 Node *sync;
2869 if (is_pre) {
2870 sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2871 } else {
2872 sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2873 }
2874 sync = _gvn.transform(sync);
2875 set_memory(sync, TypeRawPtr::BOTTOM);
2876 return true;
2877 }
2878
2879 //----------------------------inline_unsafe_allocate---------------------------
2880 // public native Object Unsafe.allocateInstance(Class<?> cls);
2881 bool LibraryCallKit::inline_unsafe_allocate() {
2882
2883 #if INCLUDE_JVMTI
2884 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
2885 return false;
2886 }
2887 #endif //INCLUDE_JVMTI
2888
2889 if (callee()->is_static()) return false; // caller must have the capability!
2890
2891 null_check_receiver(); // null-check, then ignore
2892 Node* cls = null_check(argument(1));
2893 if (stopped()) return true;
2894
2895 Node* kls = load_klass_from_mirror(cls, false, nullptr, 0);
2896 kls = null_check(kls);
2897 if (stopped()) return true; // argument was like int.class
2898
2899 #if INCLUDE_JVMTI
2900 // Don't try to access new allocated obj in the intrinsic.
2901 // It causes perfomance issues even when jvmti event VmObjectAlloc is disabled.
2902 // Deoptimize and allocate in interpreter instead.
2903 Node* addr = makecon(TypeRawPtr::make((address) &JvmtiExport::_should_notify_object_alloc));
2904 Node* should_post_vm_object_alloc = make_load(this->control(), addr, TypeInt::INT, T_INT, MemNode::unordered);
2905 Node* chk = _gvn.transform(new CmpINode(should_post_vm_object_alloc, intcon(0)));
2906 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
2907 {
2908 BuildCutout unless(this, tst, PROB_MAX);
2909 uncommon_trap(Deoptimization::Reason_intrinsic,
2910 Deoptimization::Action_make_not_entrant);
2911 }
2912 if (stopped()) {
2913 return true;
2914 }
2915 #endif //INCLUDE_JVMTI
2916
2917 Node* test = nullptr;
2918 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2919 // Note: The argument might still be an illegal value like
2920 // Serializable.class or Object[].class. The runtime will handle it.
2921 // But we must make an explicit check for initialization.
2922 Node* insp = off_heap_plus_addr(kls, in_bytes(InstanceKlass::init_state_offset()));
2923 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2924 // can generate code to load it as unsigned byte.
2925 Node* inst = make_load(nullptr, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::acquire);
2926 Node* bits = intcon(InstanceKlass::fully_initialized);
2927 test = _gvn.transform(new SubINode(inst, bits));
2928 // The 'test' is non-zero if we need to take a slow path.
2929 }
2930
2931 Node* obj = new_instance(kls, test);
2932 set_result(obj);
2933 return true;
2934 }
2935
2936 //------------------------inline_native_time_funcs--------------
2937 // inline code for System.currentTimeMillis() and System.nanoTime()
2938 // these have the same type and signature
2939 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2940 const TypeFunc* tf = OptoRuntime::void_long_Type();
2941 const TypePtr* no_memory_effects = nullptr;
2942 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2943 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2944 #ifdef ASSERT
2945 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2946 assert(value_top == top(), "second value must be top");
2947 #endif
2948 set_result(value);
2949 return true;
2950 }
2951
2952 //--------------------inline_native_vthread_start_transition--------------------
2953 // inline void startTransition(boolean is_mount);
2954 // inline void startFinalTransition();
2955 // Pseudocode of implementation:
2956 //
2957 // java_lang_Thread::set_is_in_vthread_transition(vthread, true);
2958 // carrier->set_is_in_vthread_transition(true);
2959 // OrderAccess::storeload();
2960 // int disable_requests = java_lang_Thread::vthread_transition_disable_count(vthread)
2961 // + global_vthread_transition_disable_count();
2962 // if (disable_requests > 0) {
2963 // slow path: runtime call
2964 // }
2965 bool LibraryCallKit::inline_native_vthread_start_transition(address funcAddr, const char* funcName, bool is_final_transition) {
2966 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
2967 IdealKit ideal(this);
2968
2969 Node* thread = ideal.thread();
2970 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
2971 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
2972 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
2973 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(1), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
2974 insert_mem_bar(Op_MemBarStoreLoad);
2975 ideal.sync_kit(this);
2976
2977 Node* global_disable_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::global_vthread_transition_disable_count_address()));
2978 Node* global_disable = ideal.load(ideal.ctrl(), global_disable_addr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, true /*require_atomic_access*/);
2979 Node* vt_disable_addr = basic_plus_adr(vt_oop, java_lang_Thread::vthread_transition_disable_count_offset());
2980 const TypePtr* vt_disable_addr_t = _gvn.type(vt_disable_addr)->is_ptr();
2981 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*/);
2982 Node* disabled = _gvn.transform(new AddINode(global_disable, vt_disable));
2983
2984 ideal.if_then(disabled, BoolTest::ne, ideal.ConI(0)); {
2985 sync_kit(ideal);
2986 Node* is_mount = is_final_transition ? ideal.ConI(0) : argument(1);
2987 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
2988 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
2989 ideal.sync_kit(this);
2990 }
2991 ideal.end_if();
2992
2993 final_sync(ideal);
2994 return true;
2995 }
2996
2997 bool LibraryCallKit::inline_native_vthread_end_transition(address funcAddr, const char* funcName, bool is_first_transition) {
2998 Node* vt_oop = must_be_not_null(argument(0), true); // VirtualThread this argument
2999 IdealKit ideal(this);
3000
3001 Node* _notify_jvmti_addr = makecon(TypeRawPtr::make((address)MountUnmountDisabler::notify_jvmti_events_address()));
3002 Node* _notify_jvmti = ideal.load(ideal.ctrl(), _notify_jvmti_addr, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3003
3004 ideal.if_then(_notify_jvmti, BoolTest::eq, ideal.ConI(1)); {
3005 sync_kit(ideal);
3006 Node* is_mount = is_first_transition ? ideal.ConI(1) : argument(1);
3007 const TypeFunc* tf = OptoRuntime::vthread_transition_Type();
3008 make_runtime_call(RC_NO_LEAF, tf, funcAddr, funcName, TypePtr::BOTTOM, vt_oop, is_mount);
3009 ideal.sync_kit(this);
3010 } ideal.else_(); {
3011 Node* thread = ideal.thread();
3012 Node* jt_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_in_vthread_transition_offset()));
3013 Node* vt_addr = basic_plus_adr(vt_oop, java_lang_Thread::is_in_vthread_transition_offset());
3014
3015 sync_kit(ideal);
3016 access_store_at(nullptr, jt_addr, _gvn.type(jt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3017 access_store_at(nullptr, vt_addr, _gvn.type(vt_addr)->is_ptr(), ideal.ConI(0), TypeInt::BOOL, T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3018 ideal.sync_kit(this);
3019 } ideal.end_if();
3020
3021 final_sync(ideal);
3022 return true;
3023 }
3024
3025 #if INCLUDE_JVMTI
3026
3027 // Always update the is_disable_suspend bit.
3028 bool LibraryCallKit::inline_native_notify_jvmti_sync() {
3029 if (!DoJVMTIVirtualThreadTransitions) {
3030 return true;
3031 }
3032 IdealKit ideal(this);
3033
3034 {
3035 // unconditionally update the is_disable_suspend bit in current JavaThread
3036 Node* thread = ideal.thread();
3037 Node* arg = argument(0); // argument for notification
3038 Node* addr = off_heap_plus_addr(thread, in_bytes(JavaThread::is_disable_suspend_offset()));
3039 const TypePtr *addr_type = _gvn.type(addr)->isa_ptr();
3040
3041 sync_kit(ideal);
3042 access_store_at(nullptr, addr, addr_type, arg, _gvn.type(arg), T_BOOLEAN, IN_NATIVE | MO_UNORDERED);
3043 ideal.sync_kit(this);
3044 }
3045 final_sync(ideal);
3046
3047 return true;
3048 }
3049
3050 #endif // INCLUDE_JVMTI
3051
3052 #ifdef JFR_HAVE_INTRINSICS
3053
3054 /**
3055 * if oop->klass != null
3056 * // normal class
3057 * epoch = _epoch_state ? 2 : 1
3058 * if oop->klass->trace_id & ((epoch << META_SHIFT) | epoch)) != epoch {
3059 * ... // enter slow path when the klass is first recorded or the epoch of JFR shifts
3060 * }
3061 * id = oop->klass->trace_id >> TRACE_ID_SHIFT // normal class path
3062 * else
3063 * // primitive class
3064 * if oop->array_klass != null
3065 * id = (oop->array_klass->trace_id >> TRACE_ID_SHIFT) + 1 // primitive class path
3066 * else
3067 * id = LAST_TYPE_ID + 1 // void class path
3068 * if (!signaled)
3069 * signaled = true
3070 */
3071 bool LibraryCallKit::inline_native_classID() {
3072 Node* cls = argument(0);
3073
3074 IdealKit ideal(this);
3075 #define __ ideal.
3076 IdealVariable result(ideal); __ declarations_done();
3077 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3078 basic_plus_adr(cls, java_lang_Class::klass_offset()),
3079 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3080
3081
3082 __ if_then(kls, BoolTest::ne, null()); {
3083 Node* kls_trace_id_addr = basic_plus_adr(kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3084 Node* kls_trace_id_raw = ideal.load(ideal.ctrl(), kls_trace_id_addr,TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3085
3086 Node* epoch_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_address()));
3087 Node* epoch = ideal.load(ideal.ctrl(), epoch_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw);
3088 epoch = _gvn.transform(new LShiftLNode(longcon(1), epoch));
3089 Node* mask = _gvn.transform(new LShiftLNode(epoch, intcon(META_SHIFT)));
3090 mask = _gvn.transform(new OrLNode(mask, epoch));
3091 Node* kls_trace_id_raw_and_mask = _gvn.transform(new AndLNode(kls_trace_id_raw, mask));
3092
3093 float unlikely = PROB_UNLIKELY(0.999);
3094 __ if_then(kls_trace_id_raw_and_mask, BoolTest::ne, epoch, unlikely); {
3095 sync_kit(ideal);
3096 make_runtime_call(RC_LEAF,
3097 OptoRuntime::class_id_load_barrier_Type(),
3098 CAST_FROM_FN_PTR(address, JfrIntrinsicSupport::load_barrier),
3099 "class id load barrier",
3100 TypePtr::BOTTOM,
3101 kls);
3102 ideal.sync_kit(this);
3103 } __ end_if();
3104
3105 ideal.set(result, _gvn.transform(new URShiftLNode(kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT))));
3106 } __ else_(); {
3107 Node* array_kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(),
3108 basic_plus_adr(cls, java_lang_Class::array_klass_offset()),
3109 TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
3110 __ if_then(array_kls, BoolTest::ne, null()); {
3111 Node* array_kls_trace_id_addr = basic_plus_adr(array_kls, in_bytes(KLASS_TRACE_ID_OFFSET));
3112 Node* array_kls_trace_id_raw = ideal.load(ideal.ctrl(), array_kls_trace_id_addr, TypeLong::LONG, T_LONG, Compile::AliasIdxRaw);
3113 Node* array_kls_trace_id = _gvn.transform(new URShiftLNode(array_kls_trace_id_raw, ideal.ConI(TRACE_ID_SHIFT)));
3114 ideal.set(result, _gvn.transform(new AddLNode(array_kls_trace_id, longcon(1))));
3115 } __ else_(); {
3116 // void class case
3117 ideal.set(result, longcon(LAST_TYPE_ID + 1));
3118 } __ end_if();
3119
3120 Node* signaled_flag_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::signal_address()));
3121 Node* signaled = ideal.load(ideal.ctrl(), signaled_flag_address, TypeInt::BOOL, T_BOOLEAN, Compile::AliasIdxRaw, true, MemNode::acquire);
3122 __ if_then(signaled, BoolTest::ne, ideal.ConI(1)); {
3123 ideal.store(ideal.ctrl(), signaled_flag_address, ideal.ConI(1), T_BOOLEAN, Compile::AliasIdxRaw, MemNode::release, true);
3124 } __ end_if();
3125 } __ end_if();
3126
3127 final_sync(ideal);
3128 set_result(ideal.value(result));
3129 #undef __
3130 return true;
3131 }
3132
3133 //------------------------inline_native_jvm_commit------------------
3134 bool LibraryCallKit::inline_native_jvm_commit() {
3135 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3136
3137 // Save input memory and i_o state.
3138 Node* input_memory_state = reset_memory();
3139 set_all_memory(input_memory_state);
3140 Node* input_io_state = i_o();
3141
3142 // TLS.
3143 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3144 // Jfr java buffer.
3145 Node* java_buffer_offset = _gvn.transform(AddPNode::make_off_heap(tls_ptr, MakeConX(in_bytes(JAVA_BUFFER_OFFSET_JFR))));
3146 Node* java_buffer = _gvn.transform(new LoadPNode(control(), input_memory_state, java_buffer_offset, TypePtr::BOTTOM, TypeRawPtr::NOTNULL, MemNode::unordered));
3147 Node* java_buffer_pos_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_POS_OFFSET))));
3148
3149 // Load the current value of the notified field in the JfrThreadLocal.
3150 Node* notified_offset = off_heap_plus_addr(tls_ptr, in_bytes(NOTIFY_OFFSET_JFR));
3151 Node* notified = make_load(control(), notified_offset, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3152
3153 // Test for notification.
3154 Node* notified_cmp = _gvn.transform(new CmpINode(notified, _gvn.intcon(1)));
3155 Node* test_notified = _gvn.transform(new BoolNode(notified_cmp, BoolTest::eq));
3156 IfNode* iff_notified = create_and_map_if(control(), test_notified, PROB_MIN, COUNT_UNKNOWN);
3157
3158 // True branch, is notified.
3159 Node* is_notified = _gvn.transform(new IfTrueNode(iff_notified));
3160 set_control(is_notified);
3161
3162 // Reset notified state.
3163 store_to_memory(control(), notified_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::unordered);
3164 Node* notified_reset_memory = reset_memory();
3165
3166 // 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.
3167 Node* current_pos_X = _gvn.transform(new LoadXNode(control(), input_memory_state, java_buffer_pos_offset, TypeRawPtr::NOTNULL, TypeX_X, MemNode::unordered));
3168 // Convert the machine-word to a long.
3169 Node* current_pos = ConvX2L(current_pos_X);
3170
3171 // False branch, not notified.
3172 Node* not_notified = _gvn.transform(new IfFalseNode(iff_notified));
3173 set_control(not_notified);
3174 set_all_memory(input_memory_state);
3175
3176 // Arg is the next position as a long.
3177 Node* arg = argument(0);
3178 // Convert long to machine-word.
3179 Node* next_pos_X = ConvL2X(arg);
3180
3181 // Store the next_position to the underlying jfr java buffer.
3182 store_to_memory(control(), java_buffer_pos_offset, next_pos_X, LP64_ONLY(T_LONG) NOT_LP64(T_INT), MemNode::release);
3183
3184 Node* commit_memory = reset_memory();
3185 set_all_memory(commit_memory);
3186
3187 // 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.
3188 Node* java_buffer_flags_offset = _gvn.transform(AddPNode::make_off_heap(java_buffer, MakeConX(in_bytes(JFR_BUFFER_FLAGS_OFFSET))));
3189 Node* flags = make_load(control(), java_buffer_flags_offset, TypeInt::UBYTE, T_BYTE, MemNode::unordered);
3190 Node* lease_constant = _gvn.intcon(4);
3191
3192 // And flags with lease constant.
3193 Node* lease = _gvn.transform(new AndINode(flags, lease_constant));
3194
3195 // Branch on lease to conditionalize returning the leased java buffer.
3196 Node* lease_cmp = _gvn.transform(new CmpINode(lease, lease_constant));
3197 Node* test_lease = _gvn.transform(new BoolNode(lease_cmp, BoolTest::eq));
3198 IfNode* iff_lease = create_and_map_if(control(), test_lease, PROB_MIN, COUNT_UNKNOWN);
3199
3200 // False branch, not a lease.
3201 Node* not_lease = _gvn.transform(new IfFalseNode(iff_lease));
3202
3203 // True branch, is lease.
3204 Node* is_lease = _gvn.transform(new IfTrueNode(iff_lease));
3205 set_control(is_lease);
3206
3207 // Make a runtime call, which can safepoint, to return the leased buffer. This updates both the JfrThreadLocal and the Java event writer oop.
3208 Node* call_return_lease = make_runtime_call(RC_NO_LEAF,
3209 OptoRuntime::void_void_Type(),
3210 SharedRuntime::jfr_return_lease(),
3211 "return_lease", TypePtr::BOTTOM);
3212 Node* call_return_lease_control = _gvn.transform(new ProjNode(call_return_lease, TypeFunc::Control));
3213
3214 RegionNode* lease_compare_rgn = new RegionNode(PATH_LIMIT);
3215 record_for_igvn(lease_compare_rgn);
3216 PhiNode* lease_compare_mem = new PhiNode(lease_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3217 record_for_igvn(lease_compare_mem);
3218 PhiNode* lease_compare_io = new PhiNode(lease_compare_rgn, Type::ABIO);
3219 record_for_igvn(lease_compare_io);
3220 PhiNode* lease_result_value = new PhiNode(lease_compare_rgn, TypeLong::LONG);
3221 record_for_igvn(lease_result_value);
3222
3223 // Update control and phi nodes.
3224 lease_compare_rgn->init_req(_true_path, call_return_lease_control);
3225 lease_compare_rgn->init_req(_false_path, not_lease);
3226
3227 lease_compare_mem->init_req(_true_path, reset_memory());
3228 lease_compare_mem->init_req(_false_path, commit_memory);
3229
3230 lease_compare_io->init_req(_true_path, i_o());
3231 lease_compare_io->init_req(_false_path, input_io_state);
3232
3233 lease_result_value->init_req(_true_path, _gvn.longcon(0)); // if the lease was returned, return 0L.
3234 lease_result_value->init_req(_false_path, arg); // if not lease, return new updated position.
3235
3236 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3237 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3238 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3239 PhiNode* result_value = new PhiNode(result_rgn, TypeLong::LONG);
3240
3241 // Update control and phi nodes.
3242 result_rgn->init_req(_true_path, is_notified);
3243 result_rgn->init_req(_false_path, _gvn.transform(lease_compare_rgn));
3244
3245 result_mem->init_req(_true_path, notified_reset_memory);
3246 result_mem->init_req(_false_path, _gvn.transform(lease_compare_mem));
3247
3248 result_io->init_req(_true_path, input_io_state);
3249 result_io->init_req(_false_path, _gvn.transform(lease_compare_io));
3250
3251 result_value->init_req(_true_path, current_pos);
3252 result_value->init_req(_false_path, _gvn.transform(lease_result_value));
3253
3254 // Set output state.
3255 set_control(_gvn.transform(result_rgn));
3256 set_all_memory(_gvn.transform(result_mem));
3257 set_i_o(_gvn.transform(result_io));
3258 set_result(result_rgn, result_value);
3259 return true;
3260 }
3261
3262 /*
3263 * The intrinsic is a model of this pseudo-code:
3264 *
3265 * JfrThreadLocal* const tl = Thread::jfr_thread_local()
3266 * jobject h_event_writer = tl->java_event_writer();
3267 * if (h_event_writer == nullptr) {
3268 * return nullptr;
3269 * }
3270 * oop threadObj = Thread::threadObj();
3271 * oop vthread = java_lang_Thread::vthread(threadObj);
3272 * traceid tid;
3273 * bool pinVirtualThread;
3274 * bool excluded;
3275 * if (vthread != threadObj) { // i.e. current thread is virtual
3276 * tid = java_lang_Thread::tid(vthread);
3277 * u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(vthread);
3278 * pinVirtualThread = VMContinuations;
3279 * excluded = vthread_epoch_raw & excluded_mask;
3280 * if (!excluded) {
3281 * traceid current_epoch = JfrTraceIdEpoch::current_generation();
3282 * u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3283 * if (vthread_epoch != current_epoch) {
3284 * write_checkpoint();
3285 * }
3286 * }
3287 * } else {
3288 * tid = java_lang_Thread::tid(threadObj);
3289 * u2 thread_epoch_raw = java_lang_Thread::jfr_epoch(threadObj);
3290 * pinVirtualThread = false;
3291 * excluded = thread_epoch_raw & excluded_mask;
3292 * }
3293 * oop event_writer = JNIHandles::resolve_non_null(h_event_writer);
3294 * traceid tid_in_event_writer = getField(event_writer, "threadID");
3295 * if (tid_in_event_writer != tid) {
3296 * setField(event_writer, "pinVirtualThread", pinVirtualThread);
3297 * setField(event_writer, "excluded", excluded);
3298 * setField(event_writer, "threadID", tid);
3299 * }
3300 * return event_writer
3301 */
3302 bool LibraryCallKit::inline_native_getEventWriter() {
3303 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3304
3305 // Save input memory and i_o state.
3306 Node* input_memory_state = reset_memory();
3307 set_all_memory(input_memory_state);
3308 Node* input_io_state = i_o();
3309
3310 // The most significant bit of the u2 is used to denote thread exclusion
3311 Node* excluded_shift = _gvn.intcon(15);
3312 Node* excluded_mask = _gvn.intcon(1 << 15);
3313 // The epoch generation is the range [1-32767]
3314 Node* epoch_mask = _gvn.intcon(32767);
3315
3316 // TLS
3317 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3318
3319 // Load the address of java event writer jobject handle from the jfr_thread_local structure.
3320 Node* jobj_ptr = off_heap_plus_addr(tls_ptr, in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
3321
3322 // Load the eventwriter jobject handle.
3323 Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
3324
3325 // Null check the jobject handle.
3326 Node* jobj_cmp_null = _gvn.transform(new CmpPNode(jobj, null()));
3327 Node* test_jobj_not_equal_null = _gvn.transform(new BoolNode(jobj_cmp_null, BoolTest::ne));
3328 IfNode* iff_jobj_not_equal_null = create_and_map_if(control(), test_jobj_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3329
3330 // False path, jobj is null.
3331 Node* jobj_is_null = _gvn.transform(new IfFalseNode(iff_jobj_not_equal_null));
3332
3333 // True path, jobj is not null.
3334 Node* jobj_is_not_null = _gvn.transform(new IfTrueNode(iff_jobj_not_equal_null));
3335
3336 set_control(jobj_is_not_null);
3337
3338 // Load the threadObj for the CarrierThread.
3339 Node* threadObj = generate_current_thread(tls_ptr);
3340
3341 // Load the vthread.
3342 Node* vthread = generate_virtual_thread(tls_ptr);
3343
3344 // If vthread != threadObj, this is a virtual thread.
3345 Node* vthread_cmp_threadObj = _gvn.transform(new CmpPNode(vthread, threadObj));
3346 Node* test_vthread_not_equal_threadObj = _gvn.transform(new BoolNode(vthread_cmp_threadObj, BoolTest::ne));
3347 IfNode* iff_vthread_not_equal_threadObj =
3348 create_and_map_if(jobj_is_not_null, test_vthread_not_equal_threadObj, PROB_FAIR, COUNT_UNKNOWN);
3349
3350 // False branch, fallback to threadObj.
3351 Node* vthread_equal_threadObj = _gvn.transform(new IfFalseNode(iff_vthread_not_equal_threadObj));
3352 set_control(vthread_equal_threadObj);
3353
3354 // Load the tid field from the vthread object.
3355 Node* thread_obj_tid = load_field_from_object(threadObj, "tid", "J");
3356
3357 // Load the raw epoch value from the threadObj.
3358 Node* threadObj_epoch_offset = basic_plus_adr(threadObj, java_lang_Thread::jfr_epoch_offset());
3359 Node* threadObj_epoch_raw = access_load_at(threadObj, threadObj_epoch_offset,
3360 _gvn.type(threadObj_epoch_offset)->isa_ptr(),
3361 TypeInt::CHAR, T_CHAR,
3362 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3363
3364 // Mask off the excluded information from the epoch.
3365 Node * threadObj_is_excluded = _gvn.transform(new AndINode(threadObj_epoch_raw, excluded_mask));
3366
3367 // True branch, this is a virtual thread.
3368 Node* vthread_not_equal_threadObj = _gvn.transform(new IfTrueNode(iff_vthread_not_equal_threadObj));
3369 set_control(vthread_not_equal_threadObj);
3370
3371 // Load the tid field from the vthread object.
3372 Node* vthread_tid = load_field_from_object(vthread, "tid", "J");
3373
3374 // Continuation support determines if a virtual thread should be pinned.
3375 Node* global_addr = makecon(TypeRawPtr::make((address)&VMContinuations));
3376 Node* continuation_support = make_load(control(), global_addr, TypeInt::BOOL, T_BOOLEAN, MemNode::unordered);
3377
3378 // Load the raw epoch value from the vthread.
3379 Node* vthread_epoch_offset = basic_plus_adr(vthread, java_lang_Thread::jfr_epoch_offset());
3380 Node* vthread_epoch_raw = access_load_at(vthread, vthread_epoch_offset, _gvn.type(vthread_epoch_offset)->is_ptr(),
3381 TypeInt::CHAR, T_CHAR,
3382 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3383
3384 // Mask off the excluded information from the epoch.
3385 Node * vthread_is_excluded = _gvn.transform(new AndINode(vthread_epoch_raw, excluded_mask));
3386
3387 // Branch on excluded to conditionalize updating the epoch for the virtual thread.
3388 Node* is_excluded_cmp = _gvn.transform(new CmpINode(vthread_is_excluded, excluded_mask));
3389 Node* test_not_excluded = _gvn.transform(new BoolNode(is_excluded_cmp, BoolTest::ne));
3390 IfNode* iff_not_excluded = create_and_map_if(control(), test_not_excluded, PROB_MAX, COUNT_UNKNOWN);
3391
3392 // False branch, vthread is excluded, no need to write epoch info.
3393 Node* excluded = _gvn.transform(new IfFalseNode(iff_not_excluded));
3394
3395 // True branch, vthread is included, update epoch info.
3396 Node* included = _gvn.transform(new IfTrueNode(iff_not_excluded));
3397 set_control(included);
3398
3399 // Get epoch value.
3400 Node* epoch = _gvn.transform(new AndINode(vthread_epoch_raw, epoch_mask));
3401
3402 // Load the current epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3403 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3404 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3405
3406 // Compare the epoch in the vthread to the current epoch generation.
3407 Node* const epoch_cmp = _gvn.transform(new CmpUNode(current_epoch_generation, epoch));
3408 Node* test_epoch_not_equal = _gvn.transform(new BoolNode(epoch_cmp, BoolTest::ne));
3409 IfNode* iff_epoch_not_equal = create_and_map_if(control(), test_epoch_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3410
3411 // False path, epoch is equal, checkpoint information is valid.
3412 Node* epoch_is_equal = _gvn.transform(new IfFalseNode(iff_epoch_not_equal));
3413
3414 // True path, epoch is not equal, write a checkpoint for the vthread.
3415 Node* epoch_is_not_equal = _gvn.transform(new IfTrueNode(iff_epoch_not_equal));
3416
3417 set_control(epoch_is_not_equal);
3418
3419 // Make a runtime call, which can safepoint, to write a checkpoint for the vthread for this epoch.
3420 // The call also updates the native thread local thread id and the vthread with the current epoch.
3421 Node* call_write_checkpoint = make_runtime_call(RC_NO_LEAF,
3422 OptoRuntime::jfr_write_checkpoint_Type(),
3423 SharedRuntime::jfr_write_checkpoint(),
3424 "write_checkpoint", TypePtr::BOTTOM);
3425 Node* call_write_checkpoint_control = _gvn.transform(new ProjNode(call_write_checkpoint, TypeFunc::Control));
3426
3427 // vthread epoch != current epoch
3428 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3429 record_for_igvn(epoch_compare_rgn);
3430 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3431 record_for_igvn(epoch_compare_mem);
3432 PhiNode* epoch_compare_io = new PhiNode(epoch_compare_rgn, Type::ABIO);
3433 record_for_igvn(epoch_compare_io);
3434
3435 // Update control and phi nodes.
3436 epoch_compare_rgn->init_req(_true_path, call_write_checkpoint_control);
3437 epoch_compare_rgn->init_req(_false_path, epoch_is_equal);
3438 epoch_compare_mem->init_req(_true_path, reset_memory());
3439 epoch_compare_mem->init_req(_false_path, input_memory_state);
3440 epoch_compare_io->init_req(_true_path, i_o());
3441 epoch_compare_io->init_req(_false_path, input_io_state);
3442
3443 // excluded != true
3444 RegionNode* exclude_compare_rgn = new RegionNode(PATH_LIMIT);
3445 record_for_igvn(exclude_compare_rgn);
3446 PhiNode* exclude_compare_mem = new PhiNode(exclude_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3447 record_for_igvn(exclude_compare_mem);
3448 PhiNode* exclude_compare_io = new PhiNode(exclude_compare_rgn, Type::ABIO);
3449 record_for_igvn(exclude_compare_io);
3450
3451 // Update control and phi nodes.
3452 exclude_compare_rgn->init_req(_true_path, _gvn.transform(epoch_compare_rgn));
3453 exclude_compare_rgn->init_req(_false_path, excluded);
3454 exclude_compare_mem->init_req(_true_path, _gvn.transform(epoch_compare_mem));
3455 exclude_compare_mem->init_req(_false_path, input_memory_state);
3456 exclude_compare_io->init_req(_true_path, _gvn.transform(epoch_compare_io));
3457 exclude_compare_io->init_req(_false_path, input_io_state);
3458
3459 // vthread != threadObj
3460 RegionNode* vthread_compare_rgn = new RegionNode(PATH_LIMIT);
3461 record_for_igvn(vthread_compare_rgn);
3462 PhiNode* vthread_compare_mem = new PhiNode(vthread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3463 PhiNode* vthread_compare_io = new PhiNode(vthread_compare_rgn, Type::ABIO);
3464 record_for_igvn(vthread_compare_io);
3465 PhiNode* tid = new PhiNode(vthread_compare_rgn, TypeLong::LONG);
3466 record_for_igvn(tid);
3467 PhiNode* exclusion = new PhiNode(vthread_compare_rgn, TypeInt::CHAR);
3468 record_for_igvn(exclusion);
3469 PhiNode* pinVirtualThread = new PhiNode(vthread_compare_rgn, TypeInt::BOOL);
3470 record_for_igvn(pinVirtualThread);
3471
3472 // Update control and phi nodes.
3473 vthread_compare_rgn->init_req(_true_path, _gvn.transform(exclude_compare_rgn));
3474 vthread_compare_rgn->init_req(_false_path, vthread_equal_threadObj);
3475 vthread_compare_mem->init_req(_true_path, _gvn.transform(exclude_compare_mem));
3476 vthread_compare_mem->init_req(_false_path, input_memory_state);
3477 vthread_compare_io->init_req(_true_path, _gvn.transform(exclude_compare_io));
3478 vthread_compare_io->init_req(_false_path, input_io_state);
3479 tid->init_req(_true_path, vthread_tid);
3480 tid->init_req(_false_path, thread_obj_tid);
3481 exclusion->init_req(_true_path, vthread_is_excluded);
3482 exclusion->init_req(_false_path, threadObj_is_excluded);
3483 pinVirtualThread->init_req(_true_path, continuation_support);
3484 pinVirtualThread->init_req(_false_path, _gvn.intcon(0));
3485
3486 // Update branch state.
3487 set_control(_gvn.transform(vthread_compare_rgn));
3488 set_all_memory(_gvn.transform(vthread_compare_mem));
3489 set_i_o(_gvn.transform(vthread_compare_io));
3490
3491 // Load the event writer oop by dereferencing the jobject handle.
3492 ciKlass* klass_EventWriter = env()->find_system_klass(ciSymbol::make("jdk/jfr/internal/event/EventWriter"));
3493 assert(klass_EventWriter->is_loaded(), "invariant");
3494 ciInstanceKlass* const instklass_EventWriter = klass_EventWriter->as_instance_klass();
3495 const TypeKlassPtr* const aklass = TypeKlassPtr::make(instklass_EventWriter);
3496 const TypeOopPtr* const xtype = aklass->as_instance_type();
3497 Node* jobj_untagged = _gvn.transform(AddPNode::make_off_heap(jobj, _gvn.MakeConX(-JNIHandles::TypeTag::global)));
3498 Node* event_writer = access_load(jobj_untagged, xtype, T_OBJECT, IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
3499
3500 // Load the current thread id from the event writer object.
3501 Node* const event_writer_tid = load_field_from_object(event_writer, "threadID", "J");
3502 // Get the field offset to, conditionally, store an updated tid value later.
3503 Node* const event_writer_tid_field = field_address_from_object(event_writer, "threadID", "J", false);
3504 // Get the field offset to, conditionally, store an updated exclusion value later.
3505 Node* const event_writer_excluded_field = field_address_from_object(event_writer, "excluded", "Z", false);
3506 // Get the field offset to, conditionally, store an updated pinVirtualThread value later.
3507 Node* const event_writer_pin_field = field_address_from_object(event_writer, "pinVirtualThread", "Z", false);
3508
3509 RegionNode* event_writer_tid_compare_rgn = new RegionNode(PATH_LIMIT);
3510 record_for_igvn(event_writer_tid_compare_rgn);
3511 PhiNode* event_writer_tid_compare_mem = new PhiNode(event_writer_tid_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3512 record_for_igvn(event_writer_tid_compare_mem);
3513 PhiNode* event_writer_tid_compare_io = new PhiNode(event_writer_tid_compare_rgn, Type::ABIO);
3514 record_for_igvn(event_writer_tid_compare_io);
3515
3516 // Compare the current tid from the thread object to what is currently stored in the event writer object.
3517 Node* const tid_cmp = _gvn.transform(new CmpLNode(event_writer_tid, _gvn.transform(tid)));
3518 Node* test_tid_not_equal = _gvn.transform(new BoolNode(tid_cmp, BoolTest::ne));
3519 IfNode* iff_tid_not_equal = create_and_map_if(_gvn.transform(vthread_compare_rgn), test_tid_not_equal, PROB_FAIR, COUNT_UNKNOWN);
3520
3521 // False path, tids are the same.
3522 Node* tid_is_equal = _gvn.transform(new IfFalseNode(iff_tid_not_equal));
3523
3524 // True path, tid is not equal, need to update the tid in the event writer.
3525 Node* tid_is_not_equal = _gvn.transform(new IfTrueNode(iff_tid_not_equal));
3526 record_for_igvn(tid_is_not_equal);
3527
3528 // Store the pin state to the event writer.
3529 store_to_memory(tid_is_not_equal, event_writer_pin_field, _gvn.transform(pinVirtualThread), T_BOOLEAN, MemNode::unordered);
3530
3531 // Store the exclusion state to the event writer.
3532 Node* excluded_bool = _gvn.transform(new URShiftINode(_gvn.transform(exclusion), excluded_shift));
3533 store_to_memory(tid_is_not_equal, event_writer_excluded_field, excluded_bool, T_BOOLEAN, MemNode::unordered);
3534
3535 // Store the tid to the event writer.
3536 store_to_memory(tid_is_not_equal, event_writer_tid_field, tid, T_LONG, MemNode::unordered);
3537
3538 // Update control and phi nodes.
3539 event_writer_tid_compare_rgn->init_req(_true_path, tid_is_not_equal);
3540 event_writer_tid_compare_rgn->init_req(_false_path, tid_is_equal);
3541 event_writer_tid_compare_mem->init_req(_true_path, reset_memory());
3542 event_writer_tid_compare_mem->init_req(_false_path, _gvn.transform(vthread_compare_mem));
3543 event_writer_tid_compare_io->init_req(_true_path, i_o());
3544 event_writer_tid_compare_io->init_req(_false_path, _gvn.transform(vthread_compare_io));
3545
3546 // Result of top level CFG, Memory, IO and Value.
3547 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3548 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3549 PhiNode* result_io = new PhiNode(result_rgn, Type::ABIO);
3550 PhiNode* result_value = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
3551
3552 // Result control.
3553 result_rgn->init_req(_true_path, _gvn.transform(event_writer_tid_compare_rgn));
3554 result_rgn->init_req(_false_path, jobj_is_null);
3555
3556 // Result memory.
3557 result_mem->init_req(_true_path, _gvn.transform(event_writer_tid_compare_mem));
3558 result_mem->init_req(_false_path, input_memory_state);
3559
3560 // Result IO.
3561 result_io->init_req(_true_path, _gvn.transform(event_writer_tid_compare_io));
3562 result_io->init_req(_false_path, input_io_state);
3563
3564 // Result value.
3565 result_value->init_req(_true_path, event_writer); // return event writer oop
3566 result_value->init_req(_false_path, null()); // return null
3567
3568 // Set output state.
3569 set_control(_gvn.transform(result_rgn));
3570 set_all_memory(_gvn.transform(result_mem));
3571 set_i_o(_gvn.transform(result_io));
3572 set_result(result_rgn, result_value);
3573 return true;
3574 }
3575
3576 /*
3577 * The intrinsic is a model of this pseudo-code:
3578 *
3579 * JfrThreadLocal* const tl = thread->jfr_thread_local();
3580 * if (carrierThread != thread) { // is virtual thread
3581 * const u2 vthread_epoch_raw = java_lang_Thread::jfr_epoch(thread);
3582 * bool excluded = vthread_epoch_raw & excluded_mask;
3583 * AtomicAccess::store(&tl->_contextual_tid, java_lang_Thread::tid(thread));
3584 * AtomicAccess::store(&tl->_contextual_thread_excluded, is_excluded);
3585 * if (!excluded) {
3586 * const u2 vthread_epoch = vthread_epoch_raw & epoch_mask;
3587 * AtomicAccess::store(&tl->_vthread_epoch, vthread_epoch);
3588 * }
3589 * AtomicAccess::release_store(&tl->_vthread, true);
3590 * return;
3591 * }
3592 * AtomicAccess::release_store(&tl->_vthread, false);
3593 */
3594 void LibraryCallKit::extend_setCurrentThread(Node* jt, Node* thread) {
3595 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3596
3597 Node* input_memory_state = reset_memory();
3598 set_all_memory(input_memory_state);
3599
3600 // The most significant bit of the u2 is used to denote thread exclusion
3601 Node* excluded_mask = _gvn.intcon(1 << 15);
3602 // The epoch generation is the range [1-32767]
3603 Node* epoch_mask = _gvn.intcon(32767);
3604
3605 Node* const carrierThread = generate_current_thread(jt);
3606 // If thread != carrierThread, this is a virtual thread.
3607 Node* thread_cmp_carrierThread = _gvn.transform(new CmpPNode(thread, carrierThread));
3608 Node* test_thread_not_equal_carrierThread = _gvn.transform(new BoolNode(thread_cmp_carrierThread, BoolTest::ne));
3609 IfNode* iff_thread_not_equal_carrierThread =
3610 create_and_map_if(control(), test_thread_not_equal_carrierThread, PROB_FAIR, COUNT_UNKNOWN);
3611
3612 Node* vthread_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_OFFSET_JFR));
3613
3614 // False branch, is carrierThread.
3615 Node* thread_equal_carrierThread = _gvn.transform(new IfFalseNode(iff_thread_not_equal_carrierThread));
3616 // Store release
3617 Node* vthread_false_memory = store_to_memory(thread_equal_carrierThread, vthread_offset, _gvn.intcon(0), T_BOOLEAN, MemNode::release, true);
3618
3619 set_all_memory(input_memory_state);
3620
3621 // True branch, is virtual thread.
3622 Node* thread_not_equal_carrierThread = _gvn.transform(new IfTrueNode(iff_thread_not_equal_carrierThread));
3623 set_control(thread_not_equal_carrierThread);
3624
3625 // Load the raw epoch value from the vthread.
3626 Node* epoch_offset = basic_plus_adr(thread, java_lang_Thread::jfr_epoch_offset());
3627 Node* epoch_raw = access_load_at(thread, epoch_offset, _gvn.type(epoch_offset)->is_ptr(), TypeInt::CHAR, T_CHAR,
3628 IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
3629
3630 // Mask off the excluded information from the epoch.
3631 Node * const is_excluded = _gvn.transform(new AndINode(epoch_raw, excluded_mask));
3632
3633 // Load the tid field from the thread.
3634 Node* tid = load_field_from_object(thread, "tid", "J");
3635
3636 // Store the vthread tid to the jfr thread local.
3637 Node* thread_id_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_ID_OFFSET_JFR));
3638 Node* tid_memory = store_to_memory(control(), thread_id_offset, tid, T_LONG, MemNode::unordered, true);
3639
3640 // Branch is_excluded to conditionalize updating the epoch .
3641 Node* excluded_cmp = _gvn.transform(new CmpINode(is_excluded, excluded_mask));
3642 Node* test_excluded = _gvn.transform(new BoolNode(excluded_cmp, BoolTest::eq));
3643 IfNode* iff_excluded = create_and_map_if(control(), test_excluded, PROB_MIN, COUNT_UNKNOWN);
3644
3645 // True branch, vthread is excluded, no need to write epoch info.
3646 Node* excluded = _gvn.transform(new IfTrueNode(iff_excluded));
3647 set_control(excluded);
3648 Node* vthread_is_excluded = _gvn.intcon(1);
3649
3650 // False branch, vthread is included, update epoch info.
3651 Node* included = _gvn.transform(new IfFalseNode(iff_excluded));
3652 set_control(included);
3653 Node* vthread_is_included = _gvn.intcon(0);
3654
3655 // Get epoch value.
3656 Node* epoch = _gvn.transform(new AndINode(epoch_raw, epoch_mask));
3657
3658 // Store the vthread epoch to the jfr thread local.
3659 Node* vthread_epoch_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EPOCH_OFFSET_JFR));
3660 Node* included_memory = store_to_memory(control(), vthread_epoch_offset, epoch, T_CHAR, MemNode::unordered, true);
3661
3662 RegionNode* excluded_rgn = new RegionNode(PATH_LIMIT);
3663 record_for_igvn(excluded_rgn);
3664 PhiNode* excluded_mem = new PhiNode(excluded_rgn, Type::MEMORY, TypePtr::BOTTOM);
3665 record_for_igvn(excluded_mem);
3666 PhiNode* exclusion = new PhiNode(excluded_rgn, TypeInt::BOOL);
3667 record_for_igvn(exclusion);
3668
3669 // Merge the excluded control and memory.
3670 excluded_rgn->init_req(_true_path, excluded);
3671 excluded_rgn->init_req(_false_path, included);
3672 excluded_mem->init_req(_true_path, tid_memory);
3673 excluded_mem->init_req(_false_path, included_memory);
3674 exclusion->init_req(_true_path, vthread_is_excluded);
3675 exclusion->init_req(_false_path, vthread_is_included);
3676
3677 // Set intermediate state.
3678 set_control(_gvn.transform(excluded_rgn));
3679 set_all_memory(excluded_mem);
3680
3681 // Store the vthread exclusion state to the jfr thread local.
3682 Node* thread_local_excluded_offset = off_heap_plus_addr(jt, in_bytes(THREAD_LOCAL_OFFSET_JFR + VTHREAD_EXCLUDED_OFFSET_JFR));
3683 store_to_memory(control(), thread_local_excluded_offset, _gvn.transform(exclusion), T_BOOLEAN, MemNode::unordered, true);
3684
3685 // Store release
3686 Node * vthread_true_memory = store_to_memory(control(), vthread_offset, _gvn.intcon(1), T_BOOLEAN, MemNode::release, true);
3687
3688 RegionNode* thread_compare_rgn = new RegionNode(PATH_LIMIT);
3689 record_for_igvn(thread_compare_rgn);
3690 PhiNode* thread_compare_mem = new PhiNode(thread_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3691 record_for_igvn(thread_compare_mem);
3692 PhiNode* vthread = new PhiNode(thread_compare_rgn, TypeInt::BOOL);
3693 record_for_igvn(vthread);
3694
3695 // Merge the thread_compare control and memory.
3696 thread_compare_rgn->init_req(_true_path, control());
3697 thread_compare_rgn->init_req(_false_path, thread_equal_carrierThread);
3698 thread_compare_mem->init_req(_true_path, vthread_true_memory);
3699 thread_compare_mem->init_req(_false_path, vthread_false_memory);
3700
3701 // Set output state.
3702 set_control(_gvn.transform(thread_compare_rgn));
3703 set_all_memory(_gvn.transform(thread_compare_mem));
3704 }
3705
3706 //------------------------inline_native_try_update_epoch------------------
3707 //
3708 // The generated code is a function of the argument type.
3709 //
3710 bool LibraryCallKit::inline_native_try_update_epoch() {
3711 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3712
3713 // Save input memory.
3714 Node* input_memory_state = reset_memory();
3715 set_all_memory(input_memory_state);
3716
3717 // Argument is an oop whose class has an injected instance field,
3718 // called 'jfr_epoch' of type T_INT, used for holding a jfr epoch value.
3719 Node* oop = argument(0);
3720 const TypeInstPtr* tinst = _gvn.type(oop)->isa_instptr();
3721 assert(tinst != nullptr, "oop is null");
3722 assert(tinst->is_loaded(), "klass is not loaded");
3723 ciInstanceKlass* const ik = tinst->instance_klass();
3724
3725 ciField* const field = ik->get_injected_instance_field_by_name(ciSymbol::make("jfr_epoch"),
3726 ciSymbol::make("I"));
3727
3728 assert(field != nullptr, "field 'jfr_epoch' of type I not injected in klass %s", ik->name()->as_utf8());
3729
3730 const int jfr_epoch_field_offset = field->offset_in_bytes();
3731 Node* oop_epoch_field_offset = basic_plus_adr(oop, jfr_epoch_field_offset);
3732 const TypePtr* adr_type = _gvn.type(oop_epoch_field_offset)->isa_ptr();
3733 const int alias_idx = C->get_alias_index(adr_type);
3734 BasicType bt = field->layout_type();
3735 const Type * oop_epoch_field_type = Type::get_const_basic_type(bt);
3736
3737 // Load the epoch value from the oop.
3738 Node* oop_epoch = access_load_at(oop,
3739 oop_epoch_field_offset,
3740 adr_type, oop_epoch_field_type,
3741 bt, IN_HEAP | MO_UNORDERED);
3742
3743 // Load the current JFR epoch generation. The value is unsigned 16-bit, so we type it as T_CHAR.
3744 Node* epoch_generation_address = makecon(TypeRawPtr::make(JfrIntrinsicSupport::epoch_generation_address()));
3745 Node* current_epoch_generation = make_load(control(), epoch_generation_address, TypeInt::CHAR, T_CHAR, MemNode::unordered);
3746
3747 // Compare the epoch in the oop against the current JFR epoch generation.
3748 Node* const epochs_cmp = _gvn.transform(new CmpINode(current_epoch_generation, oop_epoch));
3749 Node* epochs_equal_test = _gvn.transform(new BoolNode(epochs_cmp, BoolTest::eq));
3750 IfNode* iff_epochs_equal = create_and_map_if(control(), epochs_equal_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
3751
3752 // True path.
3753 Node* epochs_are_equal = _gvn.transform(new IfTrueNode(iff_epochs_equal));
3754
3755 // False path.
3756 Node* epochs_are_not_equal = _gvn.transform(new IfFalseNode(iff_epochs_equal));
3757
3758 set_control(_gvn.transform(epochs_are_not_equal));
3759
3760 // Attempt to cas the current JFR epoch generation into the oop epoch field.
3761 DecoratorSet decorators = IN_HEAP;
3762 decorators |= mo_decorator_for_access_kind(Volatile);
3763
3764 Node* result = access_atomic_cmpxchg_val_at(oop,
3765 oop_epoch_field_offset,
3766 adr_type, alias_idx,
3767 oop_epoch, // expected value
3768 current_epoch_generation, // new value
3769 oop_epoch_field_type,
3770 bt,
3771 decorators);
3772
3773 // Compare the result of the cas operation to the expected value.
3774 Node* const cas_cmp_to_expected_value = _gvn.transform(new CmpINode(result, oop_epoch));
3775 Node* cas_operation_test = _gvn.transform(new BoolNode(cas_cmp_to_expected_value, BoolTest::eq));
3776 IfNode* iff_cas_success = create_and_map_if(control(), cas_operation_test, PROB_LIKELY(0.999), COUNT_UNKNOWN);
3777
3778 // True path.
3779 Node* cas_success = _gvn.transform(new IfTrueNode(iff_cas_success));
3780
3781 // False path.
3782 Node* cas_failure = _gvn.transform(new IfFalseNode(iff_cas_success));
3783
3784 // Cas result region and phi nodes.
3785 RegionNode* cas_operation_rgn = new RegionNode(PATH_LIMIT);
3786 record_for_igvn(cas_operation_rgn);
3787 PhiNode* cas_operation_mem = new PhiNode(cas_operation_rgn, Type::MEMORY, TypePtr::BOTTOM);
3788 record_for_igvn(cas_operation_mem);
3789 PhiNode* cas_result = new PhiNode(cas_operation_rgn, TypeInt::BOOL);
3790 record_for_igvn(cas_result);
3791
3792 cas_operation_rgn->init_req(_true_path, _gvn.transform(cas_success));
3793 cas_operation_rgn->init_req(_false_path, _gvn.transform(cas_failure));
3794 cas_operation_mem->init_req(_true_path, reset_memory());
3795 cas_operation_mem->init_req(_false_path, input_memory_state);
3796 cas_result->init_req(_true_path, _gvn.intcon(1));
3797 cas_result->init_req(_false_path, _gvn.intcon(0));
3798
3799 // Epoch compare region and phi nodes.
3800 RegionNode* epoch_compare_rgn = new RegionNode(PATH_LIMIT);
3801 record_for_igvn(epoch_compare_rgn);
3802 PhiNode* epoch_compare_mem = new PhiNode(epoch_compare_rgn, Type::MEMORY, TypePtr::BOTTOM);
3803 record_for_igvn(epoch_compare_mem);
3804 PhiNode* result_value = new PhiNode(epoch_compare_rgn, TypeInt::BOOL);
3805 record_for_igvn(result_value);
3806
3807 epoch_compare_rgn->init_req(_true_path, _gvn.transform(epochs_are_equal));
3808 epoch_compare_rgn->init_req(_false_path, _gvn.transform(cas_operation_rgn));
3809 epoch_compare_mem->init_req(_true_path, _gvn.transform(input_memory_state));
3810 epoch_compare_mem->init_req(_false_path, _gvn.transform(cas_operation_mem));
3811 result_value->init_req(_true_path, _gvn.intcon(0));
3812 result_value->init_req(_false_path, _gvn.transform(cas_result));
3813
3814 // Set output state.
3815 set_result(epoch_compare_rgn, result_value);
3816 set_all_memory(_gvn.transform(epoch_compare_mem));
3817
3818 return true;
3819 }
3820
3821 #endif // JFR_HAVE_INTRINSICS
3822
3823 //------------------------inline_native_currentCarrierThread------------------
3824 bool LibraryCallKit::inline_native_currentCarrierThread() {
3825 Node* junk = nullptr;
3826 set_result(generate_current_thread(junk));
3827 return true;
3828 }
3829
3830 //------------------------inline_native_currentThread------------------
3831 bool LibraryCallKit::inline_native_currentThread() {
3832 Node* junk = nullptr;
3833 set_result(generate_virtual_thread(junk));
3834 return true;
3835 }
3836
3837 //------------------------inline_native_setVthread------------------
3838 bool LibraryCallKit::inline_native_setCurrentThread() {
3839 assert(C->method()->changes_current_thread(),
3840 "method changes current Thread but is not annotated ChangesCurrentThread");
3841 Node* arr = argument(1);
3842 Node* thread = _gvn.transform(new ThreadLocalNode());
3843 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::vthread_offset()));
3844 Node* thread_obj_handle
3845 = make_load(nullptr, p, p->bottom_type()->is_ptr(), T_OBJECT, MemNode::unordered);
3846 const TypePtr *adr_type = _gvn.type(thread_obj_handle)->isa_ptr();
3847 access_store_at(nullptr, thread_obj_handle, adr_type, arr, _gvn.type(arr), T_OBJECT, IN_NATIVE | MO_UNORDERED);
3848
3849 // Change the _monitor_owner_id of the JavaThread
3850 Node* tid = load_field_from_object(arr, "tid", "J");
3851 Node* monitor_owner_id_offset = off_heap_plus_addr(thread, in_bytes(JavaThread::monitor_owner_id_offset()));
3852 store_to_memory(control(), monitor_owner_id_offset, tid, T_LONG, MemNode::unordered, true);
3853
3854 JFR_ONLY(extend_setCurrentThread(thread, arr);)
3855 return true;
3856 }
3857
3858 const Type* LibraryCallKit::scopedValueCache_type() {
3859 ciKlass* objects_klass = ciObjArrayKlass::make(env()->Object_klass());
3860 const TypeOopPtr* etype = TypeOopPtr::make_from_klass(env()->Object_klass());
3861 const TypeAry* arr0 = TypeAry::make(etype, TypeInt::POS);
3862
3863 // Because we create the scopedValue cache lazily we have to make the
3864 // type of the result BotPTR.
3865 bool xk = etype->klass_is_exact();
3866 const Type* objects_type = TypeAryPtr::make(TypePtr::BotPTR, arr0, objects_klass, xk, 0);
3867 return objects_type;
3868 }
3869
3870 Node* LibraryCallKit::scopedValueCache_helper() {
3871 Node* thread = _gvn.transform(new ThreadLocalNode());
3872 Node* p = off_heap_plus_addr(thread, in_bytes(JavaThread::scopedValueCache_offset()));
3873 // We cannot use immutable_memory() because we might flip onto a
3874 // different carrier thread, at which point we'll need to use that
3875 // carrier thread's cache.
3876 // return _gvn.transform(LoadNode::make(_gvn, nullptr, immutable_memory(), p, p->bottom_type()->is_ptr(),
3877 // TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered));
3878 return make_load(nullptr, p, p->bottom_type()->is_ptr(), T_ADDRESS, MemNode::unordered);
3879 }
3880
3881 //------------------------inline_native_scopedValueCache------------------
3882 bool LibraryCallKit::inline_native_scopedValueCache() {
3883 Node* cache_obj_handle = scopedValueCache_helper();
3884 const Type* objects_type = scopedValueCache_type();
3885 set_result(access_load(cache_obj_handle, objects_type, T_OBJECT, IN_NATIVE));
3886
3887 return true;
3888 }
3889
3890 //------------------------inline_native_setScopedValueCache------------------
3891 bool LibraryCallKit::inline_native_setScopedValueCache() {
3892 Node* arr = argument(0);
3893 Node* cache_obj_handle = scopedValueCache_helper();
3894 const Type* objects_type = scopedValueCache_type();
3895
3896 const TypePtr *adr_type = _gvn.type(cache_obj_handle)->isa_ptr();
3897 access_store_at(nullptr, cache_obj_handle, adr_type, arr, objects_type, T_OBJECT, IN_NATIVE | MO_UNORDERED);
3898
3899 return true;
3900 }
3901
3902 //------------------------inline_native_Continuation_pin and unpin-----------
3903
3904 // Shared implementation routine for both pin and unpin.
3905 bool LibraryCallKit::inline_native_Continuation_pinning(bool unpin) {
3906 enum { _true_path = 1, _false_path = 2, PATH_LIMIT };
3907
3908 // Save input memory.
3909 Node* input_memory_state = reset_memory();
3910 set_all_memory(input_memory_state);
3911
3912 // TLS
3913 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
3914 Node* last_continuation_offset = off_heap_plus_addr(tls_ptr, in_bytes(JavaThread::cont_entry_offset()));
3915 Node* last_continuation = make_load(control(), last_continuation_offset, last_continuation_offset->get_ptr_type(), T_ADDRESS, MemNode::unordered);
3916
3917 // Null check the last continuation object.
3918 Node* continuation_cmp_null = _gvn.transform(new CmpPNode(last_continuation, null()));
3919 Node* test_continuation_not_equal_null = _gvn.transform(new BoolNode(continuation_cmp_null, BoolTest::ne));
3920 IfNode* iff_continuation_not_equal_null = create_and_map_if(control(), test_continuation_not_equal_null, PROB_MAX, COUNT_UNKNOWN);
3921
3922 // False path, last continuation is null.
3923 Node* continuation_is_null = _gvn.transform(new IfFalseNode(iff_continuation_not_equal_null));
3924
3925 // True path, last continuation is not null.
3926 Node* continuation_is_not_null = _gvn.transform(new IfTrueNode(iff_continuation_not_equal_null));
3927
3928 set_control(continuation_is_not_null);
3929
3930 // Load the pin count from the last continuation.
3931 Node* pin_count_offset = off_heap_plus_addr(last_continuation, in_bytes(ContinuationEntry::pin_count_offset()));
3932 Node* pin_count = make_load(control(), pin_count_offset, TypeInt::INT, T_INT, MemNode::unordered);
3933
3934 // The loaded pin count is compared against a context specific rhs for over/underflow detection.
3935 Node* pin_count_rhs;
3936 if (unpin) {
3937 pin_count_rhs = _gvn.intcon(0);
3938 } else {
3939 pin_count_rhs = _gvn.intcon(UINT32_MAX);
3940 }
3941 Node* pin_count_cmp = _gvn.transform(new CmpUNode(pin_count, pin_count_rhs));
3942 Node* test_pin_count_over_underflow = _gvn.transform(new BoolNode(pin_count_cmp, BoolTest::eq));
3943 IfNode* iff_pin_count_over_underflow = create_and_map_if(control(), test_pin_count_over_underflow, PROB_MIN, COUNT_UNKNOWN);
3944
3945 // True branch, pin count over/underflow.
3946 Node* pin_count_over_underflow = _gvn.transform(new IfTrueNode(iff_pin_count_over_underflow));
3947 {
3948 // Trap (but not deoptimize (Action_none)) and continue in the interpreter
3949 // which will throw IllegalStateException for pin count over/underflow.
3950 // No memory changed so far - we can use memory create by reset_memory()
3951 // at the beginning of this intrinsic. No need to call reset_memory() again.
3952 PreserveJVMState pjvms(this);
3953 set_control(pin_count_over_underflow);
3954 uncommon_trap(Deoptimization::Reason_intrinsic,
3955 Deoptimization::Action_none);
3956 assert(stopped(), "invariant");
3957 }
3958
3959 // False branch, no pin count over/underflow. Increment or decrement pin count and store back.
3960 Node* valid_pin_count = _gvn.transform(new IfFalseNode(iff_pin_count_over_underflow));
3961 set_control(valid_pin_count);
3962
3963 Node* next_pin_count;
3964 if (unpin) {
3965 next_pin_count = _gvn.transform(new SubINode(pin_count, _gvn.intcon(1)));
3966 } else {
3967 next_pin_count = _gvn.transform(new AddINode(pin_count, _gvn.intcon(1)));
3968 }
3969
3970 store_to_memory(control(), pin_count_offset, next_pin_count, T_INT, MemNode::unordered);
3971
3972 // Result of top level CFG and Memory.
3973 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
3974 record_for_igvn(result_rgn);
3975 PhiNode* result_mem = new PhiNode(result_rgn, Type::MEMORY, TypePtr::BOTTOM);
3976 record_for_igvn(result_mem);
3977
3978 result_rgn->init_req(_true_path, valid_pin_count);
3979 result_rgn->init_req(_false_path, continuation_is_null);
3980 result_mem->init_req(_true_path, reset_memory());
3981 result_mem->init_req(_false_path, input_memory_state);
3982
3983 // Set output state.
3984 set_control(_gvn.transform(result_rgn));
3985 set_all_memory(_gvn.transform(result_mem));
3986
3987 return true;
3988 }
3989
3990 //---------------------------load_mirror_from_klass----------------------------
3991 // Given a klass oop, load its java mirror (a java.lang.Class oop).
3992 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
3993 Node* p = off_heap_plus_addr(klass, in_bytes(Klass::java_mirror_offset()));
3994 Node* load = make_load(nullptr, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3995 // mirror = ((OopHandle)mirror)->resolve();
3996 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
3997 }
3998
3999 //-----------------------load_klass_from_mirror_common-------------------------
4000 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
4001 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
4002 // and branch to the given path on the region.
4003 // If never_see_null, take an uncommon trap on null, so we can optimistically
4004 // compile for the non-null case.
4005 // If the region is null, force never_see_null = true.
4006 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
4007 bool never_see_null,
4008 RegionNode* region,
4009 int null_path,
4010 int offset) {
4011 if (region == nullptr) never_see_null = true;
4012 Node* p = basic_plus_adr(mirror, offset);
4013 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4014 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
4015 Node* null_ctl = top();
4016 kls = null_check_oop(kls, &null_ctl, never_see_null);
4017 if (region != nullptr) {
4018 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
4019 region->init_req(null_path, null_ctl);
4020 } else {
4021 assert(null_ctl == top(), "no loose ends");
4022 }
4023 return kls;
4024 }
4025
4026 //--------------------(inline_native_Class_query helpers)---------------------
4027 // Use this for JVM_ACC_INTERFACE.
4028 // Fall through if (mods & mask) == bits, take the guard otherwise.
4029 Node* LibraryCallKit::generate_klass_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region,
4030 ByteSize offset, const Type* type, BasicType bt) {
4031 // Branch around if the given klass has the given modifier bit set.
4032 // Like generate_guard, adds a new path onto the region.
4033 Node* modp = off_heap_plus_addr(kls, in_bytes(offset));
4034 Node* mods = make_load(nullptr, modp, type, bt, MemNode::unordered);
4035 Node* mask = intcon(modifier_mask);
4036 Node* bits = intcon(modifier_bits);
4037 Node* mbit = _gvn.transform(new AndINode(mods, mask));
4038 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
4039 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4040 return generate_fair_guard(bol, region);
4041 }
4042 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
4043 return generate_klass_flags_guard(kls, JVM_ACC_INTERFACE, 0, region,
4044 InstanceKlass::access_flags_offset(), TypeInt::CHAR, T_CHAR);
4045 }
4046
4047 // Use this for testing if Klass is_hidden, has_finalizer, and is_cloneable_fast.
4048 Node* LibraryCallKit::generate_misc_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
4049 return generate_klass_flags_guard(kls, modifier_mask, modifier_bits, region,
4050 Klass::misc_flags_offset(), TypeInt::UBYTE, T_BOOLEAN);
4051 }
4052
4053 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
4054 return generate_misc_flags_guard(kls, KlassFlags::_misc_is_hidden_class, 0, region);
4055 }
4056
4057 //-------------------------inline_native_Class_query-------------------
4058 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
4059 const Type* return_type = TypeInt::BOOL;
4060 Node* prim_return_value = top(); // what happens if it's a primitive class?
4061 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4062 bool expect_prim = false; // most of these guys expect to work on refs
4063
4064 enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
4065
4066 Node* mirror = argument(0);
4067 Node* obj = top();
4068
4069 switch (id) {
4070 case vmIntrinsics::_isInstance:
4071 // nothing is an instance of a primitive type
4072 prim_return_value = intcon(0);
4073 obj = argument(1);
4074 break;
4075 case vmIntrinsics::_isHidden:
4076 prim_return_value = intcon(0);
4077 break;
4078 case vmIntrinsics::_getSuperclass:
4079 prim_return_value = null();
4080 return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
4081 break;
4082 default:
4083 fatal_unexpected_iid(id);
4084 break;
4085 }
4086
4087 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4088 if (mirror_con == nullptr) return false; // cannot happen?
4089
4090 #ifndef PRODUCT
4091 if (C->print_intrinsics() || C->print_inlining()) {
4092 ciType* k = mirror_con->java_mirror_type();
4093 if (k) {
4094 tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
4095 k->print_name();
4096 tty->cr();
4097 }
4098 }
4099 #endif
4100
4101 // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
4102 RegionNode* region = new RegionNode(PATH_LIMIT);
4103 record_for_igvn(region);
4104 PhiNode* phi = new PhiNode(region, return_type);
4105
4106 // The mirror will never be null of Reflection.getClassAccessFlags, however
4107 // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
4108 // if it is. See bug 4774291.
4109
4110 // For Reflection.getClassAccessFlags(), the null check occurs in
4111 // the wrong place; see inline_unsafe_access(), above, for a similar
4112 // situation.
4113 mirror = null_check(mirror);
4114 // If mirror or obj is dead, only null-path is taken.
4115 if (stopped()) return true;
4116
4117 if (expect_prim) never_see_null = false; // expect nulls (meaning prims)
4118
4119 // Now load the mirror's klass metaobject, and null-check it.
4120 // Side-effects region with the control path if the klass is null.
4121 Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
4122 // If kls is null, we have a primitive mirror.
4123 phi->init_req(_prim_path, prim_return_value);
4124 if (stopped()) { set_result(region, phi); return true; }
4125 bool safe_for_replace = (region->in(_prim_path) == top());
4126
4127 Node* p; // handy temp
4128 Node* null_ctl;
4129
4130 // Now that we have the non-null klass, we can perform the real query.
4131 // For constant classes, the query will constant-fold in LoadNode::Value.
4132 Node* query_value = top();
4133 switch (id) {
4134 case vmIntrinsics::_isInstance:
4135 // nothing is an instance of a primitive type
4136 query_value = gen_instanceof(obj, kls, safe_for_replace);
4137 break;
4138
4139 case vmIntrinsics::_isHidden:
4140 // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
4141 if (generate_hidden_class_guard(kls, region) != nullptr)
4142 // A guard was added. If the guard is taken, it was an hidden class.
4143 phi->add_req(intcon(1));
4144 // If we fall through, it's a plain class.
4145 query_value = intcon(0);
4146 break;
4147
4148
4149 case vmIntrinsics::_getSuperclass:
4150 // The rules here are somewhat unfortunate, but we can still do better
4151 // with random logic than with a JNI call.
4152 // Interfaces store null or Object as _super, but must report null.
4153 // Arrays store an intermediate super as _super, but must report Object.
4154 // Other types can report the actual _super.
4155 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
4156 if (generate_array_guard(kls, region) != nullptr) {
4157 // A guard was added. If the guard is taken, it was an array.
4158 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
4159 }
4160 // Check for interface after array since this checks AccessFlags offset into InstanceKlass.
4161 // In other words, we are accessing subtype-specific information, so we need to determine the subtype first.
4162 if (generate_interface_guard(kls, region) != nullptr) {
4163 // A guard was added. If the guard is taken, it was an interface.
4164 phi->add_req(null());
4165 }
4166 // If we fall through, it's a plain class. Get its _super.
4167 p = off_heap_plus_addr(kls, in_bytes(Klass::super_offset()));
4168 kls = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeInstKlassPtr::OBJECT_OR_NULL));
4169 null_ctl = top();
4170 kls = null_check_oop(kls, &null_ctl);
4171 if (null_ctl != top()) {
4172 // If the guard is taken, Object.superClass is null (both klass and mirror).
4173 region->add_req(null_ctl);
4174 phi ->add_req(null());
4175 }
4176 if (!stopped()) {
4177 query_value = load_mirror_from_klass(kls);
4178 }
4179 break;
4180
4181 default:
4182 fatal_unexpected_iid(id);
4183 break;
4184 }
4185
4186 // Fall-through is the normal case of a query to a real class.
4187 phi->init_req(1, query_value);
4188 region->init_req(1, control());
4189
4190 C->set_has_split_ifs(true); // Has chance for split-if optimization
4191 set_result(region, phi);
4192 return true;
4193 }
4194
4195 //-------------------------inline_Class_cast-------------------
4196 bool LibraryCallKit::inline_Class_cast() {
4197 Node* mirror = argument(0); // Class
4198 Node* obj = argument(1);
4199 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
4200 if (mirror_con == nullptr) {
4201 return false; // dead path (mirror->is_top()).
4202 }
4203 if (obj == nullptr || obj->is_top()) {
4204 return false; // dead path
4205 }
4206 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
4207
4208 // First, see if Class.cast() can be folded statically.
4209 // java_mirror_type() returns non-null for compile-time Class constants.
4210 ciType* tm = mirror_con->java_mirror_type();
4211 if (tm != nullptr && tm->is_klass() &&
4212 tp != nullptr) {
4213 if (!tp->is_loaded()) {
4214 // Don't use intrinsic when class is not loaded.
4215 return false;
4216 } else {
4217 int static_res = C->static_subtype_check(TypeKlassPtr::make(tm->as_klass(), Type::trust_interfaces), tp->as_klass_type());
4218 if (static_res == Compile::SSC_always_true) {
4219 // isInstance() is true - fold the code.
4220 set_result(obj);
4221 return true;
4222 } else if (static_res == Compile::SSC_always_false) {
4223 // Don't use intrinsic, have to throw ClassCastException.
4224 // If the reference is null, the non-intrinsic bytecode will
4225 // be optimized appropriately.
4226 return false;
4227 }
4228 }
4229 }
4230
4231 // Bailout intrinsic and do normal inlining if exception path is frequent.
4232 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
4233 return false;
4234 }
4235
4236 // Generate dynamic checks.
4237 // Class.cast() is java implementation of _checkcast bytecode.
4238 // Do checkcast (Parse::do_checkcast()) optimizations here.
4239
4240 mirror = null_check(mirror);
4241 // If mirror is dead, only null-path is taken.
4242 if (stopped()) {
4243 return true;
4244 }
4245
4246 // Not-subtype or the mirror's klass ptr is null (in case it is a primitive).
4247 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
4248 RegionNode* region = new RegionNode(PATH_LIMIT);
4249 record_for_igvn(region);
4250
4251 // Now load the mirror's klass metaobject, and null-check it.
4252 // If kls is null, we have a primitive mirror and
4253 // nothing is an instance of a primitive type.
4254 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
4255
4256 Node* res = top();
4257 if (!stopped()) {
4258 Node* bad_type_ctrl = top();
4259 // Do checkcast optimizations.
4260 res = gen_checkcast(obj, kls, &bad_type_ctrl);
4261 region->init_req(_bad_type_path, bad_type_ctrl);
4262 }
4263 if (region->in(_prim_path) != top() ||
4264 region->in(_bad_type_path) != top()) {
4265 // Let Interpreter throw ClassCastException.
4266 PreserveJVMState pjvms(this);
4267 set_control(_gvn.transform(region));
4268 uncommon_trap(Deoptimization::Reason_intrinsic,
4269 Deoptimization::Action_maybe_recompile);
4270 }
4271 if (!stopped()) {
4272 set_result(res);
4273 }
4274 return true;
4275 }
4276
4277
4278 //--------------------------inline_native_subtype_check------------------------
4279 // This intrinsic takes the JNI calls out of the heart of
4280 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
4281 bool LibraryCallKit::inline_native_subtype_check() {
4282 // Pull both arguments off the stack.
4283 Node* args[2]; // two java.lang.Class mirrors: superc, subc
4284 args[0] = argument(0);
4285 args[1] = argument(1);
4286 Node* klasses[2]; // corresponding Klasses: superk, subk
4287 klasses[0] = klasses[1] = top();
4288
4289 enum {
4290 // A full decision tree on {superc is prim, subc is prim}:
4291 _prim_0_path = 1, // {P,N} => false
4292 // {P,P} & superc!=subc => false
4293 _prim_same_path, // {P,P} & superc==subc => true
4294 _prim_1_path, // {N,P} => false
4295 _ref_subtype_path, // {N,N} & subtype check wins => true
4296 _both_ref_path, // {N,N} & subtype check loses => false
4297 PATH_LIMIT
4298 };
4299
4300 RegionNode* region = new RegionNode(PATH_LIMIT);
4301 Node* phi = new PhiNode(region, TypeInt::BOOL);
4302 record_for_igvn(region);
4303
4304 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
4305 const TypeKlassPtr* kls_type = TypeInstKlassPtr::OBJECT_OR_NULL;
4306 int class_klass_offset = java_lang_Class::klass_offset();
4307
4308 // First null-check both mirrors and load each mirror's klass metaobject.
4309 int which_arg;
4310 for (which_arg = 0; which_arg <= 1; which_arg++) {
4311 Node* arg = args[which_arg];
4312 arg = null_check(arg);
4313 if (stopped()) break;
4314 args[which_arg] = arg;
4315
4316 Node* p = basic_plus_adr(arg, class_klass_offset);
4317 Node* kls = LoadKlassNode::make(_gvn, immutable_memory(), p, adr_type, kls_type);
4318 klasses[which_arg] = _gvn.transform(kls);
4319 }
4320
4321 // Having loaded both klasses, test each for null.
4322 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4323 for (which_arg = 0; which_arg <= 1; which_arg++) {
4324 Node* kls = klasses[which_arg];
4325 Node* null_ctl = top();
4326 kls = null_check_oop(kls, &null_ctl, never_see_null);
4327 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
4328 region->init_req(prim_path, null_ctl);
4329 if (stopped()) break;
4330 klasses[which_arg] = kls;
4331 }
4332
4333 if (!stopped()) {
4334 // now we have two reference types, in klasses[0..1]
4335 Node* subk = klasses[1]; // the argument to isAssignableFrom
4336 Node* superk = klasses[0]; // the receiver
4337 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
4338 // now we have a successful reference subtype check
4339 region->set_req(_ref_subtype_path, control());
4340 }
4341
4342 // If both operands are primitive (both klasses null), then
4343 // we must return true when they are identical primitives.
4344 // It is convenient to test this after the first null klass check.
4345 set_control(region->in(_prim_0_path)); // go back to first null check
4346 if (!stopped()) {
4347 // Since superc is primitive, make a guard for the superc==subc case.
4348 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
4349 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
4350 generate_guard(bol_eq, region, PROB_FAIR);
4351 if (region->req() == PATH_LIMIT+1) {
4352 // A guard was added. If the added guard is taken, superc==subc.
4353 region->swap_edges(PATH_LIMIT, _prim_same_path);
4354 region->del_req(PATH_LIMIT);
4355 }
4356 region->set_req(_prim_0_path, control()); // Not equal after all.
4357 }
4358
4359 // these are the only paths that produce 'true':
4360 phi->set_req(_prim_same_path, intcon(1));
4361 phi->set_req(_ref_subtype_path, intcon(1));
4362
4363 // pull together the cases:
4364 assert(region->req() == PATH_LIMIT, "sane region");
4365 for (uint i = 1; i < region->req(); i++) {
4366 Node* ctl = region->in(i);
4367 if (ctl == nullptr || ctl == top()) {
4368 region->set_req(i, top());
4369 phi ->set_req(i, top());
4370 } else if (phi->in(i) == nullptr) {
4371 phi->set_req(i, intcon(0)); // all other paths produce 'false'
4372 }
4373 }
4374
4375 set_control(_gvn.transform(region));
4376 set_result(_gvn.transform(phi));
4377 return true;
4378 }
4379
4380 //---------------------generate_array_guard_common------------------------
4381 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
4382 bool obj_array, bool not_array, Node** obj) {
4383
4384 if (stopped()) {
4385 return nullptr;
4386 }
4387
4388 // If obj_array/non_array==false/false:
4389 // Branch around if the given klass is in fact an array (either obj or prim).
4390 // If obj_array/non_array==false/true:
4391 // Branch around if the given klass is not an array klass of any kind.
4392 // If obj_array/non_array==true/true:
4393 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
4394 // If obj_array/non_array==true/false:
4395 // Branch around if the kls is an oop array (Object[] or subtype)
4396 //
4397 // Like generate_guard, adds a new path onto the region.
4398 jint layout_con = 0;
4399 Node* layout_val = get_layout_helper(kls, layout_con);
4400 if (layout_val == nullptr) {
4401 bool query = (obj_array
4402 ? Klass::layout_helper_is_objArray(layout_con)
4403 : Klass::layout_helper_is_array(layout_con));
4404 if (query == not_array) {
4405 return nullptr; // never a branch
4406 } else { // always a branch
4407 Node* always_branch = control();
4408 if (region != nullptr)
4409 region->add_req(always_branch);
4410 set_control(top());
4411 return always_branch;
4412 }
4413 }
4414 // Now test the correct condition.
4415 jint nval = (obj_array
4416 ? (jint)(Klass::_lh_array_tag_type_value
4417 << Klass::_lh_array_tag_shift)
4418 : Klass::_lh_neutral_value);
4419 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
4420 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
4421 // invert the test if we are looking for a non-array
4422 if (not_array) btest = BoolTest(btest).negate();
4423 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
4424 Node* ctrl = generate_fair_guard(bol, region);
4425 Node* is_array_ctrl = not_array ? control() : ctrl;
4426 if (obj != nullptr && is_array_ctrl != nullptr && is_array_ctrl != top()) {
4427 // Keep track of the fact that 'obj' is an array to prevent
4428 // array specific accesses from floating above the guard.
4429 *obj = _gvn.transform(new CheckCastPPNode(is_array_ctrl, *obj, TypeAryPtr::BOTTOM));
4430 }
4431 return ctrl;
4432 }
4433
4434
4435 //-----------------------inline_native_newArray--------------------------
4436 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
4437 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
4438 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
4439 Node* mirror;
4440 Node* count_val;
4441 if (uninitialized) {
4442 null_check_receiver();
4443 mirror = argument(1);
4444 count_val = argument(2);
4445 } else {
4446 mirror = argument(0);
4447 count_val = argument(1);
4448 }
4449
4450 mirror = null_check(mirror);
4451 // If mirror or obj is dead, only null-path is taken.
4452 if (stopped()) return true;
4453
4454 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
4455 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4456 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4457 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4458 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4459
4460 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
4461 Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
4462 result_reg, _slow_path);
4463 Node* normal_ctl = control();
4464 Node* no_array_ctl = result_reg->in(_slow_path);
4465
4466 // Generate code for the slow case. We make a call to newArray().
4467 set_control(no_array_ctl);
4468 if (!stopped()) {
4469 // Either the input type is void.class, or else the
4470 // array klass has not yet been cached. Either the
4471 // ensuing call will throw an exception, or else it
4472 // will cache the array klass for next time.
4473 PreserveJVMState pjvms(this);
4474 CallJavaNode* slow_call = nullptr;
4475 if (uninitialized) {
4476 // Generate optimized virtual call (holder class 'Unsafe' is final)
4477 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false, true);
4478 } else {
4479 slow_call = generate_method_call_static(vmIntrinsics::_newArray, true);
4480 }
4481 Node* slow_result = set_results_for_java_call(slow_call);
4482 // this->control() comes from set_results_for_java_call
4483 result_reg->set_req(_slow_path, control());
4484 result_val->set_req(_slow_path, slow_result);
4485 result_io ->set_req(_slow_path, i_o());
4486 result_mem->set_req(_slow_path, reset_memory());
4487 }
4488
4489 set_control(normal_ctl);
4490 if (!stopped()) {
4491 // Normal case: The array type has been cached in the java.lang.Class.
4492 // The following call works fine even if the array type is polymorphic.
4493 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4494 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
4495 result_reg->init_req(_normal_path, control());
4496 result_val->init_req(_normal_path, obj);
4497 result_io ->init_req(_normal_path, i_o());
4498 result_mem->init_req(_normal_path, reset_memory());
4499
4500 if (uninitialized) {
4501 // Mark the allocation so that zeroing is skipped
4502 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj);
4503 alloc->maybe_set_complete(&_gvn);
4504 }
4505 }
4506
4507 // Return the combined state.
4508 set_i_o( _gvn.transform(result_io) );
4509 set_all_memory( _gvn.transform(result_mem));
4510
4511 C->set_has_split_ifs(true); // Has chance for split-if optimization
4512 set_result(result_reg, result_val);
4513 return true;
4514 }
4515
4516 //----------------------inline_native_getLength--------------------------
4517 // public static native int java.lang.reflect.Array.getLength(Object array);
4518 bool LibraryCallKit::inline_native_getLength() {
4519 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
4520
4521 Node* array = null_check(argument(0));
4522 // If array is dead, only null-path is taken.
4523 if (stopped()) return true;
4524
4525 // Deoptimize if it is a non-array.
4526 Node* non_array = generate_non_array_guard(load_object_klass(array), nullptr, &array);
4527
4528 if (non_array != nullptr) {
4529 PreserveJVMState pjvms(this);
4530 set_control(non_array);
4531 uncommon_trap(Deoptimization::Reason_intrinsic,
4532 Deoptimization::Action_maybe_recompile);
4533 }
4534
4535 // If control is dead, only non-array-path is taken.
4536 if (stopped()) return true;
4537
4538 // The works fine even if the array type is polymorphic.
4539 // It could be a dynamic mix of int[], boolean[], Object[], etc.
4540 Node* result = load_array_length(array);
4541
4542 C->set_has_split_ifs(true); // Has chance for split-if optimization
4543 set_result(result);
4544 return true;
4545 }
4546
4547 //------------------------inline_array_copyOf----------------------------
4548 // public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);
4549 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);
4550 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
4551 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
4552
4553 // Get the arguments.
4554 Node* original = argument(0);
4555 Node* start = is_copyOfRange? argument(1): intcon(0);
4556 Node* end = is_copyOfRange? argument(2): argument(1);
4557 Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
4558
4559 Node* newcopy = nullptr;
4560
4561 // Set the original stack and the reexecute bit for the interpreter to reexecute
4562 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
4563 { PreserveReexecuteState preexecs(this);
4564 jvms()->set_should_reexecute(true);
4565
4566 array_type_mirror = null_check(array_type_mirror);
4567 original = null_check(original);
4568
4569 // Check if a null path was taken unconditionally.
4570 if (stopped()) return true;
4571
4572 Node* orig_length = load_array_length(original);
4573
4574 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, nullptr, 0);
4575 klass_node = null_check(klass_node);
4576
4577 RegionNode* bailout = new RegionNode(1);
4578 record_for_igvn(bailout);
4579
4580 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
4581 // Bail out if that is so.
4582 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
4583 if (not_objArray != nullptr) {
4584 // Improve the klass node's type from the new optimistic assumption:
4585 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
4586 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
4587 Node* cast = new CastPPNode(control(), klass_node, akls);
4588 klass_node = _gvn.transform(cast);
4589 }
4590
4591 // Bail out if either start or end is negative.
4592 generate_negative_guard(start, bailout, &start);
4593 generate_negative_guard(end, bailout, &end);
4594
4595 Node* length = end;
4596 if (_gvn.type(start) != TypeInt::ZERO) {
4597 length = _gvn.transform(new SubINode(end, start));
4598 }
4599
4600 // Bail out if length is negative (i.e., if start > end).
4601 // Without this the new_array would throw
4602 // NegativeArraySizeException but IllegalArgumentException is what
4603 // should be thrown
4604 generate_negative_guard(length, bailout, &length);
4605
4606 // Bail out if start is larger than the original length
4607 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
4608 generate_negative_guard(orig_tail, bailout, &orig_tail);
4609
4610 if (bailout->req() > 1) {
4611 PreserveJVMState pjvms(this);
4612 set_control(_gvn.transform(bailout));
4613 uncommon_trap(Deoptimization::Reason_intrinsic,
4614 Deoptimization::Action_maybe_recompile);
4615 }
4616
4617 if (!stopped()) {
4618 // How many elements will we copy from the original?
4619 // The answer is MinI(orig_tail, length).
4620 Node* moved = _gvn.transform(new MinINode(orig_tail, length));
4621
4622 // Generate a direct call to the right arraycopy function(s).
4623 // We know the copy is disjoint but we might not know if the
4624 // oop stores need checking.
4625 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
4626 // This will fail a store-check if x contains any non-nulls.
4627
4628 // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
4629 // loads/stores but it is legal only if we're sure the
4630 // Arrays.copyOf would succeed. So we need all input arguments
4631 // to the copyOf to be validated, including that the copy to the
4632 // new array won't trigger an ArrayStoreException. That subtype
4633 // check can be optimized if we know something on the type of
4634 // the input array from type speculation.
4635 if (_gvn.type(klass_node)->singleton()) {
4636 const TypeKlassPtr* subk = _gvn.type(load_object_klass(original))->is_klassptr();
4637 const TypeKlassPtr* superk = _gvn.type(klass_node)->is_klassptr();
4638
4639 int test = C->static_subtype_check(superk, subk);
4640 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
4641 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
4642 if (t_original->speculative_type() != nullptr) {
4643 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
4644 }
4645 }
4646 }
4647
4648 bool validated = false;
4649 // Reason_class_check rather than Reason_intrinsic because we
4650 // want to intrinsify even if this traps.
4651 if (!too_many_traps(Deoptimization::Reason_class_check)) {
4652 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
4653
4654 if (not_subtype_ctrl != top()) {
4655 PreserveJVMState pjvms(this);
4656 set_control(not_subtype_ctrl);
4657 uncommon_trap(Deoptimization::Reason_class_check,
4658 Deoptimization::Action_make_not_entrant);
4659 assert(stopped(), "Should be stopped");
4660 }
4661 validated = true;
4662 }
4663
4664 if (!stopped()) {
4665 newcopy = new_array(klass_node, length, 0); // no arguments to push
4666
4667 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, true,
4668 load_object_klass(original), klass_node);
4669 if (!is_copyOfRange) {
4670 ac->set_copyof(validated);
4671 } else {
4672 ac->set_copyofrange(validated);
4673 }
4674 Node* n = _gvn.transform(ac);
4675 if (n == ac) {
4676 ac->connect_outputs(this);
4677 } else {
4678 assert(validated, "shouldn't transform if all arguments not validated");
4679 set_all_memory(n);
4680 }
4681 }
4682 }
4683 } // original reexecute is set back here
4684
4685 C->set_has_split_ifs(true); // Has chance for split-if optimization
4686 if (!stopped()) {
4687 set_result(newcopy);
4688 }
4689 return true;
4690 }
4691
4692
4693 //----------------------generate_virtual_guard---------------------------
4694 // Helper for hashCode and clone. Peeks inside the vtable to avoid a call.
4695 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
4696 RegionNode* slow_region) {
4697 ciMethod* method = callee();
4698 int vtable_index = method->vtable_index();
4699 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4700 "bad index %d", vtable_index);
4701 // Get the Method* out of the appropriate vtable entry.
4702 int entry_offset = in_bytes(Klass::vtable_start_offset()) +
4703 vtable_index*vtableEntry::size_in_bytes() +
4704 in_bytes(vtableEntry::method_offset());
4705 Node* entry_addr = off_heap_plus_addr(obj_klass, entry_offset);
4706 Node* target_call = make_load(nullptr, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4707
4708 // Compare the target method with the expected method (e.g., Object.hashCode).
4709 const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
4710
4711 Node* native_call = makecon(native_call_addr);
4712 Node* chk_native = _gvn.transform(new CmpPNode(target_call, native_call));
4713 Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
4714
4715 return generate_slow_guard(test_native, slow_region);
4716 }
4717
4718 //-----------------------generate_method_call----------------------------
4719 // Use generate_method_call to make a slow-call to the real
4720 // method if the fast path fails. An alternative would be to
4721 // use a stub like OptoRuntime::slow_arraycopy_Java.
4722 // This only works for expanding the current library call,
4723 // not another intrinsic. (E.g., don't use this for making an
4724 // arraycopy call inside of the copyOf intrinsic.)
4725 CallJavaNode*
4726 LibraryCallKit::generate_method_call(vmIntrinsicID method_id, bool is_virtual, bool is_static, bool res_not_null) {
4727 // When compiling the intrinsic method itself, do not use this technique.
4728 guarantee(callee() != C->method(), "cannot make slow-call to self");
4729
4730 ciMethod* method = callee();
4731 // ensure the JVMS we have will be correct for this call
4732 guarantee(method_id == method->intrinsic_id(), "must match");
4733
4734 const TypeFunc* tf = TypeFunc::make(method);
4735 if (res_not_null) {
4736 assert(tf->return_type() == T_OBJECT, "");
4737 const TypeTuple* range = tf->range();
4738 const Type** fields = TypeTuple::fields(range->cnt());
4739 fields[TypeFunc::Parms] = range->field_at(TypeFunc::Parms)->filter_speculative(TypePtr::NOTNULL);
4740 const TypeTuple* new_range = TypeTuple::make(range->cnt(), fields);
4741 tf = TypeFunc::make(tf->domain(), new_range);
4742 }
4743 CallJavaNode* slow_call;
4744 if (is_static) {
4745 assert(!is_virtual, "");
4746 slow_call = new CallStaticJavaNode(C, tf,
4747 SharedRuntime::get_resolve_static_call_stub(), method);
4748 } else if (is_virtual) {
4749 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4750 int vtable_index = Method::invalid_vtable_index;
4751 if (UseInlineCaches) {
4752 // Suppress the vtable call
4753 } else {
4754 // hashCode and clone are not a miranda methods,
4755 // so the vtable index is fixed.
4756 // No need to use the linkResolver to get it.
4757 vtable_index = method->vtable_index();
4758 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
4759 "bad index %d", vtable_index);
4760 }
4761 slow_call = new CallDynamicJavaNode(tf,
4762 SharedRuntime::get_resolve_virtual_call_stub(),
4763 method, vtable_index);
4764 } else { // neither virtual nor static: opt_virtual
4765 assert(!gvn().type(argument(0))->maybe_null(), "should not be null");
4766 slow_call = new CallStaticJavaNode(C, tf,
4767 SharedRuntime::get_resolve_opt_virtual_call_stub(), method);
4768 slow_call->set_optimized_virtual(true);
4769 }
4770 if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
4771 // To be able to issue a direct call (optimized virtual or virtual)
4772 // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
4773 // about the method being invoked should be attached to the call site to
4774 // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
4775 slow_call->set_override_symbolic_info(true);
4776 }
4777 set_arguments_for_java_call(slow_call);
4778 set_edges_for_java_call(slow_call);
4779 return slow_call;
4780 }
4781
4782
4783 /**
4784 * Build special case code for calls to hashCode on an object. This call may
4785 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
4786 * slightly different code.
4787 */
4788 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
4789 assert(is_static == callee()->is_static(), "correct intrinsic selection");
4790 assert(!(is_virtual && is_static), "either virtual, special, or static");
4791
4792 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
4793
4794 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4795 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
4796 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
4797 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4798 Node* obj = nullptr;
4799 if (!is_static) {
4800 // Check for hashing null object
4801 obj = null_check_receiver();
4802 if (stopped()) return true; // unconditionally null
4803 result_reg->init_req(_null_path, top());
4804 result_val->init_req(_null_path, top());
4805 } else {
4806 // Do a null check, and return zero if null.
4807 // System.identityHashCode(null) == 0
4808 obj = argument(0);
4809 Node* null_ctl = top();
4810 obj = null_check_oop(obj, &null_ctl);
4811 result_reg->init_req(_null_path, null_ctl);
4812 result_val->init_req(_null_path, _gvn.intcon(0));
4813 }
4814
4815 // Unconditionally null? Then return right away.
4816 if (stopped()) {
4817 set_control( result_reg->in(_null_path));
4818 if (!stopped())
4819 set_result(result_val->in(_null_path));
4820 return true;
4821 }
4822
4823 // We only go to the fast case code if we pass a number of guards. The
4824 // paths which do not pass are accumulated in the slow_region.
4825 RegionNode* slow_region = new RegionNode(1);
4826 record_for_igvn(slow_region);
4827
4828 // If this is a virtual call, we generate a funny guard. We pull out
4829 // the vtable entry corresponding to hashCode() from the target object.
4830 // If the target method which we are calling happens to be the native
4831 // Object hashCode() method, we pass the guard. We do not need this
4832 // guard for non-virtual calls -- the caller is known to be the native
4833 // Object hashCode().
4834 if (is_virtual) {
4835 // After null check, get the object's klass.
4836 Node* obj_klass = load_object_klass(obj);
4837 generate_virtual_guard(obj_klass, slow_region);
4838 }
4839
4840 // Get the header out of the object, use LoadMarkNode when available
4841 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
4842 // The control of the load must be null. Otherwise, the load can move before
4843 // the null check after castPP removal.
4844 Node* no_ctrl = nullptr;
4845 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
4846
4847 if (!UseObjectMonitorTable) {
4848 // Test the header to see if it is safe to read w.r.t. locking.
4849 Node *lock_mask = _gvn.MakeConX(markWord::lock_mask_in_place);
4850 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
4851 Node *monitor_val = _gvn.MakeConX(markWord::monitor_value);
4852 Node *chk_monitor = _gvn.transform(new CmpXNode(lmasked_header, monitor_val));
4853 Node *test_monitor = _gvn.transform(new BoolNode(chk_monitor, BoolTest::eq));
4854
4855 generate_slow_guard(test_monitor, slow_region);
4856 }
4857
4858 // Get the hash value and check to see that it has been properly assigned.
4859 // We depend on hash_mask being at most 32 bits and avoid the use of
4860 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
4861 // vm: see markWord.hpp.
4862 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
4863 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
4864 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
4865 // This hack lets the hash bits live anywhere in the mark object now, as long
4866 // as the shift drops the relevant bits into the low 32 bits. Note that
4867 // Java spec says that HashCode is an int so there's no point in capturing
4868 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
4869 hshifted_header = ConvX2I(hshifted_header);
4870 Node *hash_val = _gvn.transform(new AndINode(hshifted_header, hash_mask));
4871
4872 Node *no_hash_val = _gvn.intcon(markWord::no_hash);
4873 Node *chk_assigned = _gvn.transform(new CmpINode( hash_val, no_hash_val));
4874 Node *test_assigned = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
4875
4876 generate_slow_guard(test_assigned, slow_region);
4877
4878 Node* init_mem = reset_memory();
4879 // fill in the rest of the null path:
4880 result_io ->init_req(_null_path, i_o());
4881 result_mem->init_req(_null_path, init_mem);
4882
4883 result_val->init_req(_fast_path, hash_val);
4884 result_reg->init_req(_fast_path, control());
4885 result_io ->init_req(_fast_path, i_o());
4886 result_mem->init_req(_fast_path, init_mem);
4887
4888 // Generate code for the slow case. We make a call to hashCode().
4889 set_control(_gvn.transform(slow_region));
4890 if (!stopped()) {
4891 // No need for PreserveJVMState, because we're using up the present state.
4892 set_all_memory(init_mem);
4893 vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
4894 CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static, false);
4895 Node* slow_result = set_results_for_java_call(slow_call);
4896 // this->control() comes from set_results_for_java_call
4897 result_reg->init_req(_slow_path, control());
4898 result_val->init_req(_slow_path, slow_result);
4899 result_io ->set_req(_slow_path, i_o());
4900 result_mem ->set_req(_slow_path, reset_memory());
4901 }
4902
4903 // Return the combined state.
4904 set_i_o( _gvn.transform(result_io) );
4905 set_all_memory( _gvn.transform(result_mem));
4906
4907 set_result(result_reg, result_val);
4908 return true;
4909 }
4910
4911 //---------------------------inline_native_getClass----------------------------
4912 // public final native Class<?> java.lang.Object.getClass();
4913 //
4914 // Build special case code for calls to getClass on an object.
4915 bool LibraryCallKit::inline_native_getClass() {
4916 Node* obj = null_check_receiver();
4917 if (stopped()) return true;
4918 set_result(load_mirror_from_klass(load_object_klass(obj)));
4919 return true;
4920 }
4921
4922 //-----------------inline_native_Reflection_getCallerClass---------------------
4923 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
4924 //
4925 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
4926 //
4927 // NOTE: This code must perform the same logic as JVM_GetCallerClass
4928 // in that it must skip particular security frames and checks for
4929 // caller sensitive methods.
4930 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
4931 #ifndef PRODUCT
4932 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4933 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
4934 }
4935 #endif
4936
4937 if (!jvms()->has_method()) {
4938 #ifndef PRODUCT
4939 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4940 tty->print_cr(" Bailing out because intrinsic was inlined at top level");
4941 }
4942 #endif
4943 return false;
4944 }
4945
4946 // Walk back up the JVM state to find the caller at the required
4947 // depth.
4948 JVMState* caller_jvms = jvms();
4949
4950 // Cf. JVM_GetCallerClass
4951 // NOTE: Start the loop at depth 1 because the current JVM state does
4952 // not include the Reflection.getCallerClass() frame.
4953 for (int n = 1; caller_jvms != nullptr; caller_jvms = caller_jvms->caller(), n++) {
4954 ciMethod* m = caller_jvms->method();
4955 switch (n) {
4956 case 0:
4957 fatal("current JVM state does not include the Reflection.getCallerClass frame");
4958 break;
4959 case 1:
4960 // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
4961 if (!m->caller_sensitive()) {
4962 #ifndef PRODUCT
4963 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4964 tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);
4965 }
4966 #endif
4967 return false; // bail-out; let JVM_GetCallerClass do the work
4968 }
4969 break;
4970 default:
4971 if (!m->is_ignored_by_security_stack_walk()) {
4972 // We have reached the desired frame; return the holder class.
4973 // Acquire method holder as java.lang.Class and push as constant.
4974 ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
4975 ciInstance* caller_mirror = caller_klass->java_mirror();
4976 set_result(makecon(TypeInstPtr::make(caller_mirror)));
4977
4978 #ifndef PRODUCT
4979 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4980 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());
4981 tty->print_cr(" JVM state at this point:");
4982 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4983 ciMethod* m = jvms()->of_depth(i)->method();
4984 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
4985 }
4986 }
4987 #endif
4988 return true;
4989 }
4990 break;
4991 }
4992 }
4993
4994 #ifndef PRODUCT
4995 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
4996 tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
4997 tty->print_cr(" JVM state at this point:");
4998 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
4999 ciMethod* m = jvms()->of_depth(i)->method();
5000 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
5001 }
5002 }
5003 #endif
5004
5005 return false; // bail-out; let JVM_GetCallerClass do the work
5006 }
5007
5008 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
5009 Node* arg = argument(0);
5010 Node* result = nullptr;
5011
5012 switch (id) {
5013 case vmIntrinsics::_floatToRawIntBits: result = new MoveF2INode(arg); break;
5014 case vmIntrinsics::_intBitsToFloat: result = new MoveI2FNode(arg); break;
5015 case vmIntrinsics::_doubleToRawLongBits: result = new MoveD2LNode(arg); break;
5016 case vmIntrinsics::_longBitsToDouble: result = new MoveL2DNode(arg); break;
5017 case vmIntrinsics::_floatToFloat16: result = new ConvF2HFNode(arg); break;
5018 case vmIntrinsics::_float16ToFloat: result = new ConvHF2FNode(arg); break;
5019
5020 case vmIntrinsics::_doubleToLongBits: {
5021 // two paths (plus control) merge in a wood
5022 RegionNode *r = new RegionNode(3);
5023 Node *phi = new PhiNode(r, TypeLong::LONG);
5024
5025 Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
5026 // Build the boolean node
5027 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5028
5029 // Branch either way.
5030 // NaN case is less traveled, which makes all the difference.
5031 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5032 Node *opt_isnan = _gvn.transform(ifisnan);
5033 assert( opt_isnan->is_If(), "Expect an IfNode");
5034 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5035 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5036
5037 set_control(iftrue);
5038
5039 static const jlong nan_bits = CONST64(0x7ff8000000000000);
5040 Node *slow_result = longcon(nan_bits); // return NaN
5041 phi->init_req(1, _gvn.transform( slow_result ));
5042 r->init_req(1, iftrue);
5043
5044 // Else fall through
5045 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5046 set_control(iffalse);
5047
5048 phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
5049 r->init_req(2, iffalse);
5050
5051 // Post merge
5052 set_control(_gvn.transform(r));
5053 record_for_igvn(r);
5054
5055 C->set_has_split_ifs(true); // Has chance for split-if optimization
5056 result = phi;
5057 assert(result->bottom_type()->isa_long(), "must be");
5058 break;
5059 }
5060
5061 case vmIntrinsics::_floatToIntBits: {
5062 // two paths (plus control) merge in a wood
5063 RegionNode *r = new RegionNode(3);
5064 Node *phi = new PhiNode(r, TypeInt::INT);
5065
5066 Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
5067 // Build the boolean node
5068 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
5069
5070 // Branch either way.
5071 // NaN case is less traveled, which makes all the difference.
5072 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
5073 Node *opt_isnan = _gvn.transform(ifisnan);
5074 assert( opt_isnan->is_If(), "Expect an IfNode");
5075 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
5076 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
5077
5078 set_control(iftrue);
5079
5080 static const jint nan_bits = 0x7fc00000;
5081 Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
5082 phi->init_req(1, _gvn.transform( slow_result ));
5083 r->init_req(1, iftrue);
5084
5085 // Else fall through
5086 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
5087 set_control(iffalse);
5088
5089 phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
5090 r->init_req(2, iffalse);
5091
5092 // Post merge
5093 set_control(_gvn.transform(r));
5094 record_for_igvn(r);
5095
5096 C->set_has_split_ifs(true); // Has chance for split-if optimization
5097 result = phi;
5098 assert(result->bottom_type()->isa_int(), "must be");
5099 break;
5100 }
5101
5102 default:
5103 fatal_unexpected_iid(id);
5104 break;
5105 }
5106 set_result(_gvn.transform(result));
5107 return true;
5108 }
5109
5110 bool LibraryCallKit::inline_fp_range_check(vmIntrinsics::ID id) {
5111 Node* arg = argument(0);
5112 Node* result = nullptr;
5113
5114 switch (id) {
5115 case vmIntrinsics::_floatIsInfinite:
5116 result = new IsInfiniteFNode(arg);
5117 break;
5118 case vmIntrinsics::_floatIsFinite:
5119 result = new IsFiniteFNode(arg);
5120 break;
5121 case vmIntrinsics::_doubleIsInfinite:
5122 result = new IsInfiniteDNode(arg);
5123 break;
5124 case vmIntrinsics::_doubleIsFinite:
5125 result = new IsFiniteDNode(arg);
5126 break;
5127 default:
5128 fatal_unexpected_iid(id);
5129 break;
5130 }
5131 set_result(_gvn.transform(result));
5132 return true;
5133 }
5134
5135 //----------------------inline_unsafe_copyMemory-------------------------
5136 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
5137
5138 static bool has_wide_mem(PhaseGVN& gvn, Node* addr, Node* base) {
5139 const TypeAryPtr* addr_t = gvn.type(addr)->isa_aryptr();
5140 const Type* base_t = gvn.type(base);
5141
5142 bool in_native = (base_t == TypePtr::NULL_PTR);
5143 bool in_heap = !TypePtr::NULL_PTR->higher_equal(base_t);
5144 bool is_mixed = !in_heap && !in_native;
5145
5146 if (is_mixed) {
5147 return true; // mixed accesses can touch both on-heap and off-heap memory
5148 }
5149 if (in_heap) {
5150 bool is_prim_array = (addr_t != nullptr) && (addr_t->elem() != Type::BOTTOM);
5151 if (!is_prim_array) {
5152 // Though Unsafe.copyMemory() ensures at runtime for on-heap accesses that base is a primitive array,
5153 // there's not enough type information available to determine proper memory slice for it.
5154 return true;
5155 }
5156 }
5157 return false;
5158 }
5159
5160 bool LibraryCallKit::inline_unsafe_copyMemory() {
5161 if (callee()->is_static()) return false; // caller must have the capability!
5162 null_check_receiver(); // null-check receiver
5163 if (stopped()) return true;
5164
5165 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5166
5167 Node* src_base = argument(1); // type: oop
5168 Node* src_off = ConvL2X(argument(2)); // type: long
5169 Node* dst_base = argument(4); // type: oop
5170 Node* dst_off = ConvL2X(argument(5)); // type: long
5171 Node* size = ConvL2X(argument(7)); // type: long
5172
5173 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5174 "fieldOffset must be byte-scaled");
5175
5176 Node* src_addr = make_unsafe_address(src_base, src_off);
5177 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5178
5179 Node* thread = _gvn.transform(new ThreadLocalNode());
5180 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5181 BasicType doing_unsafe_access_bt = T_BYTE;
5182 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5183
5184 // update volatile field
5185 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5186
5187 int flags = RC_LEAF | RC_NO_FP;
5188
5189 const TypePtr* dst_type = TypePtr::BOTTOM;
5190
5191 // Adjust memory effects of the runtime call based on input values.
5192 if (!has_wide_mem(_gvn, src_addr, src_base) &&
5193 !has_wide_mem(_gvn, dst_addr, dst_base)) {
5194 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5195
5196 const TypePtr* src_type = _gvn.type(src_addr)->is_ptr();
5197 if (C->get_alias_index(src_type) == C->get_alias_index(dst_type)) {
5198 flags |= RC_NARROW_MEM; // narrow in memory
5199 }
5200 }
5201
5202 // Call it. Note that the length argument is not scaled.
5203 make_runtime_call(flags,
5204 OptoRuntime::fast_arraycopy_Type(),
5205 StubRoutines::unsafe_arraycopy(),
5206 "unsafe_arraycopy",
5207 dst_type,
5208 src_addr, dst_addr, size XTOP);
5209
5210 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5211
5212 return true;
5213 }
5214
5215 // unsafe_setmemory(void *base, ulong offset, size_t length, char fill_value);
5216 // Fill 'length' bytes starting from 'base[offset]' with 'fill_value'
5217 bool LibraryCallKit::inline_unsafe_setMemory() {
5218 if (callee()->is_static()) return false; // caller must have the capability!
5219 null_check_receiver(); // null-check receiver
5220 if (stopped()) return true;
5221
5222 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
5223
5224 Node* dst_base = argument(1); // type: oop
5225 Node* dst_off = ConvL2X(argument(2)); // type: long
5226 Node* size = ConvL2X(argument(4)); // type: long
5227 Node* byte = argument(6); // type: byte
5228
5229 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
5230 "fieldOffset must be byte-scaled");
5231
5232 Node* dst_addr = make_unsafe_address(dst_base, dst_off);
5233
5234 Node* thread = _gvn.transform(new ThreadLocalNode());
5235 Node* doing_unsafe_access_addr = off_heap_plus_addr(thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
5236 BasicType doing_unsafe_access_bt = T_BYTE;
5237 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
5238
5239 // update volatile field
5240 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, MemNode::unordered);
5241
5242 int flags = RC_LEAF | RC_NO_FP;
5243
5244 const TypePtr* dst_type = TypePtr::BOTTOM;
5245
5246 // Adjust memory effects of the runtime call based on input values.
5247 if (!has_wide_mem(_gvn, dst_addr, dst_base)) {
5248 dst_type = _gvn.type(dst_addr)->is_ptr(); // narrow out memory
5249
5250 flags |= RC_NARROW_MEM; // narrow in memory
5251 }
5252
5253 // Call it. Note that the length argument is not scaled.
5254 make_runtime_call(flags,
5255 OptoRuntime::unsafe_setmemory_Type(),
5256 StubRoutines::unsafe_setmemory(),
5257 "unsafe_setmemory",
5258 dst_type,
5259 dst_addr, size XTOP, byte);
5260
5261 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, MemNode::unordered);
5262
5263 return true;
5264 }
5265
5266 #undef XTOP
5267
5268 //------------------------clone_coping-----------------------------------
5269 // Helper function for inline_native_clone.
5270 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
5271 assert(obj_size != nullptr, "");
5272 Node* raw_obj = alloc_obj->in(1);
5273 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
5274
5275 AllocateNode* alloc = nullptr;
5276 if (ReduceBulkZeroing &&
5277 // If we are implementing an array clone without knowing its source type
5278 // (can happen when compiling the array-guarded branch of a reflective
5279 // Object.clone() invocation), initialize the array within the allocation.
5280 // This is needed because some GCs (e.g. ZGC) might fall back in this case
5281 // to a runtime clone call that assumes fully initialized source arrays.
5282 (!is_array || obj->get_ptr_type()->isa_aryptr() != nullptr)) {
5283 // We will be completely responsible for initializing this object -
5284 // mark Initialize node as complete.
5285 alloc = AllocateNode::Ideal_allocation(alloc_obj);
5286 // The object was just allocated - there should be no any stores!
5287 guarantee(alloc != nullptr && alloc->maybe_set_complete(&_gvn), "");
5288 // Mark as complete_with_arraycopy so that on AllocateNode
5289 // expansion, we know this AllocateNode is initialized by an array
5290 // copy and a StoreStore barrier exists after the array copy.
5291 alloc->initialization()->set_complete_with_arraycopy();
5292 }
5293
5294 Node* size = _gvn.transform(obj_size);
5295 access_clone(obj, alloc_obj, size, is_array);
5296
5297 // Do not let reads from the cloned object float above the arraycopy.
5298 if (alloc != nullptr) {
5299 // Do not let stores that initialize this object be reordered with
5300 // a subsequent store that would make this object accessible by
5301 // other threads.
5302 // Record what AllocateNode this StoreStore protects so that
5303 // escape analysis can go from the MemBarStoreStoreNode to the
5304 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
5305 // based on the escape status of the AllocateNode.
5306 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
5307 } else {
5308 insert_mem_bar(Op_MemBarCPUOrder);
5309 }
5310 }
5311
5312 //------------------------inline_native_clone----------------------------
5313 // protected native Object java.lang.Object.clone();
5314 //
5315 // Here are the simple edge cases:
5316 // null receiver => normal trap
5317 // virtual and clone was overridden => slow path to out-of-line clone
5318 // not cloneable or finalizer => slow path to out-of-line Object.clone
5319 //
5320 // The general case has two steps, allocation and copying.
5321 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
5322 //
5323 // Copying also has two cases, oop arrays and everything else.
5324 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
5325 // Everything else uses the tight inline loop supplied by CopyArrayNode.
5326 //
5327 // These steps fold up nicely if and when the cloned object's klass
5328 // can be sharply typed as an object array, a type array, or an instance.
5329 //
5330 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
5331 PhiNode* result_val;
5332
5333 // Set the reexecute bit for the interpreter to reexecute
5334 // the bytecode that invokes Object.clone if deoptimization happens.
5335 { PreserveReexecuteState preexecs(this);
5336 jvms()->set_should_reexecute(true);
5337
5338 Node* obj = null_check_receiver();
5339 if (stopped()) return true;
5340
5341 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
5342
5343 // If we are going to clone an instance, we need its exact type to
5344 // know the number and types of fields to convert the clone to
5345 // loads/stores. Maybe a speculative type can help us.
5346 if (!obj_type->klass_is_exact() &&
5347 obj_type->speculative_type() != nullptr &&
5348 obj_type->speculative_type()->is_instance_klass()) {
5349 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
5350 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
5351 !spec_ik->has_injected_fields()) {
5352 if (!obj_type->isa_instptr() ||
5353 obj_type->is_instptr()->instance_klass()->has_subklass()) {
5354 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
5355 }
5356 }
5357 }
5358
5359 // Conservatively insert a memory barrier on all memory slices.
5360 // Do not let writes into the original float below the clone.
5361 insert_mem_bar(Op_MemBarCPUOrder);
5362
5363 // paths into result_reg:
5364 enum {
5365 _slow_path = 1, // out-of-line call to clone method (virtual or not)
5366 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
5367 _array_path, // plain array allocation, plus arrayof_long_arraycopy
5368 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
5369 PATH_LIMIT
5370 };
5371 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
5372 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
5373 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
5374 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
5375 record_for_igvn(result_reg);
5376
5377 Node* obj_klass = load_object_klass(obj);
5378 Node* array_obj = obj;
5379 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)nullptr, &array_obj);
5380 if (array_ctl != nullptr) {
5381 // It's an array.
5382 PreserveJVMState pjvms(this);
5383 set_control(array_ctl);
5384 Node* obj_length = load_array_length(array_obj);
5385 Node* array_size = nullptr; // Size of the array without object alignment padding.
5386 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &array_size, /*deoptimize_on_exception=*/true);
5387
5388 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
5389 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, false, BarrierSetC2::Parsing)) {
5390 // If it is an oop array, it requires very special treatment,
5391 // because gc barriers are required when accessing the array.
5392 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)nullptr);
5393 if (is_obja != nullptr) {
5394 PreserveJVMState pjvms2(this);
5395 set_control(is_obja);
5396 // Generate a direct call to the right arraycopy function(s).
5397 // Clones are always tightly coupled.
5398 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, array_obj, intcon(0), alloc_obj, intcon(0), obj_length, true, false);
5399 ac->set_clone_oop_array();
5400 Node* n = _gvn.transform(ac);
5401 assert(n == ac, "cannot disappear");
5402 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
5403
5404 result_reg->init_req(_objArray_path, control());
5405 result_val->init_req(_objArray_path, alloc_obj);
5406 result_i_o ->set_req(_objArray_path, i_o());
5407 result_mem ->set_req(_objArray_path, reset_memory());
5408 }
5409 }
5410 // Otherwise, there are no barriers to worry about.
5411 // (We can dispense with card marks if we know the allocation
5412 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
5413 // causes the non-eden paths to take compensating steps to
5414 // simulate a fresh allocation, so that no further
5415 // card marks are required in compiled code to initialize
5416 // the object.)
5417
5418 if (!stopped()) {
5419 copy_to_clone(array_obj, alloc_obj, array_size, true);
5420
5421 // Present the results of the copy.
5422 result_reg->init_req(_array_path, control());
5423 result_val->init_req(_array_path, alloc_obj);
5424 result_i_o ->set_req(_array_path, i_o());
5425 result_mem ->set_req(_array_path, reset_memory());
5426 }
5427 }
5428
5429 // We only go to the instance fast case code if we pass a number of guards.
5430 // The paths which do not pass are accumulated in the slow_region.
5431 RegionNode* slow_region = new RegionNode(1);
5432 record_for_igvn(slow_region);
5433 if (!stopped()) {
5434 // It's an instance (we did array above). Make the slow-path tests.
5435 // If this is a virtual call, we generate a funny guard. We grab
5436 // the vtable entry corresponding to clone() from the target object.
5437 // If the target method which we are calling happens to be the
5438 // Object clone() method, we pass the guard. We do not need this
5439 // guard for non-virtual calls; the caller is known to be the native
5440 // Object clone().
5441 if (is_virtual) {
5442 generate_virtual_guard(obj_klass, slow_region);
5443 }
5444
5445 // The object must be easily cloneable and must not have a finalizer.
5446 // Both of these conditions may be checked in a single test.
5447 // We could optimize the test further, but we don't care.
5448 generate_misc_flags_guard(obj_klass,
5449 // Test both conditions:
5450 KlassFlags::_misc_is_cloneable_fast | KlassFlags::_misc_has_finalizer,
5451 // Must be cloneable but not finalizer:
5452 KlassFlags::_misc_is_cloneable_fast,
5453 slow_region);
5454 }
5455
5456 if (!stopped()) {
5457 // It's an instance, and it passed the slow-path tests.
5458 PreserveJVMState pjvms(this);
5459 Node* obj_size = nullptr; // Total object size, including object alignment padding.
5460 // Need to deoptimize on exception from allocation since Object.clone intrinsic
5461 // is reexecuted if deoptimization occurs and there could be problems when merging
5462 // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
5463 Node* alloc_obj = new_instance(obj_klass, nullptr, &obj_size, /*deoptimize_on_exception=*/true);
5464
5465 copy_to_clone(obj, alloc_obj, obj_size, false);
5466
5467 // Present the results of the slow call.
5468 result_reg->init_req(_instance_path, control());
5469 result_val->init_req(_instance_path, alloc_obj);
5470 result_i_o ->set_req(_instance_path, i_o());
5471 result_mem ->set_req(_instance_path, reset_memory());
5472 }
5473
5474 // Generate code for the slow case. We make a call to clone().
5475 set_control(_gvn.transform(slow_region));
5476 if (!stopped()) {
5477 PreserveJVMState pjvms(this);
5478 CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual, false, true);
5479 // We need to deoptimize on exception (see comment above)
5480 Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
5481 // this->control() comes from set_results_for_java_call
5482 result_reg->init_req(_slow_path, control());
5483 result_val->init_req(_slow_path, slow_result);
5484 result_i_o ->set_req(_slow_path, i_o());
5485 result_mem ->set_req(_slow_path, reset_memory());
5486 }
5487
5488 // Return the combined state.
5489 set_control( _gvn.transform(result_reg));
5490 set_i_o( _gvn.transform(result_i_o));
5491 set_all_memory( _gvn.transform(result_mem));
5492 } // original reexecute is set back here
5493
5494 set_result(_gvn.transform(result_val));
5495 return true;
5496 }
5497
5498 // If we have a tightly coupled allocation, the arraycopy may take care
5499 // of the array initialization. If one of the guards we insert between
5500 // the allocation and the arraycopy causes a deoptimization, an
5501 // uninitialized array will escape the compiled method. To prevent that
5502 // we set the JVM state for uncommon traps between the allocation and
5503 // the arraycopy to the state before the allocation so, in case of
5504 // deoptimization, we'll reexecute the allocation and the
5505 // initialization.
5506 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
5507 if (alloc != nullptr) {
5508 ciMethod* trap_method = alloc->jvms()->method();
5509 int trap_bci = alloc->jvms()->bci();
5510
5511 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
5512 !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
5513 // Make sure there's no store between the allocation and the
5514 // arraycopy otherwise visible side effects could be rexecuted
5515 // in case of deoptimization and cause incorrect execution.
5516 bool no_interfering_store = true;
5517 Node* mem = alloc->in(TypeFunc::Memory);
5518 if (mem->is_MergeMem()) {
5519 for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
5520 Node* n = mms.memory();
5521 if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5522 assert(n->is_Store(), "what else?");
5523 no_interfering_store = false;
5524 break;
5525 }
5526 }
5527 } else {
5528 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
5529 Node* n = mms.memory();
5530 if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
5531 assert(n->is_Store(), "what else?");
5532 no_interfering_store = false;
5533 break;
5534 }
5535 }
5536 }
5537
5538 if (no_interfering_store) {
5539 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5540
5541 JVMState* saved_jvms = jvms();
5542 saved_reexecute_sp = _reexecute_sp;
5543
5544 set_jvms(sfpt->jvms());
5545 _reexecute_sp = jvms()->sp();
5546
5547 return saved_jvms;
5548 }
5549 }
5550 }
5551 return nullptr;
5552 }
5553
5554 // Clone the JVMState of the array allocation and create a new safepoint with it. Re-push the array length to the stack
5555 // such that uncommon traps can be emitted to re-execute the array allocation in the interpreter.
5556 SafePointNode* LibraryCallKit::create_safepoint_with_state_before_array_allocation(const AllocateArrayNode* alloc) const {
5557 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
5558 uint size = alloc->req();
5559 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
5560 old_jvms->set_map(sfpt);
5561 for (uint i = 0; i < size; i++) {
5562 sfpt->init_req(i, alloc->in(i));
5563 }
5564 // re-push array length for deoptimization
5565 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
5566 old_jvms->set_sp(old_jvms->sp()+1);
5567 old_jvms->set_monoff(old_jvms->monoff()+1);
5568 old_jvms->set_scloff(old_jvms->scloff()+1);
5569 old_jvms->set_endoff(old_jvms->endoff()+1);
5570 old_jvms->set_should_reexecute(true);
5571
5572 sfpt->set_i_o(map()->i_o());
5573 sfpt->set_memory(map()->memory());
5574 sfpt->set_control(map()->control());
5575 return sfpt;
5576 }
5577
5578 // In case of a deoptimization, we restart execution at the
5579 // allocation, allocating a new array. We would leave an uninitialized
5580 // array in the heap that GCs wouldn't expect. Move the allocation
5581 // after the traps so we don't allocate the array if we
5582 // deoptimize. This is possible because tightly_coupled_allocation()
5583 // guarantees there's no observer of the allocated array at this point
5584 // and the control flow is simple enough.
5585 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms_before_guards,
5586 int saved_reexecute_sp, uint new_idx) {
5587 if (saved_jvms_before_guards != nullptr && !stopped()) {
5588 replace_unrelated_uncommon_traps_with_alloc_state(alloc, saved_jvms_before_guards);
5589
5590 assert(alloc != nullptr, "only with a tightly coupled allocation");
5591 // restore JVM state to the state at the arraycopy
5592 saved_jvms_before_guards->map()->set_control(map()->control());
5593 assert(saved_jvms_before_guards->map()->memory() == map()->memory(), "memory state changed?");
5594 assert(saved_jvms_before_guards->map()->i_o() == map()->i_o(), "IO state changed?");
5595 // If we've improved the types of some nodes (null check) while
5596 // emitting the guards, propagate them to the current state
5597 map()->replaced_nodes().apply(saved_jvms_before_guards->map(), new_idx);
5598 set_jvms(saved_jvms_before_guards);
5599 _reexecute_sp = saved_reexecute_sp;
5600
5601 // Remove the allocation from above the guards
5602 CallProjections callprojs;
5603 alloc->extract_projections(&callprojs, true);
5604 InitializeNode* init = alloc->initialization();
5605 Node* alloc_mem = alloc->in(TypeFunc::Memory);
5606 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
5607 init->replace_mem_projs_by(alloc_mem, C);
5608
5609 // The CastIINode created in GraphKit::new_array (in AllocateArrayNode::make_ideal_length) must stay below
5610 // the allocation (i.e. is only valid if the allocation succeeds):
5611 // 1) replace CastIINode with AllocateArrayNode's length here
5612 // 2) Create CastIINode again once allocation has moved (see below) at the end of this method
5613 //
5614 // Multiple identical CastIINodes might exist here. Each GraphKit::load_array_length() call will generate
5615 // new separate CastIINode (arraycopy guard checks or any array length use between array allocation and ararycopy)
5616 Node* init_control = init->proj_out(TypeFunc::Control);
5617 Node* alloc_length = alloc->Ideal_length();
5618 #ifdef ASSERT
5619 Node* prev_cast = nullptr;
5620 #endif
5621 for (uint i = 0; i < init_control->outcnt(); i++) {
5622 Node* init_out = init_control->raw_out(i);
5623 if (init_out->is_CastII() && init_out->in(TypeFunc::Control) == init_control && init_out->in(1) == alloc_length) {
5624 #ifdef ASSERT
5625 if (prev_cast == nullptr) {
5626 prev_cast = init_out;
5627 } else {
5628 if (prev_cast->cmp(*init_out) == false) {
5629 prev_cast->dump();
5630 init_out->dump();
5631 assert(false, "not equal CastIINode");
5632 }
5633 }
5634 #endif
5635 C->gvn_replace_by(init_out, alloc_length);
5636 }
5637 }
5638 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
5639
5640 // move the allocation here (after the guards)
5641 _gvn.hash_delete(alloc);
5642 alloc->set_req(TypeFunc::Control, control());
5643 alloc->set_req(TypeFunc::I_O, i_o());
5644 Node *mem = reset_memory();
5645 set_all_memory(mem);
5646 alloc->set_req(TypeFunc::Memory, mem);
5647 set_control(init->proj_out_or_null(TypeFunc::Control));
5648 set_i_o(callprojs.fallthrough_ioproj);
5649
5650 // Update memory as done in GraphKit::set_output_for_allocation()
5651 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
5652 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
5653 if (ary_type->isa_aryptr() && length_type != nullptr) {
5654 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
5655 }
5656 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
5657 int elemidx = C->get_alias_index(telemref);
5658 // Need to properly move every memory projection for the Initialize
5659 #ifdef ASSERT
5660 int mark_idx = C->get_alias_index(ary_type->add_offset(oopDesc::mark_offset_in_bytes()));
5661 int klass_idx = C->get_alias_index(ary_type->add_offset(oopDesc::klass_offset_in_bytes()));
5662 #endif
5663 auto move_proj = [&](ProjNode* proj) {
5664 int alias_idx = C->get_alias_index(proj->adr_type());
5665 assert(alias_idx == Compile::AliasIdxRaw ||
5666 alias_idx == elemidx ||
5667 alias_idx == mark_idx ||
5668 alias_idx == klass_idx, "should be raw memory or array element type");
5669 set_memory(proj, alias_idx);
5670 };
5671 init->for_each_proj(move_proj, TypeFunc::Memory);
5672
5673 Node* allocx = _gvn.transform(alloc);
5674 assert(allocx == alloc, "where has the allocation gone?");
5675 assert(dest->is_CheckCastPP(), "not an allocation result?");
5676
5677 _gvn.hash_delete(dest);
5678 dest->set_req(0, control());
5679 Node* destx = _gvn.transform(dest);
5680 assert(destx == dest, "where has the allocation result gone?");
5681
5682 array_ideal_length(alloc, ary_type, true);
5683 }
5684 }
5685
5686 // Unrelated UCTs between the array allocation and the array copy, which are considered safe by tightly_coupled_allocation(),
5687 // need to be replaced by an UCT with a state before the array allocation (including the array length). This is necessary
5688 // because we could hit one of these UCTs (which are executed before the emitted array copy guards and the actual array
5689 // allocation which is moved down in arraycopy_move_allocation_here()). When later resuming execution in the interpreter,
5690 // we would have wrongly skipped the array allocation. To prevent this, we resume execution at the array allocation in
5691 // the interpreter similar to what we are doing for the newly emitted guards for the array copy.
5692 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(AllocateArrayNode* alloc,
5693 JVMState* saved_jvms_before_guards) {
5694 if (saved_jvms_before_guards->map()->control()->is_IfProj()) {
5695 // There is at least one unrelated uncommon trap which needs to be replaced.
5696 SafePointNode* sfpt = create_safepoint_with_state_before_array_allocation(alloc);
5697
5698 JVMState* saved_jvms = jvms();
5699 const int saved_reexecute_sp = _reexecute_sp;
5700 set_jvms(sfpt->jvms());
5701 _reexecute_sp = jvms()->sp();
5702
5703 replace_unrelated_uncommon_traps_with_alloc_state(saved_jvms_before_guards);
5704
5705 // Restore state
5706 set_jvms(saved_jvms);
5707 _reexecute_sp = saved_reexecute_sp;
5708 }
5709 }
5710
5711 // Replace the unrelated uncommon traps with new uncommon trap nodes by reusing the action and reason. The new uncommon
5712 // traps will have the state of the array allocation. Let the old uncommon trap nodes die.
5713 void LibraryCallKit::replace_unrelated_uncommon_traps_with_alloc_state(JVMState* saved_jvms_before_guards) {
5714 Node* if_proj = saved_jvms_before_guards->map()->control(); // Start the search right before the newly emitted guards
5715 while (if_proj->is_IfProj()) {
5716 CallStaticJavaNode* uncommon_trap = get_uncommon_trap_from_success_proj(if_proj);
5717 if (uncommon_trap != nullptr) {
5718 create_new_uncommon_trap(uncommon_trap);
5719 }
5720 assert(if_proj->in(0)->is_If(), "must be If");
5721 if_proj = if_proj->in(0)->in(0);
5722 }
5723 assert(if_proj->is_Proj() && if_proj->in(0)->is_Initialize(),
5724 "must have reached control projection of init node");
5725 }
5726
5727 void LibraryCallKit::create_new_uncommon_trap(CallStaticJavaNode* uncommon_trap_call) {
5728 const int trap_request = uncommon_trap_call->uncommon_trap_request();
5729 assert(trap_request != 0, "no valid UCT trap request");
5730 PreserveJVMState pjvms(this);
5731 set_control(uncommon_trap_call->in(0));
5732 uncommon_trap(Deoptimization::trap_request_reason(trap_request),
5733 Deoptimization::trap_request_action(trap_request));
5734 assert(stopped(), "Should be stopped");
5735 _gvn.hash_delete(uncommon_trap_call);
5736 uncommon_trap_call->set_req(0, top()); // not used anymore, kill it
5737 }
5738
5739 // Common checks for array sorting intrinsics arguments.
5740 // Returns `true` if checks passed.
5741 bool LibraryCallKit::check_array_sort_arguments(Node* elementType, Node* obj, BasicType& bt) {
5742 // check address of the class
5743 if (elementType == nullptr || elementType->is_top()) {
5744 return false; // dead path
5745 }
5746 const TypeInstPtr* elem_klass = gvn().type(elementType)->isa_instptr();
5747 if (elem_klass == nullptr) {
5748 return false; // dead path
5749 }
5750 // java_mirror_type() returns non-null for compile-time Class constants only
5751 ciType* elem_type = elem_klass->java_mirror_type();
5752 if (elem_type == nullptr) {
5753 return false;
5754 }
5755 bt = elem_type->basic_type();
5756 // Disable the intrinsic if the CPU does not support SIMD sort
5757 if (!Matcher::supports_simd_sort(bt)) {
5758 return false;
5759 }
5760 // check address of the array
5761 if (obj == nullptr || obj->is_top()) {
5762 return false; // dead path
5763 }
5764 const TypeAryPtr* obj_t = _gvn.type(obj)->isa_aryptr();
5765 if (obj_t == nullptr || obj_t->elem() == Type::BOTTOM) {
5766 return false; // failed input validation
5767 }
5768 return true;
5769 }
5770
5771 //------------------------------inline_array_partition-----------------------
5772 bool LibraryCallKit::inline_array_partition() {
5773 address stubAddr = StubRoutines::select_array_partition_function();
5774 if (stubAddr == nullptr) {
5775 return false; // Intrinsic's stub is not implemented on this platform
5776 }
5777 assert(callee()->signature()->size() == 9, "arrayPartition has 8 parameters (one long)");
5778
5779 // no receiver because it is a static method
5780 Node* elementType = argument(0);
5781 Node* obj = argument(1);
5782 Node* offset = argument(2); // long
5783 Node* fromIndex = argument(4);
5784 Node* toIndex = argument(5);
5785 Node* indexPivot1 = argument(6);
5786 Node* indexPivot2 = argument(7);
5787 // PartitionOperation: argument(8) is ignored
5788
5789 Node* pivotIndices = nullptr;
5790 BasicType bt = T_ILLEGAL;
5791
5792 if (!check_array_sort_arguments(elementType, obj, bt)) {
5793 return false;
5794 }
5795 null_check(obj);
5796 // If obj is dead, only null-path is taken.
5797 if (stopped()) {
5798 return true;
5799 }
5800 // Set the original stack and the reexecute bit for the interpreter to reexecute
5801 // the bytecode that invokes DualPivotQuicksort.partition() if deoptimization happens.
5802 { PreserveReexecuteState preexecs(this);
5803 jvms()->set_should_reexecute(true);
5804
5805 Node* obj_adr = make_unsafe_address(obj, offset);
5806
5807 // create the pivotIndices array of type int and size = 2
5808 Node* size = intcon(2);
5809 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_INT)));
5810 pivotIndices = new_array(klass_node, size, 0); // no arguments to push
5811 AllocateArrayNode* alloc = tightly_coupled_allocation(pivotIndices);
5812 guarantee(alloc != nullptr, "created above");
5813 Node* pivotIndices_adr = basic_plus_adr(pivotIndices, arrayOopDesc::base_offset_in_bytes(T_INT));
5814
5815 // pass the basic type enum to the stub
5816 Node* elemType = intcon(bt);
5817
5818 // Call the stub
5819 const char *stubName = "array_partition_stub";
5820 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_partition_Type(),
5821 stubAddr, stubName, TypePtr::BOTTOM,
5822 obj_adr, elemType, fromIndex, toIndex, pivotIndices_adr,
5823 indexPivot1, indexPivot2);
5824
5825 } // original reexecute is set back here
5826
5827 if (!stopped()) {
5828 set_result(pivotIndices);
5829 }
5830
5831 return true;
5832 }
5833
5834
5835 //------------------------------inline_array_sort-----------------------
5836 bool LibraryCallKit::inline_array_sort() {
5837 address stubAddr = StubRoutines::select_arraysort_function();
5838 if (stubAddr == nullptr) {
5839 return false; // Intrinsic's stub is not implemented on this platform
5840 }
5841 assert(callee()->signature()->size() == 7, "arraySort has 6 parameters (one long)");
5842
5843 // no receiver because it is a static method
5844 Node* elementType = argument(0);
5845 Node* obj = argument(1);
5846 Node* offset = argument(2); // long
5847 Node* fromIndex = argument(4);
5848 Node* toIndex = argument(5);
5849 // SortOperation: argument(6) is ignored
5850
5851 BasicType bt = T_ILLEGAL;
5852
5853 if (!check_array_sort_arguments(elementType, obj, bt)) {
5854 return false;
5855 }
5856 null_check(obj);
5857 // If obj is dead, only null-path is taken.
5858 if (stopped()) {
5859 return true;
5860 }
5861 Node* obj_adr = make_unsafe_address(obj, offset);
5862
5863 // pass the basic type enum to the stub
5864 Node* elemType = intcon(bt);
5865
5866 // Call the stub.
5867 const char *stubName = "arraysort_stub";
5868 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::array_sort_Type(),
5869 stubAddr, stubName, TypePtr::BOTTOM,
5870 obj_adr, elemType, fromIndex, toIndex);
5871
5872 return true;
5873 }
5874
5875
5876 //------------------------------inline_arraycopy-----------------------
5877 // public static native void java.lang.System.arraycopy(Object src, int srcPos,
5878 // Object dest, int destPos,
5879 // int length);
5880 bool LibraryCallKit::inline_arraycopy() {
5881 // Get the arguments.
5882 Node* src = argument(0); // type: oop
5883 Node* src_offset = argument(1); // type: int
5884 Node* dest = argument(2); // type: oop
5885 Node* dest_offset = argument(3); // type: int
5886 Node* length = argument(4); // type: int
5887
5888 uint new_idx = C->unique();
5889
5890 // Check for allocation before we add nodes that would confuse
5891 // tightly_coupled_allocation()
5892 AllocateArrayNode* alloc = tightly_coupled_allocation(dest);
5893
5894 int saved_reexecute_sp = -1;
5895 JVMState* saved_jvms_before_guards = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
5896 // See arraycopy_restore_alloc_state() comment
5897 // if alloc == null we don't have to worry about a tightly coupled allocation so we can emit all needed guards
5898 // if saved_jvms_before_guards is not null (then alloc is not null) then we can handle guards and a tightly coupled allocation
5899 // if saved_jvms_before_guards is null and alloc is not null, we can't emit any guards
5900 bool can_emit_guards = (alloc == nullptr || saved_jvms_before_guards != nullptr);
5901
5902 // The following tests must be performed
5903 // (1) src and dest are arrays.
5904 // (2) src and dest arrays must have elements of the same BasicType
5905 // (3) src and dest must not be null.
5906 // (4) src_offset must not be negative.
5907 // (5) dest_offset must not be negative.
5908 // (6) length must not be negative.
5909 // (7) src_offset + length must not exceed length of src.
5910 // (8) dest_offset + length must not exceed length of dest.
5911 // (9) each element of an oop array must be assignable
5912
5913 // (3) src and dest must not be null.
5914 // always do this here because we need the JVM state for uncommon traps
5915 Node* null_ctl = top();
5916 src = saved_jvms_before_guards != nullptr ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
5917 assert(null_ctl->is_top(), "no null control here");
5918 dest = null_check(dest, T_ARRAY);
5919
5920 if (!can_emit_guards) {
5921 // if saved_jvms_before_guards is null and alloc is not null, we don't emit any
5922 // guards but the arraycopy node could still take advantage of a
5923 // tightly allocated allocation. tightly_coupled_allocation() is
5924 // called again to make sure it takes the null check above into
5925 // account: the null check is mandatory and if it caused an
5926 // uncommon trap to be emitted then the allocation can't be
5927 // considered tightly coupled in this context.
5928 alloc = tightly_coupled_allocation(dest);
5929 }
5930
5931 bool validated = false;
5932
5933 const Type* src_type = _gvn.type(src);
5934 const Type* dest_type = _gvn.type(dest);
5935 const TypeAryPtr* top_src = src_type->isa_aryptr();
5936 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5937
5938 // Do we have the type of src?
5939 bool has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5940 // Do we have the type of dest?
5941 bool has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5942 // Is the type for src from speculation?
5943 bool src_spec = false;
5944 // Is the type for dest from speculation?
5945 bool dest_spec = false;
5946
5947 if ((!has_src || !has_dest) && can_emit_guards) {
5948 // We don't have sufficient type information, let's see if
5949 // speculative types can help. We need to have types for both src
5950 // and dest so that it pays off.
5951
5952 // Do we already have or could we have type information for src
5953 bool could_have_src = has_src;
5954 // Do we already have or could we have type information for dest
5955 bool could_have_dest = has_dest;
5956
5957 ciKlass* src_k = nullptr;
5958 if (!has_src) {
5959 src_k = src_type->speculative_type_not_null();
5960 if (src_k != nullptr && src_k->is_array_klass()) {
5961 could_have_src = true;
5962 }
5963 }
5964
5965 ciKlass* dest_k = nullptr;
5966 if (!has_dest) {
5967 dest_k = dest_type->speculative_type_not_null();
5968 if (dest_k != nullptr && dest_k->is_array_klass()) {
5969 could_have_dest = true;
5970 }
5971 }
5972
5973 if (could_have_src && could_have_dest) {
5974 // This is going to pay off so emit the required guards
5975 if (!has_src) {
5976 src = maybe_cast_profiled_obj(src, src_k, true);
5977 src_type = _gvn.type(src);
5978 top_src = src_type->isa_aryptr();
5979 has_src = (top_src != nullptr && top_src->elem() != Type::BOTTOM);
5980 src_spec = true;
5981 }
5982 if (!has_dest) {
5983 dest = maybe_cast_profiled_obj(dest, dest_k, true);
5984 dest_type = _gvn.type(dest);
5985 top_dest = dest_type->isa_aryptr();
5986 has_dest = (top_dest != nullptr && top_dest->elem() != Type::BOTTOM);
5987 dest_spec = true;
5988 }
5989 }
5990 }
5991
5992 if (has_src && has_dest && can_emit_guards) {
5993 BasicType src_elem = top_src->isa_aryptr()->elem()->array_element_basic_type();
5994 BasicType dest_elem = top_dest->isa_aryptr()->elem()->array_element_basic_type();
5995 if (is_reference_type(src_elem, true)) src_elem = T_OBJECT;
5996 if (is_reference_type(dest_elem, true)) dest_elem = T_OBJECT;
5997
5998 if (src_elem == dest_elem && src_elem == T_OBJECT) {
5999 // If both arrays are object arrays then having the exact types
6000 // for both will remove the need for a subtype check at runtime
6001 // before the call and may make it possible to pick a faster copy
6002 // routine (without a subtype check on every element)
6003 // Do we have the exact type of src?
6004 bool could_have_src = src_spec;
6005 // Do we have the exact type of dest?
6006 bool could_have_dest = dest_spec;
6007 ciKlass* src_k = nullptr;
6008 ciKlass* dest_k = nullptr;
6009 if (!src_spec) {
6010 src_k = src_type->speculative_type_not_null();
6011 if (src_k != nullptr && src_k->is_array_klass()) {
6012 could_have_src = true;
6013 }
6014 }
6015 if (!dest_spec) {
6016 dest_k = dest_type->speculative_type_not_null();
6017 if (dest_k != nullptr && dest_k->is_array_klass()) {
6018 could_have_dest = true;
6019 }
6020 }
6021 if (could_have_src && could_have_dest) {
6022 // If we can have both exact types, emit the missing guards
6023 if (could_have_src && !src_spec) {
6024 src = maybe_cast_profiled_obj(src, src_k, true);
6025 }
6026 if (could_have_dest && !dest_spec) {
6027 dest = maybe_cast_profiled_obj(dest, dest_k, true);
6028 }
6029 }
6030 }
6031 }
6032
6033 ciMethod* trap_method = method();
6034 int trap_bci = bci();
6035 if (saved_jvms_before_guards != nullptr) {
6036 trap_method = alloc->jvms()->method();
6037 trap_bci = alloc->jvms()->bci();
6038 }
6039
6040 bool negative_length_guard_generated = false;
6041
6042 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
6043 can_emit_guards &&
6044 !src->is_top() && !dest->is_top()) {
6045 // validate arguments: enables transformation the ArrayCopyNode
6046 validated = true;
6047
6048 RegionNode* slow_region = new RegionNode(1);
6049 record_for_igvn(slow_region);
6050
6051 // (1) src and dest are arrays.
6052 generate_non_array_guard(load_object_klass(src), slow_region, &src);
6053 generate_non_array_guard(load_object_klass(dest), slow_region, &dest);
6054
6055 // (2) src and dest arrays must have elements of the same BasicType
6056 // done at macro expansion or at Ideal transformation time
6057
6058 // (4) src_offset must not be negative.
6059 generate_negative_guard(src_offset, slow_region);
6060
6061 // (5) dest_offset must not be negative.
6062 generate_negative_guard(dest_offset, slow_region);
6063
6064 // (7) src_offset + length must not exceed length of src.
6065 generate_limit_guard(src_offset, length,
6066 load_array_length(src),
6067 slow_region);
6068
6069 // (8) dest_offset + length must not exceed length of dest.
6070 generate_limit_guard(dest_offset, length,
6071 load_array_length(dest),
6072 slow_region);
6073
6074 // (6) length must not be negative.
6075 // This is also checked in generate_arraycopy() during macro expansion, but
6076 // we also have to check it here for the case where the ArrayCopyNode will
6077 // be eliminated by Escape Analysis.
6078 if (EliminateAllocations) {
6079 generate_negative_guard(length, slow_region);
6080 negative_length_guard_generated = true;
6081 }
6082
6083 // (9) each element of an oop array must be assignable
6084 Node* dest_klass = load_object_klass(dest);
6085 if (src != dest) {
6086 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
6087
6088 if (not_subtype_ctrl != top()) {
6089 PreserveJVMState pjvms(this);
6090 set_control(not_subtype_ctrl);
6091 uncommon_trap(Deoptimization::Reason_intrinsic,
6092 Deoptimization::Action_make_not_entrant);
6093 assert(stopped(), "Should be stopped");
6094 }
6095 }
6096 {
6097 PreserveJVMState pjvms(this);
6098 set_control(_gvn.transform(slow_region));
6099 uncommon_trap(Deoptimization::Reason_intrinsic,
6100 Deoptimization::Action_make_not_entrant);
6101 assert(stopped(), "Should be stopped");
6102 }
6103
6104 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
6105 const Type *toop = dest_klass_t->cast_to_exactness(false)->as_instance_type();
6106 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
6107 arraycopy_move_allocation_here(alloc, dest, saved_jvms_before_guards, saved_reexecute_sp, new_idx);
6108 }
6109
6110 if (stopped()) {
6111 return true;
6112 }
6113
6114 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != nullptr, negative_length_guard_generated,
6115 // Create LoadRange and LoadKlass nodes for use during macro expansion here
6116 // so the compiler has a chance to eliminate them: during macro expansion,
6117 // we have to set their control (CastPP nodes are eliminated).
6118 load_object_klass(src), load_object_klass(dest),
6119 load_array_length(src), load_array_length(dest));
6120
6121 ac->set_arraycopy(validated);
6122
6123 Node* n = _gvn.transform(ac);
6124 if (n == ac) {
6125 ac->connect_outputs(this);
6126 } else {
6127 assert(validated, "shouldn't transform if all arguments not validated");
6128 set_all_memory(n);
6129 }
6130 clear_upper_avx();
6131
6132
6133 return true;
6134 }
6135
6136
6137 // Helper function which determines if an arraycopy immediately follows
6138 // an allocation, with no intervening tests or other escapes for the object.
6139 AllocateArrayNode*
6140 LibraryCallKit::tightly_coupled_allocation(Node* ptr) {
6141 if (stopped()) return nullptr; // no fast path
6142 if (!C->do_aliasing()) return nullptr; // no MergeMems around
6143
6144 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr);
6145 if (alloc == nullptr) return nullptr;
6146
6147 Node* rawmem = memory(Compile::AliasIdxRaw);
6148 // Is the allocation's memory state untouched?
6149 if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
6150 // Bail out if there have been raw-memory effects since the allocation.
6151 // (Example: There might have been a call or safepoint.)
6152 return nullptr;
6153 }
6154 rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
6155 if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
6156 return nullptr;
6157 }
6158
6159 // There must be no unexpected observers of this allocation.
6160 for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
6161 Node* obs = ptr->fast_out(i);
6162 if (obs != this->map()) {
6163 return nullptr;
6164 }
6165 }
6166
6167 // This arraycopy must unconditionally follow the allocation of the ptr.
6168 Node* alloc_ctl = ptr->in(0);
6169 Node* ctl = control();
6170 while (ctl != alloc_ctl) {
6171 // There may be guards which feed into the slow_region.
6172 // Any other control flow means that we might not get a chance
6173 // to finish initializing the allocated object.
6174 // Various low-level checks bottom out in uncommon traps. These
6175 // are considered safe since we've already checked above that
6176 // there is no unexpected observer of this allocation.
6177 if (get_uncommon_trap_from_success_proj(ctl) != nullptr) {
6178 assert(ctl->in(0)->is_If(), "must be If");
6179 ctl = ctl->in(0)->in(0);
6180 } else {
6181 return nullptr;
6182 }
6183 }
6184
6185 // If we get this far, we have an allocation which immediately
6186 // precedes the arraycopy, and we can take over zeroing the new object.
6187 // The arraycopy will finish the initialization, and provide
6188 // a new control state to which we will anchor the destination pointer.
6189
6190 return alloc;
6191 }
6192
6193 CallStaticJavaNode* LibraryCallKit::get_uncommon_trap_from_success_proj(Node* node) {
6194 if (node->is_IfProj()) {
6195 IfProjNode* other_proj = node->as_IfProj()->other_if_proj();
6196 for (DUIterator_Fast jmax, j = other_proj->fast_outs(jmax); j < jmax; j++) {
6197 Node* obs = other_proj->fast_out(j);
6198 if (obs->in(0) == other_proj && obs->is_CallStaticJava() &&
6199 (obs->as_CallStaticJava()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point())) {
6200 return obs->as_CallStaticJava();
6201 }
6202 }
6203 }
6204 return nullptr;
6205 }
6206
6207 //-------------inline_encodeISOArray-----------------------------------
6208 // int sun.nio.cs.ISO_8859_1.Encoder#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6209 // int java.lang.StringCoding#encodeISOArray0(byte[] sa, int sp, byte[] da, int dp, int len)
6210 // int java.lang.StringCoding#encodeAsciiArray0(char[] sa, int sp, byte[] da, int dp, int len)
6211 // encode char[] to byte[] in ISO_8859_1 or ASCII
6212 bool LibraryCallKit::inline_encodeISOArray(bool ascii) {
6213 assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
6214 // no receiver since it is static method
6215 Node *src = argument(0);
6216 Node *src_offset = argument(1);
6217 Node *dst = argument(2);
6218 Node *dst_offset = argument(3);
6219 Node *length = argument(4);
6220
6221 // Cast source & target arrays to not-null
6222 src = must_be_not_null(src, true);
6223 dst = must_be_not_null(dst, true);
6224 if (stopped()) {
6225 return true;
6226 }
6227
6228 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6229 const TypeAryPtr* dst_type = dst->Value(&_gvn)->isa_aryptr();
6230 if (src_type == nullptr || src_type->elem() == Type::BOTTOM ||
6231 dst_type == nullptr || dst_type->elem() == Type::BOTTOM) {
6232 // failed array check
6233 return false;
6234 }
6235
6236 // Figure out the size and type of the elements we will be copying.
6237 BasicType src_elem = src_type->elem()->array_element_basic_type();
6238 BasicType dst_elem = dst_type->elem()->array_element_basic_type();
6239 if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
6240 return false;
6241 }
6242
6243 // Check source & target bounds
6244 RegionNode* bailout = create_bailout();
6245 generate_string_range_check(src, src_offset, length, src_elem == T_BYTE, bailout);
6246 generate_string_range_check(dst, dst_offset, length, false, bailout);
6247 if (check_bailout(bailout)) {
6248 return true;
6249 }
6250
6251 Node* src_start = array_element_address(src, src_offset, T_CHAR);
6252 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
6253 // 'src_start' points to src array + scaled offset
6254 // 'dst_start' points to dst array + scaled offset
6255
6256 // See GraphKit::compress_string
6257 const TypePtr* adr_type;
6258 Node* mem = capture_memory(adr_type, src_type, dst_type);
6259 Node* enc = new EncodeISOArrayNode(control(), mem, adr_type, src_start, dst_start, length, ascii);
6260 enc = _gvn.transform(enc);
6261 Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
6262 memory_effect(res_mem, src_type, dst_type);
6263
6264 set_result(enc);
6265 clear_upper_avx();
6266
6267 return true;
6268 }
6269
6270 //-------------inline_multiplyToLen-----------------------------------
6271 bool LibraryCallKit::inline_multiplyToLen() {
6272 assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
6273
6274 address stubAddr = StubRoutines::multiplyToLen();
6275 if (stubAddr == nullptr) {
6276 return false; // Intrinsic's stub is not implemented on this platform
6277 }
6278 const char* stubName = "multiplyToLen";
6279
6280 assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
6281
6282 // no receiver because it is a static method
6283 Node* x = argument(0);
6284 Node* xlen = argument(1);
6285 Node* y = argument(2);
6286 Node* ylen = argument(3);
6287 Node* z = argument(4);
6288
6289 x = must_be_not_null(x, true);
6290 y = must_be_not_null(y, true);
6291
6292 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6293 const TypeAryPtr* y_type = y->Value(&_gvn)->isa_aryptr();
6294 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6295 y_type == nullptr || y_type->elem() == Type::BOTTOM) {
6296 // failed array check
6297 return false;
6298 }
6299
6300 BasicType x_elem = x_type->elem()->array_element_basic_type();
6301 BasicType y_elem = y_type->elem()->array_element_basic_type();
6302 if (x_elem != T_INT || y_elem != T_INT) {
6303 return false;
6304 }
6305
6306 Node* x_start = array_element_address(x, intcon(0), x_elem);
6307 Node* y_start = array_element_address(y, intcon(0), y_elem);
6308 // 'x_start' points to x array + scaled xlen
6309 // 'y_start' points to y array + scaled ylen
6310
6311 Node* z_start = array_element_address(z, intcon(0), T_INT);
6312
6313 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6314 OptoRuntime::multiplyToLen_Type(),
6315 stubAddr, stubName, TypePtr::BOTTOM,
6316 x_start, xlen, y_start, ylen, z_start);
6317
6318 C->set_has_split_ifs(true); // Has chance for split-if optimization
6319 set_result(z);
6320 return true;
6321 }
6322
6323 //-------------inline_squareToLen------------------------------------
6324 bool LibraryCallKit::inline_squareToLen() {
6325 assert(UseSquareToLenIntrinsic, "not implemented on this platform");
6326
6327 address stubAddr = StubRoutines::squareToLen();
6328 if (stubAddr == nullptr) {
6329 return false; // Intrinsic's stub is not implemented on this platform
6330 }
6331 const char* stubName = "squareToLen";
6332
6333 assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
6334
6335 Node* x = argument(0);
6336 Node* len = argument(1);
6337 Node* z = argument(2);
6338 Node* zlen = argument(3);
6339
6340 x = must_be_not_null(x, true);
6341 z = must_be_not_null(z, true);
6342
6343 const TypeAryPtr* x_type = x->Value(&_gvn)->isa_aryptr();
6344 const TypeAryPtr* z_type = z->Value(&_gvn)->isa_aryptr();
6345 if (x_type == nullptr || x_type->elem() == Type::BOTTOM ||
6346 z_type == nullptr || z_type->elem() == Type::BOTTOM) {
6347 // failed array check
6348 return false;
6349 }
6350
6351 BasicType x_elem = x_type->elem()->array_element_basic_type();
6352 BasicType z_elem = z_type->elem()->array_element_basic_type();
6353 if (x_elem != T_INT || z_elem != T_INT) {
6354 return false;
6355 }
6356
6357
6358 Node* x_start = array_element_address(x, intcon(0), x_elem);
6359 Node* z_start = array_element_address(z, intcon(0), z_elem);
6360
6361 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6362 OptoRuntime::squareToLen_Type(),
6363 stubAddr, stubName, TypePtr::BOTTOM,
6364 x_start, len, z_start, zlen);
6365
6366 set_result(z);
6367 return true;
6368 }
6369
6370 //-------------inline_mulAdd------------------------------------------
6371 bool LibraryCallKit::inline_mulAdd() {
6372 assert(UseMulAddIntrinsic, "not implemented on this platform");
6373
6374 address stubAddr = StubRoutines::mulAdd();
6375 if (stubAddr == nullptr) {
6376 return false; // Intrinsic's stub is not implemented on this platform
6377 }
6378 const char* stubName = "mulAdd";
6379
6380 assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
6381
6382 Node* out = argument(0);
6383 Node* in = argument(1);
6384 Node* offset = argument(2);
6385 Node* len = argument(3);
6386 Node* k = argument(4);
6387
6388 in = must_be_not_null(in, true);
6389 out = must_be_not_null(out, true);
6390
6391 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
6392 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
6393 if (out_type == nullptr || out_type->elem() == Type::BOTTOM ||
6394 in_type == nullptr || in_type->elem() == Type::BOTTOM) {
6395 // failed array check
6396 return false;
6397 }
6398
6399 BasicType out_elem = out_type->elem()->array_element_basic_type();
6400 BasicType in_elem = in_type->elem()->array_element_basic_type();
6401 if (out_elem != T_INT || in_elem != T_INT) {
6402 return false;
6403 }
6404
6405 Node* outlen = load_array_length(out);
6406 Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
6407 Node* out_start = array_element_address(out, intcon(0), out_elem);
6408 Node* in_start = array_element_address(in, intcon(0), in_elem);
6409
6410 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
6411 OptoRuntime::mulAdd_Type(),
6412 stubAddr, stubName, TypePtr::BOTTOM,
6413 out_start,in_start, new_offset, len, k);
6414 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6415 set_result(result);
6416 return true;
6417 }
6418
6419 //-------------inline_montgomeryMultiply-----------------------------------
6420 bool LibraryCallKit::inline_montgomeryMultiply() {
6421 address stubAddr = StubRoutines::montgomeryMultiply();
6422 if (stubAddr == nullptr) {
6423 return false; // Intrinsic's stub is not implemented on this platform
6424 }
6425
6426 assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
6427 const char* stubName = "montgomery_multiply";
6428
6429 assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
6430
6431 Node* a = argument(0);
6432 Node* b = argument(1);
6433 Node* n = argument(2);
6434 Node* len = argument(3);
6435 Node* inv = argument(4);
6436 Node* m = argument(6);
6437
6438 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6439 const TypeAryPtr* b_type = b->Value(&_gvn)->isa_aryptr();
6440 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6441 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6442 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6443 b_type == nullptr || b_type->elem() == Type::BOTTOM ||
6444 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6445 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6446 // failed array check
6447 return false;
6448 }
6449
6450 BasicType a_elem = a_type->elem()->array_element_basic_type();
6451 BasicType b_elem = b_type->elem()->array_element_basic_type();
6452 BasicType n_elem = n_type->elem()->array_element_basic_type();
6453 BasicType m_elem = m_type->elem()->array_element_basic_type();
6454 if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6455 return false;
6456 }
6457
6458 // Make the call
6459 {
6460 Node* a_start = array_element_address(a, intcon(0), a_elem);
6461 Node* b_start = array_element_address(b, intcon(0), b_elem);
6462 Node* n_start = array_element_address(n, intcon(0), n_elem);
6463 Node* m_start = array_element_address(m, intcon(0), m_elem);
6464
6465 Node* call = make_runtime_call(RC_LEAF,
6466 OptoRuntime::montgomeryMultiply_Type(),
6467 stubAddr, stubName, TypePtr::BOTTOM,
6468 a_start, b_start, n_start, len, inv, top(),
6469 m_start);
6470 set_result(m);
6471 }
6472
6473 return true;
6474 }
6475
6476 bool LibraryCallKit::inline_montgomerySquare() {
6477 address stubAddr = StubRoutines::montgomerySquare();
6478 if (stubAddr == nullptr) {
6479 return false; // Intrinsic's stub is not implemented on this platform
6480 }
6481
6482 assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
6483 const char* stubName = "montgomery_square";
6484
6485 assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
6486
6487 Node* a = argument(0);
6488 Node* n = argument(1);
6489 Node* len = argument(2);
6490 Node* inv = argument(3);
6491 Node* m = argument(5);
6492
6493 const TypeAryPtr* a_type = a->Value(&_gvn)->isa_aryptr();
6494 const TypeAryPtr* n_type = n->Value(&_gvn)->isa_aryptr();
6495 const TypeAryPtr* m_type = m->Value(&_gvn)->isa_aryptr();
6496 if (a_type == nullptr || a_type->elem() == Type::BOTTOM ||
6497 n_type == nullptr || n_type->elem() == Type::BOTTOM ||
6498 m_type == nullptr || m_type->elem() == Type::BOTTOM) {
6499 // failed array check
6500 return false;
6501 }
6502
6503 BasicType a_elem = a_type->elem()->array_element_basic_type();
6504 BasicType n_elem = n_type->elem()->array_element_basic_type();
6505 BasicType m_elem = m_type->elem()->array_element_basic_type();
6506 if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
6507 return false;
6508 }
6509
6510 // Make the call
6511 {
6512 Node* a_start = array_element_address(a, intcon(0), a_elem);
6513 Node* n_start = array_element_address(n, intcon(0), n_elem);
6514 Node* m_start = array_element_address(m, intcon(0), m_elem);
6515
6516 Node* call = make_runtime_call(RC_LEAF,
6517 OptoRuntime::montgomerySquare_Type(),
6518 stubAddr, stubName, TypePtr::BOTTOM,
6519 a_start, n_start, len, inv, top(),
6520 m_start);
6521 set_result(m);
6522 }
6523
6524 return true;
6525 }
6526
6527 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
6528 address stubAddr = nullptr;
6529 const char* stubName = nullptr;
6530
6531 stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
6532 if (stubAddr == nullptr) {
6533 return false; // Intrinsic's stub is not implemented on this platform
6534 }
6535
6536 stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
6537
6538 assert(callee()->signature()->size() == 5, "expected 5 arguments");
6539
6540 Node* newArr = argument(0);
6541 Node* oldArr = argument(1);
6542 Node* newIdx = argument(2);
6543 Node* shiftCount = argument(3);
6544 Node* numIter = argument(4);
6545
6546 const TypeAryPtr* newArr_type = newArr->Value(&_gvn)->isa_aryptr();
6547 const TypeAryPtr* oldArr_type = oldArr->Value(&_gvn)->isa_aryptr();
6548 if (newArr_type == nullptr || newArr_type->elem() == Type::BOTTOM ||
6549 oldArr_type == nullptr || oldArr_type->elem() == Type::BOTTOM) {
6550 return false;
6551 }
6552
6553 BasicType newArr_elem = newArr_type->elem()->array_element_basic_type();
6554 BasicType oldArr_elem = oldArr_type->elem()->array_element_basic_type();
6555 if (newArr_elem != T_INT || oldArr_elem != T_INT) {
6556 return false;
6557 }
6558
6559 // Make the call
6560 {
6561 Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
6562 Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
6563
6564 Node* call = make_runtime_call(RC_LEAF,
6565 OptoRuntime::bigIntegerShift_Type(),
6566 stubAddr,
6567 stubName,
6568 TypePtr::BOTTOM,
6569 newArr_start,
6570 oldArr_start,
6571 newIdx,
6572 shiftCount,
6573 numIter);
6574 }
6575
6576 return true;
6577 }
6578
6579 //-------------inline_vectorizedMismatch------------------------------
6580 bool LibraryCallKit::inline_vectorizedMismatch() {
6581 assert(UseVectorizedMismatchIntrinsic, "not implemented on this platform");
6582
6583 assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
6584 Node* obja = argument(0); // Object
6585 Node* aoffset = argument(1); // long
6586 Node* objb = argument(3); // Object
6587 Node* boffset = argument(4); // long
6588 Node* length = argument(6); // int
6589 Node* scale = argument(7); // int
6590
6591 const TypeAryPtr* obja_t = _gvn.type(obja)->isa_aryptr();
6592 const TypeAryPtr* objb_t = _gvn.type(objb)->isa_aryptr();
6593 if (obja_t == nullptr || obja_t->elem() == Type::BOTTOM ||
6594 objb_t == nullptr || objb_t->elem() == Type::BOTTOM ||
6595 scale == top()) {
6596 return false; // failed input validation
6597 }
6598
6599 Node* obja_adr = make_unsafe_address(obja, aoffset);
6600 Node* objb_adr = make_unsafe_address(objb, boffset);
6601
6602 // Partial inlining handling for inputs smaller than ArrayOperationPartialInlineSize bytes in size.
6603 //
6604 // inline_limit = ArrayOperationPartialInlineSize / element_size;
6605 // if (length <= inline_limit) {
6606 // inline_path:
6607 // vmask = VectorMaskGen length
6608 // vload1 = LoadVectorMasked obja, vmask
6609 // vload2 = LoadVectorMasked objb, vmask
6610 // result1 = VectorCmpMasked vload1, vload2, vmask
6611 // } else {
6612 // call_stub_path:
6613 // result2 = call vectorizedMismatch_stub(obja, objb, length, scale)
6614 // }
6615 // exit_block:
6616 // return Phi(result1, result2);
6617 //
6618 enum { inline_path = 1, // input is small enough to process it all at once
6619 stub_path = 2, // input is too large; call into the VM
6620 PATH_LIMIT = 3
6621 };
6622
6623 Node* exit_block = new RegionNode(PATH_LIMIT);
6624 Node* result_phi = new PhiNode(exit_block, TypeInt::INT);
6625 Node* memory_phi = new PhiNode(exit_block, Type::MEMORY, TypePtr::BOTTOM);
6626
6627 Node* call_stub_path = control();
6628
6629 BasicType elem_bt = T_ILLEGAL;
6630
6631 const TypeInt* scale_t = _gvn.type(scale)->is_int();
6632 if (scale_t->is_con()) {
6633 switch (scale_t->get_con()) {
6634 case 0: elem_bt = T_BYTE; break;
6635 case 1: elem_bt = T_SHORT; break;
6636 case 2: elem_bt = T_INT; break;
6637 case 3: elem_bt = T_LONG; break;
6638
6639 default: elem_bt = T_ILLEGAL; break; // not supported
6640 }
6641 }
6642
6643 int inline_limit = 0;
6644 bool do_partial_inline = false;
6645
6646 if (elem_bt != T_ILLEGAL && ArrayOperationPartialInlineSize > 0) {
6647 inline_limit = ArrayOperationPartialInlineSize / type2aelembytes(elem_bt);
6648 do_partial_inline = inline_limit >= 16;
6649 }
6650
6651 if (do_partial_inline) {
6652 assert(elem_bt != T_ILLEGAL, "sanity");
6653
6654 if (Matcher::match_rule_supported_vector(Op_VectorMaskGen, inline_limit, elem_bt) &&
6655 Matcher::match_rule_supported_vector(Op_LoadVectorMasked, inline_limit, elem_bt) &&
6656 Matcher::match_rule_supported_vector(Op_VectorCmpMasked, inline_limit, elem_bt)) {
6657
6658 const TypeVect* vt = TypeVect::make(elem_bt, inline_limit);
6659 Node* cmp_length = _gvn.transform(new CmpINode(length, intcon(inline_limit)));
6660 Node* bol_gt = _gvn.transform(new BoolNode(cmp_length, BoolTest::gt));
6661
6662 call_stub_path = generate_guard(bol_gt, nullptr, PROB_MIN);
6663
6664 if (!stopped()) {
6665 Node* casted_length = _gvn.transform(new CastIINode(control(), length, TypeInt::make(0, inline_limit, Type::WidenMin)));
6666
6667 const TypePtr* obja_adr_t = _gvn.type(obja_adr)->isa_ptr();
6668 const TypePtr* objb_adr_t = _gvn.type(objb_adr)->isa_ptr();
6669 Node* obja_adr_mem = memory(C->get_alias_index(obja_adr_t));
6670 Node* objb_adr_mem = memory(C->get_alias_index(objb_adr_t));
6671
6672 Node* vmask = _gvn.transform(VectorMaskGenNode::make(ConvI2X(casted_length), elem_bt));
6673 Node* vload_obja = _gvn.transform(new LoadVectorMaskedNode(control(), obja_adr_mem, obja_adr, obja_adr_t, vt, vmask));
6674 Node* vload_objb = _gvn.transform(new LoadVectorMaskedNode(control(), objb_adr_mem, objb_adr, objb_adr_t, vt, vmask));
6675 Node* result = _gvn.transform(new VectorCmpMaskedNode(vload_obja, vload_objb, vmask, TypeInt::INT));
6676
6677 exit_block->init_req(inline_path, control());
6678 memory_phi->init_req(inline_path, map()->memory());
6679 result_phi->init_req(inline_path, result);
6680
6681 C->set_max_vector_size(MAX2((uint)ArrayOperationPartialInlineSize, C->max_vector_size()));
6682 clear_upper_avx();
6683 }
6684 }
6685 }
6686
6687 if (call_stub_path != nullptr) {
6688 set_control(call_stub_path);
6689
6690 Node* call = make_runtime_call(RC_LEAF,
6691 OptoRuntime::vectorizedMismatch_Type(),
6692 StubRoutines::vectorizedMismatch(), "vectorizedMismatch", TypePtr::BOTTOM,
6693 obja_adr, objb_adr, length, scale);
6694
6695 exit_block->init_req(stub_path, control());
6696 memory_phi->init_req(stub_path, map()->memory());
6697 result_phi->init_req(stub_path, _gvn.transform(new ProjNode(call, TypeFunc::Parms)));
6698 }
6699
6700 exit_block = _gvn.transform(exit_block);
6701 memory_phi = _gvn.transform(memory_phi);
6702 result_phi = _gvn.transform(result_phi);
6703
6704 record_for_igvn(exit_block);
6705 record_for_igvn(memory_phi);
6706 record_for_igvn(result_phi);
6707
6708 set_control(exit_block);
6709 set_all_memory(memory_phi);
6710 set_result(result_phi);
6711
6712 return true;
6713 }
6714
6715 //------------------------------inline_vectorizedHashcode----------------------------
6716 bool LibraryCallKit::inline_vectorizedHashCode() {
6717 assert(UseVectorizedHashCodeIntrinsic, "not implemented on this platform");
6718
6719 assert(callee()->signature()->size() == 5, "vectorizedHashCode has 5 parameters");
6720 Node* array = argument(0);
6721 Node* offset = argument(1);
6722 Node* length = argument(2);
6723 Node* initialValue = argument(3);
6724 Node* basic_type = argument(4);
6725
6726 if (basic_type == top()) {
6727 return false; // failed input validation
6728 }
6729
6730 const TypeInt* basic_type_t = _gvn.type(basic_type)->is_int();
6731 if (!basic_type_t->is_con()) {
6732 return false; // Only intrinsify if mode argument is constant
6733 }
6734
6735 array = must_be_not_null(array, true);
6736
6737 BasicType bt = (BasicType)basic_type_t->get_con();
6738
6739 // Resolve address of first element
6740 Node* array_start = array_element_address(array, offset, bt);
6741
6742 const TypeAryPtr* in_adr_type = TypeAryPtr::get_array_body_type(bt);
6743 set_result(_gvn.transform(new VectorizedHashCodeNode(control(), memory(in_adr_type), in_adr_type,
6744 array_start, length, initialValue, basic_type)));
6745 clear_upper_avx();
6746
6747 return true;
6748 }
6749
6750 /**
6751 * Calculate CRC32 for byte.
6752 * int java.util.zip.CRC32.update(int crc, int b)
6753 */
6754 bool LibraryCallKit::inline_updateCRC32() {
6755 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6756 assert(callee()->signature()->size() == 2, "update has 2 parameters");
6757 // no receiver since it is static method
6758 Node* crc = argument(0); // type: int
6759 Node* b = argument(1); // type: int
6760
6761 /*
6762 * int c = ~ crc;
6763 * b = timesXtoThe32[(b ^ c) & 0xFF];
6764 * b = b ^ (c >>> 8);
6765 * crc = ~b;
6766 */
6767
6768 Node* M1 = intcon(-1);
6769 crc = _gvn.transform(new XorINode(crc, M1));
6770 Node* result = _gvn.transform(new XorINode(crc, b));
6771 result = _gvn.transform(new AndINode(result, intcon(0xFF)));
6772
6773 Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
6774 Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
6775 Node* adr = off_heap_plus_addr(base, ConvI2X(offset));
6776 result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
6777
6778 crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
6779 result = _gvn.transform(new XorINode(crc, result));
6780 result = _gvn.transform(new XorINode(result, M1));
6781 set_result(result);
6782 return true;
6783 }
6784
6785 /**
6786 * Calculate CRC32 for byte[] array.
6787 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
6788 */
6789 bool LibraryCallKit::inline_updateBytesCRC32() {
6790 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6791 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6792 // no receiver since it is static method
6793 Node* crc = argument(0); // type: int
6794 Node* src = argument(1); // type: oop
6795 Node* offset = argument(2); // type: int
6796 Node* length = argument(3); // type: int
6797
6798 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6799 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6800 // failed array check
6801 return false;
6802 }
6803
6804 // Figure out the size and type of the elements we will be copying.
6805 BasicType src_elem = src_type->elem()->array_element_basic_type();
6806 if (src_elem != T_BYTE) {
6807 return false;
6808 }
6809
6810 // 'src_start' points to src array + scaled offset
6811 src = must_be_not_null(src, true);
6812 Node* src_start = array_element_address(src, offset, src_elem);
6813
6814 // We assume that range check is done by caller.
6815 // TODO: generate range check (offset+length < src.length) in debug VM.
6816
6817 // Call the stub.
6818 address stubAddr = StubRoutines::updateBytesCRC32();
6819 const char *stubName = "updateBytesCRC32";
6820
6821 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6822 stubAddr, stubName, TypePtr::BOTTOM,
6823 crc, src_start, length);
6824 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6825 set_result(result);
6826 return true;
6827 }
6828
6829 /**
6830 * Calculate CRC32 for ByteBuffer.
6831 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
6832 */
6833 bool LibraryCallKit::inline_updateByteBufferCRC32() {
6834 assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions support");
6835 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
6836 // no receiver since it is static method
6837 Node* crc = argument(0); // type: int
6838 Node* src = argument(1); // type: long
6839 Node* offset = argument(3); // type: int
6840 Node* length = argument(4); // type: int
6841
6842 src = ConvL2X(src); // adjust Java long to machine word
6843 Node* base = _gvn.transform(new CastX2PNode(src));
6844 offset = ConvI2X(offset);
6845
6846 // 'src_start' points to src array + scaled offset
6847 Node* src_start = off_heap_plus_addr(base, offset);
6848
6849 // Call the stub.
6850 address stubAddr = StubRoutines::updateBytesCRC32();
6851 const char *stubName = "updateBytesCRC32";
6852
6853 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
6854 stubAddr, stubName, TypePtr::BOTTOM,
6855 crc, src_start, length);
6856 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6857 set_result(result);
6858 return true;
6859 }
6860
6861 //------------------------------get_table_from_crc32c_class-----------------------
6862 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
6863 Node* table = load_field_from_object(nullptr, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
6864 assert (table != nullptr, "wrong version of java.util.zip.CRC32C");
6865
6866 return table;
6867 }
6868
6869 //------------------------------inline_updateBytesCRC32C-----------------------
6870 //
6871 // Calculate CRC32C for byte[] array.
6872 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
6873 //
6874 bool LibraryCallKit::inline_updateBytesCRC32C() {
6875 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6876 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6877 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6878 // no receiver since it is a static method
6879 Node* crc = argument(0); // type: int
6880 Node* src = argument(1); // type: oop
6881 Node* offset = argument(2); // type: int
6882 Node* end = argument(3); // type: int
6883
6884 Node* length = _gvn.transform(new SubINode(end, offset));
6885
6886 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6887 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6888 // failed array check
6889 return false;
6890 }
6891
6892 // Figure out the size and type of the elements we will be copying.
6893 BasicType src_elem = src_type->elem()->array_element_basic_type();
6894 if (src_elem != T_BYTE) {
6895 return false;
6896 }
6897
6898 // 'src_start' points to src array + scaled offset
6899 src = must_be_not_null(src, true);
6900 Node* src_start = array_element_address(src, offset, src_elem);
6901
6902 // static final int[] byteTable in class CRC32C
6903 Node* table = get_table_from_crc32c_class(callee()->holder());
6904 table = must_be_not_null(table, true);
6905 Node* table_start = array_element_address(table, intcon(0), T_INT);
6906
6907 // We assume that range check is done by caller.
6908 // TODO: generate range check (offset+length < src.length) in debug VM.
6909
6910 // Call the stub.
6911 address stubAddr = StubRoutines::updateBytesCRC32C();
6912 const char *stubName = "updateBytesCRC32C";
6913
6914 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6915 stubAddr, stubName, TypePtr::BOTTOM,
6916 crc, src_start, length, table_start);
6917 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6918 set_result(result);
6919 return true;
6920 }
6921
6922 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
6923 //
6924 // Calculate CRC32C for DirectByteBuffer.
6925 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
6926 //
6927 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
6928 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
6929 assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
6930 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
6931 // no receiver since it is a static method
6932 Node* crc = argument(0); // type: int
6933 Node* src = argument(1); // type: long
6934 Node* offset = argument(3); // type: int
6935 Node* end = argument(4); // type: int
6936
6937 Node* length = _gvn.transform(new SubINode(end, offset));
6938
6939 src = ConvL2X(src); // adjust Java long to machine word
6940 Node* base = _gvn.transform(new CastX2PNode(src));
6941 offset = ConvI2X(offset);
6942
6943 // 'src_start' points to src array + scaled offset
6944 Node* src_start = off_heap_plus_addr(base, offset);
6945
6946 // static final int[] byteTable in class CRC32C
6947 Node* table = get_table_from_crc32c_class(callee()->holder());
6948 table = must_be_not_null(table, true);
6949 Node* table_start = array_element_address(table, intcon(0), T_INT);
6950
6951 // Call the stub.
6952 address stubAddr = StubRoutines::updateBytesCRC32C();
6953 const char *stubName = "updateBytesCRC32C";
6954
6955 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
6956 stubAddr, stubName, TypePtr::BOTTOM,
6957 crc, src_start, length, table_start);
6958 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6959 set_result(result);
6960 return true;
6961 }
6962
6963 //------------------------------inline_updateBytesAdler32----------------------
6964 //
6965 // Calculate Adler32 checksum for byte[] array.
6966 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
6967 //
6968 bool LibraryCallKit::inline_updateBytesAdler32() {
6969 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
6970 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
6971 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
6972 // no receiver since it is static method
6973 Node* crc = argument(0); // type: int
6974 Node* src = argument(1); // type: oop
6975 Node* offset = argument(2); // type: int
6976 Node* length = argument(3); // type: int
6977
6978 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
6979 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
6980 // failed array check
6981 return false;
6982 }
6983
6984 // Figure out the size and type of the elements we will be copying.
6985 BasicType src_elem = src_type->elem()->array_element_basic_type();
6986 if (src_elem != T_BYTE) {
6987 return false;
6988 }
6989
6990 // 'src_start' points to src array + scaled offset
6991 Node* src_start = array_element_address(src, offset, src_elem);
6992
6993 // We assume that range check is done by caller.
6994 // TODO: generate range check (offset+length < src.length) in debug VM.
6995
6996 // Call the stub.
6997 address stubAddr = StubRoutines::updateBytesAdler32();
6998 const char *stubName = "updateBytesAdler32";
6999
7000 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7001 stubAddr, stubName, TypePtr::BOTTOM,
7002 crc, src_start, length);
7003 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7004 set_result(result);
7005 return true;
7006 }
7007
7008 //------------------------------inline_updateByteBufferAdler32---------------
7009 //
7010 // Calculate Adler32 checksum for DirectByteBuffer.
7011 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
7012 //
7013 bool LibraryCallKit::inline_updateByteBufferAdler32() {
7014 assert(UseAdler32Intrinsics, "Adler32 Intrinsic support need"); // check if we actually need to check this flag or check a different one
7015 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
7016 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
7017 // no receiver since it is static method
7018 Node* crc = argument(0); // type: int
7019 Node* src = argument(1); // type: long
7020 Node* offset = argument(3); // type: int
7021 Node* length = argument(4); // type: int
7022
7023 src = ConvL2X(src); // adjust Java long to machine word
7024 Node* base = _gvn.transform(new CastX2PNode(src));
7025 offset = ConvI2X(offset);
7026
7027 // 'src_start' points to src array + scaled offset
7028 Node* src_start = off_heap_plus_addr(base, offset);
7029
7030 // Call the stub.
7031 address stubAddr = StubRoutines::updateBytesAdler32();
7032 const char *stubName = "updateBytesAdler32";
7033
7034 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
7035 stubAddr, stubName, TypePtr::BOTTOM,
7036 crc, src_start, length);
7037
7038 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
7039 set_result(result);
7040 return true;
7041 }
7042
7043 //----------------------------inline_reference_get0----------------------------
7044 // public T java.lang.ref.Reference.get();
7045 bool LibraryCallKit::inline_reference_get0() {
7046 const int referent_offset = java_lang_ref_Reference::referent_offset();
7047
7048 // Get the argument:
7049 Node* reference_obj = null_check_receiver();
7050 if (stopped()) return true;
7051
7052 DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
7053 Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7054 decorators, /*is_static*/ false,
7055 env()->Reference_klass());
7056 if (result == nullptr) return false;
7057
7058 // Add memory barrier to prevent commoning reads from this field
7059 // across safepoint since GC can change its value.
7060 insert_mem_bar(Op_MemBarCPUOrder);
7061
7062 set_result(result);
7063 return true;
7064 }
7065
7066 //----------------------------inline_reference_refersTo0----------------------------
7067 // bool java.lang.ref.Reference.refersTo0();
7068 // bool java.lang.ref.PhantomReference.refersTo0();
7069 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
7070 // Get arguments:
7071 Node* reference_obj = null_check_receiver();
7072 Node* other_obj = argument(1);
7073 if (stopped()) return true;
7074
7075 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7076 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7077 Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
7078 decorators, /*is_static*/ false,
7079 env()->Reference_klass());
7080 if (referent == nullptr) return false;
7081
7082 // Add memory barrier to prevent commoning reads from this field
7083 // across safepoint since GC can change its value.
7084 insert_mem_bar(Op_MemBarCPUOrder);
7085
7086 Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
7087 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
7088 IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
7089
7090 RegionNode* region = new RegionNode(3);
7091 PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
7092
7093 Node* if_true = _gvn.transform(new IfTrueNode(if_node));
7094 region->init_req(1, if_true);
7095 phi->init_req(1, intcon(1));
7096
7097 Node* if_false = _gvn.transform(new IfFalseNode(if_node));
7098 region->init_req(2, if_false);
7099 phi->init_req(2, intcon(0));
7100
7101 set_control(_gvn.transform(region));
7102 record_for_igvn(region);
7103 set_result(_gvn.transform(phi));
7104 return true;
7105 }
7106
7107 //----------------------------inline_reference_clear0----------------------------
7108 // void java.lang.ref.Reference.clear0();
7109 // void java.lang.ref.PhantomReference.clear0();
7110 bool LibraryCallKit::inline_reference_clear0(bool is_phantom) {
7111 // This matches the implementation in JVM_ReferenceClear, see the comments there.
7112
7113 // Get arguments
7114 Node* reference_obj = null_check_receiver();
7115 if (stopped()) return true;
7116
7117 // Common access parameters
7118 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
7119 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
7120 Node* referent_field_addr = basic_plus_adr(reference_obj, java_lang_ref_Reference::referent_offset());
7121 const TypePtr* referent_field_addr_type = _gvn.type(referent_field_addr)->isa_ptr();
7122 const Type* val_type = TypeOopPtr::make_from_klass(env()->Object_klass());
7123
7124 Node* referent = access_load_at(reference_obj,
7125 referent_field_addr,
7126 referent_field_addr_type,
7127 val_type,
7128 T_OBJECT,
7129 decorators);
7130
7131 IdealKit ideal(this);
7132 #define __ ideal.
7133 __ if_then(referent, BoolTest::ne, null());
7134 sync_kit(ideal);
7135 access_store_at(reference_obj,
7136 referent_field_addr,
7137 referent_field_addr_type,
7138 null(),
7139 val_type,
7140 T_OBJECT,
7141 decorators);
7142 __ sync_kit(this);
7143 __ end_if();
7144 final_sync(ideal);
7145 #undef __
7146
7147 return true;
7148 }
7149
7150 //-----------------------inline_reference_reachabilityFence-----------------
7151 // bool java.lang.ref.Reference.reachabilityFence();
7152 bool LibraryCallKit::inline_reference_reachabilityFence() {
7153 Node* referent = argument(0);
7154 insert_reachability_fence(referent);
7155 return true;
7156 }
7157
7158 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
7159 DecoratorSet decorators, bool is_static,
7160 ciInstanceKlass* fromKls) {
7161 if (fromKls == nullptr) {
7162 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7163 assert(tinst != nullptr, "obj is null");
7164 assert(tinst->is_loaded(), "obj is not loaded");
7165 fromKls = tinst->instance_klass();
7166 }
7167 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7168 ciSymbol::make(fieldTypeString),
7169 is_static);
7170
7171 assert(field != nullptr, "undefined field %s %s %s", fieldTypeString, fromKls->name()->as_utf8(), fieldName);
7172 if (field == nullptr) return (Node *) nullptr;
7173
7174 if (is_static) {
7175 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7176 fromObj = makecon(tip);
7177 }
7178
7179 // Next code copied from Parse::do_get_xxx():
7180
7181 // Compute address and memory type.
7182 int offset = field->offset_in_bytes();
7183 bool is_vol = field->is_volatile();
7184 ciType* field_klass = field->type();
7185 assert(field_klass->is_loaded(), "should be loaded");
7186 const TypePtr* adr_type = C->alias_type(field)->adr_type();
7187 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7188 assert(C->get_alias_index(adr_type) == C->get_alias_index(_gvn.type(adr)->isa_ptr()),
7189 "slice of address and input slice don't match");
7190 BasicType bt = field->layout_type();
7191
7192 // Build the resultant type of the load
7193 const Type *type;
7194 if (bt == T_OBJECT) {
7195 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
7196 } else {
7197 type = Type::get_const_basic_type(bt);
7198 }
7199
7200 if (is_vol) {
7201 decorators |= MO_SEQ_CST;
7202 }
7203
7204 return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
7205 }
7206
7207 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
7208 bool is_exact /* true */, bool is_static /* false */,
7209 ciInstanceKlass * fromKls /* nullptr */) {
7210 if (fromKls == nullptr) {
7211 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
7212 assert(tinst != nullptr, "obj is null");
7213 assert(tinst->is_loaded(), "obj is not loaded");
7214 assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
7215 fromKls = tinst->instance_klass();
7216 }
7217 else {
7218 assert(is_static, "only for static field access");
7219 }
7220 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
7221 ciSymbol::make(fieldTypeString),
7222 is_static);
7223
7224 assert(field != nullptr, "undefined field");
7225 assert(!field->is_volatile(), "not defined for volatile fields");
7226
7227 if (is_static) {
7228 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
7229 fromObj = makecon(tip);
7230 }
7231
7232 // Next code copied from Parse::do_get_xxx():
7233
7234 // Compute address and memory type.
7235 int offset = field->offset_in_bytes();
7236 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
7237
7238 return adr;
7239 }
7240
7241 //------------------------------inline_aescrypt_Block-----------------------
7242 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
7243 address stubAddr = nullptr;
7244 const char *stubName;
7245 bool is_decrypt = false;
7246 assert(UseAES, "need AES instruction support");
7247
7248 switch(id) {
7249 case vmIntrinsics::_aescrypt_encryptBlock:
7250 stubAddr = StubRoutines::aescrypt_encryptBlock();
7251 stubName = "aescrypt_encryptBlock";
7252 break;
7253 case vmIntrinsics::_aescrypt_decryptBlock:
7254 stubAddr = StubRoutines::aescrypt_decryptBlock();
7255 stubName = "aescrypt_decryptBlock";
7256 is_decrypt = true;
7257 break;
7258 default:
7259 break;
7260 }
7261 if (stubAddr == nullptr) return false;
7262
7263 Node* aescrypt_object = argument(0);
7264 Node* src = argument(1);
7265 Node* src_offset = argument(2);
7266 Node* dest = argument(3);
7267 Node* dest_offset = argument(4);
7268
7269 src = must_be_not_null(src, true);
7270 dest = must_be_not_null(dest, true);
7271
7272 // (1) src and dest are arrays.
7273 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7274 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7275 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7276 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7277
7278 // for the quick and dirty code we will skip all the checks.
7279 // we are just trying to get the call to be generated.
7280 Node* src_start = src;
7281 Node* dest_start = dest;
7282 if (src_offset != nullptr || dest_offset != nullptr) {
7283 assert(src_offset != nullptr && dest_offset != nullptr, "");
7284 src_start = array_element_address(src, src_offset, T_BYTE);
7285 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7286 }
7287
7288 // now need to get the start of its expanded key array
7289 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7290 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7291 if (k_start == nullptr) return false;
7292
7293 // Call the stub.
7294 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
7295 stubAddr, stubName, TypePtr::BOTTOM,
7296 src_start, dest_start, k_start);
7297
7298 return true;
7299 }
7300
7301 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
7302 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
7303 address stubAddr = nullptr;
7304 const char *stubName = nullptr;
7305 bool is_decrypt = false;
7306 assert(UseAES, "need AES instruction support");
7307
7308 switch(id) {
7309 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
7310 stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
7311 stubName = "cipherBlockChaining_encryptAESCrypt";
7312 break;
7313 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
7314 stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
7315 stubName = "cipherBlockChaining_decryptAESCrypt";
7316 is_decrypt = true;
7317 break;
7318 default:
7319 break;
7320 }
7321 if (stubAddr == nullptr) return false;
7322
7323 Node* cipherBlockChaining_object = argument(0);
7324 Node* src = argument(1);
7325 Node* src_offset = argument(2);
7326 Node* len = argument(3);
7327 Node* dest = argument(4);
7328 Node* dest_offset = argument(5);
7329
7330 src = must_be_not_null(src, false);
7331 dest = must_be_not_null(dest, false);
7332
7333 // (1) src and dest are arrays.
7334 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7335 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7336 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7337 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7338
7339 // checks are the responsibility of the caller
7340 Node* src_start = src;
7341 Node* dest_start = dest;
7342 if (src_offset != nullptr || dest_offset != nullptr) {
7343 assert(src_offset != nullptr && dest_offset != nullptr, "");
7344 src_start = array_element_address(src, src_offset, T_BYTE);
7345 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7346 }
7347
7348 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7349 // (because of the predicated logic executed earlier).
7350 // so we cast it here safely.
7351 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7352
7353 Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7354 if (embeddedCipherObj == nullptr) return false;
7355
7356 // cast it to what we know it will be at runtime
7357 const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
7358 assert(tinst != nullptr, "CBC obj is null");
7359 assert(tinst->is_loaded(), "CBC obj is not loaded");
7360 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7361 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7362
7363 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7364 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7365 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7366 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7367 aescrypt_object = _gvn.transform(aescrypt_object);
7368
7369 // we need to get the start of the aescrypt_object's expanded key array
7370 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7371 if (k_start == nullptr) return false;
7372
7373 // similarly, get the start address of the r vector
7374 Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
7375 if (objRvec == nullptr) return false;
7376 Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
7377
7378 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7379 Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7380 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
7381 stubAddr, stubName, TypePtr::BOTTOM,
7382 src_start, dest_start, k_start, r_start, len);
7383
7384 // return cipher length (int)
7385 Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
7386 set_result(retvalue);
7387 return true;
7388 }
7389
7390 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
7391 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
7392 address stubAddr = nullptr;
7393 const char *stubName = nullptr;
7394 bool is_decrypt = false;
7395 assert(UseAES, "need AES instruction support");
7396
7397 switch (id) {
7398 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
7399 stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
7400 stubName = "electronicCodeBook_encryptAESCrypt";
7401 break;
7402 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
7403 stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
7404 stubName = "electronicCodeBook_decryptAESCrypt";
7405 is_decrypt = true;
7406 break;
7407 default:
7408 break;
7409 }
7410
7411 if (stubAddr == nullptr) return false;
7412
7413 Node* electronicCodeBook_object = argument(0);
7414 Node* src = argument(1);
7415 Node* src_offset = argument(2);
7416 Node* len = argument(3);
7417 Node* dest = argument(4);
7418 Node* dest_offset = argument(5);
7419
7420 // (1) src and dest are arrays.
7421 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7422 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7423 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7424 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7425
7426 // checks are the responsibility of the caller
7427 Node* src_start = src;
7428 Node* dest_start = dest;
7429 if (src_offset != nullptr || dest_offset != nullptr) {
7430 assert(src_offset != nullptr && dest_offset != nullptr, "");
7431 src_start = array_element_address(src, src_offset, T_BYTE);
7432 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7433 }
7434
7435 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7436 // (because of the predicated logic executed earlier).
7437 // so we cast it here safely.
7438 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7439
7440 Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7441 if (embeddedCipherObj == nullptr) return false;
7442
7443 // cast it to what we know it will be at runtime
7444 const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
7445 assert(tinst != nullptr, "ECB obj is null");
7446 assert(tinst->is_loaded(), "ECB obj is not loaded");
7447 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7448 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7449
7450 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7451 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7452 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7453 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7454 aescrypt_object = _gvn.transform(aescrypt_object);
7455
7456 // we need to get the start of the aescrypt_object's expanded key array
7457 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, is_decrypt);
7458 if (k_start == nullptr) return false;
7459
7460 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7461 Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
7462 OptoRuntime::electronicCodeBook_aescrypt_Type(),
7463 stubAddr, stubName, TypePtr::BOTTOM,
7464 src_start, dest_start, k_start, len);
7465
7466 // return cipher length (int)
7467 Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
7468 set_result(retvalue);
7469 return true;
7470 }
7471
7472 //------------------------------inline_counterMode_AESCrypt-----------------------
7473 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
7474 assert(UseAES, "need AES instruction support");
7475 if (!UseAESCTRIntrinsics) return false;
7476
7477 address stubAddr = nullptr;
7478 const char *stubName = nullptr;
7479 if (id == vmIntrinsics::_counterMode_AESCrypt) {
7480 stubAddr = StubRoutines::counterMode_AESCrypt();
7481 stubName = "counterMode_AESCrypt";
7482 }
7483 if (stubAddr == nullptr) return false;
7484
7485 Node* counterMode_object = argument(0);
7486 Node* src = argument(1);
7487 Node* src_offset = argument(2);
7488 Node* len = argument(3);
7489 Node* dest = argument(4);
7490 Node* dest_offset = argument(5);
7491
7492 // (1) src and dest are arrays.
7493 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
7494 const TypeAryPtr* dest_type = dest->Value(&_gvn)->isa_aryptr();
7495 assert( src_type != nullptr && src_type->elem() != Type::BOTTOM &&
7496 dest_type != nullptr && dest_type->elem() != Type::BOTTOM, "args are strange");
7497
7498 // checks are the responsibility of the caller
7499 Node* src_start = src;
7500 Node* dest_start = dest;
7501 if (src_offset != nullptr || dest_offset != nullptr) {
7502 assert(src_offset != nullptr && dest_offset != nullptr, "");
7503 src_start = array_element_address(src, src_offset, T_BYTE);
7504 dest_start = array_element_address(dest, dest_offset, T_BYTE);
7505 }
7506
7507 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
7508 // (because of the predicated logic executed earlier).
7509 // so we cast it here safely.
7510 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
7511 Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7512 if (embeddedCipherObj == nullptr) return false;
7513 // cast it to what we know it will be at runtime
7514 const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
7515 assert(tinst != nullptr, "CTR obj is null");
7516 assert(tinst->is_loaded(), "CTR obj is not loaded");
7517 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7518 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
7519 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7520 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
7521 const TypeOopPtr* xtype = aklass->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
7522 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
7523 aescrypt_object = _gvn.transform(aescrypt_object);
7524 // we need to get the start of the aescrypt_object's expanded key array
7525 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
7526 if (k_start == nullptr) return false;
7527 // similarly, get the start address of the r vector
7528 Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
7529 if (obj_counter == nullptr) return false;
7530 Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
7531
7532 Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
7533 if (saved_encCounter == nullptr) return false;
7534 Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
7535 Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
7536
7537 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
7538 Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
7539 OptoRuntime::counterMode_aescrypt_Type(),
7540 stubAddr, stubName, TypePtr::BOTTOM,
7541 src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
7542
7543 // return cipher length (int)
7544 Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
7545 set_result(retvalue);
7546 return true;
7547 }
7548
7549 //------------------------------get_key_start_from_aescrypt_object-----------------------
7550 Node* LibraryCallKit::get_key_start_from_aescrypt_object(Node* aescrypt_object, bool is_decrypt) {
7551 // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
7552 // Intel's extension is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
7553 // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
7554 // The following platform specific stubs of encryption and decryption use the same round keys.
7555 #if defined(PPC64) || defined(S390) || defined(RISCV64)
7556 bool use_decryption_key = false;
7557 #else
7558 bool use_decryption_key = is_decrypt;
7559 #endif
7560 Node* objAESCryptKey = load_field_from_object(aescrypt_object, use_decryption_key ? "sessionKd" : "sessionKe", "[I");
7561 assert(objAESCryptKey != nullptr, "wrong version of com.sun.crypto.provider.AES_Crypt");
7562 if (objAESCryptKey == nullptr) return (Node *) nullptr;
7563
7564 // now have the array, need to get the start address of the selected key array
7565 Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
7566 return k_start;
7567 }
7568
7569 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
7570 // Return node representing slow path of predicate check.
7571 // the pseudo code we want to emulate with this predicate is:
7572 // for encryption:
7573 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7574 // for decryption:
7575 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7576 // note cipher==plain is more conservative than the original java code but that's OK
7577 //
7578 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
7579 // The receiver was checked for null already.
7580 Node* objCBC = argument(0);
7581
7582 Node* src = argument(1);
7583 Node* dest = argument(4);
7584
7585 // Load embeddedCipher field of CipherBlockChaining object.
7586 Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7587
7588 // get AESCrypt klass for instanceOf check
7589 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7590 // will have same classloader as CipherBlockChaining object
7591 const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
7592 assert(tinst != nullptr, "CBCobj is null");
7593 assert(tinst->is_loaded(), "CBCobj is not loaded");
7594
7595 // we want to do an instanceof comparison against the AESCrypt class
7596 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7597 if (!klass_AESCrypt->is_loaded()) {
7598 // if AESCrypt is not even loaded, we never take the intrinsic fast path
7599 Node* ctrl = control();
7600 set_control(top()); // no regular fast path
7601 return ctrl;
7602 }
7603
7604 src = must_be_not_null(src, true);
7605 dest = must_be_not_null(dest, true);
7606
7607 // Resolve oops to stable for CmpP below.
7608 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7609
7610 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7611 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7612 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7613
7614 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7615
7616 // for encryption, we are done
7617 if (!decrypting)
7618 return instof_false; // even if it is null
7619
7620 // for decryption, we need to add a further check to avoid
7621 // taking the intrinsic path when cipher and plain are the same
7622 // see the original java code for why.
7623 RegionNode* region = new RegionNode(3);
7624 region->init_req(1, instof_false);
7625
7626 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7627 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7628 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7629 region->init_req(2, src_dest_conjoint);
7630
7631 record_for_igvn(region);
7632 return _gvn.transform(region);
7633 }
7634
7635 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
7636 // Return node representing slow path of predicate check.
7637 // the pseudo code we want to emulate with this predicate is:
7638 // for encryption:
7639 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7640 // for decryption:
7641 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7642 // note cipher==plain is more conservative than the original java code but that's OK
7643 //
7644 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
7645 // The receiver was checked for null already.
7646 Node* objECB = argument(0);
7647
7648 // Load embeddedCipher field of ElectronicCodeBook object.
7649 Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7650
7651 // get AESCrypt klass for instanceOf check
7652 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7653 // will have same classloader as ElectronicCodeBook object
7654 const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
7655 assert(tinst != nullptr, "ECBobj is null");
7656 assert(tinst->is_loaded(), "ECBobj is not loaded");
7657
7658 // we want to do an instanceof comparison against the AESCrypt class
7659 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7660 if (!klass_AESCrypt->is_loaded()) {
7661 // if AESCrypt is not even loaded, we never take the intrinsic fast path
7662 Node* ctrl = control();
7663 set_control(top()); // no regular fast path
7664 return ctrl;
7665 }
7666 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7667
7668 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7669 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7670 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7671
7672 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7673
7674 // for encryption, we are done
7675 if (!decrypting)
7676 return instof_false; // even if it is null
7677
7678 // for decryption, we need to add a further check to avoid
7679 // taking the intrinsic path when cipher and plain are the same
7680 // see the original java code for why.
7681 RegionNode* region = new RegionNode(3);
7682 region->init_req(1, instof_false);
7683 Node* src = argument(1);
7684 Node* dest = argument(4);
7685 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
7686 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
7687 Node* src_dest_conjoint = generate_guard(bool_src_dest, nullptr, PROB_MIN);
7688 region->init_req(2, src_dest_conjoint);
7689
7690 record_for_igvn(region);
7691 return _gvn.transform(region);
7692 }
7693
7694 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
7695 // Return node representing slow path of predicate check.
7696 // the pseudo code we want to emulate with this predicate is:
7697 // for encryption:
7698 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
7699 // for decryption:
7700 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
7701 // note cipher==plain is more conservative than the original java code but that's OK
7702 //
7703
7704 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
7705 // The receiver was checked for null already.
7706 Node* objCTR = argument(0);
7707
7708 // Load embeddedCipher field of CipherBlockChaining object.
7709 Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
7710
7711 // get AESCrypt klass for instanceOf check
7712 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
7713 // will have same classloader as CipherBlockChaining object
7714 const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
7715 assert(tinst != nullptr, "CTRobj is null");
7716 assert(tinst->is_loaded(), "CTRobj is not loaded");
7717
7718 // we want to do an instanceof comparison against the AESCrypt class
7719 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
7720 if (!klass_AESCrypt->is_loaded()) {
7721 // if AESCrypt is not even loaded, we never take the intrinsic fast path
7722 Node* ctrl = control();
7723 set_control(top()); // no regular fast path
7724 return ctrl;
7725 }
7726
7727 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
7728 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
7729 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
7730 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
7731 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
7732
7733 return instof_false; // even if it is null
7734 }
7735
7736 //------------------------------inline_ghash_processBlocks
7737 bool LibraryCallKit::inline_ghash_processBlocks() {
7738 address stubAddr;
7739 const char *stubName;
7740 assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
7741
7742 stubAddr = StubRoutines::ghash_processBlocks();
7743 stubName = "ghash_processBlocks";
7744
7745 Node* data = argument(0);
7746 Node* offset = argument(1);
7747 Node* len = argument(2);
7748 Node* state = argument(3);
7749 Node* subkeyH = argument(4);
7750
7751 state = must_be_not_null(state, true);
7752 subkeyH = must_be_not_null(subkeyH, true);
7753 data = must_be_not_null(data, true);
7754
7755 Node* state_start = array_element_address(state, intcon(0), T_LONG);
7756 assert(state_start, "state is null");
7757 Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);
7758 assert(subkeyH_start, "subkeyH is null");
7759 Node* data_start = array_element_address(data, offset, T_BYTE);
7760 assert(data_start, "data is null");
7761
7762 Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
7763 OptoRuntime::ghash_processBlocks_Type(),
7764 stubAddr, stubName, TypePtr::BOTTOM,
7765 state_start, subkeyH_start, data_start, len);
7766 return true;
7767 }
7768
7769 //------------------------------inline_chacha20Block
7770 bool LibraryCallKit::inline_chacha20Block() {
7771 address stubAddr;
7772 const char *stubName;
7773 assert(UseChaCha20Intrinsics, "need ChaCha20 intrinsics support");
7774
7775 stubAddr = StubRoutines::chacha20Block();
7776 stubName = "chacha20Block";
7777
7778 Node* state = argument(0);
7779 Node* result = argument(1);
7780
7781 state = must_be_not_null(state, true);
7782 result = must_be_not_null(result, true);
7783
7784 Node* state_start = array_element_address(state, intcon(0), T_INT);
7785 assert(state_start, "state is null");
7786 Node* result_start = array_element_address(result, intcon(0), T_BYTE);
7787 assert(result_start, "result is null");
7788
7789 Node* cc20Blk = make_runtime_call(RC_LEAF|RC_NO_FP,
7790 OptoRuntime::chacha20Block_Type(),
7791 stubAddr, stubName, TypePtr::BOTTOM,
7792 state_start, result_start);
7793 // return key stream length (int)
7794 Node* retvalue = _gvn.transform(new ProjNode(cc20Blk, TypeFunc::Parms));
7795 set_result(retvalue);
7796 return true;
7797 }
7798
7799 //------------------------------inline_kyberNtt
7800 bool LibraryCallKit::inline_kyberNtt() {
7801 address stubAddr;
7802 const char *stubName;
7803 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7804 assert(callee()->signature()->size() == 2, "kyberNtt has 2 parameters");
7805
7806 stubAddr = StubRoutines::kyberNtt();
7807 stubName = "kyberNtt";
7808 if (!stubAddr) return false;
7809
7810 Node* coeffs = argument(0);
7811 Node* ntt_zetas = argument(1);
7812
7813 coeffs = must_be_not_null(coeffs, true);
7814 ntt_zetas = must_be_not_null(ntt_zetas, true);
7815
7816 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
7817 assert(coeffs_start, "coeffs is null");
7818 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_SHORT);
7819 assert(ntt_zetas_start, "ntt_zetas is null");
7820 Node* kyberNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
7821 OptoRuntime::kyberNtt_Type(),
7822 stubAddr, stubName, TypePtr::BOTTOM,
7823 coeffs_start, ntt_zetas_start);
7824 // return an int
7825 Node* retvalue = _gvn.transform(new ProjNode(kyberNtt, TypeFunc::Parms));
7826 set_result(retvalue);
7827 return true;
7828 }
7829
7830 //------------------------------inline_kyberInverseNtt
7831 bool LibraryCallKit::inline_kyberInverseNtt() {
7832 address stubAddr;
7833 const char *stubName;
7834 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7835 assert(callee()->signature()->size() == 2, "kyberInverseNtt has 2 parameters");
7836
7837 stubAddr = StubRoutines::kyberInverseNtt();
7838 stubName = "kyberInverseNtt";
7839 if (!stubAddr) return false;
7840
7841 Node* coeffs = argument(0);
7842 Node* zetas = argument(1);
7843
7844 coeffs = must_be_not_null(coeffs, true);
7845 zetas = must_be_not_null(zetas, true);
7846
7847 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
7848 assert(coeffs_start, "coeffs is null");
7849 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
7850 assert(zetas_start, "inverseNtt_zetas is null");
7851 Node* kyberInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
7852 OptoRuntime::kyberInverseNtt_Type(),
7853 stubAddr, stubName, TypePtr::BOTTOM,
7854 coeffs_start, zetas_start);
7855
7856 // return an int
7857 Node* retvalue = _gvn.transform(new ProjNode(kyberInverseNtt, TypeFunc::Parms));
7858 set_result(retvalue);
7859 return true;
7860 }
7861
7862 //------------------------------inline_kyberNttMult
7863 bool LibraryCallKit::inline_kyberNttMult() {
7864 address stubAddr;
7865 const char *stubName;
7866 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7867 assert(callee()->signature()->size() == 4, "kyberNttMult has 4 parameters");
7868
7869 stubAddr = StubRoutines::kyberNttMult();
7870 stubName = "kyberNttMult";
7871 if (!stubAddr) return false;
7872
7873 Node* result = argument(0);
7874 Node* ntta = argument(1);
7875 Node* nttb = argument(2);
7876 Node* zetas = argument(3);
7877
7878 result = must_be_not_null(result, true);
7879 ntta = must_be_not_null(ntta, true);
7880 nttb = must_be_not_null(nttb, true);
7881 zetas = must_be_not_null(zetas, true);
7882
7883 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
7884 assert(result_start, "result is null");
7885 Node* ntta_start = array_element_address(ntta, intcon(0), T_SHORT);
7886 assert(ntta_start, "ntta is null");
7887 Node* nttb_start = array_element_address(nttb, intcon(0), T_SHORT);
7888 assert(nttb_start, "nttb is null");
7889 Node* zetas_start = array_element_address(zetas, intcon(0), T_SHORT);
7890 assert(zetas_start, "nttMult_zetas is null");
7891 Node* kyberNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
7892 OptoRuntime::kyberNttMult_Type(),
7893 stubAddr, stubName, TypePtr::BOTTOM,
7894 result_start, ntta_start, nttb_start,
7895 zetas_start);
7896
7897 // return an int
7898 Node* retvalue = _gvn.transform(new ProjNode(kyberNttMult, TypeFunc::Parms));
7899 set_result(retvalue);
7900
7901 return true;
7902 }
7903
7904 //------------------------------inline_kyberAddPoly_2
7905 bool LibraryCallKit::inline_kyberAddPoly_2() {
7906 address stubAddr;
7907 const char *stubName;
7908 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7909 assert(callee()->signature()->size() == 3, "kyberAddPoly_2 has 3 parameters");
7910
7911 stubAddr = StubRoutines::kyberAddPoly_2();
7912 stubName = "kyberAddPoly_2";
7913 if (!stubAddr) return false;
7914
7915 Node* result = argument(0);
7916 Node* a = argument(1);
7917 Node* b = argument(2);
7918
7919 result = must_be_not_null(result, true);
7920 a = must_be_not_null(a, true);
7921 b = must_be_not_null(b, true);
7922
7923 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
7924 assert(result_start, "result is null");
7925 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
7926 assert(a_start, "a is null");
7927 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
7928 assert(b_start, "b is null");
7929 Node* kyberAddPoly_2 = make_runtime_call(RC_LEAF|RC_NO_FP,
7930 OptoRuntime::kyberAddPoly_2_Type(),
7931 stubAddr, stubName, TypePtr::BOTTOM,
7932 result_start, a_start, b_start);
7933 // return an int
7934 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_2, TypeFunc::Parms));
7935 set_result(retvalue);
7936 return true;
7937 }
7938
7939 //------------------------------inline_kyberAddPoly_3
7940 bool LibraryCallKit::inline_kyberAddPoly_3() {
7941 address stubAddr;
7942 const char *stubName;
7943 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7944 assert(callee()->signature()->size() == 4, "kyberAddPoly_3 has 4 parameters");
7945
7946 stubAddr = StubRoutines::kyberAddPoly_3();
7947 stubName = "kyberAddPoly_3";
7948 if (!stubAddr) return false;
7949
7950 Node* result = argument(0);
7951 Node* a = argument(1);
7952 Node* b = argument(2);
7953 Node* c = argument(3);
7954
7955 result = must_be_not_null(result, true);
7956 a = must_be_not_null(a, true);
7957 b = must_be_not_null(b, true);
7958 c = must_be_not_null(c, true);
7959
7960 Node* result_start = array_element_address(result, intcon(0), T_SHORT);
7961 assert(result_start, "result is null");
7962 Node* a_start = array_element_address(a, intcon(0), T_SHORT);
7963 assert(a_start, "a is null");
7964 Node* b_start = array_element_address(b, intcon(0), T_SHORT);
7965 assert(b_start, "b is null");
7966 Node* c_start = array_element_address(c, intcon(0), T_SHORT);
7967 assert(c_start, "c is null");
7968 Node* kyberAddPoly_3 = make_runtime_call(RC_LEAF|RC_NO_FP,
7969 OptoRuntime::kyberAddPoly_3_Type(),
7970 stubAddr, stubName, TypePtr::BOTTOM,
7971 result_start, a_start, b_start, c_start);
7972 // return an int
7973 Node* retvalue = _gvn.transform(new ProjNode(kyberAddPoly_3, TypeFunc::Parms));
7974 set_result(retvalue);
7975 return true;
7976 }
7977
7978 //------------------------------inline_kyber12To16
7979 bool LibraryCallKit::inline_kyber12To16() {
7980 address stubAddr;
7981 const char *stubName;
7982 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
7983 assert(callee()->signature()->size() == 4, "kyber12To16 has 4 parameters");
7984
7985 stubAddr = StubRoutines::kyber12To16();
7986 stubName = "kyber12To16";
7987 if (!stubAddr) return false;
7988
7989 Node* condensed = argument(0);
7990 Node* condensedOffs = argument(1);
7991 Node* parsed = argument(2);
7992 Node* parsedLength = argument(3);
7993
7994 condensed = must_be_not_null(condensed, true);
7995 parsed = must_be_not_null(parsed, true);
7996
7997 Node* condensed_start = array_element_address(condensed, intcon(0), T_BYTE);
7998 assert(condensed_start, "condensed is null");
7999 Node* parsed_start = array_element_address(parsed, intcon(0), T_SHORT);
8000 assert(parsed_start, "parsed is null");
8001 Node* kyber12To16 = make_runtime_call(RC_LEAF|RC_NO_FP,
8002 OptoRuntime::kyber12To16_Type(),
8003 stubAddr, stubName, TypePtr::BOTTOM,
8004 condensed_start, condensedOffs, parsed_start, parsedLength);
8005 // return an int
8006 Node* retvalue = _gvn.transform(new ProjNode(kyber12To16, TypeFunc::Parms));
8007 set_result(retvalue);
8008 return true;
8009
8010 }
8011
8012 //------------------------------inline_kyberBarrettReduce
8013 bool LibraryCallKit::inline_kyberBarrettReduce() {
8014 address stubAddr;
8015 const char *stubName;
8016 assert(UseKyberIntrinsics, "need Kyber intrinsics support");
8017 assert(callee()->signature()->size() == 1, "kyberBarrettReduce has 1 parameters");
8018
8019 stubAddr = StubRoutines::kyberBarrettReduce();
8020 stubName = "kyberBarrettReduce";
8021 if (!stubAddr) return false;
8022
8023 Node* coeffs = argument(0);
8024
8025 coeffs = must_be_not_null(coeffs, true);
8026
8027 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_SHORT);
8028 assert(coeffs_start, "coeffs is null");
8029 Node* kyberBarrettReduce = make_runtime_call(RC_LEAF|RC_NO_FP,
8030 OptoRuntime::kyberBarrettReduce_Type(),
8031 stubAddr, stubName, TypePtr::BOTTOM,
8032 coeffs_start);
8033 // return an int
8034 Node* retvalue = _gvn.transform(new ProjNode(kyberBarrettReduce, TypeFunc::Parms));
8035 set_result(retvalue);
8036 return true;
8037 }
8038
8039 //------------------------------inline_dilithiumAlmostNtt
8040 bool LibraryCallKit::inline_dilithiumAlmostNtt() {
8041 address stubAddr;
8042 const char *stubName;
8043 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8044 assert(callee()->signature()->size() == 2, "dilithiumAlmostNtt has 2 parameters");
8045
8046 stubAddr = StubRoutines::dilithiumAlmostNtt();
8047 stubName = "dilithiumAlmostNtt";
8048 if (!stubAddr) return false;
8049
8050 Node* coeffs = argument(0);
8051 Node* ntt_zetas = argument(1);
8052
8053 coeffs = must_be_not_null(coeffs, true);
8054 ntt_zetas = must_be_not_null(ntt_zetas, true);
8055
8056 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8057 assert(coeffs_start, "coeffs is null");
8058 Node* ntt_zetas_start = array_element_address(ntt_zetas, intcon(0), T_INT);
8059 assert(ntt_zetas_start, "ntt_zetas is null");
8060 Node* dilithiumAlmostNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8061 OptoRuntime::dilithiumAlmostNtt_Type(),
8062 stubAddr, stubName, TypePtr::BOTTOM,
8063 coeffs_start, ntt_zetas_start);
8064 // return an int
8065 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostNtt, TypeFunc::Parms));
8066 set_result(retvalue);
8067 return true;
8068 }
8069
8070 //------------------------------inline_dilithiumAlmostInverseNtt
8071 bool LibraryCallKit::inline_dilithiumAlmostInverseNtt() {
8072 address stubAddr;
8073 const char *stubName;
8074 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8075 assert(callee()->signature()->size() == 2, "dilithiumAlmostInverseNtt has 2 parameters");
8076
8077 stubAddr = StubRoutines::dilithiumAlmostInverseNtt();
8078 stubName = "dilithiumAlmostInverseNtt";
8079 if (!stubAddr) return false;
8080
8081 Node* coeffs = argument(0);
8082 Node* zetas = argument(1);
8083
8084 coeffs = must_be_not_null(coeffs, true);
8085 zetas = must_be_not_null(zetas, true);
8086
8087 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8088 assert(coeffs_start, "coeffs is null");
8089 Node* zetas_start = array_element_address(zetas, intcon(0), T_INT);
8090 assert(zetas_start, "inverseNtt_zetas is null");
8091 Node* dilithiumAlmostInverseNtt = make_runtime_call(RC_LEAF|RC_NO_FP,
8092 OptoRuntime::dilithiumAlmostInverseNtt_Type(),
8093 stubAddr, stubName, TypePtr::BOTTOM,
8094 coeffs_start, zetas_start);
8095 // return an int
8096 Node* retvalue = _gvn.transform(new ProjNode(dilithiumAlmostInverseNtt, TypeFunc::Parms));
8097 set_result(retvalue);
8098 return true;
8099 }
8100
8101 //------------------------------inline_dilithiumNttMult
8102 bool LibraryCallKit::inline_dilithiumNttMult() {
8103 address stubAddr;
8104 const char *stubName;
8105 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8106 assert(callee()->signature()->size() == 3, "dilithiumNttMult has 3 parameters");
8107
8108 stubAddr = StubRoutines::dilithiumNttMult();
8109 stubName = "dilithiumNttMult";
8110 if (!stubAddr) return false;
8111
8112 Node* result = argument(0);
8113 Node* ntta = argument(1);
8114 Node* nttb = argument(2);
8115 Node* zetas = argument(3);
8116
8117 result = must_be_not_null(result, true);
8118 ntta = must_be_not_null(ntta, true);
8119 nttb = must_be_not_null(nttb, true);
8120 zetas = must_be_not_null(zetas, true);
8121
8122 Node* result_start = array_element_address(result, intcon(0), T_INT);
8123 assert(result_start, "result is null");
8124 Node* ntta_start = array_element_address(ntta, intcon(0), T_INT);
8125 assert(ntta_start, "ntta is null");
8126 Node* nttb_start = array_element_address(nttb, intcon(0), T_INT);
8127 assert(nttb_start, "nttb is null");
8128 Node* dilithiumNttMult = make_runtime_call(RC_LEAF|RC_NO_FP,
8129 OptoRuntime::dilithiumNttMult_Type(),
8130 stubAddr, stubName, TypePtr::BOTTOM,
8131 result_start, ntta_start, nttb_start);
8132
8133 // return an int
8134 Node* retvalue = _gvn.transform(new ProjNode(dilithiumNttMult, TypeFunc::Parms));
8135 set_result(retvalue);
8136
8137 return true;
8138 }
8139
8140 //------------------------------inline_dilithiumMontMulByConstant
8141 bool LibraryCallKit::inline_dilithiumMontMulByConstant() {
8142 address stubAddr;
8143 const char *stubName;
8144 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8145 assert(callee()->signature()->size() == 2, "dilithiumMontMulByConstant has 2 parameters");
8146
8147 stubAddr = StubRoutines::dilithiumMontMulByConstant();
8148 stubName = "dilithiumMontMulByConstant";
8149 if (!stubAddr) return false;
8150
8151 Node* coeffs = argument(0);
8152 Node* constant = argument(1);
8153
8154 coeffs = must_be_not_null(coeffs, true);
8155
8156 Node* coeffs_start = array_element_address(coeffs, intcon(0), T_INT);
8157 assert(coeffs_start, "coeffs is null");
8158 Node* dilithiumMontMulByConstant = make_runtime_call(RC_LEAF|RC_NO_FP,
8159 OptoRuntime::dilithiumMontMulByConstant_Type(),
8160 stubAddr, stubName, TypePtr::BOTTOM,
8161 coeffs_start, constant);
8162
8163 // return an int
8164 Node* retvalue = _gvn.transform(new ProjNode(dilithiumMontMulByConstant, TypeFunc::Parms));
8165 set_result(retvalue);
8166 return true;
8167 }
8168
8169
8170 //------------------------------inline_dilithiumDecomposePoly
8171 bool LibraryCallKit::inline_dilithiumDecomposePoly() {
8172 address stubAddr;
8173 const char *stubName;
8174 assert(UseDilithiumIntrinsics, "need Dilithium intrinsics support");
8175 assert(callee()->signature()->size() == 5, "dilithiumDecomposePoly has 5 parameters");
8176
8177 stubAddr = StubRoutines::dilithiumDecomposePoly();
8178 stubName = "dilithiumDecomposePoly";
8179 if (!stubAddr) return false;
8180
8181 Node* input = argument(0);
8182 Node* lowPart = argument(1);
8183 Node* highPart = argument(2);
8184 Node* twoGamma2 = argument(3);
8185 Node* multiplier = argument(4);
8186
8187 input = must_be_not_null(input, true);
8188 lowPart = must_be_not_null(lowPart, true);
8189 highPart = must_be_not_null(highPart, true);
8190
8191 Node* input_start = array_element_address(input, intcon(0), T_INT);
8192 assert(input_start, "input is null");
8193 Node* lowPart_start = array_element_address(lowPart, intcon(0), T_INT);
8194 assert(lowPart_start, "lowPart is null");
8195 Node* highPart_start = array_element_address(highPart, intcon(0), T_INT);
8196 assert(highPart_start, "highPart is null");
8197
8198 Node* dilithiumDecomposePoly = make_runtime_call(RC_LEAF|RC_NO_FP,
8199 OptoRuntime::dilithiumDecomposePoly_Type(),
8200 stubAddr, stubName, TypePtr::BOTTOM,
8201 input_start, lowPart_start, highPart_start,
8202 twoGamma2, multiplier);
8203
8204 // return an int
8205 Node* retvalue = _gvn.transform(new ProjNode(dilithiumDecomposePoly, TypeFunc::Parms));
8206 set_result(retvalue);
8207 return true;
8208 }
8209
8210 bool LibraryCallKit::inline_base64_encodeBlock() {
8211 address stubAddr;
8212 const char *stubName;
8213 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8214 assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
8215 stubAddr = StubRoutines::base64_encodeBlock();
8216 stubName = "encodeBlock";
8217
8218 if (!stubAddr) return false;
8219 Node* base64obj = argument(0);
8220 Node* src = argument(1);
8221 Node* offset = argument(2);
8222 Node* len = argument(3);
8223 Node* dest = argument(4);
8224 Node* dp = argument(5);
8225 Node* isURL = argument(6);
8226
8227 src = must_be_not_null(src, true);
8228 dest = must_be_not_null(dest, true);
8229
8230 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8231 assert(src_start, "source array is null");
8232 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8233 assert(dest_start, "destination array is null");
8234
8235 Node* base64 = make_runtime_call(RC_LEAF,
8236 OptoRuntime::base64_encodeBlock_Type(),
8237 stubAddr, stubName, TypePtr::BOTTOM,
8238 src_start, offset, len, dest_start, dp, isURL);
8239 return true;
8240 }
8241
8242 bool LibraryCallKit::inline_base64_decodeBlock() {
8243 address stubAddr;
8244 const char *stubName;
8245 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
8246 assert(callee()->signature()->size() == 7, "base64_decodeBlock has 7 parameters");
8247 stubAddr = StubRoutines::base64_decodeBlock();
8248 stubName = "decodeBlock";
8249
8250 if (!stubAddr) return false;
8251 Node* base64obj = argument(0);
8252 Node* src = argument(1);
8253 Node* src_offset = argument(2);
8254 Node* len = argument(3);
8255 Node* dest = argument(4);
8256 Node* dest_offset = argument(5);
8257 Node* isURL = argument(6);
8258 Node* isMIME = argument(7);
8259
8260 src = must_be_not_null(src, true);
8261 dest = must_be_not_null(dest, true);
8262
8263 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
8264 assert(src_start, "source array is null");
8265 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
8266 assert(dest_start, "destination array is null");
8267
8268 Node* call = make_runtime_call(RC_LEAF,
8269 OptoRuntime::base64_decodeBlock_Type(),
8270 stubAddr, stubName, TypePtr::BOTTOM,
8271 src_start, src_offset, len, dest_start, dest_offset, isURL, isMIME);
8272 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8273 set_result(result);
8274 return true;
8275 }
8276
8277 bool LibraryCallKit::inline_poly1305_processBlocks() {
8278 address stubAddr;
8279 const char *stubName;
8280 assert(UsePoly1305Intrinsics, "need Poly intrinsics support");
8281 assert(callee()->signature()->size() == 5, "poly1305_processBlocks has %d parameters", callee()->signature()->size());
8282 stubAddr = StubRoutines::poly1305_processBlocks();
8283 stubName = "poly1305_processBlocks";
8284
8285 if (!stubAddr) return false;
8286 null_check_receiver(); // null-check receiver
8287 if (stopped()) return true;
8288
8289 Node* input = argument(1);
8290 Node* input_offset = argument(2);
8291 Node* len = argument(3);
8292 Node* alimbs = argument(4);
8293 Node* rlimbs = argument(5);
8294
8295 input = must_be_not_null(input, true);
8296 alimbs = must_be_not_null(alimbs, true);
8297 rlimbs = must_be_not_null(rlimbs, true);
8298
8299 Node* input_start = array_element_address(input, input_offset, T_BYTE);
8300 assert(input_start, "input array is null");
8301 Node* acc_start = array_element_address(alimbs, intcon(0), T_LONG);
8302 assert(acc_start, "acc array is null");
8303 Node* r_start = array_element_address(rlimbs, intcon(0), T_LONG);
8304 assert(r_start, "r array is null");
8305
8306 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8307 OptoRuntime::poly1305_processBlocks_Type(),
8308 stubAddr, stubName, TypePtr::BOTTOM,
8309 input_start, len, acc_start, r_start);
8310 return true;
8311 }
8312
8313 bool LibraryCallKit::inline_intpoly_montgomeryMult_P256() {
8314 address stubAddr;
8315 const char *stubName;
8316 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8317 assert(callee()->signature()->size() == 3, "intpoly_montgomeryMult_P256 has %d parameters", callee()->signature()->size());
8318 stubAddr = StubRoutines::intpoly_montgomeryMult_P256();
8319 stubName = "intpoly_montgomeryMult_P256";
8320
8321 if (!stubAddr) return false;
8322 null_check_receiver(); // null-check receiver
8323 if (stopped()) return true;
8324
8325 Node* a = argument(1);
8326 Node* b = argument(2);
8327 Node* r = argument(3);
8328
8329 a = must_be_not_null(a, true);
8330 b = must_be_not_null(b, true);
8331 r = must_be_not_null(r, true);
8332
8333 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8334 assert(a_start, "a array is null");
8335 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8336 assert(b_start, "b array is null");
8337 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8338 assert(r_start, "r array is null");
8339
8340 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8341 OptoRuntime::intpoly_montgomeryMult_P256_Type(),
8342 stubAddr, stubName, TypePtr::BOTTOM,
8343 a_start, b_start, r_start);
8344 return true;
8345 }
8346
8347 bool LibraryCallKit::inline_intpoly_assign() {
8348 assert(UseIntPolyIntrinsics, "need intpoly intrinsics support");
8349 assert(callee()->signature()->size() == 3, "intpoly_assign has %d parameters", callee()->signature()->size());
8350 const char *stubName = "intpoly_assign";
8351 address stubAddr = StubRoutines::intpoly_assign();
8352 if (!stubAddr) return false;
8353
8354 Node* set = argument(0);
8355 Node* a = argument(1);
8356 Node* b = argument(2);
8357 Node* arr_length = load_array_length(a);
8358
8359 a = must_be_not_null(a, true);
8360 b = must_be_not_null(b, true);
8361
8362 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8363 assert(a_start, "a array is null");
8364 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8365 assert(b_start, "b array is null");
8366
8367 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8368 OptoRuntime::intpoly_assign_Type(),
8369 stubAddr, stubName, TypePtr::BOTTOM,
8370 set, a_start, b_start, arr_length);
8371 return true;
8372 }
8373
8374 bool LibraryCallKit::inline_intpoly_mult_25519() {
8375 address stubAddr;
8376 const char *stubName;
8377 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
8378 assert(callee()->signature()->size() == 3, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
8379 stubAddr = StubRoutines::intpoly_mult_25519();
8380 stubName = "intpoly_mult_25519";
8381
8382 if (!stubAddr) return false;
8383 null_check_receiver(); // null-check receiver
8384 if (stopped()) return true;
8385
8386 Node* a = argument(1);
8387 Node* b = argument(2);
8388 Node* r = argument(3);
8389
8390 a = must_be_not_null(a, true);
8391 b = must_be_not_null(b, true);
8392 r = must_be_not_null(r, true);
8393
8394 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8395 assert(a_start, "a array is null");
8396 Node* b_start = array_element_address(b, intcon(0), T_LONG);
8397 assert(b_start, "b array is null");
8398 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8399 assert(r_start, "r array is null");
8400
8401 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8402 OptoRuntime::intpoly_mult_25519_Type(),
8403 stubAddr, stubName, TypePtr::BOTTOM,
8404 a_start, b_start, r_start);
8405 return true;
8406 }
8407
8408 bool LibraryCallKit::inline_intpoly_square_25519() {
8409 address stubAddr;
8410 const char *stubName;
8411 assert(UseIntPoly25519Intrinsics, "need intpoly25519 intrinsics support");
8412 assert(callee()->signature()->size() == 2, "intpoly_mult_25519 has %d parameters", callee()->signature()->size());
8413 stubAddr = StubRoutines::intpoly_square_25519();
8414 stubName = "intpoly_square_25519";
8415
8416 if (!stubAddr) return false;
8417 null_check_receiver(); // null-check receiver
8418 if (stopped()) return true;
8419
8420 Node* a = argument(1);
8421 Node* r = argument(2);
8422
8423 a = must_be_not_null(a, true);
8424 r = must_be_not_null(r, true);
8425
8426 Node* a_start = array_element_address(a, intcon(0), T_LONG);
8427 assert(a_start, "a array is null");
8428 Node* r_start = array_element_address(r, intcon(0), T_LONG);
8429 assert(r_start, "r array is null");
8430
8431 Node* call = make_runtime_call(RC_LEAF | RC_NO_FP,
8432 OptoRuntime::intpoly_square_25519_Type(),
8433 stubAddr, stubName, TypePtr::BOTTOM,
8434 a_start, r_start);
8435 return true;
8436 }
8437
8438 //------------------------------inline_digestBase_implCompress-----------------------
8439 //
8440 // Calculate MD5 for single-block byte[] array.
8441 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
8442 //
8443 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
8444 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
8445 //
8446 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
8447 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
8448 //
8449 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
8450 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
8451 //
8452 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
8453 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
8454 //
8455 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
8456 assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
8457
8458 Node* digestBase_obj = argument(0);
8459 Node* src = argument(1); // type oop
8460 Node* ofs = argument(2); // type int
8461
8462 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8463 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8464 // failed array check
8465 return false;
8466 }
8467 // Figure out the size and type of the elements we will be copying.
8468 BasicType src_elem = src_type->elem()->array_element_basic_type();
8469 if (src_elem != T_BYTE) {
8470 return false;
8471 }
8472 // 'src_start' points to src array + offset
8473 src = must_be_not_null(src, true);
8474 Node* src_start = array_element_address(src, ofs, src_elem);
8475 Node* state = nullptr;
8476 Node* block_size = nullptr;
8477 address stubAddr;
8478 const char *stubName;
8479
8480 switch(id) {
8481 case vmIntrinsics::_md5_implCompress:
8482 assert(UseMD5Intrinsics, "need MD5 instruction support");
8483 state = get_state_from_digest_object(digestBase_obj, T_INT);
8484 stubAddr = StubRoutines::md5_implCompress();
8485 stubName = "md5_implCompress";
8486 break;
8487 case vmIntrinsics::_sha_implCompress:
8488 assert(UseSHA1Intrinsics, "need SHA1 instruction support");
8489 state = get_state_from_digest_object(digestBase_obj, T_INT);
8490 stubAddr = StubRoutines::sha1_implCompress();
8491 stubName = "sha1_implCompress";
8492 break;
8493 case vmIntrinsics::_sha2_implCompress:
8494 assert(UseSHA256Intrinsics, "need SHA256 instruction support");
8495 state = get_state_from_digest_object(digestBase_obj, T_INT);
8496 stubAddr = StubRoutines::sha256_implCompress();
8497 stubName = "sha256_implCompress";
8498 break;
8499 case vmIntrinsics::_sha5_implCompress:
8500 assert(UseSHA512Intrinsics, "need SHA512 instruction support");
8501 state = get_state_from_digest_object(digestBase_obj, T_LONG);
8502 stubAddr = StubRoutines::sha512_implCompress();
8503 stubName = "sha512_implCompress";
8504 break;
8505 case vmIntrinsics::_sha3_implCompress:
8506 assert(UseSHA3Intrinsics, "need SHA3 instruction support");
8507 state = get_state_from_digest_object(digestBase_obj, T_LONG);
8508 stubAddr = StubRoutines::sha3_implCompress();
8509 stubName = "sha3_implCompress";
8510 block_size = get_block_size_from_digest_object(digestBase_obj);
8511 if (block_size == nullptr) return false;
8512 break;
8513 default:
8514 fatal_unexpected_iid(id);
8515 return false;
8516 }
8517 if (state == nullptr) return false;
8518
8519 assert(stubAddr != nullptr, "Stub %s is not generated", stubName);
8520 if (stubAddr == nullptr) return false;
8521
8522 // Call the stub.
8523 Node* call;
8524 if (block_size == nullptr) {
8525 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
8526 stubAddr, stubName, TypePtr::BOTTOM,
8527 src_start, state);
8528 } else {
8529 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
8530 stubAddr, stubName, TypePtr::BOTTOM,
8531 src_start, state, block_size);
8532 }
8533
8534 return true;
8535 }
8536
8537 //------------------------------inline_keccak
8538 bool LibraryCallKit::inline_keccak(vmIntrinsics::ID id) {
8539 address stubAddr = nullptr;
8540 const char *stubName;
8541 assert(UseSHA3Intrinsics, "need SHA3 intrinsics support");
8542 assert((id == vmIntrinsics::_double_keccak && callee()->signature()->size() == 2) ||
8543 (id == vmIntrinsics::_quad_keccak && callee()->signature()->size() == 4),
8544 "double_keccak wrong number of parameters");
8545
8546 int parmCnt = 0;
8547 switch (id) {
8548 case vmIntrinsics::_double_keccak:
8549 stubAddr = StubRoutines::double_keccak();
8550 stubName = "double_keccak";
8551 parmCnt = 2;
8552 break;
8553 case vmIntrinsics::_quad_keccak:
8554 stubAddr = StubRoutines::quad_keccak();
8555 stubName = "quad_keccak";
8556 parmCnt = 4;
8557 break;
8558 default:
8559 ShouldNotReachHere();
8560 }
8561
8562 if (!stubAddr) return false;
8563
8564 Node* state[4];
8565 for (int i = 0; i<parmCnt; i++) {
8566 state[i] = must_be_not_null(argument(i), true);
8567 state[i] = array_element_address(state[i], intcon(0), T_LONG);
8568 assert(state[i], "state[%d] is null", i);
8569 }
8570
8571 Node* keccak;
8572 switch (id) {
8573 case vmIntrinsics::_double_keccak:
8574 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
8575 OptoRuntime::double_keccak_Type(),
8576 stubAddr, stubName, TypePtr::BOTTOM,
8577 state[0], state[1]);
8578 break;
8579 case vmIntrinsics::_quad_keccak:
8580 keccak = make_runtime_call(RC_LEAF|RC_NO_FP,
8581 OptoRuntime::quad_keccak_Type(),
8582 stubAddr, stubName, TypePtr::BOTTOM,
8583 state[0], state[1], state[2], state[3]);
8584 break;
8585 default:
8586 ShouldNotReachHere();
8587 }
8588
8589 // return an int
8590 Node* retvalue = _gvn.transform(new ProjNode(keccak, TypeFunc::Parms));
8591 set_result(retvalue);
8592 return true;
8593 }
8594
8595
8596 //------------------------------inline_digestBase_implCompressMB-----------------------
8597 //
8598 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
8599 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
8600 //
8601 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
8602 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8603 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8604 assert((uint)predicate < 5, "sanity");
8605 assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
8606
8607 Node* digestBase_obj = argument(0); // The receiver was checked for null already.
8608 Node* src = argument(1); // byte[] array
8609 Node* ofs = argument(2); // type int
8610 Node* limit = argument(3); // type int
8611
8612 const TypeAryPtr* src_type = src->Value(&_gvn)->isa_aryptr();
8613 if (src_type == nullptr || src_type->elem() == Type::BOTTOM) {
8614 // failed array check
8615 return false;
8616 }
8617 // Figure out the size and type of the elements we will be copying.
8618 BasicType src_elem = src_type->elem()->array_element_basic_type();
8619 if (src_elem != T_BYTE) {
8620 return false;
8621 }
8622 // 'src_start' points to src array + offset
8623 src = must_be_not_null(src, false);
8624 Node* src_start = array_element_address(src, ofs, src_elem);
8625
8626 const char* klass_digestBase_name = nullptr;
8627 const char* stub_name = nullptr;
8628 address stub_addr = nullptr;
8629 BasicType elem_type = T_INT;
8630
8631 switch (predicate) {
8632 case 0:
8633 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
8634 klass_digestBase_name = "sun/security/provider/MD5";
8635 stub_name = "md5_implCompressMB";
8636 stub_addr = StubRoutines::md5_implCompressMB();
8637 }
8638 break;
8639 case 1:
8640 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
8641 klass_digestBase_name = "sun/security/provider/SHA";
8642 stub_name = "sha1_implCompressMB";
8643 stub_addr = StubRoutines::sha1_implCompressMB();
8644 }
8645 break;
8646 case 2:
8647 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
8648 klass_digestBase_name = "sun/security/provider/SHA2";
8649 stub_name = "sha256_implCompressMB";
8650 stub_addr = StubRoutines::sha256_implCompressMB();
8651 }
8652 break;
8653 case 3:
8654 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
8655 klass_digestBase_name = "sun/security/provider/SHA5";
8656 stub_name = "sha512_implCompressMB";
8657 stub_addr = StubRoutines::sha512_implCompressMB();
8658 elem_type = T_LONG;
8659 }
8660 break;
8661 case 4:
8662 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
8663 klass_digestBase_name = "sun/security/provider/SHA3";
8664 stub_name = "sha3_implCompressMB";
8665 stub_addr = StubRoutines::sha3_implCompressMB();
8666 elem_type = T_LONG;
8667 }
8668 break;
8669 default:
8670 fatal("unknown DigestBase intrinsic predicate: %d", predicate);
8671 }
8672 if (klass_digestBase_name != nullptr) {
8673 assert(stub_addr != nullptr, "Stub is generated");
8674 if (stub_addr == nullptr) return false;
8675
8676 // get DigestBase klass to lookup for SHA klass
8677 const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
8678 assert(tinst != nullptr, "digestBase_obj is not instance???");
8679 assert(tinst->is_loaded(), "DigestBase is not loaded");
8680
8681 ciKlass* klass_digestBase = tinst->instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
8682 assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
8683 ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
8684 return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, elem_type, stub_addr, stub_name, src_start, ofs, limit);
8685 }
8686 return false;
8687 }
8688
8689 //------------------------------inline_digestBase_implCompressMB-----------------------
8690 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
8691 BasicType elem_type, address stubAddr, const char *stubName,
8692 Node* src_start, Node* ofs, Node* limit) {
8693 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
8694 const TypeOopPtr* xtype = aklass->cast_to_exactness(false)->as_instance_type()->cast_to_ptr_type(TypePtr::NotNull);
8695 Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
8696 digest_obj = _gvn.transform(digest_obj);
8697
8698 Node* state = get_state_from_digest_object(digest_obj, elem_type);
8699 if (state == nullptr) return false;
8700
8701 Node* block_size = nullptr;
8702 if (strcmp("sha3_implCompressMB", stubName) == 0) {
8703 block_size = get_block_size_from_digest_object(digest_obj);
8704 if (block_size == nullptr) return false;
8705 }
8706
8707 // Call the stub.
8708 Node* call;
8709 if (block_size == nullptr) {
8710 call = make_runtime_call(RC_LEAF|RC_NO_FP,
8711 OptoRuntime::digestBase_implCompressMB_Type(false),
8712 stubAddr, stubName, TypePtr::BOTTOM,
8713 src_start, state, ofs, limit);
8714 } else {
8715 call = make_runtime_call(RC_LEAF|RC_NO_FP,
8716 OptoRuntime::digestBase_implCompressMB_Type(true),
8717 stubAddr, stubName, TypePtr::BOTTOM,
8718 src_start, state, block_size, ofs, limit);
8719 }
8720
8721 // return ofs (int)
8722 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
8723 set_result(result);
8724
8725 return true;
8726 }
8727
8728 //------------------------------inline_galoisCounterMode_AESCrypt-----------------------
8729 bool LibraryCallKit::inline_galoisCounterMode_AESCrypt() {
8730 assert(UseAES, "need AES instruction support");
8731 address stubAddr = nullptr;
8732 const char *stubName = nullptr;
8733 stubAddr = StubRoutines::galoisCounterMode_AESCrypt();
8734 stubName = "galoisCounterMode_AESCrypt";
8735
8736 if (stubAddr == nullptr) return false;
8737
8738 Node* in = argument(0);
8739 Node* inOfs = argument(1);
8740 Node* len = argument(2);
8741 Node* ct = argument(3);
8742 Node* ctOfs = argument(4);
8743 Node* out = argument(5);
8744 Node* outOfs = argument(6);
8745 Node* gctr_object = argument(7);
8746 Node* ghash_object = argument(8);
8747
8748 // (1) in, ct and out are arrays.
8749 const TypeAryPtr* in_type = in->Value(&_gvn)->isa_aryptr();
8750 const TypeAryPtr* ct_type = ct->Value(&_gvn)->isa_aryptr();
8751 const TypeAryPtr* out_type = out->Value(&_gvn)->isa_aryptr();
8752 assert( in_type != nullptr && in_type->elem() != Type::BOTTOM &&
8753 ct_type != nullptr && ct_type->elem() != Type::BOTTOM &&
8754 out_type != nullptr && out_type->elem() != Type::BOTTOM, "args are strange");
8755
8756 // checks are the responsibility of the caller
8757 Node* in_start = in;
8758 Node* ct_start = ct;
8759 Node* out_start = out;
8760 if (inOfs != nullptr || ctOfs != nullptr || outOfs != nullptr) {
8761 assert(inOfs != nullptr && ctOfs != nullptr && outOfs != nullptr, "");
8762 in_start = array_element_address(in, inOfs, T_BYTE);
8763 ct_start = array_element_address(ct, ctOfs, T_BYTE);
8764 out_start = array_element_address(out, outOfs, T_BYTE);
8765 }
8766
8767 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
8768 // (because of the predicated logic executed earlier).
8769 // so we cast it here safely.
8770 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
8771 Node* embeddedCipherObj = load_field_from_object(gctr_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8772 Node* counter = load_field_from_object(gctr_object, "counter", "[B");
8773 Node* subkeyHtbl = load_field_from_object(ghash_object, "subkeyHtbl", "[J");
8774 Node* state = load_field_from_object(ghash_object, "state", "[J");
8775
8776 if (embeddedCipherObj == nullptr || counter == nullptr || subkeyHtbl == nullptr || state == nullptr) {
8777 return false;
8778 }
8779 // cast it to what we know it will be at runtime
8780 const TypeInstPtr* tinst = _gvn.type(gctr_object)->isa_instptr();
8781 assert(tinst != nullptr, "GCTR obj is null");
8782 assert(tinst->is_loaded(), "GCTR obj is not loaded");
8783 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8784 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
8785 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8786 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
8787 const TypeOopPtr* xtype = aklass->as_instance_type();
8788 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
8789 aescrypt_object = _gvn.transform(aescrypt_object);
8790 // we need to get the start of the aescrypt_object's expanded key array
8791 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object, /* is_decrypt */ false);
8792 if (k_start == nullptr) return false;
8793 // similarly, get the start address of the r vector
8794 Node* cnt_start = array_element_address(counter, intcon(0), T_BYTE);
8795 Node* state_start = array_element_address(state, intcon(0), T_LONG);
8796 Node* subkeyHtbl_start = array_element_address(subkeyHtbl, intcon(0), T_LONG);
8797
8798
8799 // Call the stub, passing params
8800 Node* gcmCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
8801 OptoRuntime::galoisCounterMode_aescrypt_Type(),
8802 stubAddr, stubName, TypePtr::BOTTOM,
8803 in_start, len, ct_start, out_start, k_start, state_start, subkeyHtbl_start, cnt_start);
8804
8805 // return cipher length (int)
8806 Node* retvalue = _gvn.transform(new ProjNode(gcmCrypt, TypeFunc::Parms));
8807 set_result(retvalue);
8808
8809 return true;
8810 }
8811
8812 //----------------------------inline_galoisCounterMode_AESCrypt_predicate----------------------------
8813 // Return node representing slow path of predicate check.
8814 // the pseudo code we want to emulate with this predicate is:
8815 // for encryption:
8816 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
8817 // for decryption:
8818 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
8819 // note cipher==plain is more conservative than the original java code but that's OK
8820 //
8821
8822 Node* LibraryCallKit::inline_galoisCounterMode_AESCrypt_predicate() {
8823 // The receiver was checked for null already.
8824 Node* objGCTR = argument(7);
8825 // Load embeddedCipher field of GCTR object.
8826 Node* embeddedCipherObj = load_field_from_object(objGCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
8827 assert(embeddedCipherObj != nullptr, "embeddedCipherObj is null");
8828
8829 // get AESCrypt klass for instanceOf check
8830 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
8831 // will have same classloader as CipherBlockChaining object
8832 const TypeInstPtr* tinst = _gvn.type(objGCTR)->isa_instptr();
8833 assert(tinst != nullptr, "GCTR obj is null");
8834 assert(tinst->is_loaded(), "GCTR obj is not loaded");
8835
8836 // we want to do an instanceof comparison against the AESCrypt class
8837 ciKlass* klass_AESCrypt = tinst->instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AES_Crypt"));
8838 if (!klass_AESCrypt->is_loaded()) {
8839 // if AESCrypt is not even loaded, we never take the intrinsic fast path
8840 Node* ctrl = control();
8841 set_control(top()); // no regular fast path
8842 return ctrl;
8843 }
8844
8845 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
8846 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
8847 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8848 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8849 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8850
8851 return instof_false; // even if it is null
8852 }
8853
8854 //------------------------------get_state_from_digest_object-----------------------
8855 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, BasicType elem_type) {
8856 const char* state_type;
8857 switch (elem_type) {
8858 case T_BYTE: state_type = "[B"; break;
8859 case T_INT: state_type = "[I"; break;
8860 case T_LONG: state_type = "[J"; break;
8861 default: ShouldNotReachHere();
8862 }
8863 Node* digest_state = load_field_from_object(digest_object, "state", state_type);
8864 assert (digest_state != nullptr, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
8865 if (digest_state == nullptr) return (Node *) nullptr;
8866
8867 // now have the array, need to get the start address of the state array
8868 Node* state = array_element_address(digest_state, intcon(0), elem_type);
8869 return state;
8870 }
8871
8872 //------------------------------get_block_size_from_sha3_object----------------------------------
8873 Node * LibraryCallKit::get_block_size_from_digest_object(Node *digest_object) {
8874 Node* block_size = load_field_from_object(digest_object, "blockSize", "I");
8875 assert (block_size != nullptr, "sanity");
8876 return block_size;
8877 }
8878
8879 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
8880 // Return node representing slow path of predicate check.
8881 // the pseudo code we want to emulate with this predicate is:
8882 // if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
8883 //
8884 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
8885 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
8886 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
8887 assert((uint)predicate < 5, "sanity");
8888
8889 // The receiver was checked for null already.
8890 Node* digestBaseObj = argument(0);
8891
8892 // get DigestBase klass for instanceOf check
8893 const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
8894 assert(tinst != nullptr, "digestBaseObj is null");
8895 assert(tinst->is_loaded(), "DigestBase is not loaded");
8896
8897 const char* klass_name = nullptr;
8898 switch (predicate) {
8899 case 0:
8900 if (UseMD5Intrinsics) {
8901 // we want to do an instanceof comparison against the MD5 class
8902 klass_name = "sun/security/provider/MD5";
8903 }
8904 break;
8905 case 1:
8906 if (UseSHA1Intrinsics) {
8907 // we want to do an instanceof comparison against the SHA class
8908 klass_name = "sun/security/provider/SHA";
8909 }
8910 break;
8911 case 2:
8912 if (UseSHA256Intrinsics) {
8913 // we want to do an instanceof comparison against the SHA2 class
8914 klass_name = "sun/security/provider/SHA2";
8915 }
8916 break;
8917 case 3:
8918 if (UseSHA512Intrinsics) {
8919 // we want to do an instanceof comparison against the SHA5 class
8920 klass_name = "sun/security/provider/SHA5";
8921 }
8922 break;
8923 case 4:
8924 if (UseSHA3Intrinsics) {
8925 // we want to do an instanceof comparison against the SHA3 class
8926 klass_name = "sun/security/provider/SHA3";
8927 }
8928 break;
8929 default:
8930 fatal("unknown SHA intrinsic predicate: %d", predicate);
8931 }
8932
8933 ciKlass* klass = nullptr;
8934 if (klass_name != nullptr) {
8935 klass = tinst->instance_klass()->find_klass(ciSymbol::make(klass_name));
8936 }
8937 if ((klass == nullptr) || !klass->is_loaded()) {
8938 // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
8939 Node* ctrl = control();
8940 set_control(top()); // no intrinsic path
8941 return ctrl;
8942 }
8943 ciInstanceKlass* instklass = klass->as_instance_klass();
8944
8945 Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
8946 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
8947 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
8948 Node* instof_false = generate_guard(bool_instof, nullptr, PROB_MIN);
8949
8950 return instof_false; // even if it is null
8951 }
8952
8953 //-------------inline_fma-----------------------------------
8954 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
8955 Node *a = nullptr;
8956 Node *b = nullptr;
8957 Node *c = nullptr;
8958 Node* result = nullptr;
8959 switch (id) {
8960 case vmIntrinsics::_fmaD:
8961 assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
8962 // no receiver since it is static method
8963 a = argument(0);
8964 b = argument(2);
8965 c = argument(4);
8966 result = _gvn.transform(new FmaDNode(a, b, c));
8967 break;
8968 case vmIntrinsics::_fmaF:
8969 assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
8970 a = argument(0);
8971 b = argument(1);
8972 c = argument(2);
8973 result = _gvn.transform(new FmaFNode(a, b, c));
8974 break;
8975 default:
8976 fatal_unexpected_iid(id); break;
8977 }
8978 set_result(result);
8979 return true;
8980 }
8981
8982 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
8983 // argument(0) is receiver
8984 Node* codePoint = argument(1);
8985 Node* n = nullptr;
8986
8987 switch (id) {
8988 case vmIntrinsics::_isDigit :
8989 n = new DigitNode(control(), codePoint);
8990 break;
8991 case vmIntrinsics::_isLowerCase :
8992 n = new LowerCaseNode(control(), codePoint);
8993 break;
8994 case vmIntrinsics::_isUpperCase :
8995 n = new UpperCaseNode(control(), codePoint);
8996 break;
8997 case vmIntrinsics::_isWhitespace :
8998 n = new WhitespaceNode(control(), codePoint);
8999 break;
9000 default:
9001 fatal_unexpected_iid(id);
9002 }
9003
9004 set_result(_gvn.transform(n));
9005 return true;
9006 }
9007
9008 bool LibraryCallKit::inline_profileBoolean() {
9009 Node* counts = argument(1);
9010 const TypeAryPtr* ary = nullptr;
9011 ciArray* aobj = nullptr;
9012 if (counts->is_Con()
9013 && (ary = counts->bottom_type()->isa_aryptr()) != nullptr
9014 && (aobj = ary->const_oop()->as_array()) != nullptr
9015 && (aobj->length() == 2)) {
9016 // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
9017 jint false_cnt = aobj->element_value(0).as_int();
9018 jint true_cnt = aobj->element_value(1).as_int();
9019
9020 if (C->log() != nullptr) {
9021 C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
9022 false_cnt, true_cnt);
9023 }
9024
9025 if (false_cnt + true_cnt == 0) {
9026 // According to profile, never executed.
9027 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9028 Deoptimization::Action_reinterpret);
9029 return true;
9030 }
9031
9032 // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
9033 // is a number of each value occurrences.
9034 Node* result = argument(0);
9035 if (false_cnt == 0 || true_cnt == 0) {
9036 // According to profile, one value has been never seen.
9037 int expected_val = (false_cnt == 0) ? 1 : 0;
9038
9039 Node* cmp = _gvn.transform(new CmpINode(result, intcon(expected_val)));
9040 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
9041
9042 IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
9043 Node* fast_path = _gvn.transform(new IfTrueNode(check));
9044 Node* slow_path = _gvn.transform(new IfFalseNode(check));
9045
9046 { // Slow path: uncommon trap for never seen value and then reexecute
9047 // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
9048 // the value has been seen at least once.
9049 PreserveJVMState pjvms(this);
9050 PreserveReexecuteState preexecs(this);
9051 jvms()->set_should_reexecute(true);
9052
9053 set_control(slow_path);
9054 set_i_o(i_o());
9055
9056 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
9057 Deoptimization::Action_reinterpret);
9058 }
9059 // The guard for never seen value enables sharpening of the result and
9060 // returning a constant. It allows to eliminate branches on the same value
9061 // later on.
9062 set_control(fast_path);
9063 result = intcon(expected_val);
9064 }
9065 // Stop profiling.
9066 // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
9067 // By replacing method body with profile data (represented as ProfileBooleanNode
9068 // on IR level) we effectively disable profiling.
9069 // It enables full speed execution once optimized code is generated.
9070 Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
9071 C->record_for_igvn(profile);
9072 set_result(profile);
9073 return true;
9074 } else {
9075 // Continue profiling.
9076 // Profile data isn't available at the moment. So, execute method's bytecode version.
9077 // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
9078 // is compiled and counters aren't available since corresponding MethodHandle
9079 // isn't a compile-time constant.
9080 return false;
9081 }
9082 }
9083
9084 bool LibraryCallKit::inline_isCompileConstant() {
9085 Node* n = argument(0);
9086 set_result(n->is_Con() ? intcon(1) : intcon(0));
9087 return true;
9088 }
9089
9090 //------------------------------- inline_getObjectSize --------------------------------------
9091 //
9092 // Calculate the runtime size of the object/array.
9093 // native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
9094 //
9095 bool LibraryCallKit::inline_getObjectSize() {
9096 Node* obj = argument(3);
9097 Node* klass_node = load_object_klass(obj);
9098
9099 jint layout_con = Klass::_lh_neutral_value;
9100 Node* layout_val = get_layout_helper(klass_node, layout_con);
9101 int layout_is_con = (layout_val == nullptr);
9102
9103 if (layout_is_con) {
9104 // Layout helper is constant, can figure out things at compile time.
9105
9106 if (Klass::layout_helper_is_instance(layout_con)) {
9107 // Instance case: layout_con contains the size itself.
9108 Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
9109 set_result(size);
9110 } else {
9111 // Array case: size is round(header + element_size*arraylength).
9112 // Since arraylength is different for every array instance, we have to
9113 // compute the whole thing at runtime.
9114
9115 Node* arr_length = load_array_length(obj);
9116
9117 int round_mask = MinObjAlignmentInBytes - 1;
9118 int hsize = Klass::layout_helper_header_size(layout_con);
9119 int eshift = Klass::layout_helper_log2_element_size(layout_con);
9120
9121 if ((round_mask & ~right_n_bits(eshift)) == 0) {
9122 round_mask = 0; // strength-reduce it if it goes away completely
9123 }
9124 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
9125 Node* header_size = intcon(hsize + round_mask);
9126
9127 Node* lengthx = ConvI2X(arr_length);
9128 Node* headerx = ConvI2X(header_size);
9129
9130 Node* abody = lengthx;
9131 if (eshift != 0) {
9132 abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
9133 }
9134 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
9135 if (round_mask != 0) {
9136 size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
9137 }
9138 size = ConvX2L(size);
9139 set_result(size);
9140 }
9141 } else {
9142 // Layout helper is not constant, need to test for array-ness at runtime.
9143
9144 enum { _instance_path = 1, _array_path, PATH_LIMIT };
9145 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
9146 PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
9147 record_for_igvn(result_reg);
9148
9149 Node* array_ctl = generate_array_guard(klass_node, nullptr, &obj);
9150 if (array_ctl != nullptr) {
9151 // Array case: size is round(header + element_size*arraylength).
9152 // Since arraylength is different for every array instance, we have to
9153 // compute the whole thing at runtime.
9154
9155 PreserveJVMState pjvms(this);
9156 set_control(array_ctl);
9157 Node* arr_length = load_array_length(obj);
9158
9159 int round_mask = MinObjAlignmentInBytes - 1;
9160 Node* mask = intcon(round_mask);
9161
9162 Node* hss = intcon(Klass::_lh_header_size_shift);
9163 Node* hsm = intcon(Klass::_lh_header_size_mask);
9164 Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
9165 header_size = _gvn.transform(new AndINode(header_size, hsm));
9166 header_size = _gvn.transform(new AddINode(header_size, mask));
9167
9168 // There is no need to mask or shift this value.
9169 // The semantics of LShiftINode include an implicit mask to 0x1F.
9170 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
9171 Node* elem_shift = layout_val;
9172
9173 Node* lengthx = ConvI2X(arr_length);
9174 Node* headerx = ConvI2X(header_size);
9175
9176 Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
9177 Node* size = _gvn.transform(new AddXNode(headerx, abody));
9178 if (round_mask != 0) {
9179 size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
9180 }
9181 size = ConvX2L(size);
9182
9183 result_reg->init_req(_array_path, control());
9184 result_val->init_req(_array_path, size);
9185 }
9186
9187 if (!stopped()) {
9188 // Instance case: the layout helper gives us instance size almost directly,
9189 // but we need to mask out the _lh_instance_slow_path_bit.
9190 Node* size = ConvI2X(layout_val);
9191 assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
9192 Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
9193 size = _gvn.transform(new AndXNode(size, mask));
9194 size = ConvX2L(size);
9195
9196 result_reg->init_req(_instance_path, control());
9197 result_val->init_req(_instance_path, size);
9198 }
9199
9200 set_result(result_reg, result_val);
9201 }
9202
9203 return true;
9204 }
9205
9206 //------------------------------- inline_blackhole --------------------------------------
9207 //
9208 // Make sure all arguments to this node are alive.
9209 // This matches methods that were requested to be blackholed through compile commands.
9210 //
9211 bool LibraryCallKit::inline_blackhole() {
9212 assert(callee()->is_static(), "Should have been checked before: only static methods here");
9213 assert(callee()->is_empty(), "Should have been checked before: only empty methods here");
9214 assert(callee()->holder()->is_loaded(), "Should have been checked before: only methods for loaded classes here");
9215
9216 // Blackhole node pinches only the control, not memory. This allows
9217 // the blackhole to be pinned in the loop that computes blackholed
9218 // values, but have no other side effects, like breaking the optimizations
9219 // across the blackhole.
9220
9221 Node* bh = _gvn.transform(new BlackholeNode(control()));
9222 set_control(_gvn.transform(new ProjNode(bh, TypeFunc::Control)));
9223
9224 // Bind call arguments as blackhole arguments to keep them alive
9225 uint nargs = callee()->arg_size();
9226 for (uint i = 0; i < nargs; i++) {
9227 bh->add_req(argument(i));
9228 }
9229
9230 return true;
9231 }
9232
9233 Node* LibraryCallKit::unbox_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* box) {
9234 const TypeInstPtr* box_type = _gvn.type(box)->isa_instptr();
9235 if (box_type == nullptr || box_type->instance_klass() != float16_box_type->instance_klass()) {
9236 return nullptr; // box klass is not Float16
9237 }
9238
9239 // Null check; get notnull casted pointer
9240 Node* null_ctl = top();
9241 Node* not_null_box = null_check_oop(box, &null_ctl, true);
9242 // If not_null_box is dead, only null-path is taken
9243 if (stopped()) {
9244 set_control(null_ctl);
9245 return nullptr;
9246 }
9247 assert(not_null_box->bottom_type()->is_instptr()->maybe_null() == false, "");
9248 const TypePtr* adr_type = C->alias_type(field)->adr_type();
9249 Node* adr = basic_plus_adr(not_null_box, field->offset_in_bytes());
9250 return access_load_at(not_null_box, adr, adr_type, TypeInt::SHORT, T_SHORT, IN_HEAP);
9251 }
9252
9253 Node* LibraryCallKit::box_fp16_value(const TypeInstPtr* float16_box_type, ciField* field, Node* value) {
9254 PreserveReexecuteState preexecs(this);
9255 jvms()->set_should_reexecute(true);
9256
9257 const TypeKlassPtr* klass_type = float16_box_type->as_klass_type();
9258 Node* klass_node = makecon(klass_type);
9259 Node* box = new_instance(klass_node);
9260
9261 Node* value_field = basic_plus_adr(box, field->offset_in_bytes());
9262 const TypePtr* value_adr_type = value_field->bottom_type()->is_ptr();
9263
9264 Node* field_store = _gvn.transform(access_store_at(box,
9265 value_field,
9266 value_adr_type,
9267 value,
9268 TypeInt::SHORT,
9269 T_SHORT,
9270 IN_HEAP));
9271 set_memory(field_store, value_adr_type);
9272 return box;
9273 }
9274
9275 bool LibraryCallKit::inline_fp16_operations(vmIntrinsics::ID id, int num_args) {
9276 if (!Matcher::match_rule_supported(Op_ReinterpretS2HF) ||
9277 !Matcher::match_rule_supported(Op_ReinterpretHF2S)) {
9278 return false;
9279 }
9280
9281 const TypeInstPtr* box_type = _gvn.type(argument(0))->isa_instptr();
9282 if (box_type == nullptr || box_type->const_oop() == nullptr) {
9283 return false;
9284 }
9285
9286 ciInstanceKlass* float16_klass = box_type->const_oop()->as_instance()->java_lang_Class_klass()->as_instance_klass();
9287 const TypeInstPtr* float16_box_type = TypeInstPtr::make_exact(TypePtr::NotNull, float16_klass);
9288 ciField* field = float16_klass->get_field_by_name(ciSymbols::value_name(),
9289 ciSymbols::short_signature(),
9290 false);
9291 assert(field != nullptr, "");
9292
9293 // Transformed nodes
9294 Node* fld1 = nullptr;
9295 Node* fld2 = nullptr;
9296 Node* fld3 = nullptr;
9297 switch(num_args) {
9298 case 3:
9299 fld3 = unbox_fp16_value(float16_box_type, field, argument(3));
9300 if (fld3 == nullptr) {
9301 return false;
9302 }
9303 fld3 = _gvn.transform(new ReinterpretS2HFNode(fld3));
9304 // fall-through
9305 case 2:
9306 fld2 = unbox_fp16_value(float16_box_type, field, argument(2));
9307 if (fld2 == nullptr) {
9308 return false;
9309 }
9310 fld2 = _gvn.transform(new ReinterpretS2HFNode(fld2));
9311 // fall-through
9312 case 1:
9313 fld1 = unbox_fp16_value(float16_box_type, field, argument(1));
9314 if (fld1 == nullptr) {
9315 return false;
9316 }
9317 fld1 = _gvn.transform(new ReinterpretS2HFNode(fld1));
9318 break;
9319 default: fatal("Unsupported number of arguments %d", num_args);
9320 }
9321
9322 Node* result = nullptr;
9323 switch (id) {
9324 // Unary operations
9325 case vmIntrinsics::_sqrt_float16:
9326 result = _gvn.transform(new SqrtHFNode(C, control(), fld1));
9327 break;
9328 // Ternary operations
9329 case vmIntrinsics::_fma_float16:
9330 result = _gvn.transform(new FmaHFNode(fld1, fld2, fld3));
9331 break;
9332 default:
9333 fatal_unexpected_iid(id);
9334 break;
9335 }
9336 result = _gvn.transform(new ReinterpretHF2SNode(result));
9337 set_result(box_fp16_value(float16_box_type, field, result));
9338 return true;
9339 }
9340