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