1 /*
2 * Copyright (c) 1999, 2021, 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 "precompiled.hpp"
26 #include "asm/macroAssembler.hpp"
27 #include "ci/ciUtilities.inline.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "compiler/compileBroker.hpp"
31 #include "compiler/compileLog.hpp"
32 #include "gc/shared/barrierSet.hpp"
33 #include "jfr/support/jfrIntrinsics.hpp"
34 #include "memory/resourceArea.hpp"
35 #include "oops/klass.inline.hpp"
36 #include "oops/objArrayKlass.hpp"
37 #include "opto/addnode.hpp"
38 #include "opto/arraycopynode.hpp"
39 #include "opto/c2compiler.hpp"
40 #include "opto/castnode.hpp"
41 #include "opto/cfgnode.hpp"
42 #include "opto/convertnode.hpp"
43 #include "opto/countbitsnode.hpp"
44 #include "opto/idealKit.hpp"
45 #include "opto/library_call.hpp"
46 #include "opto/mathexactnode.hpp"
47 #include "opto/mulnode.hpp"
48 #include "opto/narrowptrnode.hpp"
49 #include "opto/opaquenode.hpp"
50 #include "opto/parse.hpp"
51 #include "opto/runtime.hpp"
52 #include "opto/rootnode.hpp"
53 #include "opto/subnode.hpp"
54 #include "prims/nativeLookup.hpp"
55 #include "prims/unsafe.hpp"
56 #include "runtime/objectMonitor.hpp"
57 #include "runtime/sharedRuntime.hpp"
58 #include "utilities/macros.hpp"
59 #include "utilities/powerOfTwo.hpp"
60
61 //---------------------------make_vm_intrinsic----------------------------
make_vm_intrinsic(ciMethod * m,bool is_virtual)62 CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) {
63 vmIntrinsics::ID id = m->intrinsic_id();
64 assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
65
66 if (!m->is_loaded()) {
67 // Do not attempt to inline unloaded methods.
68 return NULL;
69 }
70
71 C2Compiler* compiler = (C2Compiler*)CompileBroker::compiler(CompLevel_full_optimization);
72 bool is_available = false;
73
74 {
75 // For calling is_intrinsic_supported and is_intrinsic_disabled_by_flag
76 // the compiler must transition to '_thread_in_vm' state because both
77 // methods access VM-internal data.
78 VM_ENTRY_MARK;
79 methodHandle mh(THREAD, m->get_Method());
80 is_available = compiler != NULL && compiler->is_intrinsic_supported(mh, is_virtual) &&
81 !C->directive()->is_intrinsic_disabled(mh) &&
82 !vmIntrinsics::is_disabled_by_flags(mh);
83
84 }
85
86 if (is_available) {
87 assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility");
88 assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?");
89 return new LibraryIntrinsic(m, is_virtual,
90 vmIntrinsics::predicates_needed(id),
91 vmIntrinsics::does_virtual_dispatch(id),
92 (vmIntrinsics::ID) id);
93 } else {
94 return NULL;
95 }
96 }
97
generate(JVMState * jvms)98 JVMState* LibraryIntrinsic::generate(JVMState* jvms) {
99 LibraryCallKit kit(jvms, this);
100 Compile* C = kit.C;
101 int nodes = C->unique();
102 #ifndef PRODUCT
103 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
104 char buf[1000];
105 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
106 tty->print_cr("Intrinsic %s", str);
107 }
108 #endif
109 ciMethod* callee = kit.callee();
110 const int bci = kit.bci();
111
112 // Try to inline the intrinsic.
113 if ((CheckIntrinsics ? callee->intrinsic_candidate() : true) &&
114 kit.try_to_inline(_last_predicate)) {
115 const char *inline_msg = is_virtual() ? "(intrinsic, virtual)"
116 : "(intrinsic)";
117 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, inline_msg);
118 if (C->print_intrinsics() || C->print_inlining()) {
119 C->print_inlining(callee, jvms->depth() - 1, bci, inline_msg);
120 }
121 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
122 if (C->log()) {
123 C->log()->elem("intrinsic id='%s'%s nodes='%d'",
124 vmIntrinsics::name_at(intrinsic_id()),
125 (is_virtual() ? " virtual='1'" : ""),
126 C->unique() - nodes);
127 }
128 // Push the result from the inlined method onto the stack.
129 kit.push_result();
130 C->print_inlining_update(this);
131 return kit.transfer_exceptions_into_jvms();
132 }
133
134 // The intrinsic bailed out
135 if (jvms->has_method()) {
136 // Not a root compile.
137 const char* msg;
138 if (callee->intrinsic_candidate()) {
139 msg = is_virtual() ? "failed to inline (intrinsic, virtual)" : "failed to inline (intrinsic)";
140 } else {
141 msg = is_virtual() ? "failed to inline (intrinsic, virtual), method not annotated"
142 : "failed to inline (intrinsic), method not annotated";
143 }
144 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, msg);
145 if (C->print_intrinsics() || C->print_inlining()) {
146 C->print_inlining(callee, jvms->depth() - 1, bci, msg);
147 }
148 } else {
149 // Root compile
150 ResourceMark rm;
151 stringStream msg_stream;
152 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
153 vmIntrinsics::name_at(intrinsic_id()),
154 is_virtual() ? " (virtual)" : "", bci);
155 const char *msg = msg_stream.as_string();
156 log_debug(jit, inlining)("%s", msg);
157 if (C->print_intrinsics() || C->print_inlining()) {
158 tty->print("%s", msg);
159 }
160 }
161 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
162 C->print_inlining_update(this);
163
164 return NULL;
165 }
166
generate_predicate(JVMState * jvms,int predicate)167 Node* LibraryIntrinsic::generate_predicate(JVMState* jvms, int predicate) {
168 LibraryCallKit kit(jvms, this);
169 Compile* C = kit.C;
170 int nodes = C->unique();
171 _last_predicate = predicate;
172 #ifndef PRODUCT
173 assert(is_predicated() && predicate < predicates_count(), "sanity");
174 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
175 char buf[1000];
176 const char* str = vmIntrinsics::short_name_as_C_string(intrinsic_id(), buf, sizeof(buf));
177 tty->print_cr("Predicate for intrinsic %s", str);
178 }
179 #endif
180 ciMethod* callee = kit.callee();
181 const int bci = kit.bci();
182
183 Node* slow_ctl = kit.try_to_predicate(predicate);
184 if (!kit.failing()) {
185 const char *inline_msg = is_virtual() ? "(intrinsic, virtual, predicate)"
186 : "(intrinsic, predicate)";
187 CompileTask::print_inlining_ul(callee, jvms->depth() - 1, bci, inline_msg);
188 if (C->print_intrinsics() || C->print_inlining()) {
189 C->print_inlining(callee, jvms->depth() - 1, bci, inline_msg);
190 }
191 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_worked);
192 if (C->log()) {
193 C->log()->elem("predicate_intrinsic id='%s'%s nodes='%d'",
194 vmIntrinsics::name_at(intrinsic_id()),
195 (is_virtual() ? " virtual='1'" : ""),
196 C->unique() - nodes);
197 }
198 return slow_ctl; // Could be NULL if the check folds.
199 }
200
201 // The intrinsic bailed out
202 if (jvms->has_method()) {
203 // Not a root compile.
204 const char* msg = "failed to generate predicate for intrinsic";
205 CompileTask::print_inlining_ul(kit.callee(), jvms->depth() - 1, bci, msg);
206 if (C->print_intrinsics() || C->print_inlining()) {
207 C->print_inlining(kit.callee(), jvms->depth() - 1, bci, msg);
208 }
209 } else {
210 // Root compile
211 ResourceMark rm;
212 stringStream msg_stream;
213 msg_stream.print("Did not generate intrinsic %s%s at bci:%d in",
214 vmIntrinsics::name_at(intrinsic_id()),
215 is_virtual() ? " (virtual)" : "", bci);
216 const char *msg = msg_stream.as_string();
217 log_debug(jit, inlining)("%s", msg);
218 if (C->print_intrinsics() || C->print_inlining()) {
219 C->print_inlining_stream()->print("%s", msg);
220 }
221 }
222 C->gather_intrinsic_statistics(intrinsic_id(), is_virtual(), Compile::_intrinsic_failed);
223 return NULL;
224 }
225
try_to_inline(int predicate)226 bool LibraryCallKit::try_to_inline(int predicate) {
227 // Handle symbolic names for otherwise undistinguished boolean switches:
228 const bool is_store = true;
229 const bool is_compress = true;
230 const bool is_static = true;
231 const bool is_volatile = true;
232
233 if (!jvms()->has_method()) {
234 // Root JVMState has a null method.
235 assert(map()->memory()->Opcode() == Op_Parm, "");
236 // Insert the memory aliasing node
237 set_all_memory(reset_memory());
238 }
239 assert(merged_memory(), "");
240
241 switch (intrinsic_id()) {
242 case vmIntrinsics::_hashCode: return inline_native_hashcode(intrinsic()->is_virtual(), !is_static);
243 case vmIntrinsics::_identityHashCode: return inline_native_hashcode(/*!virtual*/ false, is_static);
244 case vmIntrinsics::_getClass: return inline_native_getClass();
245
246 case vmIntrinsics::_ceil:
247 case vmIntrinsics::_floor:
248 case vmIntrinsics::_rint:
249 case vmIntrinsics::_dsin:
250 case vmIntrinsics::_dcos:
251 case vmIntrinsics::_dtan:
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::_dexp:
259 case vmIntrinsics::_dlog:
260 case vmIntrinsics::_dlog10:
261 case vmIntrinsics::_dpow:
262 case vmIntrinsics::_dcopySign:
263 case vmIntrinsics::_fcopySign:
264 case vmIntrinsics::_dsignum:
265 case vmIntrinsics::_fsignum: return inline_math_native(intrinsic_id());
266
267 case vmIntrinsics::_min:
268 case vmIntrinsics::_max: return inline_min_max(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::_negateExactI: return inline_math_negateExactI();
284 case vmIntrinsics::_negateExactL: return inline_math_negateExactL();
285 case vmIntrinsics::_subtractExactI: return inline_math_subtractExactI(false /* subtract */);
286 case vmIntrinsics::_subtractExactL: return inline_math_subtractExactL(false /* subtract */);
287
288 case vmIntrinsics::_arraycopy: return inline_arraycopy();
289
290 case vmIntrinsics::_compareToL: return inline_string_compareTo(StrIntrinsicNode::LL);
291 case vmIntrinsics::_compareToU: return inline_string_compareTo(StrIntrinsicNode::UU);
292 case vmIntrinsics::_compareToLU: return inline_string_compareTo(StrIntrinsicNode::LU);
293 case vmIntrinsics::_compareToUL: return inline_string_compareTo(StrIntrinsicNode::UL);
294
295 case vmIntrinsics::_indexOfL: return inline_string_indexOf(StrIntrinsicNode::LL);
296 case vmIntrinsics::_indexOfU: return inline_string_indexOf(StrIntrinsicNode::UU);
297 case vmIntrinsics::_indexOfUL: return inline_string_indexOf(StrIntrinsicNode::UL);
298 case vmIntrinsics::_indexOfIL: return inline_string_indexOfI(StrIntrinsicNode::LL);
299 case vmIntrinsics::_indexOfIU: return inline_string_indexOfI(StrIntrinsicNode::UU);
300 case vmIntrinsics::_indexOfIUL: return inline_string_indexOfI(StrIntrinsicNode::UL);
301 case vmIntrinsics::_indexOfU_char: return inline_string_indexOfChar(StrIntrinsicNode::U);
302 case vmIntrinsics::_indexOfL_char: return inline_string_indexOfChar(StrIntrinsicNode::L);
303
304 case vmIntrinsics::_equalsL: return inline_string_equals(StrIntrinsicNode::LL);
305 case vmIntrinsics::_equalsU: return inline_string_equals(StrIntrinsicNode::UU);
306
307 case vmIntrinsics::_toBytesStringU: return inline_string_toBytesU();
308 case vmIntrinsics::_getCharsStringU: return inline_string_getCharsU();
309 case vmIntrinsics::_getCharStringU: return inline_string_char_access(!is_store);
310 case vmIntrinsics::_putCharStringU: return inline_string_char_access( is_store);
311
312 case vmIntrinsics::_compressStringC:
313 case vmIntrinsics::_compressStringB: return inline_string_copy( is_compress);
314 case vmIntrinsics::_inflateStringC:
315 case vmIntrinsics::_inflateStringB: return inline_string_copy(!is_compress);
316
317 case vmIntrinsics::_getReference: return inline_unsafe_access(!is_store, T_OBJECT, Relaxed, false);
318 case vmIntrinsics::_getBoolean: return inline_unsafe_access(!is_store, T_BOOLEAN, Relaxed, false);
319 case vmIntrinsics::_getByte: return inline_unsafe_access(!is_store, T_BYTE, Relaxed, false);
320 case vmIntrinsics::_getShort: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, false);
321 case vmIntrinsics::_getChar: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, false);
322 case vmIntrinsics::_getInt: return inline_unsafe_access(!is_store, T_INT, Relaxed, false);
323 case vmIntrinsics::_getLong: return inline_unsafe_access(!is_store, T_LONG, Relaxed, false);
324 case vmIntrinsics::_getFloat: return inline_unsafe_access(!is_store, T_FLOAT, Relaxed, false);
325 case vmIntrinsics::_getDouble: return inline_unsafe_access(!is_store, T_DOUBLE, Relaxed, false);
326
327 case vmIntrinsics::_putReference: return inline_unsafe_access( is_store, T_OBJECT, Relaxed, false);
328 case vmIntrinsics::_putBoolean: return inline_unsafe_access( is_store, T_BOOLEAN, Relaxed, false);
329 case vmIntrinsics::_putByte: return inline_unsafe_access( is_store, T_BYTE, Relaxed, false);
330 case vmIntrinsics::_putShort: return inline_unsafe_access( is_store, T_SHORT, Relaxed, false);
331 case vmIntrinsics::_putChar: return inline_unsafe_access( is_store, T_CHAR, Relaxed, false);
332 case vmIntrinsics::_putInt: return inline_unsafe_access( is_store, T_INT, Relaxed, false);
333 case vmIntrinsics::_putLong: return inline_unsafe_access( is_store, T_LONG, Relaxed, false);
334 case vmIntrinsics::_putFloat: return inline_unsafe_access( is_store, T_FLOAT, Relaxed, false);
335 case vmIntrinsics::_putDouble: return inline_unsafe_access( is_store, T_DOUBLE, Relaxed, false);
336
337 case vmIntrinsics::_getReferenceVolatile: return inline_unsafe_access(!is_store, T_OBJECT, Volatile, false);
338 case vmIntrinsics::_getBooleanVolatile: return inline_unsafe_access(!is_store, T_BOOLEAN, Volatile, false);
339 case vmIntrinsics::_getByteVolatile: return inline_unsafe_access(!is_store, T_BYTE, Volatile, false);
340 case vmIntrinsics::_getShortVolatile: return inline_unsafe_access(!is_store, T_SHORT, Volatile, false);
341 case vmIntrinsics::_getCharVolatile: return inline_unsafe_access(!is_store, T_CHAR, Volatile, false);
342 case vmIntrinsics::_getIntVolatile: return inline_unsafe_access(!is_store, T_INT, Volatile, false);
343 case vmIntrinsics::_getLongVolatile: return inline_unsafe_access(!is_store, T_LONG, Volatile, false);
344 case vmIntrinsics::_getFloatVolatile: return inline_unsafe_access(!is_store, T_FLOAT, Volatile, false);
345 case vmIntrinsics::_getDoubleVolatile: return inline_unsafe_access(!is_store, T_DOUBLE, Volatile, false);
346
347 case vmIntrinsics::_putReferenceVolatile: return inline_unsafe_access( is_store, T_OBJECT, Volatile, false);
348 case vmIntrinsics::_putBooleanVolatile: return inline_unsafe_access( is_store, T_BOOLEAN, Volatile, false);
349 case vmIntrinsics::_putByteVolatile: return inline_unsafe_access( is_store, T_BYTE, Volatile, false);
350 case vmIntrinsics::_putShortVolatile: return inline_unsafe_access( is_store, T_SHORT, Volatile, false);
351 case vmIntrinsics::_putCharVolatile: return inline_unsafe_access( is_store, T_CHAR, Volatile, false);
352 case vmIntrinsics::_putIntVolatile: return inline_unsafe_access( is_store, T_INT, Volatile, false);
353 case vmIntrinsics::_putLongVolatile: return inline_unsafe_access( is_store, T_LONG, Volatile, false);
354 case vmIntrinsics::_putFloatVolatile: return inline_unsafe_access( is_store, T_FLOAT, Volatile, false);
355 case vmIntrinsics::_putDoubleVolatile: return inline_unsafe_access( is_store, T_DOUBLE, Volatile, false);
356
357 case vmIntrinsics::_getShortUnaligned: return inline_unsafe_access(!is_store, T_SHORT, Relaxed, true);
358 case vmIntrinsics::_getCharUnaligned: return inline_unsafe_access(!is_store, T_CHAR, Relaxed, true);
359 case vmIntrinsics::_getIntUnaligned: return inline_unsafe_access(!is_store, T_INT, Relaxed, true);
360 case vmIntrinsics::_getLongUnaligned: return inline_unsafe_access(!is_store, T_LONG, Relaxed, true);
361
362 case vmIntrinsics::_putShortUnaligned: return inline_unsafe_access( is_store, T_SHORT, Relaxed, true);
363 case vmIntrinsics::_putCharUnaligned: return inline_unsafe_access( is_store, T_CHAR, Relaxed, true);
364 case vmIntrinsics::_putIntUnaligned: return inline_unsafe_access( is_store, T_INT, Relaxed, true);
365 case vmIntrinsics::_putLongUnaligned: return inline_unsafe_access( is_store, T_LONG, Relaxed, true);
366
367 case vmIntrinsics::_getReferenceAcquire: return inline_unsafe_access(!is_store, T_OBJECT, Acquire, false);
368 case vmIntrinsics::_getBooleanAcquire: return inline_unsafe_access(!is_store, T_BOOLEAN, Acquire, false);
369 case vmIntrinsics::_getByteAcquire: return inline_unsafe_access(!is_store, T_BYTE, Acquire, false);
370 case vmIntrinsics::_getShortAcquire: return inline_unsafe_access(!is_store, T_SHORT, Acquire, false);
371 case vmIntrinsics::_getCharAcquire: return inline_unsafe_access(!is_store, T_CHAR, Acquire, false);
372 case vmIntrinsics::_getIntAcquire: return inline_unsafe_access(!is_store, T_INT, Acquire, false);
373 case vmIntrinsics::_getLongAcquire: return inline_unsafe_access(!is_store, T_LONG, Acquire, false);
374 case vmIntrinsics::_getFloatAcquire: return inline_unsafe_access(!is_store, T_FLOAT, Acquire, false);
375 case vmIntrinsics::_getDoubleAcquire: return inline_unsafe_access(!is_store, T_DOUBLE, Acquire, false);
376
377 case vmIntrinsics::_putReferenceRelease: return inline_unsafe_access( is_store, T_OBJECT, Release, false);
378 case vmIntrinsics::_putBooleanRelease: return inline_unsafe_access( is_store, T_BOOLEAN, Release, false);
379 case vmIntrinsics::_putByteRelease: return inline_unsafe_access( is_store, T_BYTE, Release, false);
380 case vmIntrinsics::_putShortRelease: return inline_unsafe_access( is_store, T_SHORT, Release, false);
381 case vmIntrinsics::_putCharRelease: return inline_unsafe_access( is_store, T_CHAR, Release, false);
382 case vmIntrinsics::_putIntRelease: return inline_unsafe_access( is_store, T_INT, Release, false);
383 case vmIntrinsics::_putLongRelease: return inline_unsafe_access( is_store, T_LONG, Release, false);
384 case vmIntrinsics::_putFloatRelease: return inline_unsafe_access( is_store, T_FLOAT, Release, false);
385 case vmIntrinsics::_putDoubleRelease: return inline_unsafe_access( is_store, T_DOUBLE, Release, false);
386
387 case vmIntrinsics::_getReferenceOpaque: return inline_unsafe_access(!is_store, T_OBJECT, Opaque, false);
388 case vmIntrinsics::_getBooleanOpaque: return inline_unsafe_access(!is_store, T_BOOLEAN, Opaque, false);
389 case vmIntrinsics::_getByteOpaque: return inline_unsafe_access(!is_store, T_BYTE, Opaque, false);
390 case vmIntrinsics::_getShortOpaque: return inline_unsafe_access(!is_store, T_SHORT, Opaque, false);
391 case vmIntrinsics::_getCharOpaque: return inline_unsafe_access(!is_store, T_CHAR, Opaque, false);
392 case vmIntrinsics::_getIntOpaque: return inline_unsafe_access(!is_store, T_INT, Opaque, false);
393 case vmIntrinsics::_getLongOpaque: return inline_unsafe_access(!is_store, T_LONG, Opaque, false);
394 case vmIntrinsics::_getFloatOpaque: return inline_unsafe_access(!is_store, T_FLOAT, Opaque, false);
395 case vmIntrinsics::_getDoubleOpaque: return inline_unsafe_access(!is_store, T_DOUBLE, Opaque, false);
396
397 case vmIntrinsics::_putReferenceOpaque: return inline_unsafe_access( is_store, T_OBJECT, Opaque, false);
398 case vmIntrinsics::_putBooleanOpaque: return inline_unsafe_access( is_store, T_BOOLEAN, Opaque, false);
399 case vmIntrinsics::_putByteOpaque: return inline_unsafe_access( is_store, T_BYTE, Opaque, false);
400 case vmIntrinsics::_putShortOpaque: return inline_unsafe_access( is_store, T_SHORT, Opaque, false);
401 case vmIntrinsics::_putCharOpaque: return inline_unsafe_access( is_store, T_CHAR, Opaque, false);
402 case vmIntrinsics::_putIntOpaque: return inline_unsafe_access( is_store, T_INT, Opaque, false);
403 case vmIntrinsics::_putLongOpaque: return inline_unsafe_access( is_store, T_LONG, Opaque, false);
404 case vmIntrinsics::_putFloatOpaque: return inline_unsafe_access( is_store, T_FLOAT, Opaque, false);
405 case vmIntrinsics::_putDoubleOpaque: return inline_unsafe_access( is_store, T_DOUBLE, Opaque, false);
406
407 case vmIntrinsics::_compareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap, Volatile);
408 case vmIntrinsics::_compareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap, Volatile);
409 case vmIntrinsics::_compareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap, Volatile);
410 case vmIntrinsics::_compareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap, Volatile);
411 case vmIntrinsics::_compareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap, Volatile);
412
413 case vmIntrinsics::_weakCompareAndSetReferencePlain: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Relaxed);
414 case vmIntrinsics::_weakCompareAndSetReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Acquire);
415 case vmIntrinsics::_weakCompareAndSetReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Release);
416 case vmIntrinsics::_weakCompareAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_swap_weak, Volatile);
417 case vmIntrinsics::_weakCompareAndSetBytePlain: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Relaxed);
418 case vmIntrinsics::_weakCompareAndSetByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Acquire);
419 case vmIntrinsics::_weakCompareAndSetByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Release);
420 case vmIntrinsics::_weakCompareAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_swap_weak, Volatile);
421 case vmIntrinsics::_weakCompareAndSetShortPlain: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Relaxed);
422 case vmIntrinsics::_weakCompareAndSetShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Acquire);
423 case vmIntrinsics::_weakCompareAndSetShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Release);
424 case vmIntrinsics::_weakCompareAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_swap_weak, Volatile);
425 case vmIntrinsics::_weakCompareAndSetIntPlain: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Relaxed);
426 case vmIntrinsics::_weakCompareAndSetIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Acquire);
427 case vmIntrinsics::_weakCompareAndSetIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Release);
428 case vmIntrinsics::_weakCompareAndSetInt: return inline_unsafe_load_store(T_INT, LS_cmp_swap_weak, Volatile);
429 case vmIntrinsics::_weakCompareAndSetLongPlain: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Relaxed);
430 case vmIntrinsics::_weakCompareAndSetLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Acquire);
431 case vmIntrinsics::_weakCompareAndSetLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Release);
432 case vmIntrinsics::_weakCompareAndSetLong: return inline_unsafe_load_store(T_LONG, LS_cmp_swap_weak, Volatile);
433
434 case vmIntrinsics::_compareAndExchangeReference: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Volatile);
435 case vmIntrinsics::_compareAndExchangeReferenceAcquire: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Acquire);
436 case vmIntrinsics::_compareAndExchangeReferenceRelease: return inline_unsafe_load_store(T_OBJECT, LS_cmp_exchange, Release);
437 case vmIntrinsics::_compareAndExchangeByte: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Volatile);
438 case vmIntrinsics::_compareAndExchangeByteAcquire: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Acquire);
439 case vmIntrinsics::_compareAndExchangeByteRelease: return inline_unsafe_load_store(T_BYTE, LS_cmp_exchange, Release);
440 case vmIntrinsics::_compareAndExchangeShort: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Volatile);
441 case vmIntrinsics::_compareAndExchangeShortAcquire: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Acquire);
442 case vmIntrinsics::_compareAndExchangeShortRelease: return inline_unsafe_load_store(T_SHORT, LS_cmp_exchange, Release);
443 case vmIntrinsics::_compareAndExchangeInt: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Volatile);
444 case vmIntrinsics::_compareAndExchangeIntAcquire: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Acquire);
445 case vmIntrinsics::_compareAndExchangeIntRelease: return inline_unsafe_load_store(T_INT, LS_cmp_exchange, Release);
446 case vmIntrinsics::_compareAndExchangeLong: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Volatile);
447 case vmIntrinsics::_compareAndExchangeLongAcquire: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Acquire);
448 case vmIntrinsics::_compareAndExchangeLongRelease: return inline_unsafe_load_store(T_LONG, LS_cmp_exchange, Release);
449
450 case vmIntrinsics::_getAndAddByte: return inline_unsafe_load_store(T_BYTE, LS_get_add, Volatile);
451 case vmIntrinsics::_getAndAddShort: return inline_unsafe_load_store(T_SHORT, LS_get_add, Volatile);
452 case vmIntrinsics::_getAndAddInt: return inline_unsafe_load_store(T_INT, LS_get_add, Volatile);
453 case vmIntrinsics::_getAndAddLong: return inline_unsafe_load_store(T_LONG, LS_get_add, Volatile);
454
455 case vmIntrinsics::_getAndSetByte: return inline_unsafe_load_store(T_BYTE, LS_get_set, Volatile);
456 case vmIntrinsics::_getAndSetShort: return inline_unsafe_load_store(T_SHORT, LS_get_set, Volatile);
457 case vmIntrinsics::_getAndSetInt: return inline_unsafe_load_store(T_INT, LS_get_set, Volatile);
458 case vmIntrinsics::_getAndSetLong: return inline_unsafe_load_store(T_LONG, LS_get_set, Volatile);
459 case vmIntrinsics::_getAndSetReference: return inline_unsafe_load_store(T_OBJECT, LS_get_set, Volatile);
460
461 case vmIntrinsics::_loadFence:
462 case vmIntrinsics::_storeFence:
463 case vmIntrinsics::_fullFence: return inline_unsafe_fence(intrinsic_id());
464
465 case vmIntrinsics::_onSpinWait: return inline_onspinwait();
466
467 case vmIntrinsics::_currentThread: return inline_native_currentThread();
468
469 #ifdef JFR_HAVE_INTRINSICS
470 case vmIntrinsics::_counterTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, JFR_TIME_FUNCTION), "counterTime");
471 case vmIntrinsics::_getClassId: return inline_native_classID();
472 case vmIntrinsics::_getEventWriter: return inline_native_getEventWriter();
473 #endif
474 case vmIntrinsics::_currentTimeMillis: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeMillis), "currentTimeMillis");
475 case vmIntrinsics::_nanoTime: return inline_native_time_funcs(CAST_FROM_FN_PTR(address, os::javaTimeNanos), "nanoTime");
476 case vmIntrinsics::_writeback0: return inline_unsafe_writeback0();
477 case vmIntrinsics::_writebackPreSync0: return inline_unsafe_writebackSync0(true);
478 case vmIntrinsics::_writebackPostSync0: return inline_unsafe_writebackSync0(false);
479 case vmIntrinsics::_allocateInstance: return inline_unsafe_allocate();
480 case vmIntrinsics::_copyMemory: return inline_unsafe_copyMemory();
481 case vmIntrinsics::_getLength: return inline_native_getLength();
482 case vmIntrinsics::_copyOf: return inline_array_copyOf(false);
483 case vmIntrinsics::_copyOfRange: return inline_array_copyOf(true);
484 case vmIntrinsics::_equalsB: return inline_array_equals(StrIntrinsicNode::LL);
485 case vmIntrinsics::_equalsC: return inline_array_equals(StrIntrinsicNode::UU);
486 case vmIntrinsics::_Preconditions_checkIndex: return inline_preconditions_checkIndex(T_INT);
487 case vmIntrinsics::_Preconditions_checkLongIndex: return inline_preconditions_checkIndex(T_LONG);
488 case vmIntrinsics::_clone: return inline_native_clone(intrinsic()->is_virtual());
489
490 case vmIntrinsics::_allocateUninitializedArray: return inline_unsafe_newArray(true);
491 case vmIntrinsics::_newArray: return inline_unsafe_newArray(false);
492
493 case vmIntrinsics::_isAssignableFrom: return inline_native_subtype_check();
494
495 case vmIntrinsics::_isInstance:
496 case vmIntrinsics::_getModifiers:
497 case vmIntrinsics::_isInterface:
498 case vmIntrinsics::_isArray:
499 case vmIntrinsics::_isPrimitive:
500 case vmIntrinsics::_isHidden:
501 case vmIntrinsics::_getSuperclass:
502 case vmIntrinsics::_getClassAccessFlags: return inline_native_Class_query(intrinsic_id());
503
504 case vmIntrinsics::_floatToRawIntBits:
505 case vmIntrinsics::_floatToIntBits:
506 case vmIntrinsics::_intBitsToFloat:
507 case vmIntrinsics::_doubleToRawLongBits:
508 case vmIntrinsics::_doubleToLongBits:
509 case vmIntrinsics::_longBitsToDouble: return inline_fp_conversions(intrinsic_id());
510
511 case vmIntrinsics::_numberOfLeadingZeros_i:
512 case vmIntrinsics::_numberOfLeadingZeros_l:
513 case vmIntrinsics::_numberOfTrailingZeros_i:
514 case vmIntrinsics::_numberOfTrailingZeros_l:
515 case vmIntrinsics::_bitCount_i:
516 case vmIntrinsics::_bitCount_l:
517 case vmIntrinsics::_reverseBytes_i:
518 case vmIntrinsics::_reverseBytes_l:
519 case vmIntrinsics::_reverseBytes_s:
520 case vmIntrinsics::_reverseBytes_c: return inline_number_methods(intrinsic_id());
521
522 case vmIntrinsics::_getCallerClass: return inline_native_Reflection_getCallerClass();
523
524 case vmIntrinsics::_Reference_get: return inline_reference_get();
525 case vmIntrinsics::_Reference_refersTo0: return inline_reference_refersTo0(false);
526 case vmIntrinsics::_PhantomReference_refersTo0: return inline_reference_refersTo0(true);
527
528 case vmIntrinsics::_Class_cast: return inline_Class_cast();
529
530 case vmIntrinsics::_aescrypt_encryptBlock:
531 case vmIntrinsics::_aescrypt_decryptBlock: return inline_aescrypt_Block(intrinsic_id());
532
533 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
534 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
535 return inline_cipherBlockChaining_AESCrypt(intrinsic_id());
536
537 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
538 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
539 return inline_electronicCodeBook_AESCrypt(intrinsic_id());
540
541 case vmIntrinsics::_counterMode_AESCrypt:
542 return inline_counterMode_AESCrypt(intrinsic_id());
543
544 case vmIntrinsics::_md5_implCompress:
545 case vmIntrinsics::_sha_implCompress:
546 case vmIntrinsics::_sha2_implCompress:
547 case vmIntrinsics::_sha5_implCompress:
548 case vmIntrinsics::_sha3_implCompress:
549 return inline_digestBase_implCompress(intrinsic_id());
550
551 case vmIntrinsics::_digestBase_implCompressMB:
552 return inline_digestBase_implCompressMB(predicate);
553
554 case vmIntrinsics::_multiplyToLen:
555 return inline_multiplyToLen();
556
557 case vmIntrinsics::_squareToLen:
558 return inline_squareToLen();
559
560 case vmIntrinsics::_mulAdd:
561 return inline_mulAdd();
562
563 case vmIntrinsics::_montgomeryMultiply:
564 return inline_montgomeryMultiply();
565 case vmIntrinsics::_montgomerySquare:
566 return inline_montgomerySquare();
567
568 case vmIntrinsics::_bigIntegerRightShiftWorker:
569 return inline_bigIntegerShift(true);
570 case vmIntrinsics::_bigIntegerLeftShiftWorker:
571 return inline_bigIntegerShift(false);
572
573 case vmIntrinsics::_vectorizedMismatch:
574 return inline_vectorizedMismatch();
575
576 case vmIntrinsics::_ghash_processBlocks:
577 return inline_ghash_processBlocks();
578 case vmIntrinsics::_base64_encodeBlock:
579 return inline_base64_encodeBlock();
580 case vmIntrinsics::_base64_decodeBlock:
581 return inline_base64_decodeBlock();
582
583 case vmIntrinsics::_encodeISOArray:
584 case vmIntrinsics::_encodeByteISOArray:
585 return inline_encodeISOArray();
586
587 case vmIntrinsics::_updateCRC32:
588 return inline_updateCRC32();
589 case vmIntrinsics::_updateBytesCRC32:
590 return inline_updateBytesCRC32();
591 case vmIntrinsics::_updateByteBufferCRC32:
592 return inline_updateByteBufferCRC32();
593
594 case vmIntrinsics::_updateBytesCRC32C:
595 return inline_updateBytesCRC32C();
596 case vmIntrinsics::_updateDirectByteBufferCRC32C:
597 return inline_updateDirectByteBufferCRC32C();
598
599 case vmIntrinsics::_updateBytesAdler32:
600 return inline_updateBytesAdler32();
601 case vmIntrinsics::_updateByteBufferAdler32:
602 return inline_updateByteBufferAdler32();
603
604 case vmIntrinsics::_profileBoolean:
605 return inline_profileBoolean();
606 case vmIntrinsics::_isCompileConstant:
607 return inline_isCompileConstant();
608
609 case vmIntrinsics::_hasNegatives:
610 return inline_hasNegatives();
611
612 case vmIntrinsics::_fmaD:
613 case vmIntrinsics::_fmaF:
614 return inline_fma(intrinsic_id());
615
616 case vmIntrinsics::_isDigit:
617 case vmIntrinsics::_isLowerCase:
618 case vmIntrinsics::_isUpperCase:
619 case vmIntrinsics::_isWhitespace:
620 return inline_character_compare(intrinsic_id());
621
622 case vmIntrinsics::_maxF:
623 case vmIntrinsics::_minF:
624 case vmIntrinsics::_maxD:
625 case vmIntrinsics::_minD:
626 return inline_fp_min_max(intrinsic_id());
627
628 case vmIntrinsics::_VectorUnaryOp:
629 return inline_vector_nary_operation(1);
630 case vmIntrinsics::_VectorBinaryOp:
631 return inline_vector_nary_operation(2);
632 case vmIntrinsics::_VectorTernaryOp:
633 return inline_vector_nary_operation(3);
634 case vmIntrinsics::_VectorBroadcastCoerced:
635 return inline_vector_broadcast_coerced();
636 case vmIntrinsics::_VectorShuffleIota:
637 return inline_vector_shuffle_iota();
638 case vmIntrinsics::_VectorShuffleToVector:
639 return inline_vector_shuffle_to_vector();
640 case vmIntrinsics::_VectorLoadOp:
641 return inline_vector_mem_operation(/*is_store=*/false);
642 case vmIntrinsics::_VectorStoreOp:
643 return inline_vector_mem_operation(/*is_store=*/true);
644 case vmIntrinsics::_VectorGatherOp:
645 return inline_vector_gather_scatter(/*is_scatter*/ false);
646 case vmIntrinsics::_VectorScatterOp:
647 return inline_vector_gather_scatter(/*is_scatter*/ true);
648 case vmIntrinsics::_VectorReductionCoerced:
649 return inline_vector_reduction();
650 case vmIntrinsics::_VectorTest:
651 return inline_vector_test();
652 case vmIntrinsics::_VectorBlend:
653 return inline_vector_blend();
654 case vmIntrinsics::_VectorRearrange:
655 return inline_vector_rearrange();
656 case vmIntrinsics::_VectorCompare:
657 return inline_vector_compare();
658 case vmIntrinsics::_VectorBroadcastInt:
659 return inline_vector_broadcast_int();
660 case vmIntrinsics::_VectorConvert:
661 return inline_vector_convert();
662 case vmIntrinsics::_VectorInsert:
663 return inline_vector_insert();
664 case vmIntrinsics::_VectorExtract:
665 return inline_vector_extract();
666
667 case vmIntrinsics::_getObjectSize:
668 return inline_getObjectSize();
669
670 default:
671 // If you get here, it may be that someone has added a new intrinsic
672 // to the list in vmSymbols.hpp without implementing it here.
673 #ifndef PRODUCT
674 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
675 tty->print_cr("*** Warning: Unimplemented intrinsic %s(%d)",
676 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
677 }
678 #endif
679 return false;
680 }
681 }
682
try_to_predicate(int predicate)683 Node* LibraryCallKit::try_to_predicate(int predicate) {
684 if (!jvms()->has_method()) {
685 // Root JVMState has a null method.
686 assert(map()->memory()->Opcode() == Op_Parm, "");
687 // Insert the memory aliasing node
688 set_all_memory(reset_memory());
689 }
690 assert(merged_memory(), "");
691
692 switch (intrinsic_id()) {
693 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
694 return inline_cipherBlockChaining_AESCrypt_predicate(false);
695 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
696 return inline_cipherBlockChaining_AESCrypt_predicate(true);
697 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
698 return inline_electronicCodeBook_AESCrypt_predicate(false);
699 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
700 return inline_electronicCodeBook_AESCrypt_predicate(true);
701 case vmIntrinsics::_counterMode_AESCrypt:
702 return inline_counterMode_AESCrypt_predicate();
703 case vmIntrinsics::_digestBase_implCompressMB:
704 return inline_digestBase_implCompressMB_predicate(predicate);
705
706 default:
707 // If you get here, it may be that someone has added a new intrinsic
708 // to the list in vmSymbols.hpp without implementing it here.
709 #ifndef PRODUCT
710 if ((PrintMiscellaneous && (Verbose || WizardMode)) || PrintOpto) {
711 tty->print_cr("*** Warning: Unimplemented predicate for intrinsic %s(%d)",
712 vmIntrinsics::name_at(intrinsic_id()), vmIntrinsics::as_int(intrinsic_id()));
713 }
714 #endif
715 Node* slow_ctl = control();
716 set_control(top()); // No fast path instrinsic
717 return slow_ctl;
718 }
719 }
720
721 //------------------------------set_result-------------------------------
722 // Helper function for finishing intrinsics.
set_result(RegionNode * region,PhiNode * value)723 void LibraryCallKit::set_result(RegionNode* region, PhiNode* value) {
724 record_for_igvn(region);
725 set_control(_gvn.transform(region));
726 set_result( _gvn.transform(value));
727 assert(value->type()->basic_type() == result()->bottom_type()->basic_type(), "sanity");
728 }
729
730 //------------------------------generate_guard---------------------------
731 // Helper function for generating guarded fast-slow graph structures.
732 // The given 'test', if true, guards a slow path. If the test fails
733 // then a fast path can be taken. (We generally hope it fails.)
734 // In all cases, GraphKit::control() is updated to the fast path.
735 // The returned value represents the control for the slow path.
736 // The return value is never 'top'; it is either a valid control
737 // or NULL if it is obvious that the slow path can never be taken.
738 // Also, if region and the slow control are not NULL, the slow edge
739 // is appended to the region.
generate_guard(Node * test,RegionNode * region,float true_prob)740 Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_prob) {
741 if (stopped()) {
742 // Already short circuited.
743 return NULL;
744 }
745
746 // Build an if node and its projections.
747 // If test is true we take the slow path, which we assume is uncommon.
748 if (_gvn.type(test) == TypeInt::ZERO) {
749 // The slow branch is never taken. No need to build this guard.
750 return NULL;
751 }
752
753 IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN);
754
755 Node* if_slow = _gvn.transform(new IfTrueNode(iff));
756 if (if_slow == top()) {
757 // The slow branch is never taken. No need to build this guard.
758 return NULL;
759 }
760
761 if (region != NULL)
762 region->add_req(if_slow);
763
764 Node* if_fast = _gvn.transform(new IfFalseNode(iff));
765 set_control(if_fast);
766
767 return if_slow;
768 }
769
generate_slow_guard(Node * test,RegionNode * region)770 inline Node* LibraryCallKit::generate_slow_guard(Node* test, RegionNode* region) {
771 return generate_guard(test, region, PROB_UNLIKELY_MAG(3));
772 }
generate_fair_guard(Node * test,RegionNode * region)773 inline Node* LibraryCallKit::generate_fair_guard(Node* test, RegionNode* region) {
774 return generate_guard(test, region, PROB_FAIR);
775 }
776
generate_negative_guard(Node * index,RegionNode * region,Node ** pos_index)777 inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* region,
778 Node* *pos_index) {
779 if (stopped())
780 return NULL; // already stopped
781 if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint]
782 return NULL; // index is already adequately typed
783 Node* cmp_lt = _gvn.transform(new CmpINode(index, intcon(0)));
784 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
785 Node* is_neg = generate_guard(bol_lt, region, PROB_MIN);
786 if (is_neg != NULL && pos_index != NULL) {
787 // Emulate effect of Parse::adjust_map_after_if.
788 Node* ccast = new CastIINode(index, TypeInt::POS);
789 ccast->set_req(0, control());
790 (*pos_index) = _gvn.transform(ccast);
791 }
792 return is_neg;
793 }
794
795 // Make sure that 'position' is a valid limit index, in [0..length].
796 // There are two equivalent plans for checking this:
797 // A. (offset + copyLength) unsigned<= arrayLength
798 // B. offset <= (arrayLength - copyLength)
799 // We require that all of the values above, except for the sum and
800 // difference, are already known to be non-negative.
801 // Plan A is robust in the face of overflow, if offset and copyLength
802 // are both hugely positive.
803 //
804 // Plan B is less direct and intuitive, but it does not overflow at
805 // all, since the difference of two non-negatives is always
806 // representable. Whenever Java methods must perform the equivalent
807 // check they generally use Plan B instead of Plan A.
808 // For the moment we use Plan A.
generate_limit_guard(Node * offset,Node * subseq_length,Node * array_length,RegionNode * region)809 inline Node* LibraryCallKit::generate_limit_guard(Node* offset,
810 Node* subseq_length,
811 Node* array_length,
812 RegionNode* region) {
813 if (stopped())
814 return NULL; // already stopped
815 bool zero_offset = _gvn.type(offset) == TypeInt::ZERO;
816 if (zero_offset && subseq_length->eqv_uncast(array_length))
817 return NULL; // common case of whole-array copy
818 Node* last = subseq_length;
819 if (!zero_offset) // last += offset
820 last = _gvn.transform(new AddINode(last, offset));
821 Node* cmp_lt = _gvn.transform(new CmpUNode(array_length, last));
822 Node* bol_lt = _gvn.transform(new BoolNode(cmp_lt, BoolTest::lt));
823 Node* is_over = generate_guard(bol_lt, region, PROB_MIN);
824 return is_over;
825 }
826
827 // Emit range checks for the given String.value byte array
generate_string_range_check(Node * array,Node * offset,Node * count,bool char_count)828 void LibraryCallKit::generate_string_range_check(Node* array, Node* offset, Node* count, bool char_count) {
829 if (stopped()) {
830 return; // already stopped
831 }
832 RegionNode* bailout = new RegionNode(1);
833 record_for_igvn(bailout);
834 if (char_count) {
835 // Convert char count to byte count
836 count = _gvn.transform(new LShiftINode(count, intcon(1)));
837 }
838
839 // Offset and count must not be negative
840 generate_negative_guard(offset, bailout);
841 generate_negative_guard(count, bailout);
842 // Offset + count must not exceed length of array
843 generate_limit_guard(offset, count, load_array_length(array), bailout);
844
845 if (bailout->req() > 1) {
846 PreserveJVMState pjvms(this);
847 set_control(_gvn.transform(bailout));
848 uncommon_trap(Deoptimization::Reason_intrinsic,
849 Deoptimization::Action_maybe_recompile);
850 }
851 }
852
853 //--------------------------generate_current_thread--------------------
generate_current_thread(Node * & tls_output)854 Node* LibraryCallKit::generate_current_thread(Node* &tls_output) {
855 ciKlass* thread_klass = env()->Thread_klass();
856 const Type* thread_type = TypeOopPtr::make_from_klass(thread_klass)->cast_to_ptr_type(TypePtr::NotNull);
857 Node* thread = _gvn.transform(new ThreadLocalNode());
858 Node* p = basic_plus_adr(top()/*!oop*/, thread, in_bytes(JavaThread::threadObj_offset()));
859 tls_output = thread;
860 Node* thread_obj_handle = LoadNode::make(_gvn, NULL, immutable_memory(), p, p->bottom_type()->is_ptr(), TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
861 thread_obj_handle = _gvn.transform(thread_obj_handle);
862 return access_load(thread_obj_handle, thread_type, T_OBJECT, IN_NATIVE | C2_IMMUTABLE_MEMORY);
863 }
864
865
866 //------------------------------make_string_method_node------------------------
867 // Helper method for String intrinsic functions. This version is called with
868 // str1 and str2 pointing to byte[] nodes containing Latin1 or UTF16 encoded
869 // characters (depending on 'is_byte'). cnt1 and cnt2 are pointing to Int nodes
870 // containing the lengths of str1 and str2.
make_string_method_node(int opcode,Node * str1_start,Node * cnt1,Node * str2_start,Node * cnt2,StrIntrinsicNode::ArgEnc ae)871 Node* LibraryCallKit::make_string_method_node(int opcode, Node* str1_start, Node* cnt1, Node* str2_start, Node* cnt2, StrIntrinsicNode::ArgEnc ae) {
872 Node* result = NULL;
873 switch (opcode) {
874 case Op_StrIndexOf:
875 result = new StrIndexOfNode(control(), memory(TypeAryPtr::BYTES),
876 str1_start, cnt1, str2_start, cnt2, ae);
877 break;
878 case Op_StrComp:
879 result = new StrCompNode(control(), memory(TypeAryPtr::BYTES),
880 str1_start, cnt1, str2_start, cnt2, ae);
881 break;
882 case Op_StrEquals:
883 // We already know that cnt1 == cnt2 here (checked in 'inline_string_equals').
884 // Use the constant length if there is one because optimized match rule may exist.
885 result = new StrEqualsNode(control(), memory(TypeAryPtr::BYTES),
886 str1_start, str2_start, cnt2->is_Con() ? cnt2 : cnt1, ae);
887 break;
888 default:
889 ShouldNotReachHere();
890 return NULL;
891 }
892
893 // All these intrinsics have checks.
894 C->set_has_split_ifs(true); // Has chance for split-if optimization
895 clear_upper_avx();
896
897 return _gvn.transform(result);
898 }
899
900 //------------------------------inline_string_compareTo------------------------
inline_string_compareTo(StrIntrinsicNode::ArgEnc ae)901 bool LibraryCallKit::inline_string_compareTo(StrIntrinsicNode::ArgEnc ae) {
902 Node* arg1 = argument(0);
903 Node* arg2 = argument(1);
904
905 arg1 = must_be_not_null(arg1, true);
906 arg2 = must_be_not_null(arg2, true);
907
908 // Get start addr and length of first argument
909 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
910 Node* arg1_cnt = load_array_length(arg1);
911
912 // Get start addr and length of second argument
913 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
914 Node* arg2_cnt = load_array_length(arg2);
915
916 Node* result = make_string_method_node(Op_StrComp, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
917 set_result(result);
918 return true;
919 }
920
921 //------------------------------inline_string_equals------------------------
inline_string_equals(StrIntrinsicNode::ArgEnc ae)922 bool LibraryCallKit::inline_string_equals(StrIntrinsicNode::ArgEnc ae) {
923 Node* arg1 = argument(0);
924 Node* arg2 = argument(1);
925
926 // paths (plus control) merge
927 RegionNode* region = new RegionNode(3);
928 Node* phi = new PhiNode(region, TypeInt::BOOL);
929
930 if (!stopped()) {
931
932 arg1 = must_be_not_null(arg1, true);
933 arg2 = must_be_not_null(arg2, true);
934
935 // Get start addr and length of first argument
936 Node* arg1_start = array_element_address(arg1, intcon(0), T_BYTE);
937 Node* arg1_cnt = load_array_length(arg1);
938
939 // Get start addr and length of second argument
940 Node* arg2_start = array_element_address(arg2, intcon(0), T_BYTE);
941 Node* arg2_cnt = load_array_length(arg2);
942
943 // Check for arg1_cnt != arg2_cnt
944 Node* cmp = _gvn.transform(new CmpINode(arg1_cnt, arg2_cnt));
945 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
946 Node* if_ne = generate_slow_guard(bol, NULL);
947 if (if_ne != NULL) {
948 phi->init_req(2, intcon(0));
949 region->init_req(2, if_ne);
950 }
951
952 // Check for count == 0 is done by assembler code for StrEquals.
953
954 if (!stopped()) {
955 Node* equals = make_string_method_node(Op_StrEquals, arg1_start, arg1_cnt, arg2_start, arg2_cnt, ae);
956 phi->init_req(1, equals);
957 region->init_req(1, control());
958 }
959 }
960
961 // post merge
962 set_control(_gvn.transform(region));
963 record_for_igvn(region);
964
965 set_result(_gvn.transform(phi));
966 return true;
967 }
968
969 //------------------------------inline_array_equals----------------------------
inline_array_equals(StrIntrinsicNode::ArgEnc ae)970 bool LibraryCallKit::inline_array_equals(StrIntrinsicNode::ArgEnc ae) {
971 assert(ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::LL, "unsupported array types");
972 Node* arg1 = argument(0);
973 Node* arg2 = argument(1);
974
975 const TypeAryPtr* mtype = (ae == StrIntrinsicNode::UU) ? TypeAryPtr::CHARS : TypeAryPtr::BYTES;
976 set_result(_gvn.transform(new AryEqNode(control(), memory(mtype), arg1, arg2, ae)));
977 clear_upper_avx();
978
979 return true;
980 }
981
982 //------------------------------inline_hasNegatives------------------------------
inline_hasNegatives()983 bool LibraryCallKit::inline_hasNegatives() {
984 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
985 return false;
986 }
987
988 assert(callee()->signature()->size() == 3, "hasNegatives has 3 parameters");
989 // no receiver since it is static method
990 Node* ba = argument(0);
991 Node* offset = argument(1);
992 Node* len = argument(2);
993
994 ba = must_be_not_null(ba, true);
995
996 // Range checks
997 generate_string_range_check(ba, offset, len, false);
998 if (stopped()) {
999 return true;
1000 }
1001 Node* ba_start = array_element_address(ba, offset, T_BYTE);
1002 Node* result = new HasNegativesNode(control(), memory(TypeAryPtr::BYTES), ba_start, len);
1003 set_result(_gvn.transform(result));
1004 return true;
1005 }
1006
inline_preconditions_checkIndex(BasicType bt)1007 bool LibraryCallKit::inline_preconditions_checkIndex(BasicType bt) {
1008 Node* index = argument(0);
1009 Node* length = bt == T_INT ? argument(1) : argument(2);
1010 if (too_many_traps(Deoptimization::Reason_intrinsic) || too_many_traps(Deoptimization::Reason_range_check)) {
1011 return false;
1012 }
1013
1014 // check that length is positive
1015 Node* len_pos_cmp = _gvn.transform(CmpNode::make(length, integercon(0, bt), bt));
1016 Node* len_pos_bol = _gvn.transform(new BoolNode(len_pos_cmp, BoolTest::ge));
1017
1018 {
1019 BuildCutout unless(this, len_pos_bol, PROB_MAX);
1020 uncommon_trap(Deoptimization::Reason_intrinsic,
1021 Deoptimization::Action_make_not_entrant);
1022 }
1023
1024 // length is now known postive, add a cast node to make this explicit
1025 jlong upper_bound = _gvn.type(length)->is_integer(bt)->hi_as_long();
1026 Node* casted_length = ConstraintCastNode::make(control(), length, TypeInteger::make(0, upper_bound, Type::WidenMax, bt), bt);
1027 casted_length = _gvn.transform(casted_length);
1028 replace_in_map(length, casted_length);
1029 length = casted_length;
1030
1031 if (stopped()) {
1032 return false;
1033 }
1034
1035 // Use an unsigned comparison for the range check itself
1036 Node* rc_cmp = _gvn.transform(CmpNode::make(index, length, bt, true));
1037 BoolTest::mask btest = BoolTest::lt;
1038 Node* rc_bool = _gvn.transform(new BoolNode(rc_cmp, btest));
1039 RangeCheckNode* rc = new RangeCheckNode(control(), rc_bool, PROB_MAX, COUNT_UNKNOWN);
1040 _gvn.set_type(rc, rc->Value(&_gvn));
1041 if (!rc_bool->is_Con()) {
1042 record_for_igvn(rc);
1043 }
1044 set_control(_gvn.transform(new IfTrueNode(rc)));
1045 {
1046 PreserveJVMState pjvms(this);
1047 set_control(_gvn.transform(new IfFalseNode(rc)));
1048 uncommon_trap(Deoptimization::Reason_range_check,
1049 Deoptimization::Action_make_not_entrant);
1050 }
1051
1052 if (stopped()) {
1053 return false;
1054 }
1055
1056 // index is now known to be >= 0 and < length, cast it
1057 Node* result = ConstraintCastNode::make(control(), index, TypeInteger::make(0, upper_bound, Type::WidenMax, bt), bt);
1058 result = _gvn.transform(result);
1059 set_result(result);
1060 replace_in_map(index, result);
1061 clear_upper_avx();
1062 return true;
1063 }
1064
1065 //------------------------------inline_string_indexOf------------------------
inline_string_indexOf(StrIntrinsicNode::ArgEnc ae)1066 bool LibraryCallKit::inline_string_indexOf(StrIntrinsicNode::ArgEnc ae) {
1067 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1068 return false;
1069 }
1070 Node* src = argument(0);
1071 Node* tgt = argument(1);
1072
1073 // Make the merge point
1074 RegionNode* result_rgn = new RegionNode(4);
1075 Node* result_phi = new PhiNode(result_rgn, TypeInt::INT);
1076
1077 src = must_be_not_null(src, true);
1078 tgt = must_be_not_null(tgt, true);
1079
1080 // Get start addr and length of source string
1081 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
1082 Node* src_count = load_array_length(src);
1083
1084 // Get start addr and length of substring
1085 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1086 Node* tgt_count = load_array_length(tgt);
1087
1088 if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
1089 // Divide src size by 2 if String is UTF16 encoded
1090 src_count = _gvn.transform(new RShiftINode(src_count, intcon(1)));
1091 }
1092 if (ae == StrIntrinsicNode::UU) {
1093 // Divide substring size by 2 if String is UTF16 encoded
1094 tgt_count = _gvn.transform(new RShiftINode(tgt_count, intcon(1)));
1095 }
1096
1097 Node* result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count, result_rgn, result_phi, ae);
1098 if (result != NULL) {
1099 result_phi->init_req(3, result);
1100 result_rgn->init_req(3, control());
1101 }
1102 set_control(_gvn.transform(result_rgn));
1103 record_for_igvn(result_rgn);
1104 set_result(_gvn.transform(result_phi));
1105
1106 return true;
1107 }
1108
1109 //-----------------------------inline_string_indexOf-----------------------
inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae)1110 bool LibraryCallKit::inline_string_indexOfI(StrIntrinsicNode::ArgEnc ae) {
1111 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1112 return false;
1113 }
1114 if (!Matcher::match_rule_supported(Op_StrIndexOf)) {
1115 return false;
1116 }
1117 assert(callee()->signature()->size() == 5, "String.indexOf() has 5 arguments");
1118 Node* src = argument(0); // byte[]
1119 Node* src_count = argument(1); // char count
1120 Node* tgt = argument(2); // byte[]
1121 Node* tgt_count = argument(3); // char count
1122 Node* from_index = argument(4); // char index
1123
1124 src = must_be_not_null(src, true);
1125 tgt = must_be_not_null(tgt, true);
1126
1127 // Multiply byte array index by 2 if String is UTF16 encoded
1128 Node* src_offset = (ae == StrIntrinsicNode::LL) ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1129 src_count = _gvn.transform(new SubINode(src_count, from_index));
1130 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1131 Node* tgt_start = array_element_address(tgt, intcon(0), T_BYTE);
1132
1133 // Range checks
1134 generate_string_range_check(src, src_offset, src_count, ae != StrIntrinsicNode::LL);
1135 generate_string_range_check(tgt, intcon(0), tgt_count, ae == StrIntrinsicNode::UU);
1136 if (stopped()) {
1137 return true;
1138 }
1139
1140 RegionNode* region = new RegionNode(5);
1141 Node* phi = new PhiNode(region, TypeInt::INT);
1142
1143 Node* result = make_indexOf_node(src_start, src_count, tgt_start, tgt_count, region, phi, ae);
1144 if (result != NULL) {
1145 // The result is index relative to from_index if substring was found, -1 otherwise.
1146 // Generate code which will fold into cmove.
1147 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1148 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1149
1150 Node* if_lt = generate_slow_guard(bol, NULL);
1151 if (if_lt != NULL) {
1152 // result == -1
1153 phi->init_req(3, result);
1154 region->init_req(3, if_lt);
1155 }
1156 if (!stopped()) {
1157 result = _gvn.transform(new AddINode(result, from_index));
1158 phi->init_req(4, result);
1159 region->init_req(4, control());
1160 }
1161 }
1162
1163 set_control(_gvn.transform(region));
1164 record_for_igvn(region);
1165 set_result(_gvn.transform(phi));
1166 clear_upper_avx();
1167
1168 return true;
1169 }
1170
1171 // Create StrIndexOfNode with fast path checks
make_indexOf_node(Node * src_start,Node * src_count,Node * tgt_start,Node * tgt_count,RegionNode * region,Node * phi,StrIntrinsicNode::ArgEnc ae)1172 Node* LibraryCallKit::make_indexOf_node(Node* src_start, Node* src_count, Node* tgt_start, Node* tgt_count,
1173 RegionNode* region, Node* phi, StrIntrinsicNode::ArgEnc ae) {
1174 // Check for substr count > string count
1175 Node* cmp = _gvn.transform(new CmpINode(tgt_count, src_count));
1176 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::gt));
1177 Node* if_gt = generate_slow_guard(bol, NULL);
1178 if (if_gt != NULL) {
1179 phi->init_req(1, intcon(-1));
1180 region->init_req(1, if_gt);
1181 }
1182 if (!stopped()) {
1183 // Check for substr count == 0
1184 cmp = _gvn.transform(new CmpINode(tgt_count, intcon(0)));
1185 bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
1186 Node* if_zero = generate_slow_guard(bol, NULL);
1187 if (if_zero != NULL) {
1188 phi->init_req(2, intcon(0));
1189 region->init_req(2, if_zero);
1190 }
1191 }
1192 if (!stopped()) {
1193 return make_string_method_node(Op_StrIndexOf, src_start, src_count, tgt_start, tgt_count, ae);
1194 }
1195 return NULL;
1196 }
1197
1198 //-----------------------------inline_string_indexOfChar-----------------------
inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae)1199 bool LibraryCallKit::inline_string_indexOfChar(StrIntrinsicNode::ArgEnc ae) {
1200 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1201 return false;
1202 }
1203 if (!Matcher::match_rule_supported(Op_StrIndexOfChar)) {
1204 return false;
1205 }
1206 assert(callee()->signature()->size() == 4, "String.indexOfChar() has 4 arguments");
1207 Node* src = argument(0); // byte[]
1208 Node* tgt = argument(1); // tgt is int ch
1209 Node* from_index = argument(2);
1210 Node* max = argument(3);
1211
1212 src = must_be_not_null(src, true);
1213
1214 Node* src_offset = ae == StrIntrinsicNode::L ? from_index : _gvn.transform(new LShiftINode(from_index, intcon(1)));
1215 Node* src_start = array_element_address(src, src_offset, T_BYTE);
1216 Node* src_count = _gvn.transform(new SubINode(max, from_index));
1217
1218 // Range checks
1219 generate_string_range_check(src, src_offset, src_count, ae == StrIntrinsicNode::U);
1220 if (stopped()) {
1221 return true;
1222 }
1223
1224 RegionNode* region = new RegionNode(3);
1225 Node* phi = new PhiNode(region, TypeInt::INT);
1226
1227 Node* result = new StrIndexOfCharNode(control(), memory(TypeAryPtr::BYTES), src_start, src_count, tgt, ae);
1228 C->set_has_split_ifs(true); // Has chance for split-if optimization
1229 _gvn.transform(result);
1230
1231 Node* cmp = _gvn.transform(new CmpINode(result, intcon(0)));
1232 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::lt));
1233
1234 Node* if_lt = generate_slow_guard(bol, NULL);
1235 if (if_lt != NULL) {
1236 // result == -1
1237 phi->init_req(2, result);
1238 region->init_req(2, if_lt);
1239 }
1240 if (!stopped()) {
1241 result = _gvn.transform(new AddINode(result, from_index));
1242 phi->init_req(1, result);
1243 region->init_req(1, control());
1244 }
1245 set_control(_gvn.transform(region));
1246 record_for_igvn(region);
1247 set_result(_gvn.transform(phi));
1248
1249 return true;
1250 }
1251 //---------------------------inline_string_copy---------------------
1252 // compressIt == true --> generate a compressed copy operation (compress char[]/byte[] to byte[])
1253 // int StringUTF16.compress(char[] src, int srcOff, byte[] dst, int dstOff, int len)
1254 // int StringUTF16.compress(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
1255 // compressIt == false --> generate an inflated copy operation (inflate byte[] to char[]/byte[])
1256 // void StringLatin1.inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len)
1257 // void StringLatin1.inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len)
inline_string_copy(bool compress)1258 bool LibraryCallKit::inline_string_copy(bool compress) {
1259 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1260 return false;
1261 }
1262 int nargs = 5; // 2 oops, 3 ints
1263 assert(callee()->signature()->size() == nargs, "string copy has 5 arguments");
1264
1265 Node* src = argument(0);
1266 Node* src_offset = argument(1);
1267 Node* dst = argument(2);
1268 Node* dst_offset = argument(3);
1269 Node* length = argument(4);
1270
1271 // Check for allocation before we add nodes that would confuse
1272 // tightly_coupled_allocation()
1273 AllocateArrayNode* alloc = tightly_coupled_allocation(dst, NULL);
1274
1275 // Figure out the size and type of the elements we will be copying.
1276 const Type* src_type = src->Value(&_gvn);
1277 const Type* dst_type = dst->Value(&_gvn);
1278 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
1279 BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
1280 assert((compress && dst_elem == T_BYTE && (src_elem == T_BYTE || src_elem == T_CHAR)) ||
1281 (!compress && src_elem == T_BYTE && (dst_elem == T_BYTE || dst_elem == T_CHAR)),
1282 "Unsupported array types for inline_string_copy");
1283
1284 src = must_be_not_null(src, true);
1285 dst = must_be_not_null(dst, true);
1286
1287 // Convert char[] offsets to byte[] offsets
1288 bool convert_src = (compress && src_elem == T_BYTE);
1289 bool convert_dst = (!compress && dst_elem == T_BYTE);
1290 if (convert_src) {
1291 src_offset = _gvn.transform(new LShiftINode(src_offset, intcon(1)));
1292 } else if (convert_dst) {
1293 dst_offset = _gvn.transform(new LShiftINode(dst_offset, intcon(1)));
1294 }
1295
1296 // Range checks
1297 generate_string_range_check(src, src_offset, length, convert_src);
1298 generate_string_range_check(dst, dst_offset, length, convert_dst);
1299 if (stopped()) {
1300 return true;
1301 }
1302
1303 Node* src_start = array_element_address(src, src_offset, src_elem);
1304 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
1305 // 'src_start' points to src array + scaled offset
1306 // 'dst_start' points to dst array + scaled offset
1307 Node* count = NULL;
1308 if (compress) {
1309 count = compress_string(src_start, TypeAryPtr::get_array_body_type(src_elem), dst_start, length);
1310 } else {
1311 inflate_string(src_start, dst_start, TypeAryPtr::get_array_body_type(dst_elem), length);
1312 }
1313
1314 if (alloc != NULL) {
1315 if (alloc->maybe_set_complete(&_gvn)) {
1316 // "You break it, you buy it."
1317 InitializeNode* init = alloc->initialization();
1318 assert(init->is_complete(), "we just did this");
1319 init->set_complete_with_arraycopy();
1320 assert(dst->is_CheckCastPP(), "sanity");
1321 assert(dst->in(0)->in(0) == init, "dest pinned");
1322 }
1323 // Do not let stores that initialize this object be reordered with
1324 // a subsequent store that would make this object accessible by
1325 // other threads.
1326 // Record what AllocateNode this StoreStore protects so that
1327 // escape analysis can go from the MemBarStoreStoreNode to the
1328 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1329 // based on the escape status of the AllocateNode.
1330 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1331 }
1332 if (compress) {
1333 set_result(_gvn.transform(count));
1334 }
1335 clear_upper_avx();
1336
1337 return true;
1338 }
1339
1340 #ifdef _LP64
1341 #define XTOP ,top() /*additional argument*/
1342 #else //_LP64
1343 #define XTOP /*no additional argument*/
1344 #endif //_LP64
1345
1346 //------------------------inline_string_toBytesU--------------------------
1347 // public static byte[] StringUTF16.toBytes(char[] value, int off, int len)
inline_string_toBytesU()1348 bool LibraryCallKit::inline_string_toBytesU() {
1349 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1350 return false;
1351 }
1352 // Get the arguments.
1353 Node* value = argument(0);
1354 Node* offset = argument(1);
1355 Node* length = argument(2);
1356
1357 Node* newcopy = NULL;
1358
1359 // Set the original stack and the reexecute bit for the interpreter to reexecute
1360 // the bytecode that invokes StringUTF16.toBytes() if deoptimization happens.
1361 { PreserveReexecuteState preexecs(this);
1362 jvms()->set_should_reexecute(true);
1363
1364 // Check if a null path was taken unconditionally.
1365 value = null_check(value);
1366
1367 RegionNode* bailout = new RegionNode(1);
1368 record_for_igvn(bailout);
1369
1370 // Range checks
1371 generate_negative_guard(offset, bailout);
1372 generate_negative_guard(length, bailout);
1373 generate_limit_guard(offset, length, load_array_length(value), bailout);
1374 // Make sure that resulting byte[] length does not overflow Integer.MAX_VALUE
1375 generate_limit_guard(length, intcon(0), intcon(max_jint/2), bailout);
1376
1377 if (bailout->req() > 1) {
1378 PreserveJVMState pjvms(this);
1379 set_control(_gvn.transform(bailout));
1380 uncommon_trap(Deoptimization::Reason_intrinsic,
1381 Deoptimization::Action_maybe_recompile);
1382 }
1383 if (stopped()) {
1384 return true;
1385 }
1386
1387 Node* size = _gvn.transform(new LShiftINode(length, intcon(1)));
1388 Node* klass_node = makecon(TypeKlassPtr::make(ciTypeArrayKlass::make(T_BYTE)));
1389 newcopy = new_array(klass_node, size, 0); // no arguments to push
1390 AllocateArrayNode* alloc = tightly_coupled_allocation(newcopy, NULL);
1391
1392 // Calculate starting addresses.
1393 Node* src_start = array_element_address(value, offset, T_CHAR);
1394 Node* dst_start = basic_plus_adr(newcopy, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1395
1396 // Check if src array address is aligned to HeapWordSize (dst is always aligned)
1397 const TypeInt* toffset = gvn().type(offset)->is_int();
1398 bool aligned = toffset->is_con() && ((toffset->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1399
1400 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1401 const char* copyfunc_name = "arraycopy";
1402 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1403 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1404 OptoRuntime::fast_arraycopy_Type(),
1405 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1406 src_start, dst_start, ConvI2X(length) XTOP);
1407 // Do not let reads from the cloned object float above the arraycopy.
1408 if (alloc != NULL) {
1409 if (alloc->maybe_set_complete(&_gvn)) {
1410 // "You break it, you buy it."
1411 InitializeNode* init = alloc->initialization();
1412 assert(init->is_complete(), "we just did this");
1413 init->set_complete_with_arraycopy();
1414 assert(newcopy->is_CheckCastPP(), "sanity");
1415 assert(newcopy->in(0)->in(0) == init, "dest pinned");
1416 }
1417 // Do not let stores that initialize this object be reordered with
1418 // a subsequent store that would make this object accessible by
1419 // other threads.
1420 // Record what AllocateNode this StoreStore protects so that
1421 // escape analysis can go from the MemBarStoreStoreNode to the
1422 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1423 // based on the escape status of the AllocateNode.
1424 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1425 } else {
1426 insert_mem_bar(Op_MemBarCPUOrder);
1427 }
1428 } // original reexecute is set back here
1429
1430 C->set_has_split_ifs(true); // Has chance for split-if optimization
1431 if (!stopped()) {
1432 set_result(newcopy);
1433 }
1434 clear_upper_avx();
1435
1436 return true;
1437 }
1438
1439 //------------------------inline_string_getCharsU--------------------------
1440 // public void StringUTF16.getChars(byte[] src, int srcBegin, int srcEnd, char dst[], int dstBegin)
inline_string_getCharsU()1441 bool LibraryCallKit::inline_string_getCharsU() {
1442 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
1443 return false;
1444 }
1445
1446 // Get the arguments.
1447 Node* src = argument(0);
1448 Node* src_begin = argument(1);
1449 Node* src_end = argument(2); // exclusive offset (i < src_end)
1450 Node* dst = argument(3);
1451 Node* dst_begin = argument(4);
1452
1453 // Check for allocation before we add nodes that would confuse
1454 // tightly_coupled_allocation()
1455 AllocateArrayNode* alloc = tightly_coupled_allocation(dst, NULL);
1456
1457 // Check if a null path was taken unconditionally.
1458 src = null_check(src);
1459 dst = null_check(dst);
1460 if (stopped()) {
1461 return true;
1462 }
1463
1464 // Get length and convert char[] offset to byte[] offset
1465 Node* length = _gvn.transform(new SubINode(src_end, src_begin));
1466 src_begin = _gvn.transform(new LShiftINode(src_begin, intcon(1)));
1467
1468 // Range checks
1469 generate_string_range_check(src, src_begin, length, true);
1470 generate_string_range_check(dst, dst_begin, length, false);
1471 if (stopped()) {
1472 return true;
1473 }
1474
1475 if (!stopped()) {
1476 // Calculate starting addresses.
1477 Node* src_start = array_element_address(src, src_begin, T_BYTE);
1478 Node* dst_start = array_element_address(dst, dst_begin, T_CHAR);
1479
1480 // Check if array addresses are aligned to HeapWordSize
1481 const TypeInt* tsrc = gvn().type(src_begin)->is_int();
1482 const TypeInt* tdst = gvn().type(dst_begin)->is_int();
1483 bool aligned = tsrc->is_con() && ((tsrc->get_con() * type2aelembytes(T_BYTE)) % HeapWordSize == 0) &&
1484 tdst->is_con() && ((tdst->get_con() * type2aelembytes(T_CHAR)) % HeapWordSize == 0);
1485
1486 // Figure out which arraycopy runtime method to call (disjoint, uninitialized).
1487 const char* copyfunc_name = "arraycopy";
1488 address copyfunc_addr = StubRoutines::select_arraycopy_function(T_CHAR, aligned, true, copyfunc_name, true);
1489 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
1490 OptoRuntime::fast_arraycopy_Type(),
1491 copyfunc_addr, copyfunc_name, TypeRawPtr::BOTTOM,
1492 src_start, dst_start, ConvI2X(length) XTOP);
1493 // Do not let reads from the cloned object float above the arraycopy.
1494 if (alloc != NULL) {
1495 if (alloc->maybe_set_complete(&_gvn)) {
1496 // "You break it, you buy it."
1497 InitializeNode* init = alloc->initialization();
1498 assert(init->is_complete(), "we just did this");
1499 init->set_complete_with_arraycopy();
1500 assert(dst->is_CheckCastPP(), "sanity");
1501 assert(dst->in(0)->in(0) == init, "dest pinned");
1502 }
1503 // Do not let stores that initialize this object be reordered with
1504 // a subsequent store that would make this object accessible by
1505 // other threads.
1506 // Record what AllocateNode this StoreStore protects so that
1507 // escape analysis can go from the MemBarStoreStoreNode to the
1508 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
1509 // based on the escape status of the AllocateNode.
1510 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
1511 } else {
1512 insert_mem_bar(Op_MemBarCPUOrder);
1513 }
1514 }
1515
1516 C->set_has_split_ifs(true); // Has chance for split-if optimization
1517 return true;
1518 }
1519
1520 //----------------------inline_string_char_access----------------------------
1521 // Store/Load char to/from byte[] array.
1522 // static void StringUTF16.putChar(byte[] val, int index, int c)
1523 // static char StringUTF16.getChar(byte[] val, int index)
inline_string_char_access(bool is_store)1524 bool LibraryCallKit::inline_string_char_access(bool is_store) {
1525 Node* value = argument(0);
1526 Node* index = argument(1);
1527 Node* ch = is_store ? argument(2) : NULL;
1528
1529 // This intrinsic accesses byte[] array as char[] array. Computing the offsets
1530 // correctly requires matched array shapes.
1531 assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
1532 "sanity: byte[] and char[] bases agree");
1533 assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
1534 "sanity: byte[] and char[] scales agree");
1535
1536 // Bail when getChar over constants is requested: constant folding would
1537 // reject folding mismatched char access over byte[]. A normal inlining for getChar
1538 // Java method would constant fold nicely instead.
1539 if (!is_store && value->is_Con() && index->is_Con()) {
1540 return false;
1541 }
1542
1543 value = must_be_not_null(value, true);
1544
1545 Node* adr = array_element_address(value, index, T_CHAR);
1546 if (adr->is_top()) {
1547 return false;
1548 }
1549 if (is_store) {
1550 access_store_at(value, adr, TypeAryPtr::BYTES, ch, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED);
1551 } else {
1552 ch = access_load_at(value, adr, TypeAryPtr::BYTES, TypeInt::CHAR, T_CHAR, IN_HEAP | MO_UNORDERED | C2_MISMATCHED | C2_CONTROL_DEPENDENT_LOAD);
1553 set_result(ch);
1554 }
1555 return true;
1556 }
1557
1558 //--------------------------round_double_node--------------------------------
1559 // Round a double node if necessary.
round_double_node(Node * n)1560 Node* LibraryCallKit::round_double_node(Node* n) {
1561 if (Matcher::strict_fp_requires_explicit_rounding) {
1562 #ifdef IA32
1563 if (UseSSE < 2) {
1564 n = _gvn.transform(new RoundDoubleNode(NULL, n));
1565 }
1566 #else
1567 Unimplemented();
1568 #endif // IA32
1569 }
1570 return n;
1571 }
1572
1573 //------------------------------inline_math-----------------------------------
1574 // public static double Math.abs(double)
1575 // public static double Math.sqrt(double)
1576 // public static double Math.log(double)
1577 // public static double Math.log10(double)
inline_double_math(vmIntrinsics::ID id)1578 bool LibraryCallKit::inline_double_math(vmIntrinsics::ID id) {
1579 Node* arg = round_double_node(argument(0));
1580 Node* n = NULL;
1581 switch (id) {
1582 case vmIntrinsics::_dabs: n = new AbsDNode( arg); break;
1583 case vmIntrinsics::_dsqrt: n = new SqrtDNode(C, control(), arg); break;
1584 case vmIntrinsics::_ceil: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_ceil); break;
1585 case vmIntrinsics::_floor: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_floor); break;
1586 case vmIntrinsics::_rint: n = RoundDoubleModeNode::make(_gvn, arg, RoundDoubleModeNode::rmode_rint); break;
1587 case vmIntrinsics::_dcopySign: n = CopySignDNode::make(_gvn, arg, round_double_node(argument(2))); break;
1588 case vmIntrinsics::_dsignum: n = SignumDNode::make(_gvn, arg); break;
1589 default: fatal_unexpected_iid(id); break;
1590 }
1591 set_result(_gvn.transform(n));
1592 return true;
1593 }
1594
1595 //------------------------------inline_math-----------------------------------
1596 // public static float Math.abs(float)
1597 // public static int Math.abs(int)
1598 // public static long Math.abs(long)
inline_math(vmIntrinsics::ID id)1599 bool LibraryCallKit::inline_math(vmIntrinsics::ID id) {
1600 Node* arg = argument(0);
1601 Node* n = NULL;
1602 switch (id) {
1603 case vmIntrinsics::_fabs: n = new AbsFNode( arg); break;
1604 case vmIntrinsics::_iabs: n = new AbsINode( arg); break;
1605 case vmIntrinsics::_labs: n = new AbsLNode( arg); break;
1606 case vmIntrinsics::_fcopySign: n = new CopySignFNode(arg, argument(1)); break;
1607 case vmIntrinsics::_fsignum: n = SignumFNode::make(_gvn, arg); break;
1608 default: fatal_unexpected_iid(id); break;
1609 }
1610 set_result(_gvn.transform(n));
1611 return true;
1612 }
1613
1614 //------------------------------runtime_math-----------------------------
runtime_math(const TypeFunc * call_type,address funcAddr,const char * funcName)1615 bool LibraryCallKit::runtime_math(const TypeFunc* call_type, address funcAddr, const char* funcName) {
1616 assert(call_type == OptoRuntime::Math_DD_D_Type() || call_type == OptoRuntime::Math_D_D_Type(),
1617 "must be (DD)D or (D)D type");
1618
1619 // Inputs
1620 Node* a = round_double_node(argument(0));
1621 Node* b = (call_type == OptoRuntime::Math_DD_D_Type()) ? round_double_node(argument(2)) : NULL;
1622
1623 const TypePtr* no_memory_effects = NULL;
1624 Node* trig = make_runtime_call(RC_LEAF, call_type, funcAddr, funcName,
1625 no_memory_effects,
1626 a, top(), b, b ? top() : NULL);
1627 Node* value = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+0));
1628 #ifdef ASSERT
1629 Node* value_top = _gvn.transform(new ProjNode(trig, TypeFunc::Parms+1));
1630 assert(value_top == top(), "second value must be top");
1631 #endif
1632
1633 set_result(value);
1634 return true;
1635 }
1636
1637 //------------------------------inline_math_native-----------------------------
inline_math_native(vmIntrinsics::ID id)1638 bool LibraryCallKit::inline_math_native(vmIntrinsics::ID id) {
1639 #define FN_PTR(f) CAST_FROM_FN_PTR(address, f)
1640 switch (id) {
1641 // These intrinsics are not properly supported on all hardware
1642 case vmIntrinsics::_dsin:
1643 return StubRoutines::dsin() != NULL ?
1644 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dsin(), "dsin") :
1645 runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dsin), "SIN");
1646 case vmIntrinsics::_dcos:
1647 return StubRoutines::dcos() != NULL ?
1648 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dcos(), "dcos") :
1649 runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dcos), "COS");
1650 case vmIntrinsics::_dtan:
1651 return StubRoutines::dtan() != NULL ?
1652 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dtan(), "dtan") :
1653 runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dtan), "TAN");
1654 case vmIntrinsics::_dlog:
1655 return StubRoutines::dlog() != NULL ?
1656 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog(), "dlog") :
1657 runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog), "LOG");
1658 case vmIntrinsics::_dlog10:
1659 return StubRoutines::dlog10() != NULL ?
1660 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dlog10(), "dlog10") :
1661 runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dlog10), "LOG10");
1662
1663 // These intrinsics are supported on all hardware
1664 case vmIntrinsics::_ceil:
1665 case vmIntrinsics::_floor:
1666 case vmIntrinsics::_rint: return Matcher::match_rule_supported(Op_RoundDoubleMode) ? inline_double_math(id) : false;
1667 case vmIntrinsics::_dsqrt: return Matcher::match_rule_supported(Op_SqrtD) ? inline_double_math(id) : false;
1668 case vmIntrinsics::_dabs: return Matcher::has_match_rule(Op_AbsD) ? inline_double_math(id) : false;
1669 case vmIntrinsics::_fabs: return Matcher::match_rule_supported(Op_AbsF) ? inline_math(id) : false;
1670 case vmIntrinsics::_iabs: return Matcher::match_rule_supported(Op_AbsI) ? inline_math(id) : false;
1671 case vmIntrinsics::_labs: return Matcher::match_rule_supported(Op_AbsL) ? inline_math(id) : false;
1672
1673 case vmIntrinsics::_dexp:
1674 return StubRoutines::dexp() != NULL ?
1675 runtime_math(OptoRuntime::Math_D_D_Type(), StubRoutines::dexp(), "dexp") :
1676 runtime_math(OptoRuntime::Math_D_D_Type(), FN_PTR(SharedRuntime::dexp), "EXP");
1677 case vmIntrinsics::_dpow: {
1678 Node* exp = round_double_node(argument(2));
1679 const TypeD* d = _gvn.type(exp)->isa_double_constant();
1680 if (d != NULL && d->getd() == 2.0) {
1681 // Special case: pow(x, 2.0) => x * x
1682 Node* base = round_double_node(argument(0));
1683 set_result(_gvn.transform(new MulDNode(base, base)));
1684 return true;
1685 }
1686 return StubRoutines::dpow() != NULL ?
1687 runtime_math(OptoRuntime::Math_DD_D_Type(), StubRoutines::dpow(), "dpow") :
1688 runtime_math(OptoRuntime::Math_DD_D_Type(), FN_PTR(SharedRuntime::dpow), "POW");
1689 }
1690 #undef FN_PTR
1691
1692 case vmIntrinsics::_dcopySign: return inline_double_math(id);
1693 case vmIntrinsics::_fcopySign: return inline_math(id);
1694 case vmIntrinsics::_dsignum: return inline_double_math(id);
1695 case vmIntrinsics::_fsignum: return inline_math(id);
1696
1697 // These intrinsics are not yet correctly implemented
1698 case vmIntrinsics::_datan2:
1699 return false;
1700
1701 default:
1702 fatal_unexpected_iid(id);
1703 return false;
1704 }
1705 }
1706
is_simple_name(Node * n)1707 static bool is_simple_name(Node* n) {
1708 return (n->req() == 1 // constant
1709 || (n->is_Type() && n->as_Type()->type()->singleton())
1710 || n->is_Proj() // parameter or return value
1711 || n->is_Phi() // local of some sort
1712 );
1713 }
1714
1715 //----------------------------inline_notify-----------------------------------*
inline_notify(vmIntrinsics::ID id)1716 bool LibraryCallKit::inline_notify(vmIntrinsics::ID id) {
1717 const TypeFunc* ftype = OptoRuntime::monitor_notify_Type();
1718 address func;
1719 if (id == vmIntrinsics::_notify) {
1720 func = OptoRuntime::monitor_notify_Java();
1721 } else {
1722 func = OptoRuntime::monitor_notifyAll_Java();
1723 }
1724 Node* call = make_runtime_call(RC_NO_LEAF, ftype, func, NULL, TypeRawPtr::BOTTOM, argument(0));
1725 make_slow_call_ex(call, env()->Throwable_klass(), false);
1726 return true;
1727 }
1728
1729
1730 //----------------------------inline_min_max-----------------------------------
inline_min_max(vmIntrinsics::ID id)1731 bool LibraryCallKit::inline_min_max(vmIntrinsics::ID id) {
1732 set_result(generate_min_max(id, argument(0), argument(1)));
1733 return true;
1734 }
1735
inline_math_mathExact(Node * math,Node * test)1736 void LibraryCallKit::inline_math_mathExact(Node* math, Node *test) {
1737 Node* bol = _gvn.transform( new BoolNode(test, BoolTest::overflow) );
1738 IfNode* check = create_and_map_if(control(), bol, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN);
1739 Node* fast_path = _gvn.transform( new IfFalseNode(check));
1740 Node* slow_path = _gvn.transform( new IfTrueNode(check) );
1741
1742 {
1743 PreserveJVMState pjvms(this);
1744 PreserveReexecuteState preexecs(this);
1745 jvms()->set_should_reexecute(true);
1746
1747 set_control(slow_path);
1748 set_i_o(i_o());
1749
1750 uncommon_trap(Deoptimization::Reason_intrinsic,
1751 Deoptimization::Action_none);
1752 }
1753
1754 set_control(fast_path);
1755 set_result(math);
1756 }
1757
1758 template <typename OverflowOp>
inline_math_overflow(Node * arg1,Node * arg2)1759 bool LibraryCallKit::inline_math_overflow(Node* arg1, Node* arg2) {
1760 typedef typename OverflowOp::MathOp MathOp;
1761
1762 MathOp* mathOp = new MathOp(arg1, arg2);
1763 Node* operation = _gvn.transform( mathOp );
1764 Node* ofcheck = _gvn.transform( new OverflowOp(arg1, arg2) );
1765 inline_math_mathExact(operation, ofcheck);
1766 return true;
1767 }
1768
inline_math_addExactI(bool is_increment)1769 bool LibraryCallKit::inline_math_addExactI(bool is_increment) {
1770 return inline_math_overflow<OverflowAddINode>(argument(0), is_increment ? intcon(1) : argument(1));
1771 }
1772
inline_math_addExactL(bool is_increment)1773 bool LibraryCallKit::inline_math_addExactL(bool is_increment) {
1774 return inline_math_overflow<OverflowAddLNode>(argument(0), is_increment ? longcon(1) : argument(2));
1775 }
1776
inline_math_subtractExactI(bool is_decrement)1777 bool LibraryCallKit::inline_math_subtractExactI(bool is_decrement) {
1778 return inline_math_overflow<OverflowSubINode>(argument(0), is_decrement ? intcon(1) : argument(1));
1779 }
1780
inline_math_subtractExactL(bool is_decrement)1781 bool LibraryCallKit::inline_math_subtractExactL(bool is_decrement) {
1782 return inline_math_overflow<OverflowSubLNode>(argument(0), is_decrement ? longcon(1) : argument(2));
1783 }
1784
inline_math_negateExactI()1785 bool LibraryCallKit::inline_math_negateExactI() {
1786 return inline_math_overflow<OverflowSubINode>(intcon(0), argument(0));
1787 }
1788
inline_math_negateExactL()1789 bool LibraryCallKit::inline_math_negateExactL() {
1790 return inline_math_overflow<OverflowSubLNode>(longcon(0), argument(0));
1791 }
1792
inline_math_multiplyExactI()1793 bool LibraryCallKit::inline_math_multiplyExactI() {
1794 return inline_math_overflow<OverflowMulINode>(argument(0), argument(1));
1795 }
1796
inline_math_multiplyExactL()1797 bool LibraryCallKit::inline_math_multiplyExactL() {
1798 return inline_math_overflow<OverflowMulLNode>(argument(0), argument(2));
1799 }
1800
inline_math_multiplyHigh()1801 bool LibraryCallKit::inline_math_multiplyHigh() {
1802 set_result(_gvn.transform(new MulHiLNode(argument(0), argument(2))));
1803 return true;
1804 }
1805
1806 Node*
generate_min_max(vmIntrinsics::ID id,Node * x0,Node * y0)1807 LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) {
1808 // These are the candidate return value:
1809 Node* xvalue = x0;
1810 Node* yvalue = y0;
1811
1812 if (xvalue == yvalue) {
1813 return xvalue;
1814 }
1815
1816 bool want_max = (id == vmIntrinsics::_max);
1817
1818 const TypeInt* txvalue = _gvn.type(xvalue)->isa_int();
1819 const TypeInt* tyvalue = _gvn.type(yvalue)->isa_int();
1820 if (txvalue == NULL || tyvalue == NULL) return top();
1821 // This is not really necessary, but it is consistent with a
1822 // hypothetical MaxINode::Value method:
1823 int widen = MAX2(txvalue->_widen, tyvalue->_widen);
1824
1825 // %%% This folding logic should (ideally) be in a different place.
1826 // Some should be inside IfNode, and there to be a more reliable
1827 // transformation of ?: style patterns into cmoves. We also want
1828 // more powerful optimizations around cmove and min/max.
1829
1830 // Try to find a dominating comparison of these guys.
1831 // It can simplify the index computation for Arrays.copyOf
1832 // and similar uses of System.arraycopy.
1833 // First, compute the normalized version of CmpI(x, y).
1834 int cmp_op = Op_CmpI;
1835 Node* xkey = xvalue;
1836 Node* ykey = yvalue;
1837 Node* ideal_cmpxy = _gvn.transform(new CmpINode(xkey, ykey));
1838 if (ideal_cmpxy->is_Cmp()) {
1839 // E.g., if we have CmpI(length - offset, count),
1840 // it might idealize to CmpI(length, count + offset)
1841 cmp_op = ideal_cmpxy->Opcode();
1842 xkey = ideal_cmpxy->in(1);
1843 ykey = ideal_cmpxy->in(2);
1844 }
1845
1846 // Start by locating any relevant comparisons.
1847 Node* start_from = (xkey->outcnt() < ykey->outcnt()) ? xkey : ykey;
1848 Node* cmpxy = NULL;
1849 Node* cmpyx = NULL;
1850 for (DUIterator_Fast kmax, k = start_from->fast_outs(kmax); k < kmax; k++) {
1851 Node* cmp = start_from->fast_out(k);
1852 if (cmp->outcnt() > 0 && // must have prior uses
1853 cmp->in(0) == NULL && // must be context-independent
1854 cmp->Opcode() == cmp_op) { // right kind of compare
1855 if (cmp->in(1) == xkey && cmp->in(2) == ykey) cmpxy = cmp;
1856 if (cmp->in(1) == ykey && cmp->in(2) == xkey) cmpyx = cmp;
1857 }
1858 }
1859
1860 const int NCMPS = 2;
1861 Node* cmps[NCMPS] = { cmpxy, cmpyx };
1862 int cmpn;
1863 for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1864 if (cmps[cmpn] != NULL) break; // find a result
1865 }
1866 if (cmpn < NCMPS) {
1867 // Look for a dominating test that tells us the min and max.
1868 int depth = 0; // Limit search depth for speed
1869 Node* dom = control();
1870 for (; dom != NULL; dom = IfNode::up_one_dom(dom, true)) {
1871 if (++depth >= 100) break;
1872 Node* ifproj = dom;
1873 if (!ifproj->is_Proj()) continue;
1874 Node* iff = ifproj->in(0);
1875 if (!iff->is_If()) continue;
1876 Node* bol = iff->in(1);
1877 if (!bol->is_Bool()) continue;
1878 Node* cmp = bol->in(1);
1879 if (cmp == NULL) continue;
1880 for (cmpn = 0; cmpn < NCMPS; cmpn++)
1881 if (cmps[cmpn] == cmp) break;
1882 if (cmpn == NCMPS) continue;
1883 BoolTest::mask btest = bol->as_Bool()->_test._test;
1884 if (ifproj->is_IfFalse()) btest = BoolTest(btest).negate();
1885 if (cmp->in(1) == ykey) btest = BoolTest(btest).commute();
1886 // At this point, we know that 'x btest y' is true.
1887 switch (btest) {
1888 case BoolTest::eq:
1889 // They are proven equal, so we can collapse the min/max.
1890 // Either value is the answer. Choose the simpler.
1891 if (is_simple_name(yvalue) && !is_simple_name(xvalue))
1892 return yvalue;
1893 return xvalue;
1894 case BoolTest::lt: // x < y
1895 case BoolTest::le: // x <= y
1896 return (want_max ? yvalue : xvalue);
1897 case BoolTest::gt: // x > y
1898 case BoolTest::ge: // x >= y
1899 return (want_max ? xvalue : yvalue);
1900 default:
1901 break;
1902 }
1903 }
1904 }
1905
1906 // We failed to find a dominating test.
1907 // Let's pick a test that might GVN with prior tests.
1908 Node* best_bol = NULL;
1909 BoolTest::mask best_btest = BoolTest::illegal;
1910 for (cmpn = 0; cmpn < NCMPS; cmpn++) {
1911 Node* cmp = cmps[cmpn];
1912 if (cmp == NULL) continue;
1913 for (DUIterator_Fast jmax, j = cmp->fast_outs(jmax); j < jmax; j++) {
1914 Node* bol = cmp->fast_out(j);
1915 if (!bol->is_Bool()) continue;
1916 BoolTest::mask btest = bol->as_Bool()->_test._test;
1917 if (btest == BoolTest::eq || btest == BoolTest::ne) continue;
1918 if (cmp->in(1) == ykey) btest = BoolTest(btest).commute();
1919 if (bol->outcnt() > (best_bol == NULL ? 0 : best_bol->outcnt())) {
1920 best_bol = bol->as_Bool();
1921 best_btest = btest;
1922 }
1923 }
1924 }
1925
1926 Node* answer_if_true = NULL;
1927 Node* answer_if_false = NULL;
1928 switch (best_btest) {
1929 default:
1930 if (cmpxy == NULL)
1931 cmpxy = ideal_cmpxy;
1932 best_bol = _gvn.transform(new BoolNode(cmpxy, BoolTest::lt));
1933 // and fall through:
1934 case BoolTest::lt: // x < y
1935 case BoolTest::le: // x <= y
1936 answer_if_true = (want_max ? yvalue : xvalue);
1937 answer_if_false = (want_max ? xvalue : yvalue);
1938 break;
1939 case BoolTest::gt: // x > y
1940 case BoolTest::ge: // x >= y
1941 answer_if_true = (want_max ? xvalue : yvalue);
1942 answer_if_false = (want_max ? yvalue : xvalue);
1943 break;
1944 }
1945
1946 jint hi, lo;
1947 if (want_max) {
1948 // We can sharpen the minimum.
1949 hi = MAX2(txvalue->_hi, tyvalue->_hi);
1950 lo = MAX2(txvalue->_lo, tyvalue->_lo);
1951 } else {
1952 // We can sharpen the maximum.
1953 hi = MIN2(txvalue->_hi, tyvalue->_hi);
1954 lo = MIN2(txvalue->_lo, tyvalue->_lo);
1955 }
1956
1957 // Use a flow-free graph structure, to avoid creating excess control edges
1958 // which could hinder other optimizations.
1959 // Since Math.min/max is often used with arraycopy, we want
1960 // tightly_coupled_allocation to be able to see beyond min/max expressions.
1961 Node* cmov = CMoveNode::make(NULL, best_bol,
1962 answer_if_false, answer_if_true,
1963 TypeInt::make(lo, hi, widen));
1964
1965 return _gvn.transform(cmov);
1966
1967 /*
1968 // This is not as desirable as it may seem, since Min and Max
1969 // nodes do not have a full set of optimizations.
1970 // And they would interfere, anyway, with 'if' optimizations
1971 // and with CMoveI canonical forms.
1972 switch (id) {
1973 case vmIntrinsics::_min:
1974 result_val = _gvn.transform(new (C, 3) MinINode(x,y)); break;
1975 case vmIntrinsics::_max:
1976 result_val = _gvn.transform(new (C, 3) MaxINode(x,y)); break;
1977 default:
1978 ShouldNotReachHere();
1979 }
1980 */
1981 }
1982
1983 inline int
classify_unsafe_addr(Node * & base,Node * & offset,BasicType type)1984 LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset, BasicType type) {
1985 const TypePtr* base_type = TypePtr::NULL_PTR;
1986 if (base != NULL) base_type = _gvn.type(base)->isa_ptr();
1987 if (base_type == NULL) {
1988 // Unknown type.
1989 return Type::AnyPtr;
1990 } else if (base_type == TypePtr::NULL_PTR) {
1991 // Since this is a NULL+long form, we have to switch to a rawptr.
1992 base = _gvn.transform(new CastX2PNode(offset));
1993 offset = MakeConX(0);
1994 return Type::RawPtr;
1995 } else if (base_type->base() == Type::RawPtr) {
1996 return Type::RawPtr;
1997 } else if (base_type->isa_oopptr()) {
1998 // Base is never null => always a heap address.
1999 if (!TypePtr::NULL_PTR->higher_equal(base_type)) {
2000 return Type::OopPtr;
2001 }
2002 // Offset is small => always a heap address.
2003 const TypeX* offset_type = _gvn.type(offset)->isa_intptr_t();
2004 if (offset_type != NULL &&
2005 base_type->offset() == 0 && // (should always be?)
2006 offset_type->_lo >= 0 &&
2007 !MacroAssembler::needs_explicit_null_check(offset_type->_hi)) {
2008 return Type::OopPtr;
2009 } else if (type == T_OBJECT) {
2010 // off heap access to an oop doesn't make any sense. Has to be on
2011 // heap.
2012 return Type::OopPtr;
2013 }
2014 // Otherwise, it might either be oop+off or NULL+addr.
2015 return Type::AnyPtr;
2016 } else {
2017 // No information:
2018 return Type::AnyPtr;
2019 }
2020 }
2021
make_unsafe_address(Node * & base,Node * offset,DecoratorSet decorators,BasicType type,bool can_cast)2022 Node* LibraryCallKit::make_unsafe_address(Node*& base, Node* offset, DecoratorSet decorators, BasicType type, bool can_cast) {
2023 Node* uncasted_base = base;
2024 int kind = classify_unsafe_addr(uncasted_base, offset, type);
2025 if (kind == Type::RawPtr) {
2026 return basic_plus_adr(top(), uncasted_base, offset);
2027 } else if (kind == Type::AnyPtr) {
2028 assert(base == uncasted_base, "unexpected base change");
2029 if (can_cast) {
2030 if (!_gvn.type(base)->speculative_maybe_null() &&
2031 !too_many_traps(Deoptimization::Reason_speculate_null_check)) {
2032 // According to profiling, this access is always on
2033 // heap. Casting the base to not null and thus avoiding membars
2034 // around the access should allow better optimizations
2035 Node* null_ctl = top();
2036 base = null_check_oop(base, &null_ctl, true, true, true);
2037 assert(null_ctl->is_top(), "no null control here");
2038 return basic_plus_adr(base, offset);
2039 } else if (_gvn.type(base)->speculative_always_null() &&
2040 !too_many_traps(Deoptimization::Reason_speculate_null_assert)) {
2041 // According to profiling, this access is always off
2042 // heap.
2043 base = null_assert(base);
2044 Node* raw_base = _gvn.transform(new CastX2PNode(offset));
2045 offset = MakeConX(0);
2046 return basic_plus_adr(top(), raw_base, offset);
2047 }
2048 }
2049 // We don't know if it's an on heap or off heap access. Fall back
2050 // to raw memory access.
2051 Node* raw = _gvn.transform(new CheckCastPPNode(control(), base, TypeRawPtr::BOTTOM));
2052 return basic_plus_adr(top(), raw, offset);
2053 } else {
2054 assert(base == uncasted_base, "unexpected base change");
2055 // We know it's an on heap access so base can't be null
2056 if (TypePtr::NULL_PTR->higher_equal(_gvn.type(base))) {
2057 base = must_be_not_null(base, true);
2058 }
2059 return basic_plus_adr(base, offset);
2060 }
2061 }
2062
2063 //--------------------------inline_number_methods-----------------------------
2064 // inline int Integer.numberOfLeadingZeros(int)
2065 // inline int Long.numberOfLeadingZeros(long)
2066 //
2067 // inline int Integer.numberOfTrailingZeros(int)
2068 // inline int Long.numberOfTrailingZeros(long)
2069 //
2070 // inline int Integer.bitCount(int)
2071 // inline int Long.bitCount(long)
2072 //
2073 // inline char Character.reverseBytes(char)
2074 // inline short Short.reverseBytes(short)
2075 // inline int Integer.reverseBytes(int)
2076 // inline long Long.reverseBytes(long)
inline_number_methods(vmIntrinsics::ID id)2077 bool LibraryCallKit::inline_number_methods(vmIntrinsics::ID id) {
2078 Node* arg = argument(0);
2079 Node* n = NULL;
2080 switch (id) {
2081 case vmIntrinsics::_numberOfLeadingZeros_i: n = new CountLeadingZerosINode( arg); break;
2082 case vmIntrinsics::_numberOfLeadingZeros_l: n = new CountLeadingZerosLNode( arg); break;
2083 case vmIntrinsics::_numberOfTrailingZeros_i: n = new CountTrailingZerosINode(arg); break;
2084 case vmIntrinsics::_numberOfTrailingZeros_l: n = new CountTrailingZerosLNode(arg); break;
2085 case vmIntrinsics::_bitCount_i: n = new PopCountINode( arg); break;
2086 case vmIntrinsics::_bitCount_l: n = new PopCountLNode( arg); break;
2087 case vmIntrinsics::_reverseBytes_c: n = new ReverseBytesUSNode(0, arg); break;
2088 case vmIntrinsics::_reverseBytes_s: n = new ReverseBytesSNode( 0, arg); break;
2089 case vmIntrinsics::_reverseBytes_i: n = new ReverseBytesINode( 0, arg); break;
2090 case vmIntrinsics::_reverseBytes_l: n = new ReverseBytesLNode( 0, arg); break;
2091 default: fatal_unexpected_iid(id); break;
2092 }
2093 set_result(_gvn.transform(n));
2094 return true;
2095 }
2096
2097 //----------------------------inline_unsafe_access----------------------------
2098
sharpen_unsafe_type(Compile::AliasType * alias_type,const TypePtr * adr_type)2099 const TypeOopPtr* LibraryCallKit::sharpen_unsafe_type(Compile::AliasType* alias_type, const TypePtr *adr_type) {
2100 // Attempt to infer a sharper value type from the offset and base type.
2101 ciKlass* sharpened_klass = NULL;
2102
2103 // See if it is an instance field, with an object type.
2104 if (alias_type->field() != NULL) {
2105 if (alias_type->field()->type()->is_klass()) {
2106 sharpened_klass = alias_type->field()->type()->as_klass();
2107 }
2108 }
2109
2110 // See if it is a narrow oop array.
2111 if (adr_type->isa_aryptr()) {
2112 if (adr_type->offset() >= objArrayOopDesc::base_offset_in_bytes()) {
2113 const TypeOopPtr *elem_type = adr_type->is_aryptr()->elem()->isa_oopptr();
2114 if (elem_type != NULL) {
2115 sharpened_klass = elem_type->klass();
2116 }
2117 }
2118 }
2119
2120 // The sharpened class might be unloaded if there is no class loader
2121 // contraint in place.
2122 if (sharpened_klass != NULL && sharpened_klass->is_loaded()) {
2123 const TypeOopPtr* tjp = TypeOopPtr::make_from_klass(sharpened_klass);
2124
2125 #ifndef PRODUCT
2126 if (C->print_intrinsics() || C->print_inlining()) {
2127 tty->print(" from base type: "); adr_type->dump(); tty->cr();
2128 tty->print(" sharpened value: "); tjp->dump(); tty->cr();
2129 }
2130 #endif
2131 // Sharpen the value type.
2132 return tjp;
2133 }
2134 return NULL;
2135 }
2136
mo_decorator_for_access_kind(AccessKind kind)2137 DecoratorSet LibraryCallKit::mo_decorator_for_access_kind(AccessKind kind) {
2138 switch (kind) {
2139 case Relaxed:
2140 return MO_UNORDERED;
2141 case Opaque:
2142 return MO_RELAXED;
2143 case Acquire:
2144 return MO_ACQUIRE;
2145 case Release:
2146 return MO_RELEASE;
2147 case Volatile:
2148 return MO_SEQ_CST;
2149 default:
2150 ShouldNotReachHere();
2151 return 0;
2152 }
2153 }
2154
inline_unsafe_access(bool is_store,const BasicType type,const AccessKind kind,const bool unaligned)2155 bool LibraryCallKit::inline_unsafe_access(bool is_store, const BasicType type, const AccessKind kind, const bool unaligned) {
2156 if (callee()->is_static()) return false; // caller must have the capability!
2157 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2158 guarantee(!is_store || kind != Acquire, "Acquire accesses can be produced only for loads");
2159 guarantee( is_store || kind != Release, "Release accesses can be produced only for stores");
2160 assert(type != T_OBJECT || !unaligned, "unaligned access not supported with object type");
2161
2162 if (is_reference_type(type)) {
2163 decorators |= ON_UNKNOWN_OOP_REF;
2164 }
2165
2166 if (unaligned) {
2167 decorators |= C2_UNALIGNED;
2168 }
2169
2170 #ifndef PRODUCT
2171 {
2172 ResourceMark rm;
2173 // Check the signatures.
2174 ciSignature* sig = callee()->signature();
2175 #ifdef ASSERT
2176 if (!is_store) {
2177 // Object getReference(Object base, int/long offset), etc.
2178 BasicType rtype = sig->return_type()->basic_type();
2179 assert(rtype == type, "getter must return the expected value");
2180 assert(sig->count() == 2, "oop getter has 2 arguments");
2181 assert(sig->type_at(0)->basic_type() == T_OBJECT, "getter base is object");
2182 assert(sig->type_at(1)->basic_type() == T_LONG, "getter offset is correct");
2183 } else {
2184 // void putReference(Object base, int/long offset, Object x), etc.
2185 assert(sig->return_type()->basic_type() == T_VOID, "putter must not return a value");
2186 assert(sig->count() == 3, "oop putter has 3 arguments");
2187 assert(sig->type_at(0)->basic_type() == T_OBJECT, "putter base is object");
2188 assert(sig->type_at(1)->basic_type() == T_LONG, "putter offset is correct");
2189 BasicType vtype = sig->type_at(sig->count()-1)->basic_type();
2190 assert(vtype == type, "putter must accept the expected value");
2191 }
2192 #endif // ASSERT
2193 }
2194 #endif //PRODUCT
2195
2196 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2197
2198 Node* receiver = argument(0); // type: oop
2199
2200 // Build address expression.
2201 Node* adr;
2202 Node* heap_base_oop = top();
2203 Node* offset = top();
2204 Node* val;
2205
2206 // The base is either a Java object or a value produced by Unsafe.staticFieldBase
2207 Node* base = argument(1); // type: oop
2208 // The offset is a value produced by Unsafe.staticFieldOffset or Unsafe.objectFieldOffset
2209 offset = argument(2); // type: long
2210 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2211 // to be plain byte offsets, which are also the same as those accepted
2212 // by oopDesc::field_addr.
2213 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
2214 "fieldOffset must be byte-scaled");
2215 // 32-bit machines ignore the high half!
2216 offset = ConvL2X(offset);
2217 adr = make_unsafe_address(base, offset, is_store ? ACCESS_WRITE : ACCESS_READ, type, kind == Relaxed);
2218
2219 if (_gvn.type(base)->isa_ptr() == TypePtr::NULL_PTR) {
2220 if (type != T_OBJECT) {
2221 decorators |= IN_NATIVE; // off-heap primitive access
2222 } else {
2223 return false; // off-heap oop accesses are not supported
2224 }
2225 } else {
2226 heap_base_oop = base; // on-heap or mixed access
2227 }
2228
2229 // Can base be NULL? Otherwise, always on-heap access.
2230 bool can_access_non_heap = TypePtr::NULL_PTR->higher_equal(_gvn.type(base));
2231
2232 if (!can_access_non_heap) {
2233 decorators |= IN_HEAP;
2234 }
2235
2236 val = is_store ? argument(4) : NULL;
2237
2238 const TypePtr* adr_type = _gvn.type(adr)->isa_ptr();
2239 if (adr_type == TypePtr::NULL_PTR) {
2240 return false; // off-heap access with zero address
2241 }
2242
2243 // Try to categorize the address.
2244 Compile::AliasType* alias_type = C->alias_type(adr_type);
2245 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2246
2247 if (alias_type->adr_type() == TypeInstPtr::KLASS ||
2248 alias_type->adr_type() == TypeAryPtr::RANGE) {
2249 return false; // not supported
2250 }
2251
2252 bool mismatched = false;
2253 BasicType bt = alias_type->basic_type();
2254 if (bt != T_ILLEGAL) {
2255 assert(alias_type->adr_type()->is_oopptr(), "should be on-heap access");
2256 if (bt == T_BYTE && adr_type->isa_aryptr()) {
2257 // Alias type doesn't differentiate between byte[] and boolean[]).
2258 // Use address type to get the element type.
2259 bt = adr_type->is_aryptr()->elem()->array_element_basic_type();
2260 }
2261 if (bt == T_ARRAY || bt == T_NARROWOOP) {
2262 // accessing an array field with getReference is not a mismatch
2263 bt = T_OBJECT;
2264 }
2265 if ((bt == T_OBJECT) != (type == T_OBJECT)) {
2266 // Don't intrinsify mismatched object accesses
2267 return false;
2268 }
2269 mismatched = (bt != type);
2270 } else if (alias_type->adr_type()->isa_oopptr()) {
2271 mismatched = true; // conservatively mark all "wide" on-heap accesses as mismatched
2272 }
2273
2274 assert(!mismatched || alias_type->adr_type()->is_oopptr(), "off-heap access can't be mismatched");
2275
2276 if (mismatched) {
2277 decorators |= C2_MISMATCHED;
2278 }
2279
2280 // First guess at the value type.
2281 const Type *value_type = Type::get_const_basic_type(type);
2282
2283 // Figure out the memory ordering.
2284 decorators |= mo_decorator_for_access_kind(kind);
2285
2286 if (!is_store && type == T_OBJECT) {
2287 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2288 if (tjp != NULL) {
2289 value_type = tjp;
2290 }
2291 }
2292
2293 receiver = null_check(receiver);
2294 if (stopped()) {
2295 return true;
2296 }
2297 // Heap pointers get a null-check from the interpreter,
2298 // as a courtesy. However, this is not guaranteed by Unsafe,
2299 // and it is not possible to fully distinguish unintended nulls
2300 // from intended ones in this API.
2301
2302 if (!is_store) {
2303 Node* p = NULL;
2304 // Try to constant fold a load from a constant field
2305 ciField* field = alias_type->field();
2306 if (heap_base_oop != top() && field != NULL && field->is_constant() && !mismatched) {
2307 // final or stable field
2308 p = make_constant_from_field(field, heap_base_oop);
2309 }
2310
2311 if (p == NULL) { // Could not constant fold the load
2312 p = access_load_at(heap_base_oop, adr, adr_type, value_type, type, decorators);
2313 // Normalize the value returned by getBoolean in the following cases
2314 if (type == T_BOOLEAN &&
2315 (mismatched ||
2316 heap_base_oop == top() || // - heap_base_oop is NULL or
2317 (can_access_non_heap && field == NULL)) // - heap_base_oop is potentially NULL
2318 // and the unsafe access is made to large offset
2319 // (i.e., larger than the maximum offset necessary for any
2320 // field access)
2321 ) {
2322 IdealKit ideal = IdealKit(this);
2323 #define __ ideal.
2324 IdealVariable normalized_result(ideal);
2325 __ declarations_done();
2326 __ set(normalized_result, p);
2327 __ if_then(p, BoolTest::ne, ideal.ConI(0));
2328 __ set(normalized_result, ideal.ConI(1));
2329 ideal.end_if();
2330 final_sync(ideal);
2331 p = __ value(normalized_result);
2332 #undef __
2333 }
2334 }
2335 if (type == T_ADDRESS) {
2336 p = gvn().transform(new CastP2XNode(NULL, p));
2337 p = ConvX2UL(p);
2338 }
2339 // The load node has the control of the preceding MemBarCPUOrder. All
2340 // following nodes will have the control of the MemBarCPUOrder inserted at
2341 // the end of this method. So, pushing the load onto the stack at a later
2342 // point is fine.
2343 set_result(p);
2344 } else {
2345 if (bt == T_ADDRESS) {
2346 // Repackage the long as a pointer.
2347 val = ConvL2X(val);
2348 val = gvn().transform(new CastX2PNode(val));
2349 }
2350 access_store_at(heap_base_oop, adr, adr_type, val, value_type, type, decorators);
2351 }
2352
2353 return true;
2354 }
2355
2356 //----------------------------inline_unsafe_load_store----------------------------
2357 // This method serves a couple of different customers (depending on LoadStoreKind):
2358 //
2359 // LS_cmp_swap:
2360 //
2361 // boolean compareAndSetReference(Object o, long offset, Object expected, Object x);
2362 // boolean compareAndSetInt( Object o, long offset, int expected, int x);
2363 // boolean compareAndSetLong( Object o, long offset, long expected, long x);
2364 //
2365 // LS_cmp_swap_weak:
2366 //
2367 // boolean weakCompareAndSetReference( Object o, long offset, Object expected, Object x);
2368 // boolean weakCompareAndSetReferencePlain( Object o, long offset, Object expected, Object x);
2369 // boolean weakCompareAndSetReferenceAcquire(Object o, long offset, Object expected, Object x);
2370 // boolean weakCompareAndSetReferenceRelease(Object o, long offset, Object expected, Object x);
2371 //
2372 // boolean weakCompareAndSetInt( Object o, long offset, int expected, int x);
2373 // boolean weakCompareAndSetIntPlain( Object o, long offset, int expected, int x);
2374 // boolean weakCompareAndSetIntAcquire( Object o, long offset, int expected, int x);
2375 // boolean weakCompareAndSetIntRelease( Object o, long offset, int expected, int x);
2376 //
2377 // boolean weakCompareAndSetLong( Object o, long offset, long expected, long x);
2378 // boolean weakCompareAndSetLongPlain( Object o, long offset, long expected, long x);
2379 // boolean weakCompareAndSetLongAcquire( Object o, long offset, long expected, long x);
2380 // boolean weakCompareAndSetLongRelease( Object o, long offset, long expected, long x);
2381 //
2382 // LS_cmp_exchange:
2383 //
2384 // Object compareAndExchangeReferenceVolatile(Object o, long offset, Object expected, Object x);
2385 // Object compareAndExchangeReferenceAcquire( Object o, long offset, Object expected, Object x);
2386 // Object compareAndExchangeReferenceRelease( Object o, long offset, Object expected, Object x);
2387 //
2388 // Object compareAndExchangeIntVolatile( Object o, long offset, Object expected, Object x);
2389 // Object compareAndExchangeIntAcquire( Object o, long offset, Object expected, Object x);
2390 // Object compareAndExchangeIntRelease( Object o, long offset, Object expected, Object x);
2391 //
2392 // Object compareAndExchangeLongVolatile( Object o, long offset, Object expected, Object x);
2393 // Object compareAndExchangeLongAcquire( Object o, long offset, Object expected, Object x);
2394 // Object compareAndExchangeLongRelease( Object o, long offset, Object expected, Object x);
2395 //
2396 // LS_get_add:
2397 //
2398 // int getAndAddInt( Object o, long offset, int delta)
2399 // long getAndAddLong(Object o, long offset, long delta)
2400 //
2401 // LS_get_set:
2402 //
2403 // int getAndSet(Object o, long offset, int newValue)
2404 // long getAndSet(Object o, long offset, long newValue)
2405 // Object getAndSet(Object o, long offset, Object newValue)
2406 //
inline_unsafe_load_store(const BasicType type,const LoadStoreKind kind,const AccessKind access_kind)2407 bool LibraryCallKit::inline_unsafe_load_store(const BasicType type, const LoadStoreKind kind, const AccessKind access_kind) {
2408 // This basic scheme here is the same as inline_unsafe_access, but
2409 // differs in enough details that combining them would make the code
2410 // overly confusing. (This is a true fact! I originally combined
2411 // them, but even I was confused by it!) As much code/comments as
2412 // possible are retained from inline_unsafe_access though to make
2413 // the correspondences clearer. - dl
2414
2415 if (callee()->is_static()) return false; // caller must have the capability!
2416
2417 DecoratorSet decorators = C2_UNSAFE_ACCESS;
2418 decorators |= mo_decorator_for_access_kind(access_kind);
2419
2420 #ifndef PRODUCT
2421 BasicType rtype;
2422 {
2423 ResourceMark rm;
2424 // Check the signatures.
2425 ciSignature* sig = callee()->signature();
2426 rtype = sig->return_type()->basic_type();
2427 switch(kind) {
2428 case LS_get_add:
2429 case LS_get_set: {
2430 // Check the signatures.
2431 #ifdef ASSERT
2432 assert(rtype == type, "get and set must return the expected type");
2433 assert(sig->count() == 3, "get and set has 3 arguments");
2434 assert(sig->type_at(0)->basic_type() == T_OBJECT, "get and set base is object");
2435 assert(sig->type_at(1)->basic_type() == T_LONG, "get and set offset is long");
2436 assert(sig->type_at(2)->basic_type() == type, "get and set must take expected type as new value/delta");
2437 assert(access_kind == Volatile, "mo is not passed to intrinsic nodes in current implementation");
2438 #endif // ASSERT
2439 break;
2440 }
2441 case LS_cmp_swap:
2442 case LS_cmp_swap_weak: {
2443 // Check the signatures.
2444 #ifdef ASSERT
2445 assert(rtype == T_BOOLEAN, "CAS must return boolean");
2446 assert(sig->count() == 4, "CAS has 4 arguments");
2447 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2448 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2449 #endif // ASSERT
2450 break;
2451 }
2452 case LS_cmp_exchange: {
2453 // Check the signatures.
2454 #ifdef ASSERT
2455 assert(rtype == type, "CAS must return the expected type");
2456 assert(sig->count() == 4, "CAS has 4 arguments");
2457 assert(sig->type_at(0)->basic_type() == T_OBJECT, "CAS base is object");
2458 assert(sig->type_at(1)->basic_type() == T_LONG, "CAS offset is long");
2459 #endif // ASSERT
2460 break;
2461 }
2462 default:
2463 ShouldNotReachHere();
2464 }
2465 }
2466 #endif //PRODUCT
2467
2468 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
2469
2470 // Get arguments:
2471 Node* receiver = NULL;
2472 Node* base = NULL;
2473 Node* offset = NULL;
2474 Node* oldval = NULL;
2475 Node* newval = NULL;
2476 switch(kind) {
2477 case LS_cmp_swap:
2478 case LS_cmp_swap_weak:
2479 case LS_cmp_exchange: {
2480 const bool two_slot_type = type2size[type] == 2;
2481 receiver = argument(0); // type: oop
2482 base = argument(1); // type: oop
2483 offset = argument(2); // type: long
2484 oldval = argument(4); // type: oop, int, or long
2485 newval = argument(two_slot_type ? 6 : 5); // type: oop, int, or long
2486 break;
2487 }
2488 case LS_get_add:
2489 case LS_get_set: {
2490 receiver = argument(0); // type: oop
2491 base = argument(1); // type: oop
2492 offset = argument(2); // type: long
2493 oldval = NULL;
2494 newval = argument(4); // type: oop, int, or long
2495 break;
2496 }
2497 default:
2498 ShouldNotReachHere();
2499 }
2500
2501 // Build field offset expression.
2502 // We currently rely on the cookies produced by Unsafe.xxxFieldOffset
2503 // to be plain byte offsets, which are also the same as those accepted
2504 // by oopDesc::field_addr.
2505 assert(Unsafe_field_offset_to_byte_offset(11) == 11, "fieldOffset must be byte-scaled");
2506 // 32-bit machines ignore the high half of long offsets
2507 offset = ConvL2X(offset);
2508 Node* adr = make_unsafe_address(base, offset, ACCESS_WRITE | ACCESS_READ, type, false);
2509 const TypePtr *adr_type = _gvn.type(adr)->isa_ptr();
2510
2511 Compile::AliasType* alias_type = C->alias_type(adr_type);
2512 BasicType bt = alias_type->basic_type();
2513 if (bt != T_ILLEGAL &&
2514 (is_reference_type(bt) != (type == T_OBJECT))) {
2515 // Don't intrinsify mismatched object accesses.
2516 return false;
2517 }
2518
2519 // For CAS, unlike inline_unsafe_access, there seems no point in
2520 // trying to refine types. Just use the coarse types here.
2521 assert(alias_type->index() != Compile::AliasIdxBot, "no bare pointers here");
2522 const Type *value_type = Type::get_const_basic_type(type);
2523
2524 switch (kind) {
2525 case LS_get_set:
2526 case LS_cmp_exchange: {
2527 if (type == T_OBJECT) {
2528 const TypeOopPtr* tjp = sharpen_unsafe_type(alias_type, adr_type);
2529 if (tjp != NULL) {
2530 value_type = tjp;
2531 }
2532 }
2533 break;
2534 }
2535 case LS_cmp_swap:
2536 case LS_cmp_swap_weak:
2537 case LS_get_add:
2538 break;
2539 default:
2540 ShouldNotReachHere();
2541 }
2542
2543 // Null check receiver.
2544 receiver = null_check(receiver);
2545 if (stopped()) {
2546 return true;
2547 }
2548
2549 int alias_idx = C->get_alias_index(adr_type);
2550
2551 if (is_reference_type(type)) {
2552 decorators |= IN_HEAP | ON_UNKNOWN_OOP_REF;
2553
2554 // Transformation of a value which could be NULL pointer (CastPP #NULL)
2555 // could be delayed during Parse (for example, in adjust_map_after_if()).
2556 // Execute transformation here to avoid barrier generation in such case.
2557 if (_gvn.type(newval) == TypePtr::NULL_PTR)
2558 newval = _gvn.makecon(TypePtr::NULL_PTR);
2559
2560 if (oldval != NULL && _gvn.type(oldval) == TypePtr::NULL_PTR) {
2561 // Refine the value to a null constant, when it is known to be null
2562 oldval = _gvn.makecon(TypePtr::NULL_PTR);
2563 }
2564 }
2565
2566 Node* result = NULL;
2567 switch (kind) {
2568 case LS_cmp_exchange: {
2569 result = access_atomic_cmpxchg_val_at(base, adr, adr_type, alias_idx,
2570 oldval, newval, value_type, type, decorators);
2571 break;
2572 }
2573 case LS_cmp_swap_weak:
2574 decorators |= C2_WEAK_CMPXCHG;
2575 case LS_cmp_swap: {
2576 result = access_atomic_cmpxchg_bool_at(base, adr, adr_type, alias_idx,
2577 oldval, newval, value_type, type, decorators);
2578 break;
2579 }
2580 case LS_get_set: {
2581 result = access_atomic_xchg_at(base, adr, adr_type, alias_idx,
2582 newval, value_type, type, decorators);
2583 break;
2584 }
2585 case LS_get_add: {
2586 result = access_atomic_add_at(base, adr, adr_type, alias_idx,
2587 newval, value_type, type, decorators);
2588 break;
2589 }
2590 default:
2591 ShouldNotReachHere();
2592 }
2593
2594 assert(type2size[result->bottom_type()->basic_type()] == type2size[rtype], "result type should match");
2595 set_result(result);
2596 return true;
2597 }
2598
inline_unsafe_fence(vmIntrinsics::ID id)2599 bool LibraryCallKit::inline_unsafe_fence(vmIntrinsics::ID id) {
2600 // Regardless of form, don't allow previous ld/st to move down,
2601 // then issue acquire, release, or volatile mem_bar.
2602 insert_mem_bar(Op_MemBarCPUOrder);
2603 switch(id) {
2604 case vmIntrinsics::_loadFence:
2605 insert_mem_bar(Op_LoadFence);
2606 return true;
2607 case vmIntrinsics::_storeFence:
2608 insert_mem_bar(Op_StoreFence);
2609 return true;
2610 case vmIntrinsics::_fullFence:
2611 insert_mem_bar(Op_MemBarVolatile);
2612 return true;
2613 default:
2614 fatal_unexpected_iid(id);
2615 return false;
2616 }
2617 }
2618
inline_onspinwait()2619 bool LibraryCallKit::inline_onspinwait() {
2620 insert_mem_bar(Op_OnSpinWait);
2621 return true;
2622 }
2623
klass_needs_init_guard(Node * kls)2624 bool LibraryCallKit::klass_needs_init_guard(Node* kls) {
2625 if (!kls->is_Con()) {
2626 return true;
2627 }
2628 const TypeKlassPtr* klsptr = kls->bottom_type()->isa_klassptr();
2629 if (klsptr == NULL) {
2630 return true;
2631 }
2632 ciInstanceKlass* ik = klsptr->klass()->as_instance_klass();
2633 // don't need a guard for a klass that is already initialized
2634 return !ik->is_initialized();
2635 }
2636
2637 //----------------------------inline_unsafe_writeback0-------------------------
2638 // public native void Unsafe.writeback0(long address)
inline_unsafe_writeback0()2639 bool LibraryCallKit::inline_unsafe_writeback0() {
2640 if (!Matcher::has_match_rule(Op_CacheWB)) {
2641 return false;
2642 }
2643 #ifndef PRODUCT
2644 assert(Matcher::has_match_rule(Op_CacheWBPreSync), "found match rule for CacheWB but not CacheWBPreSync");
2645 assert(Matcher::has_match_rule(Op_CacheWBPostSync), "found match rule for CacheWB but not CacheWBPostSync");
2646 ciSignature* sig = callee()->signature();
2647 assert(sig->type_at(0)->basic_type() == T_LONG, "Unsafe_writeback0 address is long!");
2648 #endif
2649 null_check_receiver(); // null-check, then ignore
2650 Node *addr = argument(1);
2651 addr = new CastX2PNode(addr);
2652 addr = _gvn.transform(addr);
2653 Node *flush = new CacheWBNode(control(), memory(TypeRawPtr::BOTTOM), addr);
2654 flush = _gvn.transform(flush);
2655 set_memory(flush, TypeRawPtr::BOTTOM);
2656 return true;
2657 }
2658
2659 //----------------------------inline_unsafe_writeback0-------------------------
2660 // public native void Unsafe.writeback0(long address)
inline_unsafe_writebackSync0(bool is_pre)2661 bool LibraryCallKit::inline_unsafe_writebackSync0(bool is_pre) {
2662 if (is_pre && !Matcher::has_match_rule(Op_CacheWBPreSync)) {
2663 return false;
2664 }
2665 if (!is_pre && !Matcher::has_match_rule(Op_CacheWBPostSync)) {
2666 return false;
2667 }
2668 #ifndef PRODUCT
2669 assert(Matcher::has_match_rule(Op_CacheWB),
2670 (is_pre ? "found match rule for CacheWBPreSync but not CacheWB"
2671 : "found match rule for CacheWBPostSync but not CacheWB"));
2672
2673 #endif
2674 null_check_receiver(); // null-check, then ignore
2675 Node *sync;
2676 if (is_pre) {
2677 sync = new CacheWBPreSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2678 } else {
2679 sync = new CacheWBPostSyncNode(control(), memory(TypeRawPtr::BOTTOM));
2680 }
2681 sync = _gvn.transform(sync);
2682 set_memory(sync, TypeRawPtr::BOTTOM);
2683 return true;
2684 }
2685
2686 //----------------------------inline_unsafe_allocate---------------------------
2687 // public native Object Unsafe.allocateInstance(Class<?> cls);
inline_unsafe_allocate()2688 bool LibraryCallKit::inline_unsafe_allocate() {
2689 if (callee()->is_static()) return false; // caller must have the capability!
2690
2691 null_check_receiver(); // null-check, then ignore
2692 Node* cls = null_check(argument(1));
2693 if (stopped()) return true;
2694
2695 Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
2696 kls = null_check(kls);
2697 if (stopped()) return true; // argument was like int.class
2698
2699 Node* test = NULL;
2700 if (LibraryCallKit::klass_needs_init_guard(kls)) {
2701 // Note: The argument might still be an illegal value like
2702 // Serializable.class or Object[].class. The runtime will handle it.
2703 // But we must make an explicit check for initialization.
2704 Node* insp = basic_plus_adr(kls, in_bytes(InstanceKlass::init_state_offset()));
2705 // Use T_BOOLEAN for InstanceKlass::_init_state so the compiler
2706 // can generate code to load it as unsigned byte.
2707 Node* inst = make_load(NULL, insp, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
2708 Node* bits = intcon(InstanceKlass::fully_initialized);
2709 test = _gvn.transform(new SubINode(inst, bits));
2710 // The 'test' is non-zero if we need to take a slow path.
2711 }
2712
2713 Node* obj = new_instance(kls, test);
2714 set_result(obj);
2715 return true;
2716 }
2717
2718 //------------------------inline_native_time_funcs--------------
2719 // inline code for System.currentTimeMillis() and System.nanoTime()
2720 // these have the same type and signature
inline_native_time_funcs(address funcAddr,const char * funcName)2721 bool LibraryCallKit::inline_native_time_funcs(address funcAddr, const char* funcName) {
2722 const TypeFunc* tf = OptoRuntime::void_long_Type();
2723 const TypePtr* no_memory_effects = NULL;
2724 Node* time = make_runtime_call(RC_LEAF, tf, funcAddr, funcName, no_memory_effects);
2725 Node* value = _gvn.transform(new ProjNode(time, TypeFunc::Parms+0));
2726 #ifdef ASSERT
2727 Node* value_top = _gvn.transform(new ProjNode(time, TypeFunc::Parms+1));
2728 assert(value_top == top(), "second value must be top");
2729 #endif
2730 set_result(value);
2731 return true;
2732 }
2733
2734 #ifdef JFR_HAVE_INTRINSICS
2735
2736 /*
2737 * oop -> myklass
2738 * myklass->trace_id |= USED
2739 * return myklass->trace_id & ~0x3
2740 */
inline_native_classID()2741 bool LibraryCallKit::inline_native_classID() {
2742 Node* cls = null_check(argument(0), T_OBJECT);
2743 Node* kls = load_klass_from_mirror(cls, false, NULL, 0);
2744 kls = null_check(kls, T_OBJECT);
2745
2746 ByteSize offset = KLASS_TRACE_ID_OFFSET;
2747 Node* insp = basic_plus_adr(kls, in_bytes(offset));
2748 Node* tvalue = make_load(NULL, insp, TypeLong::LONG, T_LONG, MemNode::unordered);
2749
2750 Node* clsused = longcon(0x01l); // set the class bit
2751 Node* orl = _gvn.transform(new OrLNode(tvalue, clsused));
2752 const TypePtr *adr_type = _gvn.type(insp)->isa_ptr();
2753 store_to_memory(control(), insp, orl, T_LONG, adr_type, MemNode::unordered);
2754
2755 #ifdef TRACE_ID_META_BITS
2756 Node* mbits = longcon(~TRACE_ID_META_BITS);
2757 tvalue = _gvn.transform(new AndLNode(tvalue, mbits));
2758 #endif
2759 #ifdef TRACE_ID_SHIFT
2760 Node* cbits = intcon(TRACE_ID_SHIFT);
2761 tvalue = _gvn.transform(new URShiftLNode(tvalue, cbits));
2762 #endif
2763
2764 set_result(tvalue);
2765 return true;
2766
2767 }
2768
inline_native_getEventWriter()2769 bool LibraryCallKit::inline_native_getEventWriter() {
2770 Node* tls_ptr = _gvn.transform(new ThreadLocalNode());
2771
2772 Node* jobj_ptr = basic_plus_adr(top(), tls_ptr,
2773 in_bytes(THREAD_LOCAL_WRITER_OFFSET_JFR));
2774
2775 Node* jobj = make_load(control(), jobj_ptr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
2776
2777 Node* jobj_cmp_null = _gvn.transform( new CmpPNode(jobj, null()) );
2778 Node* test_jobj_eq_null = _gvn.transform( new BoolNode(jobj_cmp_null, BoolTest::eq) );
2779
2780 IfNode* iff_jobj_null =
2781 create_and_map_if(control(), test_jobj_eq_null, PROB_MIN, COUNT_UNKNOWN);
2782
2783 enum { _normal_path = 1,
2784 _null_path = 2,
2785 PATH_LIMIT };
2786
2787 RegionNode* result_rgn = new RegionNode(PATH_LIMIT);
2788 PhiNode* result_val = new PhiNode(result_rgn, TypeInstPtr::BOTTOM);
2789
2790 Node* jobj_is_null = _gvn.transform(new IfTrueNode(iff_jobj_null));
2791 result_rgn->init_req(_null_path, jobj_is_null);
2792 result_val->init_req(_null_path, null());
2793
2794 Node* jobj_is_not_null = _gvn.transform(new IfFalseNode(iff_jobj_null));
2795 set_control(jobj_is_not_null);
2796 Node* res = access_load(jobj, TypeInstPtr::NOTNULL, T_OBJECT,
2797 IN_NATIVE | C2_CONTROL_DEPENDENT_LOAD);
2798 result_rgn->init_req(_normal_path, control());
2799 result_val->init_req(_normal_path, res);
2800
2801 set_result(result_rgn, result_val);
2802
2803 return true;
2804 }
2805
2806 #endif // JFR_HAVE_INTRINSICS
2807
2808 //------------------------inline_native_currentThread------------------
inline_native_currentThread()2809 bool LibraryCallKit::inline_native_currentThread() {
2810 Node* junk = NULL;
2811 set_result(generate_current_thread(junk));
2812 return true;
2813 }
2814
2815 //---------------------------load_mirror_from_klass----------------------------
2816 // Given a klass oop, load its java mirror (a java.lang.Class oop).
load_mirror_from_klass(Node * klass)2817 Node* LibraryCallKit::load_mirror_from_klass(Node* klass) {
2818 Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
2819 Node* load = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
2820 // mirror = ((OopHandle)mirror)->resolve();
2821 return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
2822 }
2823
2824 //-----------------------load_klass_from_mirror_common-------------------------
2825 // Given a java mirror (a java.lang.Class oop), load its corresponding klass oop.
2826 // Test the klass oop for null (signifying a primitive Class like Integer.TYPE),
2827 // and branch to the given path on the region.
2828 // If never_see_null, take an uncommon trap on null, so we can optimistically
2829 // compile for the non-null case.
2830 // If the region is NULL, force never_see_null = true.
load_klass_from_mirror_common(Node * mirror,bool never_see_null,RegionNode * region,int null_path,int offset)2831 Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror,
2832 bool never_see_null,
2833 RegionNode* region,
2834 int null_path,
2835 int offset) {
2836 if (region == NULL) never_see_null = true;
2837 Node* p = basic_plus_adr(mirror, offset);
2838 const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
2839 Node* kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type));
2840 Node* null_ctl = top();
2841 kls = null_check_oop(kls, &null_ctl, never_see_null);
2842 if (region != NULL) {
2843 // Set region->in(null_path) if the mirror is a primitive (e.g, int.class).
2844 region->init_req(null_path, null_ctl);
2845 } else {
2846 assert(null_ctl == top(), "no loose ends");
2847 }
2848 return kls;
2849 }
2850
2851 //--------------------(inline_native_Class_query helpers)---------------------
2852 // Use this for JVM_ACC_INTERFACE, JVM_ACC_IS_CLONEABLE_FAST, JVM_ACC_HAS_FINALIZER.
2853 // Fall through if (mods & mask) == bits, take the guard otherwise.
generate_access_flags_guard(Node * kls,int modifier_mask,int modifier_bits,RegionNode * region)2854 Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, int modifier_bits, RegionNode* region) {
2855 // Branch around if the given klass has the given modifier bit set.
2856 // Like generate_guard, adds a new path onto the region.
2857 Node* modp = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
2858 Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT, MemNode::unordered);
2859 Node* mask = intcon(modifier_mask);
2860 Node* bits = intcon(modifier_bits);
2861 Node* mbit = _gvn.transform(new AndINode(mods, mask));
2862 Node* cmp = _gvn.transform(new CmpINode(mbit, bits));
2863 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
2864 return generate_fair_guard(bol, region);
2865 }
generate_interface_guard(Node * kls,RegionNode * region)2866 Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) {
2867 return generate_access_flags_guard(kls, JVM_ACC_INTERFACE, 0, region);
2868 }
generate_hidden_class_guard(Node * kls,RegionNode * region)2869 Node* LibraryCallKit::generate_hidden_class_guard(Node* kls, RegionNode* region) {
2870 return generate_access_flags_guard(kls, JVM_ACC_IS_HIDDEN_CLASS, 0, region);
2871 }
2872
2873 //-------------------------inline_native_Class_query-------------------
inline_native_Class_query(vmIntrinsics::ID id)2874 bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) {
2875 const Type* return_type = TypeInt::BOOL;
2876 Node* prim_return_value = top(); // what happens if it's a primitive class?
2877 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
2878 bool expect_prim = false; // most of these guys expect to work on refs
2879
2880 enum { _normal_path = 1, _prim_path = 2, PATH_LIMIT };
2881
2882 Node* mirror = argument(0);
2883 Node* obj = top();
2884
2885 switch (id) {
2886 case vmIntrinsics::_isInstance:
2887 // nothing is an instance of a primitive type
2888 prim_return_value = intcon(0);
2889 obj = argument(1);
2890 break;
2891 case vmIntrinsics::_getModifiers:
2892 prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2893 assert(is_power_of_2((int)JVM_ACC_WRITTEN_FLAGS+1), "change next line");
2894 return_type = TypeInt::make(0, JVM_ACC_WRITTEN_FLAGS, Type::WidenMin);
2895 break;
2896 case vmIntrinsics::_isInterface:
2897 prim_return_value = intcon(0);
2898 break;
2899 case vmIntrinsics::_isArray:
2900 prim_return_value = intcon(0);
2901 expect_prim = true; // cf. ObjectStreamClass.getClassSignature
2902 break;
2903 case vmIntrinsics::_isPrimitive:
2904 prim_return_value = intcon(1);
2905 expect_prim = true; // obviously
2906 break;
2907 case vmIntrinsics::_isHidden:
2908 prim_return_value = intcon(0);
2909 break;
2910 case vmIntrinsics::_getSuperclass:
2911 prim_return_value = null();
2912 return_type = TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR);
2913 break;
2914 case vmIntrinsics::_getClassAccessFlags:
2915 prim_return_value = intcon(JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2916 return_type = TypeInt::INT; // not bool! 6297094
2917 break;
2918 default:
2919 fatal_unexpected_iid(id);
2920 break;
2921 }
2922
2923 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
2924 if (mirror_con == NULL) return false; // cannot happen?
2925
2926 #ifndef PRODUCT
2927 if (C->print_intrinsics() || C->print_inlining()) {
2928 ciType* k = mirror_con->java_mirror_type();
2929 if (k) {
2930 tty->print("Inlining %s on constant Class ", vmIntrinsics::name_at(intrinsic_id()));
2931 k->print_name();
2932 tty->cr();
2933 }
2934 }
2935 #endif
2936
2937 // Null-check the mirror, and the mirror's klass ptr (in case it is a primitive).
2938 RegionNode* region = new RegionNode(PATH_LIMIT);
2939 record_for_igvn(region);
2940 PhiNode* phi = new PhiNode(region, return_type);
2941
2942 // The mirror will never be null of Reflection.getClassAccessFlags, however
2943 // it may be null for Class.isInstance or Class.getModifiers. Throw a NPE
2944 // if it is. See bug 4774291.
2945
2946 // For Reflection.getClassAccessFlags(), the null check occurs in
2947 // the wrong place; see inline_unsafe_access(), above, for a similar
2948 // situation.
2949 mirror = null_check(mirror);
2950 // If mirror or obj is dead, only null-path is taken.
2951 if (stopped()) return true;
2952
2953 if (expect_prim) never_see_null = false; // expect nulls (meaning prims)
2954
2955 // Now load the mirror's klass metaobject, and null-check it.
2956 // Side-effects region with the control path if the klass is null.
2957 Node* kls = load_klass_from_mirror(mirror, never_see_null, region, _prim_path);
2958 // If kls is null, we have a primitive mirror.
2959 phi->init_req(_prim_path, prim_return_value);
2960 if (stopped()) { set_result(region, phi); return true; }
2961 bool safe_for_replace = (region->in(_prim_path) == top());
2962
2963 Node* p; // handy temp
2964 Node* null_ctl;
2965
2966 // Now that we have the non-null klass, we can perform the real query.
2967 // For constant classes, the query will constant-fold in LoadNode::Value.
2968 Node* query_value = top();
2969 switch (id) {
2970 case vmIntrinsics::_isInstance:
2971 // nothing is an instance of a primitive type
2972 query_value = gen_instanceof(obj, kls, safe_for_replace);
2973 break;
2974
2975 case vmIntrinsics::_getModifiers:
2976 p = basic_plus_adr(kls, in_bytes(Klass::modifier_flags_offset()));
2977 query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
2978 break;
2979
2980 case vmIntrinsics::_isInterface:
2981 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
2982 if (generate_interface_guard(kls, region) != NULL)
2983 // A guard was added. If the guard is taken, it was an interface.
2984 phi->add_req(intcon(1));
2985 // If we fall through, it's a plain class.
2986 query_value = intcon(0);
2987 break;
2988
2989 case vmIntrinsics::_isArray:
2990 // (To verify this code sequence, check the asserts in JVM_IsArrayClass.)
2991 if (generate_array_guard(kls, region) != NULL)
2992 // A guard was added. If the guard is taken, it was an array.
2993 phi->add_req(intcon(1));
2994 // If we fall through, it's a plain class.
2995 query_value = intcon(0);
2996 break;
2997
2998 case vmIntrinsics::_isPrimitive:
2999 query_value = intcon(0); // "normal" path produces false
3000 break;
3001
3002 case vmIntrinsics::_isHidden:
3003 // (To verify this code sequence, check the asserts in JVM_IsHiddenClass.)
3004 if (generate_hidden_class_guard(kls, region) != NULL)
3005 // A guard was added. If the guard is taken, it was an hidden class.
3006 phi->add_req(intcon(1));
3007 // If we fall through, it's a plain class.
3008 query_value = intcon(0);
3009 break;
3010
3011
3012 case vmIntrinsics::_getSuperclass:
3013 // The rules here are somewhat unfortunate, but we can still do better
3014 // with random logic than with a JNI call.
3015 // Interfaces store null or Object as _super, but must report null.
3016 // Arrays store an intermediate super as _super, but must report Object.
3017 // Other types can report the actual _super.
3018 // (To verify this code sequence, check the asserts in JVM_IsInterface.)
3019 if (generate_interface_guard(kls, region) != NULL)
3020 // A guard was added. If the guard is taken, it was an interface.
3021 phi->add_req(null());
3022 if (generate_array_guard(kls, region) != NULL)
3023 // A guard was added. If the guard is taken, it was an array.
3024 phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror())));
3025 // If we fall through, it's a plain class. Get its _super.
3026 p = basic_plus_adr(kls, in_bytes(Klass::super_offset()));
3027 kls = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL));
3028 null_ctl = top();
3029 kls = null_check_oop(kls, &null_ctl);
3030 if (null_ctl != top()) {
3031 // If the guard is taken, Object.superClass is null (both klass and mirror).
3032 region->add_req(null_ctl);
3033 phi ->add_req(null());
3034 }
3035 if (!stopped()) {
3036 query_value = load_mirror_from_klass(kls);
3037 }
3038 break;
3039
3040 case vmIntrinsics::_getClassAccessFlags:
3041 p = basic_plus_adr(kls, in_bytes(Klass::access_flags_offset()));
3042 query_value = make_load(NULL, p, TypeInt::INT, T_INT, MemNode::unordered);
3043 break;
3044
3045 default:
3046 fatal_unexpected_iid(id);
3047 break;
3048 }
3049
3050 // Fall-through is the normal case of a query to a real class.
3051 phi->init_req(1, query_value);
3052 region->init_req(1, control());
3053
3054 C->set_has_split_ifs(true); // Has chance for split-if optimization
3055 set_result(region, phi);
3056 return true;
3057 }
3058
3059 //-------------------------inline_Class_cast-------------------
inline_Class_cast()3060 bool LibraryCallKit::inline_Class_cast() {
3061 Node* mirror = argument(0); // Class
3062 Node* obj = argument(1);
3063 const TypeInstPtr* mirror_con = _gvn.type(mirror)->isa_instptr();
3064 if (mirror_con == NULL) {
3065 return false; // dead path (mirror->is_top()).
3066 }
3067 if (obj == NULL || obj->is_top()) {
3068 return false; // dead path
3069 }
3070 const TypeOopPtr* tp = _gvn.type(obj)->isa_oopptr();
3071
3072 // First, see if Class.cast() can be folded statically.
3073 // java_mirror_type() returns non-null for compile-time Class constants.
3074 ciType* tm = mirror_con->java_mirror_type();
3075 if (tm != NULL && tm->is_klass() &&
3076 tp != NULL && tp->klass() != NULL) {
3077 if (!tp->klass()->is_loaded()) {
3078 // Don't use intrinsic when class is not loaded.
3079 return false;
3080 } else {
3081 int static_res = C->static_subtype_check(tm->as_klass(), tp->klass());
3082 if (static_res == Compile::SSC_always_true) {
3083 // isInstance() is true - fold the code.
3084 set_result(obj);
3085 return true;
3086 } else if (static_res == Compile::SSC_always_false) {
3087 // Don't use intrinsic, have to throw ClassCastException.
3088 // If the reference is null, the non-intrinsic bytecode will
3089 // be optimized appropriately.
3090 return false;
3091 }
3092 }
3093 }
3094
3095 // Bailout intrinsic and do normal inlining if exception path is frequent.
3096 if (too_many_traps(Deoptimization::Reason_intrinsic)) {
3097 return false;
3098 }
3099
3100 // Generate dynamic checks.
3101 // Class.cast() is java implementation of _checkcast bytecode.
3102 // Do checkcast (Parse::do_checkcast()) optimizations here.
3103
3104 mirror = null_check(mirror);
3105 // If mirror is dead, only null-path is taken.
3106 if (stopped()) {
3107 return true;
3108 }
3109
3110 // Not-subtype or the mirror's klass ptr is NULL (in case it is a primitive).
3111 enum { _bad_type_path = 1, _prim_path = 2, PATH_LIMIT };
3112 RegionNode* region = new RegionNode(PATH_LIMIT);
3113 record_for_igvn(region);
3114
3115 // Now load the mirror's klass metaobject, and null-check it.
3116 // If kls is null, we have a primitive mirror and
3117 // nothing is an instance of a primitive type.
3118 Node* kls = load_klass_from_mirror(mirror, false, region, _prim_path);
3119
3120 Node* res = top();
3121 if (!stopped()) {
3122 Node* bad_type_ctrl = top();
3123 // Do checkcast optimizations.
3124 res = gen_checkcast(obj, kls, &bad_type_ctrl);
3125 region->init_req(_bad_type_path, bad_type_ctrl);
3126 }
3127 if (region->in(_prim_path) != top() ||
3128 region->in(_bad_type_path) != top()) {
3129 // Let Interpreter throw ClassCastException.
3130 PreserveJVMState pjvms(this);
3131 set_control(_gvn.transform(region));
3132 uncommon_trap(Deoptimization::Reason_intrinsic,
3133 Deoptimization::Action_maybe_recompile);
3134 }
3135 if (!stopped()) {
3136 set_result(res);
3137 }
3138 return true;
3139 }
3140
3141
3142 //--------------------------inline_native_subtype_check------------------------
3143 // This intrinsic takes the JNI calls out of the heart of
3144 // UnsafeFieldAccessorImpl.set, which improves Field.set, readObject, etc.
inline_native_subtype_check()3145 bool LibraryCallKit::inline_native_subtype_check() {
3146 // Pull both arguments off the stack.
3147 Node* args[2]; // two java.lang.Class mirrors: superc, subc
3148 args[0] = argument(0);
3149 args[1] = argument(1);
3150 Node* klasses[2]; // corresponding Klasses: superk, subk
3151 klasses[0] = klasses[1] = top();
3152
3153 enum {
3154 // A full decision tree on {superc is prim, subc is prim}:
3155 _prim_0_path = 1, // {P,N} => false
3156 // {P,P} & superc!=subc => false
3157 _prim_same_path, // {P,P} & superc==subc => true
3158 _prim_1_path, // {N,P} => false
3159 _ref_subtype_path, // {N,N} & subtype check wins => true
3160 _both_ref_path, // {N,N} & subtype check loses => false
3161 PATH_LIMIT
3162 };
3163
3164 RegionNode* region = new RegionNode(PATH_LIMIT);
3165 Node* phi = new PhiNode(region, TypeInt::BOOL);
3166 record_for_igvn(region);
3167
3168 const TypePtr* adr_type = TypeRawPtr::BOTTOM; // memory type of loads
3169 const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL;
3170 int class_klass_offset = java_lang_Class::klass_offset();
3171
3172 // First null-check both mirrors and load each mirror's klass metaobject.
3173 int which_arg;
3174 for (which_arg = 0; which_arg <= 1; which_arg++) {
3175 Node* arg = args[which_arg];
3176 arg = null_check(arg);
3177 if (stopped()) break;
3178 args[which_arg] = arg;
3179
3180 Node* p = basic_plus_adr(arg, class_klass_offset);
3181 Node* kls = LoadKlassNode::make(_gvn, NULL, immutable_memory(), p, adr_type, kls_type);
3182 klasses[which_arg] = _gvn.transform(kls);
3183 }
3184
3185 // Having loaded both klasses, test each for null.
3186 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3187 for (which_arg = 0; which_arg <= 1; which_arg++) {
3188 Node* kls = klasses[which_arg];
3189 Node* null_ctl = top();
3190 kls = null_check_oop(kls, &null_ctl, never_see_null);
3191 int prim_path = (which_arg == 0 ? _prim_0_path : _prim_1_path);
3192 region->init_req(prim_path, null_ctl);
3193 if (stopped()) break;
3194 klasses[which_arg] = kls;
3195 }
3196
3197 if (!stopped()) {
3198 // now we have two reference types, in klasses[0..1]
3199 Node* subk = klasses[1]; // the argument to isAssignableFrom
3200 Node* superk = klasses[0]; // the receiver
3201 region->set_req(_both_ref_path, gen_subtype_check(subk, superk));
3202 // now we have a successful reference subtype check
3203 region->set_req(_ref_subtype_path, control());
3204 }
3205
3206 // If both operands are primitive (both klasses null), then
3207 // we must return true when they are identical primitives.
3208 // It is convenient to test this after the first null klass check.
3209 set_control(region->in(_prim_0_path)); // go back to first null check
3210 if (!stopped()) {
3211 // Since superc is primitive, make a guard for the superc==subc case.
3212 Node* cmp_eq = _gvn.transform(new CmpPNode(args[0], args[1]));
3213 Node* bol_eq = _gvn.transform(new BoolNode(cmp_eq, BoolTest::eq));
3214 generate_guard(bol_eq, region, PROB_FAIR);
3215 if (region->req() == PATH_LIMIT+1) {
3216 // A guard was added. If the added guard is taken, superc==subc.
3217 region->swap_edges(PATH_LIMIT, _prim_same_path);
3218 region->del_req(PATH_LIMIT);
3219 }
3220 region->set_req(_prim_0_path, control()); // Not equal after all.
3221 }
3222
3223 // these are the only paths that produce 'true':
3224 phi->set_req(_prim_same_path, intcon(1));
3225 phi->set_req(_ref_subtype_path, intcon(1));
3226
3227 // pull together the cases:
3228 assert(region->req() == PATH_LIMIT, "sane region");
3229 for (uint i = 1; i < region->req(); i++) {
3230 Node* ctl = region->in(i);
3231 if (ctl == NULL || ctl == top()) {
3232 region->set_req(i, top());
3233 phi ->set_req(i, top());
3234 } else if (phi->in(i) == NULL) {
3235 phi->set_req(i, intcon(0)); // all other paths produce 'false'
3236 }
3237 }
3238
3239 set_control(_gvn.transform(region));
3240 set_result(_gvn.transform(phi));
3241 return true;
3242 }
3243
3244 //---------------------generate_array_guard_common------------------------
generate_array_guard_common(Node * kls,RegionNode * region,bool obj_array,bool not_array)3245 Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region,
3246 bool obj_array, bool not_array) {
3247
3248 if (stopped()) {
3249 return NULL;
3250 }
3251
3252 // If obj_array/non_array==false/false:
3253 // Branch around if the given klass is in fact an array (either obj or prim).
3254 // If obj_array/non_array==false/true:
3255 // Branch around if the given klass is not an array klass of any kind.
3256 // If obj_array/non_array==true/true:
3257 // Branch around if the kls is not an oop array (kls is int[], String, etc.)
3258 // If obj_array/non_array==true/false:
3259 // Branch around if the kls is an oop array (Object[] or subtype)
3260 //
3261 // Like generate_guard, adds a new path onto the region.
3262 jint layout_con = 0;
3263 Node* layout_val = get_layout_helper(kls, layout_con);
3264 if (layout_val == NULL) {
3265 bool query = (obj_array
3266 ? Klass::layout_helper_is_objArray(layout_con)
3267 : Klass::layout_helper_is_array(layout_con));
3268 if (query == not_array) {
3269 return NULL; // never a branch
3270 } else { // always a branch
3271 Node* always_branch = control();
3272 if (region != NULL)
3273 region->add_req(always_branch);
3274 set_control(top());
3275 return always_branch;
3276 }
3277 }
3278 // Now test the correct condition.
3279 jint nval = (obj_array
3280 ? (jint)(Klass::_lh_array_tag_type_value
3281 << Klass::_lh_array_tag_shift)
3282 : Klass::_lh_neutral_value);
3283 Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(nval)));
3284 BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array
3285 // invert the test if we are looking for a non-array
3286 if (not_array) btest = BoolTest(btest).negate();
3287 Node* bol = _gvn.transform(new BoolNode(cmp, btest));
3288 return generate_fair_guard(bol, region);
3289 }
3290
3291
3292 //-----------------------inline_native_newArray--------------------------
3293 // private static native Object java.lang.reflect.newArray(Class<?> componentType, int length);
3294 // private native Object Unsafe.allocateUninitializedArray0(Class<?> cls, int size);
inline_unsafe_newArray(bool uninitialized)3295 bool LibraryCallKit::inline_unsafe_newArray(bool uninitialized) {
3296 Node* mirror;
3297 Node* count_val;
3298 if (uninitialized) {
3299 mirror = argument(1);
3300 count_val = argument(2);
3301 } else {
3302 mirror = argument(0);
3303 count_val = argument(1);
3304 }
3305
3306 mirror = null_check(mirror);
3307 // If mirror or obj is dead, only null-path is taken.
3308 if (stopped()) return true;
3309
3310 enum { _normal_path = 1, _slow_path = 2, PATH_LIMIT };
3311 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3312 PhiNode* result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
3313 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
3314 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3315
3316 bool never_see_null = !too_many_traps(Deoptimization::Reason_null_check);
3317 Node* klass_node = load_array_klass_from_mirror(mirror, never_see_null,
3318 result_reg, _slow_path);
3319 Node* normal_ctl = control();
3320 Node* no_array_ctl = result_reg->in(_slow_path);
3321
3322 // Generate code for the slow case. We make a call to newArray().
3323 set_control(no_array_ctl);
3324 if (!stopped()) {
3325 // Either the input type is void.class, or else the
3326 // array klass has not yet been cached. Either the
3327 // ensuing call will throw an exception, or else it
3328 // will cache the array klass for next time.
3329 PreserveJVMState pjvms(this);
3330 CallJavaNode* slow_call = NULL;
3331 if (uninitialized) {
3332 // Generate optimized virtual call (holder class 'Unsafe' is final)
3333 slow_call = generate_method_call(vmIntrinsics::_allocateUninitializedArray, false, false);
3334 } else {
3335 slow_call = generate_method_call_static(vmIntrinsics::_newArray);
3336 }
3337 Node* slow_result = set_results_for_java_call(slow_call);
3338 // this->control() comes from set_results_for_java_call
3339 result_reg->set_req(_slow_path, control());
3340 result_val->set_req(_slow_path, slow_result);
3341 result_io ->set_req(_slow_path, i_o());
3342 result_mem->set_req(_slow_path, reset_memory());
3343 }
3344
3345 set_control(normal_ctl);
3346 if (!stopped()) {
3347 // Normal case: The array type has been cached in the java.lang.Class.
3348 // The following call works fine even if the array type is polymorphic.
3349 // It could be a dynamic mix of int[], boolean[], Object[], etc.
3350 Node* obj = new_array(klass_node, count_val, 0); // no arguments to push
3351 result_reg->init_req(_normal_path, control());
3352 result_val->init_req(_normal_path, obj);
3353 result_io ->init_req(_normal_path, i_o());
3354 result_mem->init_req(_normal_path, reset_memory());
3355
3356 if (uninitialized) {
3357 // Mark the allocation so that zeroing is skipped
3358 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(obj, &_gvn);
3359 alloc->maybe_set_complete(&_gvn);
3360 }
3361 }
3362
3363 // Return the combined state.
3364 set_i_o( _gvn.transform(result_io) );
3365 set_all_memory( _gvn.transform(result_mem));
3366
3367 C->set_has_split_ifs(true); // Has chance for split-if optimization
3368 set_result(result_reg, result_val);
3369 return true;
3370 }
3371
3372 //----------------------inline_native_getLength--------------------------
3373 // public static native int java.lang.reflect.Array.getLength(Object array);
inline_native_getLength()3374 bool LibraryCallKit::inline_native_getLength() {
3375 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
3376
3377 Node* array = null_check(argument(0));
3378 // If array is dead, only null-path is taken.
3379 if (stopped()) return true;
3380
3381 // Deoptimize if it is a non-array.
3382 Node* non_array = generate_non_array_guard(load_object_klass(array), NULL);
3383
3384 if (non_array != NULL) {
3385 PreserveJVMState pjvms(this);
3386 set_control(non_array);
3387 uncommon_trap(Deoptimization::Reason_intrinsic,
3388 Deoptimization::Action_maybe_recompile);
3389 }
3390
3391 // If control is dead, only non-array-path is taken.
3392 if (stopped()) return true;
3393
3394 // The works fine even if the array type is polymorphic.
3395 // It could be a dynamic mix of int[], boolean[], Object[], etc.
3396 Node* result = load_array_length(array);
3397
3398 C->set_has_split_ifs(true); // Has chance for split-if optimization
3399 set_result(result);
3400 return true;
3401 }
3402
3403 //------------------------inline_array_copyOf----------------------------
3404 // public static <T,U> T[] java.util.Arrays.copyOf( U[] original, int newLength, Class<? extends T[]> newType);
3405 // public static <T,U> T[] java.util.Arrays.copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType);
inline_array_copyOf(bool is_copyOfRange)3406 bool LibraryCallKit::inline_array_copyOf(bool is_copyOfRange) {
3407 if (too_many_traps(Deoptimization::Reason_intrinsic)) return false;
3408
3409 // Get the arguments.
3410 Node* original = argument(0);
3411 Node* start = is_copyOfRange? argument(1): intcon(0);
3412 Node* end = is_copyOfRange? argument(2): argument(1);
3413 Node* array_type_mirror = is_copyOfRange? argument(3): argument(2);
3414
3415 Node* newcopy = NULL;
3416
3417 // Set the original stack and the reexecute bit for the interpreter to reexecute
3418 // the bytecode that invokes Arrays.copyOf if deoptimization happens.
3419 { PreserveReexecuteState preexecs(this);
3420 jvms()->set_should_reexecute(true);
3421
3422 array_type_mirror = null_check(array_type_mirror);
3423 original = null_check(original);
3424
3425 // Check if a null path was taken unconditionally.
3426 if (stopped()) return true;
3427
3428 Node* orig_length = load_array_length(original);
3429
3430 Node* klass_node = load_klass_from_mirror(array_type_mirror, false, NULL, 0);
3431 klass_node = null_check(klass_node);
3432
3433 RegionNode* bailout = new RegionNode(1);
3434 record_for_igvn(bailout);
3435
3436 // Despite the generic type of Arrays.copyOf, the mirror might be int, int[], etc.
3437 // Bail out if that is so.
3438 Node* not_objArray = generate_non_objArray_guard(klass_node, bailout);
3439 if (not_objArray != NULL) {
3440 // Improve the klass node's type from the new optimistic assumption:
3441 ciKlass* ak = ciArrayKlass::make(env()->Object_klass());
3442 const Type* akls = TypeKlassPtr::make(TypePtr::NotNull, ak, 0/*offset*/);
3443 Node* cast = new CastPPNode(klass_node, akls);
3444 cast->init_req(0, control());
3445 klass_node = _gvn.transform(cast);
3446 }
3447
3448 // Bail out if either start or end is negative.
3449 generate_negative_guard(start, bailout, &start);
3450 generate_negative_guard(end, bailout, &end);
3451
3452 Node* length = end;
3453 if (_gvn.type(start) != TypeInt::ZERO) {
3454 length = _gvn.transform(new SubINode(end, start));
3455 }
3456
3457 // Bail out if length is negative.
3458 // Without this the new_array would throw
3459 // NegativeArraySizeException but IllegalArgumentException is what
3460 // should be thrown
3461 generate_negative_guard(length, bailout, &length);
3462
3463 if (bailout->req() > 1) {
3464 PreserveJVMState pjvms(this);
3465 set_control(_gvn.transform(bailout));
3466 uncommon_trap(Deoptimization::Reason_intrinsic,
3467 Deoptimization::Action_maybe_recompile);
3468 }
3469
3470 if (!stopped()) {
3471 // How many elements will we copy from the original?
3472 // The answer is MinI(orig_length - start, length).
3473 Node* orig_tail = _gvn.transform(new SubINode(orig_length, start));
3474 Node* moved = generate_min_max(vmIntrinsics::_min, orig_tail, length);
3475
3476 // Generate a direct call to the right arraycopy function(s).
3477 // We know the copy is disjoint but we might not know if the
3478 // oop stores need checking.
3479 // Extreme case: Arrays.copyOf((Integer[])x, 10, String[].class).
3480 // This will fail a store-check if x contains any non-nulls.
3481
3482 // ArrayCopyNode:Ideal may transform the ArrayCopyNode to
3483 // loads/stores but it is legal only if we're sure the
3484 // Arrays.copyOf would succeed. So we need all input arguments
3485 // to the copyOf to be validated, including that the copy to the
3486 // new array won't trigger an ArrayStoreException. That subtype
3487 // check can be optimized if we know something on the type of
3488 // the input array from type speculation.
3489 if (_gvn.type(klass_node)->singleton()) {
3490 ciKlass* subk = _gvn.type(load_object_klass(original))->is_klassptr()->klass();
3491 ciKlass* superk = _gvn.type(klass_node)->is_klassptr()->klass();
3492
3493 int test = C->static_subtype_check(superk, subk);
3494 if (test != Compile::SSC_always_true && test != Compile::SSC_always_false) {
3495 const TypeOopPtr* t_original = _gvn.type(original)->is_oopptr();
3496 if (t_original->speculative_type() != NULL) {
3497 original = maybe_cast_profiled_obj(original, t_original->speculative_type(), true);
3498 }
3499 }
3500 }
3501
3502 bool validated = false;
3503 // Reason_class_check rather than Reason_intrinsic because we
3504 // want to intrinsify even if this traps.
3505 if (!too_many_traps(Deoptimization::Reason_class_check)) {
3506 Node* not_subtype_ctrl = gen_subtype_check(original, klass_node);
3507
3508 if (not_subtype_ctrl != top()) {
3509 PreserveJVMState pjvms(this);
3510 set_control(not_subtype_ctrl);
3511 uncommon_trap(Deoptimization::Reason_class_check,
3512 Deoptimization::Action_make_not_entrant);
3513 assert(stopped(), "Should be stopped");
3514 }
3515 validated = true;
3516 }
3517
3518 if (!stopped()) {
3519 newcopy = new_array(klass_node, length, 0); // no arguments to push
3520
3521 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, original, start, newcopy, intcon(0), moved, true, false,
3522 load_object_klass(original), klass_node);
3523 if (!is_copyOfRange) {
3524 ac->set_copyof(validated);
3525 } else {
3526 ac->set_copyofrange(validated);
3527 }
3528 Node* n = _gvn.transform(ac);
3529 if (n == ac) {
3530 ac->connect_outputs(this);
3531 } else {
3532 assert(validated, "shouldn't transform if all arguments not validated");
3533 set_all_memory(n);
3534 }
3535 }
3536 }
3537 } // original reexecute is set back here
3538
3539 C->set_has_split_ifs(true); // Has chance for split-if optimization
3540 if (!stopped()) {
3541 set_result(newcopy);
3542 }
3543 return true;
3544 }
3545
3546
3547 //----------------------generate_virtual_guard---------------------------
3548 // Helper for hashCode and clone. Peeks inside the vtable to avoid a call.
generate_virtual_guard(Node * obj_klass,RegionNode * slow_region)3549 Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass,
3550 RegionNode* slow_region) {
3551 ciMethod* method = callee();
3552 int vtable_index = method->vtable_index();
3553 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
3554 "bad index %d", vtable_index);
3555 // Get the Method* out of the appropriate vtable entry.
3556 int entry_offset = in_bytes(Klass::vtable_start_offset()) +
3557 vtable_index*vtableEntry::size_in_bytes() +
3558 vtableEntry::method_offset_in_bytes();
3559 Node* entry_addr = basic_plus_adr(obj_klass, entry_offset);
3560 Node* target_call = make_load(NULL, entry_addr, TypePtr::NOTNULL, T_ADDRESS, MemNode::unordered);
3561
3562 // Compare the target method with the expected method (e.g., Object.hashCode).
3563 const TypePtr* native_call_addr = TypeMetadataPtr::make(method);
3564
3565 Node* native_call = makecon(native_call_addr);
3566 Node* chk_native = _gvn.transform(new CmpPNode(target_call, native_call));
3567 Node* test_native = _gvn.transform(new BoolNode(chk_native, BoolTest::ne));
3568
3569 return generate_slow_guard(test_native, slow_region);
3570 }
3571
3572 //-----------------------generate_method_call----------------------------
3573 // Use generate_method_call to make a slow-call to the real
3574 // method if the fast path fails. An alternative would be to
3575 // use a stub like OptoRuntime::slow_arraycopy_Java.
3576 // This only works for expanding the current library call,
3577 // not another intrinsic. (E.g., don't use this for making an
3578 // arraycopy call inside of the copyOf intrinsic.)
3579 CallJavaNode*
generate_method_call(vmIntrinsics::ID method_id,bool is_virtual,bool is_static)3580 LibraryCallKit::generate_method_call(vmIntrinsics::ID method_id, bool is_virtual, bool is_static) {
3581 // When compiling the intrinsic method itself, do not use this technique.
3582 guarantee(callee() != C->method(), "cannot make slow-call to self");
3583
3584 ciMethod* method = callee();
3585 // ensure the JVMS we have will be correct for this call
3586 guarantee(method_id == method->intrinsic_id(), "must match");
3587
3588 const TypeFunc* tf = TypeFunc::make(method);
3589 CallJavaNode* slow_call;
3590 if (is_static) {
3591 assert(!is_virtual, "");
3592 slow_call = new CallStaticJavaNode(C, tf,
3593 SharedRuntime::get_resolve_static_call_stub(),
3594 method, bci());
3595 } else if (is_virtual) {
3596 null_check_receiver();
3597 int vtable_index = Method::invalid_vtable_index;
3598 if (UseInlineCaches) {
3599 // Suppress the vtable call
3600 } else {
3601 // hashCode and clone are not a miranda methods,
3602 // so the vtable index is fixed.
3603 // No need to use the linkResolver to get it.
3604 vtable_index = method->vtable_index();
3605 assert(vtable_index >= 0 || vtable_index == Method::nonvirtual_vtable_index,
3606 "bad index %d", vtable_index);
3607 }
3608 slow_call = new CallDynamicJavaNode(tf,
3609 SharedRuntime::get_resolve_virtual_call_stub(),
3610 method, vtable_index, bci());
3611 } else { // neither virtual nor static: opt_virtual
3612 null_check_receiver();
3613 slow_call = new CallStaticJavaNode(C, tf,
3614 SharedRuntime::get_resolve_opt_virtual_call_stub(),
3615 method, bci());
3616 slow_call->set_optimized_virtual(true);
3617 }
3618 if (CallGenerator::is_inlined_method_handle_intrinsic(this->method(), bci(), callee())) {
3619 // To be able to issue a direct call (optimized virtual or virtual)
3620 // and skip a call to MH.linkTo*/invokeBasic adapter, additional information
3621 // about the method being invoked should be attached to the call site to
3622 // make resolution logic work (see SharedRuntime::resolve_{virtual,opt_virtual}_call_C).
3623 slow_call->set_override_symbolic_info(true);
3624 }
3625 set_arguments_for_java_call(slow_call);
3626 set_edges_for_java_call(slow_call);
3627 return slow_call;
3628 }
3629
3630
3631 /**
3632 * Build special case code for calls to hashCode on an object. This call may
3633 * be virtual (invokevirtual) or bound (invokespecial). For each case we generate
3634 * slightly different code.
3635 */
inline_native_hashcode(bool is_virtual,bool is_static)3636 bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) {
3637 assert(is_static == callee()->is_static(), "correct intrinsic selection");
3638 assert(!(is_virtual && is_static), "either virtual, special, or static");
3639
3640 enum { _slow_path = 1, _fast_path, _null_path, PATH_LIMIT };
3641
3642 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
3643 PhiNode* result_val = new PhiNode(result_reg, TypeInt::INT);
3644 PhiNode* result_io = new PhiNode(result_reg, Type::ABIO);
3645 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
3646 Node* obj = NULL;
3647 if (!is_static) {
3648 // Check for hashing null object
3649 obj = null_check_receiver();
3650 if (stopped()) return true; // unconditionally null
3651 result_reg->init_req(_null_path, top());
3652 result_val->init_req(_null_path, top());
3653 } else {
3654 // Do a null check, and return zero if null.
3655 // System.identityHashCode(null) == 0
3656 obj = argument(0);
3657 Node* null_ctl = top();
3658 obj = null_check_oop(obj, &null_ctl);
3659 result_reg->init_req(_null_path, null_ctl);
3660 result_val->init_req(_null_path, _gvn.intcon(0));
3661 }
3662
3663 // Unconditionally null? Then return right away.
3664 if (stopped()) {
3665 set_control( result_reg->in(_null_path));
3666 if (!stopped())
3667 set_result(result_val->in(_null_path));
3668 return true;
3669 }
3670
3671 // We only go to the fast case code if we pass a number of guards. The
3672 // paths which do not pass are accumulated in the slow_region.
3673 RegionNode* slow_region = new RegionNode(1);
3674 record_for_igvn(slow_region);
3675
3676 // If this is a virtual call, we generate a funny guard. We pull out
3677 // the vtable entry corresponding to hashCode() from the target object.
3678 // If the target method which we are calling happens to be the native
3679 // Object hashCode() method, we pass the guard. We do not need this
3680 // guard for non-virtual calls -- the caller is known to be the native
3681 // Object hashCode().
3682 if (is_virtual) {
3683 // After null check, get the object's klass.
3684 Node* obj_klass = load_object_klass(obj);
3685 generate_virtual_guard(obj_klass, slow_region);
3686 }
3687
3688 // Get the header out of the object, use LoadMarkNode when available
3689 Node* header_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3690 // The control of the load must be NULL. Otherwise, the load can move before
3691 // the null check after castPP removal.
3692 Node* no_ctrl = NULL;
3693 Node* header = make_load(no_ctrl, header_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3694
3695 // Test the header to see if it is unlocked.
3696 Node *lock_mask = _gvn.MakeConX(markWord::biased_lock_mask_in_place);
3697 Node *lmasked_header = _gvn.transform(new AndXNode(header, lock_mask));
3698 Node *unlocked_val = _gvn.MakeConX(markWord::unlocked_value);
3699 Node *chk_unlocked = _gvn.transform(new CmpXNode( lmasked_header, unlocked_val));
3700 Node *test_unlocked = _gvn.transform(new BoolNode( chk_unlocked, BoolTest::ne));
3701
3702 generate_slow_guard(test_unlocked, slow_region);
3703
3704 // Get the hash value and check to see that it has been properly assigned.
3705 // We depend on hash_mask being at most 32 bits and avoid the use of
3706 // hash_mask_in_place because it could be larger than 32 bits in a 64-bit
3707 // vm: see markWord.hpp.
3708 Node *hash_mask = _gvn.intcon(markWord::hash_mask);
3709 Node *hash_shift = _gvn.intcon(markWord::hash_shift);
3710 Node *hshifted_header= _gvn.transform(new URShiftXNode(header, hash_shift));
3711 // This hack lets the hash bits live anywhere in the mark object now, as long
3712 // as the shift drops the relevant bits into the low 32 bits. Note that
3713 // Java spec says that HashCode is an int so there's no point in capturing
3714 // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build).
3715 hshifted_header = ConvX2I(hshifted_header);
3716 Node *hash_val = _gvn.transform(new AndINode(hshifted_header, hash_mask));
3717
3718 Node *no_hash_val = _gvn.intcon(markWord::no_hash);
3719 Node *chk_assigned = _gvn.transform(new CmpINode( hash_val, no_hash_val));
3720 Node *test_assigned = _gvn.transform(new BoolNode( chk_assigned, BoolTest::eq));
3721
3722 generate_slow_guard(test_assigned, slow_region);
3723
3724 Node* init_mem = reset_memory();
3725 // fill in the rest of the null path:
3726 result_io ->init_req(_null_path, i_o());
3727 result_mem->init_req(_null_path, init_mem);
3728
3729 result_val->init_req(_fast_path, hash_val);
3730 result_reg->init_req(_fast_path, control());
3731 result_io ->init_req(_fast_path, i_o());
3732 result_mem->init_req(_fast_path, init_mem);
3733
3734 // Generate code for the slow case. We make a call to hashCode().
3735 set_control(_gvn.transform(slow_region));
3736 if (!stopped()) {
3737 // No need for PreserveJVMState, because we're using up the present state.
3738 set_all_memory(init_mem);
3739 vmIntrinsics::ID hashCode_id = is_static ? vmIntrinsics::_identityHashCode : vmIntrinsics::_hashCode;
3740 CallJavaNode* slow_call = generate_method_call(hashCode_id, is_virtual, is_static);
3741 Node* slow_result = set_results_for_java_call(slow_call);
3742 // this->control() comes from set_results_for_java_call
3743 result_reg->init_req(_slow_path, control());
3744 result_val->init_req(_slow_path, slow_result);
3745 result_io ->set_req(_slow_path, i_o());
3746 result_mem ->set_req(_slow_path, reset_memory());
3747 }
3748
3749 // Return the combined state.
3750 set_i_o( _gvn.transform(result_io) );
3751 set_all_memory( _gvn.transform(result_mem));
3752
3753 set_result(result_reg, result_val);
3754 return true;
3755 }
3756
3757 //---------------------------inline_native_getClass----------------------------
3758 // public final native Class<?> java.lang.Object.getClass();
3759 //
3760 // Build special case code for calls to getClass on an object.
inline_native_getClass()3761 bool LibraryCallKit::inline_native_getClass() {
3762 Node* obj = null_check_receiver();
3763 if (stopped()) return true;
3764 set_result(load_mirror_from_klass(load_object_klass(obj)));
3765 return true;
3766 }
3767
3768 //-----------------inline_native_Reflection_getCallerClass---------------------
3769 // public static native Class<?> sun.reflect.Reflection.getCallerClass();
3770 //
3771 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
3772 //
3773 // NOTE: This code must perform the same logic as JVM_GetCallerClass
3774 // in that it must skip particular security frames and checks for
3775 // caller sensitive methods.
inline_native_Reflection_getCallerClass()3776 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
3777 #ifndef PRODUCT
3778 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
3779 tty->print_cr("Attempting to inline sun.reflect.Reflection.getCallerClass");
3780 }
3781 #endif
3782
3783 if (!jvms()->has_method()) {
3784 #ifndef PRODUCT
3785 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
3786 tty->print_cr(" Bailing out because intrinsic was inlined at top level");
3787 }
3788 #endif
3789 return false;
3790 }
3791
3792 // Walk back up the JVM state to find the caller at the required
3793 // depth.
3794 JVMState* caller_jvms = jvms();
3795
3796 // Cf. JVM_GetCallerClass
3797 // NOTE: Start the loop at depth 1 because the current JVM state does
3798 // not include the Reflection.getCallerClass() frame.
3799 for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
3800 ciMethod* m = caller_jvms->method();
3801 switch (n) {
3802 case 0:
3803 fatal("current JVM state does not include the Reflection.getCallerClass frame");
3804 break;
3805 case 1:
3806 // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
3807 if (!m->caller_sensitive()) {
3808 #ifndef PRODUCT
3809 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
3810 tty->print_cr(" Bailing out: CallerSensitive annotation expected at frame %d", n);
3811 }
3812 #endif
3813 return false; // bail-out; let JVM_GetCallerClass do the work
3814 }
3815 break;
3816 default:
3817 if (!m->is_ignored_by_security_stack_walk()) {
3818 // We have reached the desired frame; return the holder class.
3819 // Acquire method holder as java.lang.Class and push as constant.
3820 ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
3821 ciInstance* caller_mirror = caller_klass->java_mirror();
3822 set_result(makecon(TypeInstPtr::make(caller_mirror)));
3823
3824 #ifndef PRODUCT
3825 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
3826 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());
3827 tty->print_cr(" JVM state at this point:");
3828 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
3829 ciMethod* m = jvms()->of_depth(i)->method();
3830 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
3831 }
3832 }
3833 #endif
3834 return true;
3835 }
3836 break;
3837 }
3838 }
3839
3840 #ifndef PRODUCT
3841 if ((C->print_intrinsics() || C->print_inlining()) && Verbose) {
3842 tty->print_cr(" Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
3843 tty->print_cr(" JVM state at this point:");
3844 for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
3845 ciMethod* m = jvms()->of_depth(i)->method();
3846 tty->print_cr(" %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
3847 }
3848 }
3849 #endif
3850
3851 return false; // bail-out; let JVM_GetCallerClass do the work
3852 }
3853
inline_fp_conversions(vmIntrinsics::ID id)3854 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
3855 Node* arg = argument(0);
3856 Node* result = NULL;
3857
3858 switch (id) {
3859 case vmIntrinsics::_floatToRawIntBits: result = new MoveF2INode(arg); break;
3860 case vmIntrinsics::_intBitsToFloat: result = new MoveI2FNode(arg); break;
3861 case vmIntrinsics::_doubleToRawLongBits: result = new MoveD2LNode(arg); break;
3862 case vmIntrinsics::_longBitsToDouble: result = new MoveL2DNode(arg); break;
3863
3864 case vmIntrinsics::_doubleToLongBits: {
3865 // two paths (plus control) merge in a wood
3866 RegionNode *r = new RegionNode(3);
3867 Node *phi = new PhiNode(r, TypeLong::LONG);
3868
3869 Node *cmpisnan = _gvn.transform(new CmpDNode(arg, arg));
3870 // Build the boolean node
3871 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
3872
3873 // Branch either way.
3874 // NaN case is less traveled, which makes all the difference.
3875 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
3876 Node *opt_isnan = _gvn.transform(ifisnan);
3877 assert( opt_isnan->is_If(), "Expect an IfNode");
3878 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
3879 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
3880
3881 set_control(iftrue);
3882
3883 static const jlong nan_bits = CONST64(0x7ff8000000000000);
3884 Node *slow_result = longcon(nan_bits); // return NaN
3885 phi->init_req(1, _gvn.transform( slow_result ));
3886 r->init_req(1, iftrue);
3887
3888 // Else fall through
3889 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
3890 set_control(iffalse);
3891
3892 phi->init_req(2, _gvn.transform(new MoveD2LNode(arg)));
3893 r->init_req(2, iffalse);
3894
3895 // Post merge
3896 set_control(_gvn.transform(r));
3897 record_for_igvn(r);
3898
3899 C->set_has_split_ifs(true); // Has chance for split-if optimization
3900 result = phi;
3901 assert(result->bottom_type()->isa_long(), "must be");
3902 break;
3903 }
3904
3905 case vmIntrinsics::_floatToIntBits: {
3906 // two paths (plus control) merge in a wood
3907 RegionNode *r = new RegionNode(3);
3908 Node *phi = new PhiNode(r, TypeInt::INT);
3909
3910 Node *cmpisnan = _gvn.transform(new CmpFNode(arg, arg));
3911 // Build the boolean node
3912 Node *bolisnan = _gvn.transform(new BoolNode(cmpisnan, BoolTest::ne));
3913
3914 // Branch either way.
3915 // NaN case is less traveled, which makes all the difference.
3916 IfNode *ifisnan = create_and_xform_if(control(), bolisnan, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
3917 Node *opt_isnan = _gvn.transform(ifisnan);
3918 assert( opt_isnan->is_If(), "Expect an IfNode");
3919 IfNode *opt_ifisnan = (IfNode*)opt_isnan;
3920 Node *iftrue = _gvn.transform(new IfTrueNode(opt_ifisnan));
3921
3922 set_control(iftrue);
3923
3924 static const jint nan_bits = 0x7fc00000;
3925 Node *slow_result = makecon(TypeInt::make(nan_bits)); // return NaN
3926 phi->init_req(1, _gvn.transform( slow_result ));
3927 r->init_req(1, iftrue);
3928
3929 // Else fall through
3930 Node *iffalse = _gvn.transform(new IfFalseNode(opt_ifisnan));
3931 set_control(iffalse);
3932
3933 phi->init_req(2, _gvn.transform(new MoveF2INode(arg)));
3934 r->init_req(2, iffalse);
3935
3936 // Post merge
3937 set_control(_gvn.transform(r));
3938 record_for_igvn(r);
3939
3940 C->set_has_split_ifs(true); // Has chance for split-if optimization
3941 result = phi;
3942 assert(result->bottom_type()->isa_int(), "must be");
3943 break;
3944 }
3945
3946 default:
3947 fatal_unexpected_iid(id);
3948 break;
3949 }
3950 set_result(_gvn.transform(result));
3951 return true;
3952 }
3953
3954 //----------------------inline_unsafe_copyMemory-------------------------
3955 // public native void Unsafe.copyMemory0(Object srcBase, long srcOffset, Object destBase, long destOffset, long bytes);
inline_unsafe_copyMemory()3956 bool LibraryCallKit::inline_unsafe_copyMemory() {
3957 if (callee()->is_static()) return false; // caller must have the capability!
3958 null_check_receiver(); // null-check receiver
3959 if (stopped()) return true;
3960
3961 C->set_has_unsafe_access(true); // Mark eventual nmethod as "unsafe".
3962
3963 Node* src_ptr = argument(1); // type: oop
3964 Node* src_off = ConvL2X(argument(2)); // type: long
3965 Node* dst_ptr = argument(4); // type: oop
3966 Node* dst_off = ConvL2X(argument(5)); // type: long
3967 Node* size = ConvL2X(argument(7)); // type: long
3968
3969 assert(Unsafe_field_offset_to_byte_offset(11) == 11,
3970 "fieldOffset must be byte-scaled");
3971
3972 Node* src = make_unsafe_address(src_ptr, src_off, ACCESS_READ);
3973 Node* dst = make_unsafe_address(dst_ptr, dst_off, ACCESS_WRITE);
3974
3975 // Conservatively insert a memory barrier on all memory slices.
3976 // Do not let writes of the copy source or destination float below the copy.
3977 insert_mem_bar(Op_MemBarCPUOrder);
3978
3979 Node* thread = _gvn.transform(new ThreadLocalNode());
3980 Node* doing_unsafe_access_addr = basic_plus_adr(top(), thread, in_bytes(JavaThread::doing_unsafe_access_offset()));
3981 BasicType doing_unsafe_access_bt = T_BYTE;
3982 assert((sizeof(bool) * CHAR_BIT) == 8, "not implemented");
3983
3984 // update volatile field
3985 store_to_memory(control(), doing_unsafe_access_addr, intcon(1), doing_unsafe_access_bt, Compile::AliasIdxRaw, MemNode::unordered);
3986
3987 // Call it. Note that the length argument is not scaled.
3988 make_runtime_call(RC_LEAF|RC_NO_FP,
3989 OptoRuntime::fast_arraycopy_Type(),
3990 StubRoutines::unsafe_arraycopy(),
3991 "unsafe_arraycopy",
3992 TypeRawPtr::BOTTOM,
3993 src, dst, size XTOP);
3994
3995 store_to_memory(control(), doing_unsafe_access_addr, intcon(0), doing_unsafe_access_bt, Compile::AliasIdxRaw, MemNode::unordered);
3996
3997 // Do not let reads of the copy destination float above the copy.
3998 insert_mem_bar(Op_MemBarCPUOrder);
3999
4000 return true;
4001 }
4002
4003 //------------------------clone_coping-----------------------------------
4004 // Helper function for inline_native_clone.
copy_to_clone(Node * obj,Node * alloc_obj,Node * obj_size,bool is_array)4005 void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array) {
4006 assert(obj_size != NULL, "");
4007 Node* raw_obj = alloc_obj->in(1);
4008 assert(alloc_obj->is_CheckCastPP() && raw_obj->is_Proj() && raw_obj->in(0)->is_Allocate(), "");
4009
4010 AllocateNode* alloc = NULL;
4011 if (ReduceBulkZeroing) {
4012 // We will be completely responsible for initializing this object -
4013 // mark Initialize node as complete.
4014 alloc = AllocateNode::Ideal_allocation(alloc_obj, &_gvn);
4015 // The object was just allocated - there should be no any stores!
4016 guarantee(alloc != NULL && alloc->maybe_set_complete(&_gvn), "");
4017 // Mark as complete_with_arraycopy so that on AllocateNode
4018 // expansion, we know this AllocateNode is initialized by an array
4019 // copy and a StoreStore barrier exists after the array copy.
4020 alloc->initialization()->set_complete_with_arraycopy();
4021 }
4022
4023 Node* size = _gvn.transform(obj_size);
4024 access_clone(obj, alloc_obj, size, is_array);
4025
4026 // Do not let reads from the cloned object float above the arraycopy.
4027 if (alloc != NULL) {
4028 // Do not let stores that initialize this object be reordered with
4029 // a subsequent store that would make this object accessible by
4030 // other threads.
4031 // Record what AllocateNode this StoreStore protects so that
4032 // escape analysis can go from the MemBarStoreStoreNode to the
4033 // AllocateNode and eliminate the MemBarStoreStoreNode if possible
4034 // based on the escape status of the AllocateNode.
4035 insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out_or_null(AllocateNode::RawAddress));
4036 } else {
4037 insert_mem_bar(Op_MemBarCPUOrder);
4038 }
4039 }
4040
4041 //------------------------inline_native_clone----------------------------
4042 // protected native Object java.lang.Object.clone();
4043 //
4044 // Here are the simple edge cases:
4045 // null receiver => normal trap
4046 // virtual and clone was overridden => slow path to out-of-line clone
4047 // not cloneable or finalizer => slow path to out-of-line Object.clone
4048 //
4049 // The general case has two steps, allocation and copying.
4050 // Allocation has two cases, and uses GraphKit::new_instance or new_array.
4051 //
4052 // Copying also has two cases, oop arrays and everything else.
4053 // Oop arrays use arrayof_oop_arraycopy (same as System.arraycopy).
4054 // Everything else uses the tight inline loop supplied by CopyArrayNode.
4055 //
4056 // These steps fold up nicely if and when the cloned object's klass
4057 // can be sharply typed as an object array, a type array, or an instance.
4058 //
inline_native_clone(bool is_virtual)4059 bool LibraryCallKit::inline_native_clone(bool is_virtual) {
4060 PhiNode* result_val;
4061
4062 // Set the reexecute bit for the interpreter to reexecute
4063 // the bytecode that invokes Object.clone if deoptimization happens.
4064 { PreserveReexecuteState preexecs(this);
4065 jvms()->set_should_reexecute(true);
4066
4067 Node* obj = null_check_receiver();
4068 if (stopped()) return true;
4069
4070 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
4071
4072 // If we are going to clone an instance, we need its exact type to
4073 // know the number and types of fields to convert the clone to
4074 // loads/stores. Maybe a speculative type can help us.
4075 if (!obj_type->klass_is_exact() &&
4076 obj_type->speculative_type() != NULL &&
4077 obj_type->speculative_type()->is_instance_klass()) {
4078 ciInstanceKlass* spec_ik = obj_type->speculative_type()->as_instance_klass();
4079 if (spec_ik->nof_nonstatic_fields() <= ArrayCopyLoadStoreMaxElem &&
4080 !spec_ik->has_injected_fields()) {
4081 ciKlass* k = obj_type->klass();
4082 if (!k->is_instance_klass() ||
4083 k->as_instance_klass()->is_interface() ||
4084 k->as_instance_klass()->has_subklass()) {
4085 obj = maybe_cast_profiled_obj(obj, obj_type->speculative_type(), false);
4086 }
4087 }
4088 }
4089
4090 // Conservatively insert a memory barrier on all memory slices.
4091 // Do not let writes into the original float below the clone.
4092 insert_mem_bar(Op_MemBarCPUOrder);
4093
4094 // paths into result_reg:
4095 enum {
4096 _slow_path = 1, // out-of-line call to clone method (virtual or not)
4097 _objArray_path, // plain array allocation, plus arrayof_oop_arraycopy
4098 _array_path, // plain array allocation, plus arrayof_long_arraycopy
4099 _instance_path, // plain instance allocation, plus arrayof_long_arraycopy
4100 PATH_LIMIT
4101 };
4102 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
4103 result_val = new PhiNode(result_reg, TypeInstPtr::NOTNULL);
4104 PhiNode* result_i_o = new PhiNode(result_reg, Type::ABIO);
4105 PhiNode* result_mem = new PhiNode(result_reg, Type::MEMORY, TypePtr::BOTTOM);
4106 record_for_igvn(result_reg);
4107
4108 Node* obj_klass = load_object_klass(obj);
4109 Node* array_ctl = generate_array_guard(obj_klass, (RegionNode*)NULL);
4110 if (array_ctl != NULL) {
4111 // It's an array.
4112 PreserveJVMState pjvms(this);
4113 set_control(array_ctl);
4114 Node* obj_length = load_array_length(obj);
4115 Node* obj_size = NULL;
4116 Node* alloc_obj = new_array(obj_klass, obj_length, 0, &obj_size, /*deoptimize_on_exception=*/true);
4117
4118 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4119 if (bs->array_copy_requires_gc_barriers(true, T_OBJECT, true, BarrierSetC2::Parsing)) {
4120 // If it is an oop array, it requires very special treatment,
4121 // because gc barriers are required when accessing the array.
4122 Node* is_obja = generate_objArray_guard(obj_klass, (RegionNode*)NULL);
4123 if (is_obja != NULL) {
4124 PreserveJVMState pjvms2(this);
4125 set_control(is_obja);
4126 // Generate a direct call to the right arraycopy function(s).
4127 Node* alloc = tightly_coupled_allocation(alloc_obj, NULL);
4128 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, obj, intcon(0), alloc_obj, intcon(0), obj_length, alloc != NULL, false);
4129 ac->set_clone_oop_array();
4130 Node* n = _gvn.transform(ac);
4131 assert(n == ac, "cannot disappear");
4132 ac->connect_outputs(this, /*deoptimize_on_exception=*/true);
4133
4134 result_reg->init_req(_objArray_path, control());
4135 result_val->init_req(_objArray_path, alloc_obj);
4136 result_i_o ->set_req(_objArray_path, i_o());
4137 result_mem ->set_req(_objArray_path, reset_memory());
4138 }
4139 }
4140 // Otherwise, there are no barriers to worry about.
4141 // (We can dispense with card marks if we know the allocation
4142 // comes out of eden (TLAB)... In fact, ReduceInitialCardMarks
4143 // causes the non-eden paths to take compensating steps to
4144 // simulate a fresh allocation, so that no further
4145 // card marks are required in compiled code to initialize
4146 // the object.)
4147
4148 if (!stopped()) {
4149 copy_to_clone(obj, alloc_obj, obj_size, true);
4150
4151 // Present the results of the copy.
4152 result_reg->init_req(_array_path, control());
4153 result_val->init_req(_array_path, alloc_obj);
4154 result_i_o ->set_req(_array_path, i_o());
4155 result_mem ->set_req(_array_path, reset_memory());
4156 }
4157 }
4158
4159 // We only go to the instance fast case code if we pass a number of guards.
4160 // The paths which do not pass are accumulated in the slow_region.
4161 RegionNode* slow_region = new RegionNode(1);
4162 record_for_igvn(slow_region);
4163 if (!stopped()) {
4164 // It's an instance (we did array above). Make the slow-path tests.
4165 // If this is a virtual call, we generate a funny guard. We grab
4166 // the vtable entry corresponding to clone() from the target object.
4167 // If the target method which we are calling happens to be the
4168 // Object clone() method, we pass the guard. We do not need this
4169 // guard for non-virtual calls; the caller is known to be the native
4170 // Object clone().
4171 if (is_virtual) {
4172 generate_virtual_guard(obj_klass, slow_region);
4173 }
4174
4175 // The object must be easily cloneable and must not have a finalizer.
4176 // Both of these conditions may be checked in a single test.
4177 // We could optimize the test further, but we don't care.
4178 generate_access_flags_guard(obj_klass,
4179 // Test both conditions:
4180 JVM_ACC_IS_CLONEABLE_FAST | JVM_ACC_HAS_FINALIZER,
4181 // Must be cloneable but not finalizer:
4182 JVM_ACC_IS_CLONEABLE_FAST,
4183 slow_region);
4184 }
4185
4186 if (!stopped()) {
4187 // It's an instance, and it passed the slow-path tests.
4188 PreserveJVMState pjvms(this);
4189 Node* obj_size = NULL;
4190 // Need to deoptimize on exception from allocation since Object.clone intrinsic
4191 // is reexecuted if deoptimization occurs and there could be problems when merging
4192 // exception state between multiple Object.clone versions (reexecute=true vs reexecute=false).
4193 Node* alloc_obj = new_instance(obj_klass, NULL, &obj_size, /*deoptimize_on_exception=*/true);
4194
4195 copy_to_clone(obj, alloc_obj, obj_size, false);
4196
4197 // Present the results of the slow call.
4198 result_reg->init_req(_instance_path, control());
4199 result_val->init_req(_instance_path, alloc_obj);
4200 result_i_o ->set_req(_instance_path, i_o());
4201 result_mem ->set_req(_instance_path, reset_memory());
4202 }
4203
4204 // Generate code for the slow case. We make a call to clone().
4205 set_control(_gvn.transform(slow_region));
4206 if (!stopped()) {
4207 PreserveJVMState pjvms(this);
4208 CallJavaNode* slow_call = generate_method_call(vmIntrinsics::_clone, is_virtual);
4209 // We need to deoptimize on exception (see comment above)
4210 Node* slow_result = set_results_for_java_call(slow_call, false, /* deoptimize */ true);
4211 // this->control() comes from set_results_for_java_call
4212 result_reg->init_req(_slow_path, control());
4213 result_val->init_req(_slow_path, slow_result);
4214 result_i_o ->set_req(_slow_path, i_o());
4215 result_mem ->set_req(_slow_path, reset_memory());
4216 }
4217
4218 // Return the combined state.
4219 set_control( _gvn.transform(result_reg));
4220 set_i_o( _gvn.transform(result_i_o));
4221 set_all_memory( _gvn.transform(result_mem));
4222 } // original reexecute is set back here
4223
4224 set_result(_gvn.transform(result_val));
4225 return true;
4226 }
4227
4228 // If we have a tightly coupled allocation, the arraycopy may take care
4229 // of the array initialization. If one of the guards we insert between
4230 // the allocation and the arraycopy causes a deoptimization, an
4231 // unitialized array will escape the compiled method. To prevent that
4232 // we set the JVM state for uncommon traps between the allocation and
4233 // the arraycopy to the state before the allocation so, in case of
4234 // deoptimization, we'll reexecute the allocation and the
4235 // initialization.
arraycopy_restore_alloc_state(AllocateArrayNode * alloc,int & saved_reexecute_sp)4236 JVMState* LibraryCallKit::arraycopy_restore_alloc_state(AllocateArrayNode* alloc, int& saved_reexecute_sp) {
4237 if (alloc != NULL) {
4238 ciMethod* trap_method = alloc->jvms()->method();
4239 int trap_bci = alloc->jvms()->bci();
4240
4241 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
4242 !C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_null_check)) {
4243 // Make sure there's no store between the allocation and the
4244 // arraycopy otherwise visible side effects could be rexecuted
4245 // in case of deoptimization and cause incorrect execution.
4246 bool no_interfering_store = true;
4247 Node* mem = alloc->in(TypeFunc::Memory);
4248 if (mem->is_MergeMem()) {
4249 for (MergeMemStream mms(merged_memory(), mem->as_MergeMem()); mms.next_non_empty2(); ) {
4250 Node* n = mms.memory();
4251 if (n != mms.memory2() && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4252 assert(n->is_Store(), "what else?");
4253 no_interfering_store = false;
4254 break;
4255 }
4256 }
4257 } else {
4258 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
4259 Node* n = mms.memory();
4260 if (n != mem && !(n->is_Proj() && n->in(0) == alloc->initialization())) {
4261 assert(n->is_Store(), "what else?");
4262 no_interfering_store = false;
4263 break;
4264 }
4265 }
4266 }
4267
4268 if (no_interfering_store) {
4269 JVMState* old_jvms = alloc->jvms()->clone_shallow(C);
4270 uint size = alloc->req();
4271 SafePointNode* sfpt = new SafePointNode(size, old_jvms);
4272 old_jvms->set_map(sfpt);
4273 for (uint i = 0; i < size; i++) {
4274 sfpt->init_req(i, alloc->in(i));
4275 }
4276 // re-push array length for deoptimization
4277 sfpt->ins_req(old_jvms->stkoff() + old_jvms->sp(), alloc->in(AllocateNode::ALength));
4278 old_jvms->set_sp(old_jvms->sp()+1);
4279 old_jvms->set_monoff(old_jvms->monoff()+1);
4280 old_jvms->set_scloff(old_jvms->scloff()+1);
4281 old_jvms->set_endoff(old_jvms->endoff()+1);
4282 old_jvms->set_should_reexecute(true);
4283
4284 sfpt->set_i_o(map()->i_o());
4285 sfpt->set_memory(map()->memory());
4286 sfpt->set_control(map()->control());
4287
4288 JVMState* saved_jvms = jvms();
4289 saved_reexecute_sp = _reexecute_sp;
4290
4291 set_jvms(sfpt->jvms());
4292 _reexecute_sp = jvms()->sp();
4293
4294 return saved_jvms;
4295 }
4296 }
4297 }
4298 return NULL;
4299 }
4300
4301 // In case of a deoptimization, we restart execution at the
4302 // allocation, allocating a new array. We would leave an uninitialized
4303 // array in the heap that GCs wouldn't expect. Move the allocation
4304 // after the traps so we don't allocate the array if we
4305 // deoptimize. This is possible because tightly_coupled_allocation()
4306 // guarantees there's no observer of the allocated array at this point
4307 // and the control flow is simple enough.
arraycopy_move_allocation_here(AllocateArrayNode * alloc,Node * dest,JVMState * saved_jvms,int saved_reexecute_sp,uint new_idx)4308 void LibraryCallKit::arraycopy_move_allocation_here(AllocateArrayNode* alloc, Node* dest, JVMState* saved_jvms,
4309 int saved_reexecute_sp, uint new_idx) {
4310 if (saved_jvms != NULL && !stopped()) {
4311 assert(alloc != NULL, "only with a tightly coupled allocation");
4312 // restore JVM state to the state at the arraycopy
4313 saved_jvms->map()->set_control(map()->control());
4314 assert(saved_jvms->map()->memory() == map()->memory(), "memory state changed?");
4315 assert(saved_jvms->map()->i_o() == map()->i_o(), "IO state changed?");
4316 // If we've improved the types of some nodes (null check) while
4317 // emitting the guards, propagate them to the current state
4318 map()->replaced_nodes().apply(saved_jvms->map(), new_idx);
4319 set_jvms(saved_jvms);
4320 _reexecute_sp = saved_reexecute_sp;
4321
4322 // Remove the allocation from above the guards
4323 CallProjections callprojs;
4324 alloc->extract_projections(&callprojs, true);
4325 InitializeNode* init = alloc->initialization();
4326 Node* alloc_mem = alloc->in(TypeFunc::Memory);
4327 C->gvn_replace_by(callprojs.fallthrough_ioproj, alloc->in(TypeFunc::I_O));
4328 C->gvn_replace_by(init->proj_out(TypeFunc::Memory), alloc_mem);
4329 C->gvn_replace_by(init->proj_out(TypeFunc::Control), alloc->in(0));
4330
4331 // move the allocation here (after the guards)
4332 _gvn.hash_delete(alloc);
4333 alloc->set_req(TypeFunc::Control, control());
4334 alloc->set_req(TypeFunc::I_O, i_o());
4335 Node *mem = reset_memory();
4336 set_all_memory(mem);
4337 alloc->set_req(TypeFunc::Memory, mem);
4338 set_control(init->proj_out_or_null(TypeFunc::Control));
4339 set_i_o(callprojs.fallthrough_ioproj);
4340
4341 // Update memory as done in GraphKit::set_output_for_allocation()
4342 const TypeInt* length_type = _gvn.find_int_type(alloc->in(AllocateNode::ALength));
4343 const TypeOopPtr* ary_type = _gvn.type(alloc->in(AllocateNode::KlassNode))->is_klassptr()->as_instance_type();
4344 if (ary_type->isa_aryptr() && length_type != NULL) {
4345 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4346 }
4347 const TypePtr* telemref = ary_type->add_offset(Type::OffsetBot);
4348 int elemidx = C->get_alias_index(telemref);
4349 set_memory(init->proj_out_or_null(TypeFunc::Memory), Compile::AliasIdxRaw);
4350 set_memory(init->proj_out_or_null(TypeFunc::Memory), elemidx);
4351
4352 Node* allocx = _gvn.transform(alloc);
4353 assert(allocx == alloc, "where has the allocation gone?");
4354 assert(dest->is_CheckCastPP(), "not an allocation result?");
4355
4356 _gvn.hash_delete(dest);
4357 dest->set_req(0, control());
4358 Node* destx = _gvn.transform(dest);
4359 assert(destx == dest, "where has the allocation result gone?");
4360 }
4361 }
4362
4363
4364 //------------------------------inline_arraycopy-----------------------
4365 // public static native void java.lang.System.arraycopy(Object src, int srcPos,
4366 // Object dest, int destPos,
4367 // int length);
inline_arraycopy()4368 bool LibraryCallKit::inline_arraycopy() {
4369 // Get the arguments.
4370 Node* src = argument(0); // type: oop
4371 Node* src_offset = argument(1); // type: int
4372 Node* dest = argument(2); // type: oop
4373 Node* dest_offset = argument(3); // type: int
4374 Node* length = argument(4); // type: int
4375
4376 uint new_idx = C->unique();
4377
4378 // Check for allocation before we add nodes that would confuse
4379 // tightly_coupled_allocation()
4380 AllocateArrayNode* alloc = tightly_coupled_allocation(dest, NULL);
4381
4382 int saved_reexecute_sp = -1;
4383 JVMState* saved_jvms = arraycopy_restore_alloc_state(alloc, saved_reexecute_sp);
4384 // See arraycopy_restore_alloc_state() comment
4385 // if alloc == NULL we don't have to worry about a tightly coupled allocation so we can emit all needed guards
4386 // if saved_jvms != NULL (then alloc != NULL) then we can handle guards and a tightly coupled allocation
4387 // if saved_jvms == NULL and alloc != NULL, we can't emit any guards
4388 bool can_emit_guards = (alloc == NULL || saved_jvms != NULL);
4389
4390 // The following tests must be performed
4391 // (1) src and dest are arrays.
4392 // (2) src and dest arrays must have elements of the same BasicType
4393 // (3) src and dest must not be null.
4394 // (4) src_offset must not be negative.
4395 // (5) dest_offset must not be negative.
4396 // (6) length must not be negative.
4397 // (7) src_offset + length must not exceed length of src.
4398 // (8) dest_offset + length must not exceed length of dest.
4399 // (9) each element of an oop array must be assignable
4400
4401 // (3) src and dest must not be null.
4402 // always do this here because we need the JVM state for uncommon traps
4403 Node* null_ctl = top();
4404 src = saved_jvms != NULL ? null_check_oop(src, &null_ctl, true, true) : null_check(src, T_ARRAY);
4405 assert(null_ctl->is_top(), "no null control here");
4406 dest = null_check(dest, T_ARRAY);
4407
4408 if (!can_emit_guards) {
4409 // if saved_jvms == NULL and alloc != NULL, we don't emit any
4410 // guards but the arraycopy node could still take advantage of a
4411 // tightly allocated allocation. tightly_coupled_allocation() is
4412 // called again to make sure it takes the null check above into
4413 // account: the null check is mandatory and if it caused an
4414 // uncommon trap to be emitted then the allocation can't be
4415 // considered tightly coupled in this context.
4416 alloc = tightly_coupled_allocation(dest, NULL);
4417 }
4418
4419 bool validated = false;
4420
4421 const Type* src_type = _gvn.type(src);
4422 const Type* dest_type = _gvn.type(dest);
4423 const TypeAryPtr* top_src = src_type->isa_aryptr();
4424 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
4425
4426 // Do we have the type of src?
4427 bool has_src = (top_src != NULL && top_src->klass() != NULL);
4428 // Do we have the type of dest?
4429 bool has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4430 // Is the type for src from speculation?
4431 bool src_spec = false;
4432 // Is the type for dest from speculation?
4433 bool dest_spec = false;
4434
4435 if ((!has_src || !has_dest) && can_emit_guards) {
4436 // We don't have sufficient type information, let's see if
4437 // speculative types can help. We need to have types for both src
4438 // and dest so that it pays off.
4439
4440 // Do we already have or could we have type information for src
4441 bool could_have_src = has_src;
4442 // Do we already have or could we have type information for dest
4443 bool could_have_dest = has_dest;
4444
4445 ciKlass* src_k = NULL;
4446 if (!has_src) {
4447 src_k = src_type->speculative_type_not_null();
4448 if (src_k != NULL && src_k->is_array_klass()) {
4449 could_have_src = true;
4450 }
4451 }
4452
4453 ciKlass* dest_k = NULL;
4454 if (!has_dest) {
4455 dest_k = dest_type->speculative_type_not_null();
4456 if (dest_k != NULL && dest_k->is_array_klass()) {
4457 could_have_dest = true;
4458 }
4459 }
4460
4461 if (could_have_src && could_have_dest) {
4462 // This is going to pay off so emit the required guards
4463 if (!has_src) {
4464 src = maybe_cast_profiled_obj(src, src_k, true);
4465 src_type = _gvn.type(src);
4466 top_src = src_type->isa_aryptr();
4467 has_src = (top_src != NULL && top_src->klass() != NULL);
4468 src_spec = true;
4469 }
4470 if (!has_dest) {
4471 dest = maybe_cast_profiled_obj(dest, dest_k, true);
4472 dest_type = _gvn.type(dest);
4473 top_dest = dest_type->isa_aryptr();
4474 has_dest = (top_dest != NULL && top_dest->klass() != NULL);
4475 dest_spec = true;
4476 }
4477 }
4478 }
4479
4480 if (has_src && has_dest && can_emit_guards) {
4481 BasicType src_elem = top_src->klass()->as_array_klass()->element_type()->basic_type();
4482 BasicType dest_elem = top_dest->klass()->as_array_klass()->element_type()->basic_type();
4483 if (is_reference_type(src_elem)) src_elem = T_OBJECT;
4484 if (is_reference_type(dest_elem)) dest_elem = T_OBJECT;
4485
4486 if (src_elem == dest_elem && src_elem == T_OBJECT) {
4487 // If both arrays are object arrays then having the exact types
4488 // for both will remove the need for a subtype check at runtime
4489 // before the call and may make it possible to pick a faster copy
4490 // routine (without a subtype check on every element)
4491 // Do we have the exact type of src?
4492 bool could_have_src = src_spec;
4493 // Do we have the exact type of dest?
4494 bool could_have_dest = dest_spec;
4495 ciKlass* src_k = top_src->klass();
4496 ciKlass* dest_k = top_dest->klass();
4497 if (!src_spec) {
4498 src_k = src_type->speculative_type_not_null();
4499 if (src_k != NULL && src_k->is_array_klass()) {
4500 could_have_src = true;
4501 }
4502 }
4503 if (!dest_spec) {
4504 dest_k = dest_type->speculative_type_not_null();
4505 if (dest_k != NULL && dest_k->is_array_klass()) {
4506 could_have_dest = true;
4507 }
4508 }
4509 if (could_have_src && could_have_dest) {
4510 // If we can have both exact types, emit the missing guards
4511 if (could_have_src && !src_spec) {
4512 src = maybe_cast_profiled_obj(src, src_k, true);
4513 }
4514 if (could_have_dest && !dest_spec) {
4515 dest = maybe_cast_profiled_obj(dest, dest_k, true);
4516 }
4517 }
4518 }
4519 }
4520
4521 ciMethod* trap_method = method();
4522 int trap_bci = bci();
4523 if (saved_jvms != NULL) {
4524 trap_method = alloc->jvms()->method();
4525 trap_bci = alloc->jvms()->bci();
4526 }
4527
4528 bool negative_length_guard_generated = false;
4529
4530 if (!C->too_many_traps(trap_method, trap_bci, Deoptimization::Reason_intrinsic) &&
4531 can_emit_guards &&
4532 !src->is_top() && !dest->is_top()) {
4533 // validate arguments: enables transformation the ArrayCopyNode
4534 validated = true;
4535
4536 RegionNode* slow_region = new RegionNode(1);
4537 record_for_igvn(slow_region);
4538
4539 // (1) src and dest are arrays.
4540 generate_non_array_guard(load_object_klass(src), slow_region);
4541 generate_non_array_guard(load_object_klass(dest), slow_region);
4542
4543 // (2) src and dest arrays must have elements of the same BasicType
4544 // done at macro expansion or at Ideal transformation time
4545
4546 // (4) src_offset must not be negative.
4547 generate_negative_guard(src_offset, slow_region);
4548
4549 // (5) dest_offset must not be negative.
4550 generate_negative_guard(dest_offset, slow_region);
4551
4552 // (7) src_offset + length must not exceed length of src.
4553 generate_limit_guard(src_offset, length,
4554 load_array_length(src),
4555 slow_region);
4556
4557 // (8) dest_offset + length must not exceed length of dest.
4558 generate_limit_guard(dest_offset, length,
4559 load_array_length(dest),
4560 slow_region);
4561
4562 // (6) length must not be negative.
4563 // This is also checked in generate_arraycopy() during macro expansion, but
4564 // we also have to check it here for the case where the ArrayCopyNode will
4565 // be eliminated by Escape Analysis.
4566 if (EliminateAllocations) {
4567 generate_negative_guard(length, slow_region);
4568 negative_length_guard_generated = true;
4569 }
4570
4571 // (9) each element of an oop array must be assignable
4572 Node* dest_klass = load_object_klass(dest);
4573 if (src != dest) {
4574 Node* not_subtype_ctrl = gen_subtype_check(src, dest_klass);
4575
4576 if (not_subtype_ctrl != top()) {
4577 PreserveJVMState pjvms(this);
4578 set_control(not_subtype_ctrl);
4579 uncommon_trap(Deoptimization::Reason_intrinsic,
4580 Deoptimization::Action_make_not_entrant);
4581 assert(stopped(), "Should be stopped");
4582 }
4583 }
4584 {
4585 PreserveJVMState pjvms(this);
4586 set_control(_gvn.transform(slow_region));
4587 uncommon_trap(Deoptimization::Reason_intrinsic,
4588 Deoptimization::Action_make_not_entrant);
4589 assert(stopped(), "Should be stopped");
4590 }
4591
4592 const TypeKlassPtr* dest_klass_t = _gvn.type(dest_klass)->is_klassptr();
4593 const Type *toop = TypeOopPtr::make_from_klass(dest_klass_t->klass());
4594 src = _gvn.transform(new CheckCastPPNode(control(), src, toop));
4595 }
4596
4597 arraycopy_move_allocation_here(alloc, dest, saved_jvms, saved_reexecute_sp, new_idx);
4598
4599 if (stopped()) {
4600 return true;
4601 }
4602
4603 ArrayCopyNode* ac = ArrayCopyNode::make(this, true, src, src_offset, dest, dest_offset, length, alloc != NULL, negative_length_guard_generated,
4604 // Create LoadRange and LoadKlass nodes for use during macro expansion here
4605 // so the compiler has a chance to eliminate them: during macro expansion,
4606 // we have to set their control (CastPP nodes are eliminated).
4607 load_object_klass(src), load_object_klass(dest),
4608 load_array_length(src), load_array_length(dest));
4609
4610 ac->set_arraycopy(validated);
4611
4612 Node* n = _gvn.transform(ac);
4613 if (n == ac) {
4614 ac->connect_outputs(this);
4615 } else {
4616 assert(validated, "shouldn't transform if all arguments not validated");
4617 set_all_memory(n);
4618 }
4619 clear_upper_avx();
4620
4621
4622 return true;
4623 }
4624
4625
4626 // Helper function which determines if an arraycopy immediately follows
4627 // an allocation, with no intervening tests or other escapes for the object.
4628 AllocateArrayNode*
tightly_coupled_allocation(Node * ptr,RegionNode * slow_region)4629 LibraryCallKit::tightly_coupled_allocation(Node* ptr,
4630 RegionNode* slow_region) {
4631 if (stopped()) return NULL; // no fast path
4632 if (C->AliasLevel() == 0) return NULL; // no MergeMems around
4633
4634 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(ptr, &_gvn);
4635 if (alloc == NULL) return NULL;
4636
4637 Node* rawmem = memory(Compile::AliasIdxRaw);
4638 // Is the allocation's memory state untouched?
4639 if (!(rawmem->is_Proj() && rawmem->in(0)->is_Initialize())) {
4640 // Bail out if there have been raw-memory effects since the allocation.
4641 // (Example: There might have been a call or safepoint.)
4642 return NULL;
4643 }
4644 rawmem = rawmem->in(0)->as_Initialize()->memory(Compile::AliasIdxRaw);
4645 if (!(rawmem->is_Proj() && rawmem->in(0) == alloc)) {
4646 return NULL;
4647 }
4648
4649 // There must be no unexpected observers of this allocation.
4650 for (DUIterator_Fast imax, i = ptr->fast_outs(imax); i < imax; i++) {
4651 Node* obs = ptr->fast_out(i);
4652 if (obs != this->map()) {
4653 return NULL;
4654 }
4655 }
4656
4657 // This arraycopy must unconditionally follow the allocation of the ptr.
4658 Node* alloc_ctl = ptr->in(0);
4659 Node* ctl = control();
4660 while (ctl != alloc_ctl) {
4661 // There may be guards which feed into the slow_region.
4662 // Any other control flow means that we might not get a chance
4663 // to finish initializing the allocated object.
4664 if ((ctl->is_IfFalse() || ctl->is_IfTrue()) && ctl->in(0)->is_If()) {
4665 IfNode* iff = ctl->in(0)->as_If();
4666 Node* not_ctl = iff->proj_out_or_null(1 - ctl->as_Proj()->_con);
4667 assert(not_ctl != NULL && not_ctl != ctl, "found alternate");
4668 if (slow_region != NULL && slow_region->find_edge(not_ctl) >= 1) {
4669 ctl = iff->in(0); // This test feeds the known slow_region.
4670 continue;
4671 }
4672 // One more try: Various low-level checks bottom out in
4673 // uncommon traps. If the debug-info of the trap omits
4674 // any reference to the allocation, as we've already
4675 // observed, then there can be no objection to the trap.
4676 bool found_trap = false;
4677 for (DUIterator_Fast jmax, j = not_ctl->fast_outs(jmax); j < jmax; j++) {
4678 Node* obs = not_ctl->fast_out(j);
4679 if (obs->in(0) == not_ctl && obs->is_Call() &&
4680 (obs->as_Call()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point())) {
4681 found_trap = true; break;
4682 }
4683 }
4684 if (found_trap) {
4685 ctl = iff->in(0); // This test feeds a harmless uncommon trap.
4686 continue;
4687 }
4688 }
4689 return NULL;
4690 }
4691
4692 // If we get this far, we have an allocation which immediately
4693 // precedes the arraycopy, and we can take over zeroing the new object.
4694 // The arraycopy will finish the initialization, and provide
4695 // a new control state to which we will anchor the destination pointer.
4696
4697 return alloc;
4698 }
4699
4700 //-------------inline_encodeISOArray-----------------------------------
4701 // encode char[] to byte[] in ISO_8859_1
inline_encodeISOArray()4702 bool LibraryCallKit::inline_encodeISOArray() {
4703 assert(callee()->signature()->size() == 5, "encodeISOArray has 5 parameters");
4704 // no receiver since it is static method
4705 Node *src = argument(0);
4706 Node *src_offset = argument(1);
4707 Node *dst = argument(2);
4708 Node *dst_offset = argument(3);
4709 Node *length = argument(4);
4710
4711 src = must_be_not_null(src, true);
4712 dst = must_be_not_null(dst, true);
4713
4714 const Type* src_type = src->Value(&_gvn);
4715 const Type* dst_type = dst->Value(&_gvn);
4716 const TypeAryPtr* top_src = src_type->isa_aryptr();
4717 const TypeAryPtr* top_dest = dst_type->isa_aryptr();
4718 if (top_src == NULL || top_src->klass() == NULL ||
4719 top_dest == NULL || top_dest->klass() == NULL) {
4720 // failed array check
4721 return false;
4722 }
4723
4724 // Figure out the size and type of the elements we will be copying.
4725 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4726 BasicType dst_elem = dst_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4727 if (!((src_elem == T_CHAR) || (src_elem== T_BYTE)) || dst_elem != T_BYTE) {
4728 return false;
4729 }
4730
4731 Node* src_start = array_element_address(src, src_offset, T_CHAR);
4732 Node* dst_start = array_element_address(dst, dst_offset, dst_elem);
4733 // 'src_start' points to src array + scaled offset
4734 // 'dst_start' points to dst array + scaled offset
4735
4736 const TypeAryPtr* mtype = TypeAryPtr::BYTES;
4737 Node* enc = new EncodeISOArrayNode(control(), memory(mtype), src_start, dst_start, length);
4738 enc = _gvn.transform(enc);
4739 Node* res_mem = _gvn.transform(new SCMemProjNode(enc));
4740 set_memory(res_mem, mtype);
4741 set_result(enc);
4742 clear_upper_avx();
4743
4744 return true;
4745 }
4746
4747 //-------------inline_multiplyToLen-----------------------------------
inline_multiplyToLen()4748 bool LibraryCallKit::inline_multiplyToLen() {
4749 assert(UseMultiplyToLenIntrinsic, "not implemented on this platform");
4750
4751 address stubAddr = StubRoutines::multiplyToLen();
4752 if (stubAddr == NULL) {
4753 return false; // Intrinsic's stub is not implemented on this platform
4754 }
4755 const char* stubName = "multiplyToLen";
4756
4757 assert(callee()->signature()->size() == 5, "multiplyToLen has 5 parameters");
4758
4759 // no receiver because it is a static method
4760 Node* x = argument(0);
4761 Node* xlen = argument(1);
4762 Node* y = argument(2);
4763 Node* ylen = argument(3);
4764 Node* z = argument(4);
4765
4766 x = must_be_not_null(x, true);
4767 y = must_be_not_null(y, true);
4768
4769 const Type* x_type = x->Value(&_gvn);
4770 const Type* y_type = y->Value(&_gvn);
4771 const TypeAryPtr* top_x = x_type->isa_aryptr();
4772 const TypeAryPtr* top_y = y_type->isa_aryptr();
4773 if (top_x == NULL || top_x->klass() == NULL ||
4774 top_y == NULL || top_y->klass() == NULL) {
4775 // failed array check
4776 return false;
4777 }
4778
4779 BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4780 BasicType y_elem = y_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4781 if (x_elem != T_INT || y_elem != T_INT) {
4782 return false;
4783 }
4784
4785 // Set the original stack and the reexecute bit for the interpreter to reexecute
4786 // the bytecode that invokes BigInteger.multiplyToLen() if deoptimization happens
4787 // on the return from z array allocation in runtime.
4788 { PreserveReexecuteState preexecs(this);
4789 jvms()->set_should_reexecute(true);
4790
4791 Node* x_start = array_element_address(x, intcon(0), x_elem);
4792 Node* y_start = array_element_address(y, intcon(0), y_elem);
4793 // 'x_start' points to x array + scaled xlen
4794 // 'y_start' points to y array + scaled ylen
4795
4796 // Allocate the result array
4797 Node* zlen = _gvn.transform(new AddINode(xlen, ylen));
4798 ciKlass* klass = ciTypeArrayKlass::make(T_INT);
4799 Node* klass_node = makecon(TypeKlassPtr::make(klass));
4800
4801 IdealKit ideal(this);
4802
4803 #define __ ideal.
4804 Node* one = __ ConI(1);
4805 Node* zero = __ ConI(0);
4806 IdealVariable need_alloc(ideal), z_alloc(ideal); __ declarations_done();
4807 __ set(need_alloc, zero);
4808 __ set(z_alloc, z);
4809 __ if_then(z, BoolTest::eq, null()); {
4810 __ increment (need_alloc, one);
4811 } __ else_(); {
4812 // Update graphKit memory and control from IdealKit.
4813 sync_kit(ideal);
4814 Node *cast = new CastPPNode(z, TypePtr::NOTNULL);
4815 cast->init_req(0, control());
4816 _gvn.set_type(cast, cast->bottom_type());
4817 C->record_for_igvn(cast);
4818
4819 Node* zlen_arg = load_array_length(cast);
4820 // Update IdealKit memory and control from graphKit.
4821 __ sync_kit(this);
4822 __ if_then(zlen_arg, BoolTest::lt, zlen); {
4823 __ increment (need_alloc, one);
4824 } __ end_if();
4825 } __ end_if();
4826
4827 __ if_then(__ value(need_alloc), BoolTest::ne, zero); {
4828 // Update graphKit memory and control from IdealKit.
4829 sync_kit(ideal);
4830 Node * narr = new_array(klass_node, zlen, 1);
4831 // Update IdealKit memory and control from graphKit.
4832 __ sync_kit(this);
4833 __ set(z_alloc, narr);
4834 } __ end_if();
4835
4836 sync_kit(ideal);
4837 z = __ value(z_alloc);
4838 // Can't use TypeAryPtr::INTS which uses Bottom offset.
4839 _gvn.set_type(z, TypeOopPtr::make_from_klass(klass));
4840 // Final sync IdealKit and GraphKit.
4841 final_sync(ideal);
4842 #undef __
4843
4844 Node* z_start = array_element_address(z, intcon(0), T_INT);
4845
4846 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
4847 OptoRuntime::multiplyToLen_Type(),
4848 stubAddr, stubName, TypePtr::BOTTOM,
4849 x_start, xlen, y_start, ylen, z_start, zlen);
4850 } // original reexecute is set back here
4851
4852 C->set_has_split_ifs(true); // Has chance for split-if optimization
4853 set_result(z);
4854 return true;
4855 }
4856
4857 //-------------inline_squareToLen------------------------------------
inline_squareToLen()4858 bool LibraryCallKit::inline_squareToLen() {
4859 assert(UseSquareToLenIntrinsic, "not implemented on this platform");
4860
4861 address stubAddr = StubRoutines::squareToLen();
4862 if (stubAddr == NULL) {
4863 return false; // Intrinsic's stub is not implemented on this platform
4864 }
4865 const char* stubName = "squareToLen";
4866
4867 assert(callee()->signature()->size() == 4, "implSquareToLen has 4 parameters");
4868
4869 Node* x = argument(0);
4870 Node* len = argument(1);
4871 Node* z = argument(2);
4872 Node* zlen = argument(3);
4873
4874 x = must_be_not_null(x, true);
4875 z = must_be_not_null(z, true);
4876
4877 const Type* x_type = x->Value(&_gvn);
4878 const Type* z_type = z->Value(&_gvn);
4879 const TypeAryPtr* top_x = x_type->isa_aryptr();
4880 const TypeAryPtr* top_z = z_type->isa_aryptr();
4881 if (top_x == NULL || top_x->klass() == NULL ||
4882 top_z == NULL || top_z->klass() == NULL) {
4883 // failed array check
4884 return false;
4885 }
4886
4887 BasicType x_elem = x_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4888 BasicType z_elem = z_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4889 if (x_elem != T_INT || z_elem != T_INT) {
4890 return false;
4891 }
4892
4893
4894 Node* x_start = array_element_address(x, intcon(0), x_elem);
4895 Node* z_start = array_element_address(z, intcon(0), z_elem);
4896
4897 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
4898 OptoRuntime::squareToLen_Type(),
4899 stubAddr, stubName, TypePtr::BOTTOM,
4900 x_start, len, z_start, zlen);
4901
4902 set_result(z);
4903 return true;
4904 }
4905
4906 //-------------inline_mulAdd------------------------------------------
inline_mulAdd()4907 bool LibraryCallKit::inline_mulAdd() {
4908 assert(UseMulAddIntrinsic, "not implemented on this platform");
4909
4910 address stubAddr = StubRoutines::mulAdd();
4911 if (stubAddr == NULL) {
4912 return false; // Intrinsic's stub is not implemented on this platform
4913 }
4914 const char* stubName = "mulAdd";
4915
4916 assert(callee()->signature()->size() == 5, "mulAdd has 5 parameters");
4917
4918 Node* out = argument(0);
4919 Node* in = argument(1);
4920 Node* offset = argument(2);
4921 Node* len = argument(3);
4922 Node* k = argument(4);
4923
4924 out = must_be_not_null(out, true);
4925
4926 const Type* out_type = out->Value(&_gvn);
4927 const Type* in_type = in->Value(&_gvn);
4928 const TypeAryPtr* top_out = out_type->isa_aryptr();
4929 const TypeAryPtr* top_in = in_type->isa_aryptr();
4930 if (top_out == NULL || top_out->klass() == NULL ||
4931 top_in == NULL || top_in->klass() == NULL) {
4932 // failed array check
4933 return false;
4934 }
4935
4936 BasicType out_elem = out_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4937 BasicType in_elem = in_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4938 if (out_elem != T_INT || in_elem != T_INT) {
4939 return false;
4940 }
4941
4942 Node* outlen = load_array_length(out);
4943 Node* new_offset = _gvn.transform(new SubINode(outlen, offset));
4944 Node* out_start = array_element_address(out, intcon(0), out_elem);
4945 Node* in_start = array_element_address(in, intcon(0), in_elem);
4946
4947 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP,
4948 OptoRuntime::mulAdd_Type(),
4949 stubAddr, stubName, TypePtr::BOTTOM,
4950 out_start,in_start, new_offset, len, k);
4951 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
4952 set_result(result);
4953 return true;
4954 }
4955
4956 //-------------inline_montgomeryMultiply-----------------------------------
inline_montgomeryMultiply()4957 bool LibraryCallKit::inline_montgomeryMultiply() {
4958 address stubAddr = StubRoutines::montgomeryMultiply();
4959 if (stubAddr == NULL) {
4960 return false; // Intrinsic's stub is not implemented on this platform
4961 }
4962
4963 assert(UseMontgomeryMultiplyIntrinsic, "not implemented on this platform");
4964 const char* stubName = "montgomery_multiply";
4965
4966 assert(callee()->signature()->size() == 7, "montgomeryMultiply has 7 parameters");
4967
4968 Node* a = argument(0);
4969 Node* b = argument(1);
4970 Node* n = argument(2);
4971 Node* len = argument(3);
4972 Node* inv = argument(4);
4973 Node* m = argument(6);
4974
4975 const Type* a_type = a->Value(&_gvn);
4976 const TypeAryPtr* top_a = a_type->isa_aryptr();
4977 const Type* b_type = b->Value(&_gvn);
4978 const TypeAryPtr* top_b = b_type->isa_aryptr();
4979 const Type* n_type = a->Value(&_gvn);
4980 const TypeAryPtr* top_n = n_type->isa_aryptr();
4981 const Type* m_type = a->Value(&_gvn);
4982 const TypeAryPtr* top_m = m_type->isa_aryptr();
4983 if (top_a == NULL || top_a->klass() == NULL ||
4984 top_b == NULL || top_b->klass() == NULL ||
4985 top_n == NULL || top_n->klass() == NULL ||
4986 top_m == NULL || top_m->klass() == NULL) {
4987 // failed array check
4988 return false;
4989 }
4990
4991 BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4992 BasicType b_elem = b_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4993 BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4994 BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
4995 if (a_elem != T_INT || b_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
4996 return false;
4997 }
4998
4999 // Make the call
5000 {
5001 Node* a_start = array_element_address(a, intcon(0), a_elem);
5002 Node* b_start = array_element_address(b, intcon(0), b_elem);
5003 Node* n_start = array_element_address(n, intcon(0), n_elem);
5004 Node* m_start = array_element_address(m, intcon(0), m_elem);
5005
5006 Node* call = make_runtime_call(RC_LEAF,
5007 OptoRuntime::montgomeryMultiply_Type(),
5008 stubAddr, stubName, TypePtr::BOTTOM,
5009 a_start, b_start, n_start, len, inv, top(),
5010 m_start);
5011 set_result(m);
5012 }
5013
5014 return true;
5015 }
5016
inline_montgomerySquare()5017 bool LibraryCallKit::inline_montgomerySquare() {
5018 address stubAddr = StubRoutines::montgomerySquare();
5019 if (stubAddr == NULL) {
5020 return false; // Intrinsic's stub is not implemented on this platform
5021 }
5022
5023 assert(UseMontgomerySquareIntrinsic, "not implemented on this platform");
5024 const char* stubName = "montgomery_square";
5025
5026 assert(callee()->signature()->size() == 6, "montgomerySquare has 6 parameters");
5027
5028 Node* a = argument(0);
5029 Node* n = argument(1);
5030 Node* len = argument(2);
5031 Node* inv = argument(3);
5032 Node* m = argument(5);
5033
5034 const Type* a_type = a->Value(&_gvn);
5035 const TypeAryPtr* top_a = a_type->isa_aryptr();
5036 const Type* n_type = a->Value(&_gvn);
5037 const TypeAryPtr* top_n = n_type->isa_aryptr();
5038 const Type* m_type = a->Value(&_gvn);
5039 const TypeAryPtr* top_m = m_type->isa_aryptr();
5040 if (top_a == NULL || top_a->klass() == NULL ||
5041 top_n == NULL || top_n->klass() == NULL ||
5042 top_m == NULL || top_m->klass() == NULL) {
5043 // failed array check
5044 return false;
5045 }
5046
5047 BasicType a_elem = a_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5048 BasicType n_elem = n_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5049 BasicType m_elem = m_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5050 if (a_elem != T_INT || n_elem != T_INT || m_elem != T_INT) {
5051 return false;
5052 }
5053
5054 // Make the call
5055 {
5056 Node* a_start = array_element_address(a, intcon(0), a_elem);
5057 Node* n_start = array_element_address(n, intcon(0), n_elem);
5058 Node* m_start = array_element_address(m, intcon(0), m_elem);
5059
5060 Node* call = make_runtime_call(RC_LEAF,
5061 OptoRuntime::montgomerySquare_Type(),
5062 stubAddr, stubName, TypePtr::BOTTOM,
5063 a_start, n_start, len, inv, top(),
5064 m_start);
5065 set_result(m);
5066 }
5067
5068 return true;
5069 }
5070
inline_bigIntegerShift(bool isRightShift)5071 bool LibraryCallKit::inline_bigIntegerShift(bool isRightShift) {
5072 address stubAddr = NULL;
5073 const char* stubName = NULL;
5074
5075 stubAddr = isRightShift? StubRoutines::bigIntegerRightShift(): StubRoutines::bigIntegerLeftShift();
5076 if (stubAddr == NULL) {
5077 return false; // Intrinsic's stub is not implemented on this platform
5078 }
5079
5080 stubName = isRightShift? "bigIntegerRightShiftWorker" : "bigIntegerLeftShiftWorker";
5081
5082 assert(callee()->signature()->size() == 5, "expected 5 arguments");
5083
5084 Node* newArr = argument(0);
5085 Node* oldArr = argument(1);
5086 Node* newIdx = argument(2);
5087 Node* shiftCount = argument(3);
5088 Node* numIter = argument(4);
5089
5090 const Type* newArr_type = newArr->Value(&_gvn);
5091 const TypeAryPtr* top_newArr = newArr_type->isa_aryptr();
5092 const Type* oldArr_type = oldArr->Value(&_gvn);
5093 const TypeAryPtr* top_oldArr = oldArr_type->isa_aryptr();
5094 if (top_newArr == NULL || top_newArr->klass() == NULL || top_oldArr == NULL
5095 || top_oldArr->klass() == NULL) {
5096 return false;
5097 }
5098
5099 BasicType newArr_elem = newArr_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5100 BasicType oldArr_elem = oldArr_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5101 if (newArr_elem != T_INT || oldArr_elem != T_INT) {
5102 return false;
5103 }
5104
5105 // Make the call
5106 {
5107 Node* newArr_start = array_element_address(newArr, intcon(0), newArr_elem);
5108 Node* oldArr_start = array_element_address(oldArr, intcon(0), oldArr_elem);
5109
5110 Node* call = make_runtime_call(RC_LEAF,
5111 OptoRuntime::bigIntegerShift_Type(),
5112 stubAddr,
5113 stubName,
5114 TypePtr::BOTTOM,
5115 newArr_start,
5116 oldArr_start,
5117 newIdx,
5118 shiftCount,
5119 numIter);
5120 }
5121
5122 return true;
5123 }
5124
5125 //-------------inline_vectorizedMismatch------------------------------
inline_vectorizedMismatch()5126 bool LibraryCallKit::inline_vectorizedMismatch() {
5127 assert(UseVectorizedMismatchIntrinsic, "not implementated on this platform");
5128
5129 address stubAddr = StubRoutines::vectorizedMismatch();
5130 if (stubAddr == NULL) {
5131 return false; // Intrinsic's stub is not implemented on this platform
5132 }
5133 const char* stubName = "vectorizedMismatch";
5134 int size_l = callee()->signature()->size();
5135 assert(callee()->signature()->size() == 8, "vectorizedMismatch has 6 parameters");
5136
5137 Node* obja = argument(0);
5138 Node* aoffset = argument(1);
5139 Node* objb = argument(3);
5140 Node* boffset = argument(4);
5141 Node* length = argument(6);
5142 Node* scale = argument(7);
5143
5144 const Type* a_type = obja->Value(&_gvn);
5145 const Type* b_type = objb->Value(&_gvn);
5146 const TypeAryPtr* top_a = a_type->isa_aryptr();
5147 const TypeAryPtr* top_b = b_type->isa_aryptr();
5148 if (top_a == NULL || top_a->klass() == NULL ||
5149 top_b == NULL || top_b->klass() == NULL) {
5150 // failed array check
5151 return false;
5152 }
5153
5154 Node* call;
5155 jvms()->set_should_reexecute(true);
5156
5157 Node* obja_adr = make_unsafe_address(obja, aoffset, ACCESS_READ);
5158 Node* objb_adr = make_unsafe_address(objb, boffset, ACCESS_READ);
5159
5160 call = make_runtime_call(RC_LEAF,
5161 OptoRuntime::vectorizedMismatch_Type(),
5162 stubAddr, stubName, TypePtr::BOTTOM,
5163 obja_adr, objb_adr, length, scale);
5164
5165 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5166 set_result(result);
5167 return true;
5168 }
5169
5170 /**
5171 * Calculate CRC32 for byte.
5172 * int java.util.zip.CRC32.update(int crc, int b)
5173 */
inline_updateCRC32()5174 bool LibraryCallKit::inline_updateCRC32() {
5175 assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5176 assert(callee()->signature()->size() == 2, "update has 2 parameters");
5177 // no receiver since it is static method
5178 Node* crc = argument(0); // type: int
5179 Node* b = argument(1); // type: int
5180
5181 /*
5182 * int c = ~ crc;
5183 * b = timesXtoThe32[(b ^ c) & 0xFF];
5184 * b = b ^ (c >>> 8);
5185 * crc = ~b;
5186 */
5187
5188 Node* M1 = intcon(-1);
5189 crc = _gvn.transform(new XorINode(crc, M1));
5190 Node* result = _gvn.transform(new XorINode(crc, b));
5191 result = _gvn.transform(new AndINode(result, intcon(0xFF)));
5192
5193 Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr()));
5194 Node* offset = _gvn.transform(new LShiftINode(result, intcon(0x2)));
5195 Node* adr = basic_plus_adr(top(), base, ConvI2X(offset));
5196 result = make_load(control(), adr, TypeInt::INT, T_INT, MemNode::unordered);
5197
5198 crc = _gvn.transform(new URShiftINode(crc, intcon(8)));
5199 result = _gvn.transform(new XorINode(crc, result));
5200 result = _gvn.transform(new XorINode(result, M1));
5201 set_result(result);
5202 return true;
5203 }
5204
5205 /**
5206 * Calculate CRC32 for byte[] array.
5207 * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len)
5208 */
inline_updateBytesCRC32()5209 bool LibraryCallKit::inline_updateBytesCRC32() {
5210 assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5211 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5212 // no receiver since it is static method
5213 Node* crc = argument(0); // type: int
5214 Node* src = argument(1); // type: oop
5215 Node* offset = argument(2); // type: int
5216 Node* length = argument(3); // type: int
5217
5218 const Type* src_type = src->Value(&_gvn);
5219 const TypeAryPtr* top_src = src_type->isa_aryptr();
5220 if (top_src == NULL || top_src->klass() == NULL) {
5221 // failed array check
5222 return false;
5223 }
5224
5225 // Figure out the size and type of the elements we will be copying.
5226 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5227 if (src_elem != T_BYTE) {
5228 return false;
5229 }
5230
5231 // 'src_start' points to src array + scaled offset
5232 src = must_be_not_null(src, true);
5233 Node* src_start = array_element_address(src, offset, src_elem);
5234
5235 // We assume that range check is done by caller.
5236 // TODO: generate range check (offset+length < src.length) in debug VM.
5237
5238 // Call the stub.
5239 address stubAddr = StubRoutines::updateBytesCRC32();
5240 const char *stubName = "updateBytesCRC32";
5241
5242 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5243 stubAddr, stubName, TypePtr::BOTTOM,
5244 crc, src_start, length);
5245 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5246 set_result(result);
5247 return true;
5248 }
5249
5250 /**
5251 * Calculate CRC32 for ByteBuffer.
5252 * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
5253 */
inline_updateByteBufferCRC32()5254 bool LibraryCallKit::inline_updateByteBufferCRC32() {
5255 assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support");
5256 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5257 // no receiver since it is static method
5258 Node* crc = argument(0); // type: int
5259 Node* src = argument(1); // type: long
5260 Node* offset = argument(3); // type: int
5261 Node* length = argument(4); // type: int
5262
5263 src = ConvL2X(src); // adjust Java long to machine word
5264 Node* base = _gvn.transform(new CastX2PNode(src));
5265 offset = ConvI2X(offset);
5266
5267 // 'src_start' points to src array + scaled offset
5268 Node* src_start = basic_plus_adr(top(), base, offset);
5269
5270 // Call the stub.
5271 address stubAddr = StubRoutines::updateBytesCRC32();
5272 const char *stubName = "updateBytesCRC32";
5273
5274 Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(),
5275 stubAddr, stubName, TypePtr::BOTTOM,
5276 crc, src_start, length);
5277 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5278 set_result(result);
5279 return true;
5280 }
5281
5282 //------------------------------get_table_from_crc32c_class-----------------------
get_table_from_crc32c_class(ciInstanceKlass * crc32c_class)5283 Node * LibraryCallKit::get_table_from_crc32c_class(ciInstanceKlass *crc32c_class) {
5284 Node* table = load_field_from_object(NULL, "byteTable", "[I", /*decorators*/ IN_HEAP, /*is_static*/ true, crc32c_class);
5285 assert (table != NULL, "wrong version of java.util.zip.CRC32C");
5286
5287 return table;
5288 }
5289
5290 //------------------------------inline_updateBytesCRC32C-----------------------
5291 //
5292 // Calculate CRC32C for byte[] array.
5293 // int java.util.zip.CRC32C.updateBytes(int crc, byte[] buf, int off, int end)
5294 //
inline_updateBytesCRC32C()5295 bool LibraryCallKit::inline_updateBytesCRC32C() {
5296 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5297 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5298 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5299 // no receiver since it is a static method
5300 Node* crc = argument(0); // type: int
5301 Node* src = argument(1); // type: oop
5302 Node* offset = argument(2); // type: int
5303 Node* end = argument(3); // type: int
5304
5305 Node* length = _gvn.transform(new SubINode(end, offset));
5306
5307 const Type* src_type = src->Value(&_gvn);
5308 const TypeAryPtr* top_src = src_type->isa_aryptr();
5309 if (top_src == NULL || top_src->klass() == NULL) {
5310 // failed array check
5311 return false;
5312 }
5313
5314 // Figure out the size and type of the elements we will be copying.
5315 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5316 if (src_elem != T_BYTE) {
5317 return false;
5318 }
5319
5320 // 'src_start' points to src array + scaled offset
5321 src = must_be_not_null(src, true);
5322 Node* src_start = array_element_address(src, offset, src_elem);
5323
5324 // static final int[] byteTable in class CRC32C
5325 Node* table = get_table_from_crc32c_class(callee()->holder());
5326 table = must_be_not_null(table, true);
5327 Node* table_start = array_element_address(table, intcon(0), T_INT);
5328
5329 // We assume that range check is done by caller.
5330 // TODO: generate range check (offset+length < src.length) in debug VM.
5331
5332 // Call the stub.
5333 address stubAddr = StubRoutines::updateBytesCRC32C();
5334 const char *stubName = "updateBytesCRC32C";
5335
5336 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5337 stubAddr, stubName, TypePtr::BOTTOM,
5338 crc, src_start, length, table_start);
5339 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5340 set_result(result);
5341 return true;
5342 }
5343
5344 //------------------------------inline_updateDirectByteBufferCRC32C-----------------------
5345 //
5346 // Calculate CRC32C for DirectByteBuffer.
5347 // int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
5348 //
inline_updateDirectByteBufferCRC32C()5349 bool LibraryCallKit::inline_updateDirectByteBufferCRC32C() {
5350 assert(UseCRC32CIntrinsics, "need CRC32C instruction support");
5351 assert(callee()->signature()->size() == 5, "updateDirectByteBuffer has 4 parameters and one is long");
5352 assert(callee()->holder()->is_loaded(), "CRC32C class must be loaded");
5353 // no receiver since it is a static method
5354 Node* crc = argument(0); // type: int
5355 Node* src = argument(1); // type: long
5356 Node* offset = argument(3); // type: int
5357 Node* end = argument(4); // type: int
5358
5359 Node* length = _gvn.transform(new SubINode(end, offset));
5360
5361 src = ConvL2X(src); // adjust Java long to machine word
5362 Node* base = _gvn.transform(new CastX2PNode(src));
5363 offset = ConvI2X(offset);
5364
5365 // 'src_start' points to src array + scaled offset
5366 Node* src_start = basic_plus_adr(top(), base, offset);
5367
5368 // static final int[] byteTable in class CRC32C
5369 Node* table = get_table_from_crc32c_class(callee()->holder());
5370 table = must_be_not_null(table, true);
5371 Node* table_start = array_element_address(table, intcon(0), T_INT);
5372
5373 // Call the stub.
5374 address stubAddr = StubRoutines::updateBytesCRC32C();
5375 const char *stubName = "updateBytesCRC32C";
5376
5377 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesCRC32C_Type(),
5378 stubAddr, stubName, TypePtr::BOTTOM,
5379 crc, src_start, length, table_start);
5380 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5381 set_result(result);
5382 return true;
5383 }
5384
5385 //------------------------------inline_updateBytesAdler32----------------------
5386 //
5387 // Calculate Adler32 checksum for byte[] array.
5388 // int java.util.zip.Adler32.updateBytes(int crc, byte[] buf, int off, int len)
5389 //
inline_updateBytesAdler32()5390 bool LibraryCallKit::inline_updateBytesAdler32() {
5391 assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
5392 assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters");
5393 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
5394 // no receiver since it is static method
5395 Node* crc = argument(0); // type: int
5396 Node* src = argument(1); // type: oop
5397 Node* offset = argument(2); // type: int
5398 Node* length = argument(3); // type: int
5399
5400 const Type* src_type = src->Value(&_gvn);
5401 const TypeAryPtr* top_src = src_type->isa_aryptr();
5402 if (top_src == NULL || top_src->klass() == NULL) {
5403 // failed array check
5404 return false;
5405 }
5406
5407 // Figure out the size and type of the elements we will be copying.
5408 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
5409 if (src_elem != T_BYTE) {
5410 return false;
5411 }
5412
5413 // 'src_start' points to src array + scaled offset
5414 Node* src_start = array_element_address(src, offset, src_elem);
5415
5416 // We assume that range check is done by caller.
5417 // TODO: generate range check (offset+length < src.length) in debug VM.
5418
5419 // Call the stub.
5420 address stubAddr = StubRoutines::updateBytesAdler32();
5421 const char *stubName = "updateBytesAdler32";
5422
5423 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
5424 stubAddr, stubName, TypePtr::BOTTOM,
5425 crc, src_start, length);
5426 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5427 set_result(result);
5428 return true;
5429 }
5430
5431 //------------------------------inline_updateByteBufferAdler32---------------
5432 //
5433 // Calculate Adler32 checksum for DirectByteBuffer.
5434 // int java.util.zip.Adler32.updateByteBuffer(int crc, long buf, int off, int len)
5435 //
inline_updateByteBufferAdler32()5436 bool LibraryCallKit::inline_updateByteBufferAdler32() {
5437 assert(UseAdler32Intrinsics, "Adler32 Instrinsic support need"); // check if we actually need to check this flag or check a different one
5438 assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long");
5439 assert(callee()->holder()->is_loaded(), "Adler32 class must be loaded");
5440 // no receiver since it is static method
5441 Node* crc = argument(0); // type: int
5442 Node* src = argument(1); // type: long
5443 Node* offset = argument(3); // type: int
5444 Node* length = argument(4); // type: int
5445
5446 src = ConvL2X(src); // adjust Java long to machine word
5447 Node* base = _gvn.transform(new CastX2PNode(src));
5448 offset = ConvI2X(offset);
5449
5450 // 'src_start' points to src array + scaled offset
5451 Node* src_start = basic_plus_adr(top(), base, offset);
5452
5453 // Call the stub.
5454 address stubAddr = StubRoutines::updateBytesAdler32();
5455 const char *stubName = "updateBytesAdler32";
5456
5457 Node* call = make_runtime_call(RC_LEAF, OptoRuntime::updateBytesAdler32_Type(),
5458 stubAddr, stubName, TypePtr::BOTTOM,
5459 crc, src_start, length);
5460
5461 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
5462 set_result(result);
5463 return true;
5464 }
5465
5466 //----------------------------inline_reference_get----------------------------
5467 // public T java.lang.ref.Reference.get();
inline_reference_get()5468 bool LibraryCallKit::inline_reference_get() {
5469 const int referent_offset = java_lang_ref_Reference::referent_offset();
5470
5471 // Get the argument:
5472 Node* reference_obj = null_check_receiver();
5473 if (stopped()) return true;
5474
5475 DecoratorSet decorators = IN_HEAP | ON_WEAK_OOP_REF;
5476 Node* result = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
5477 decorators, /*is_static*/ false, NULL);
5478 if (result == NULL) return false;
5479
5480 // Add memory barrier to prevent commoning reads from this field
5481 // across safepoint since GC can change its value.
5482 insert_mem_bar(Op_MemBarCPUOrder);
5483
5484 set_result(result);
5485 return true;
5486 }
5487
5488 //----------------------------inline_reference_refersTo0----------------------------
5489 // bool java.lang.ref.Reference.refersTo0();
5490 // bool java.lang.ref.PhantomReference.refersTo0();
inline_reference_refersTo0(bool is_phantom)5491 bool LibraryCallKit::inline_reference_refersTo0(bool is_phantom) {
5492 // Get arguments:
5493 Node* reference_obj = null_check_receiver();
5494 Node* other_obj = argument(1);
5495 if (stopped()) return true;
5496
5497 DecoratorSet decorators = IN_HEAP | AS_NO_KEEPALIVE;
5498 decorators |= (is_phantom ? ON_PHANTOM_OOP_REF : ON_WEAK_OOP_REF);
5499 Node* referent = load_field_from_object(reference_obj, "referent", "Ljava/lang/Object;",
5500 decorators, /*is_static*/ false, NULL);
5501 if (referent == NULL) return false;
5502
5503 // Add memory barrier to prevent commoning reads from this field
5504 // across safepoint since GC can change its value.
5505 insert_mem_bar(Op_MemBarCPUOrder);
5506
5507 Node* cmp = _gvn.transform(new CmpPNode(referent, other_obj));
5508 Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
5509 IfNode* if_node = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
5510
5511 RegionNode* region = new RegionNode(3);
5512 PhiNode* phi = new PhiNode(region, TypeInt::BOOL);
5513
5514 Node* if_true = _gvn.transform(new IfTrueNode(if_node));
5515 region->init_req(1, if_true);
5516 phi->init_req(1, intcon(1));
5517
5518 Node* if_false = _gvn.transform(new IfFalseNode(if_node));
5519 region->init_req(2, if_false);
5520 phi->init_req(2, intcon(0));
5521
5522 set_control(_gvn.transform(region));
5523 record_for_igvn(region);
5524 set_result(_gvn.transform(phi));
5525 return true;
5526 }
5527
5528
load_field_from_object(Node * fromObj,const char * fieldName,const char * fieldTypeString,DecoratorSet decorators=IN_HEAP,bool is_static=false,ciInstanceKlass * fromKls=NULL)5529 Node* LibraryCallKit::load_field_from_object(Node* fromObj, const char* fieldName, const char* fieldTypeString,
5530 DecoratorSet decorators = IN_HEAP, bool is_static = false,
5531 ciInstanceKlass* fromKls = NULL) {
5532 if (fromKls == NULL) {
5533 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5534 assert(tinst != NULL, "obj is null");
5535 assert(tinst->klass()->is_loaded(), "obj is not loaded");
5536 fromKls = tinst->klass()->as_instance_klass();
5537 } else {
5538 assert(is_static, "only for static field access");
5539 }
5540 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
5541 ciSymbol::make(fieldTypeString),
5542 is_static);
5543
5544 assert (field != NULL, "undefined field");
5545 if (field == NULL) return (Node *) NULL;
5546
5547 if (is_static) {
5548 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
5549 fromObj = makecon(tip);
5550 }
5551
5552 // Next code copied from Parse::do_get_xxx():
5553
5554 // Compute address and memory type.
5555 int offset = field->offset_in_bytes();
5556 bool is_vol = field->is_volatile();
5557 ciType* field_klass = field->type();
5558 assert(field_klass->is_loaded(), "should be loaded");
5559 const TypePtr* adr_type = C->alias_type(field)->adr_type();
5560 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
5561 BasicType bt = field->layout_type();
5562
5563 // Build the resultant type of the load
5564 const Type *type;
5565 if (bt == T_OBJECT) {
5566 type = TypeOopPtr::make_from_klass(field_klass->as_klass());
5567 } else {
5568 type = Type::get_const_basic_type(bt);
5569 }
5570
5571 if (is_vol) {
5572 decorators |= MO_SEQ_CST;
5573 }
5574
5575 return access_load_at(fromObj, adr, adr_type, type, bt, decorators);
5576 }
5577
field_address_from_object(Node * fromObj,const char * fieldName,const char * fieldTypeString,bool is_exact=true,bool is_static=false,ciInstanceKlass * fromKls=NULL)5578 Node * LibraryCallKit::field_address_from_object(Node * fromObj, const char * fieldName, const char * fieldTypeString,
5579 bool is_exact = true, bool is_static = false,
5580 ciInstanceKlass * fromKls = NULL) {
5581 if (fromKls == NULL) {
5582 const TypeInstPtr* tinst = _gvn.type(fromObj)->isa_instptr();
5583 assert(tinst != NULL, "obj is null");
5584 assert(tinst->klass()->is_loaded(), "obj is not loaded");
5585 assert(!is_exact || tinst->klass_is_exact(), "klass not exact");
5586 fromKls = tinst->klass()->as_instance_klass();
5587 }
5588 else {
5589 assert(is_static, "only for static field access");
5590 }
5591 ciField* field = fromKls->get_field_by_name(ciSymbol::make(fieldName),
5592 ciSymbol::make(fieldTypeString),
5593 is_static);
5594
5595 assert(field != NULL, "undefined field");
5596 assert(!field->is_volatile(), "not defined for volatile fields");
5597
5598 if (is_static) {
5599 const TypeInstPtr* tip = TypeInstPtr::make(fromKls->java_mirror());
5600 fromObj = makecon(tip);
5601 }
5602
5603 // Next code copied from Parse::do_get_xxx():
5604
5605 // Compute address and memory type.
5606 int offset = field->offset_in_bytes();
5607 Node *adr = basic_plus_adr(fromObj, fromObj, offset);
5608
5609 return adr;
5610 }
5611
5612 //------------------------------inline_aescrypt_Block-----------------------
inline_aescrypt_Block(vmIntrinsics::ID id)5613 bool LibraryCallKit::inline_aescrypt_Block(vmIntrinsics::ID id) {
5614 address stubAddr = NULL;
5615 const char *stubName;
5616 assert(UseAES, "need AES instruction support");
5617
5618 switch(id) {
5619 case vmIntrinsics::_aescrypt_encryptBlock:
5620 stubAddr = StubRoutines::aescrypt_encryptBlock();
5621 stubName = "aescrypt_encryptBlock";
5622 break;
5623 case vmIntrinsics::_aescrypt_decryptBlock:
5624 stubAddr = StubRoutines::aescrypt_decryptBlock();
5625 stubName = "aescrypt_decryptBlock";
5626 break;
5627 default:
5628 break;
5629 }
5630 if (stubAddr == NULL) return false;
5631
5632 Node* aescrypt_object = argument(0);
5633 Node* src = argument(1);
5634 Node* src_offset = argument(2);
5635 Node* dest = argument(3);
5636 Node* dest_offset = argument(4);
5637
5638 src = must_be_not_null(src, true);
5639 dest = must_be_not_null(dest, true);
5640
5641 // (1) src and dest are arrays.
5642 const Type* src_type = src->Value(&_gvn);
5643 const Type* dest_type = dest->Value(&_gvn);
5644 const TypeAryPtr* top_src = src_type->isa_aryptr();
5645 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5646 assert (top_src != NULL && top_src->klass() != NULL && top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5647
5648 // for the quick and dirty code we will skip all the checks.
5649 // we are just trying to get the call to be generated.
5650 Node* src_start = src;
5651 Node* dest_start = dest;
5652 if (src_offset != NULL || dest_offset != NULL) {
5653 assert(src_offset != NULL && dest_offset != NULL, "");
5654 src_start = array_element_address(src, src_offset, T_BYTE);
5655 dest_start = array_element_address(dest, dest_offset, T_BYTE);
5656 }
5657
5658 // now need to get the start of its expanded key array
5659 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5660 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5661 if (k_start == NULL) return false;
5662
5663 // Call the stub.
5664 make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::aescrypt_block_Type(),
5665 stubAddr, stubName, TypePtr::BOTTOM,
5666 src_start, dest_start, k_start);
5667
5668 return true;
5669 }
5670
5671 //------------------------------inline_cipherBlockChaining_AESCrypt-----------------------
inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id)5672 bool LibraryCallKit::inline_cipherBlockChaining_AESCrypt(vmIntrinsics::ID id) {
5673 address stubAddr = NULL;
5674 const char *stubName = NULL;
5675
5676 assert(UseAES, "need AES instruction support");
5677
5678 switch(id) {
5679 case vmIntrinsics::_cipherBlockChaining_encryptAESCrypt:
5680 stubAddr = StubRoutines::cipherBlockChaining_encryptAESCrypt();
5681 stubName = "cipherBlockChaining_encryptAESCrypt";
5682 break;
5683 case vmIntrinsics::_cipherBlockChaining_decryptAESCrypt:
5684 stubAddr = StubRoutines::cipherBlockChaining_decryptAESCrypt();
5685 stubName = "cipherBlockChaining_decryptAESCrypt";
5686 break;
5687 default:
5688 break;
5689 }
5690 if (stubAddr == NULL) return false;
5691
5692 Node* cipherBlockChaining_object = argument(0);
5693 Node* src = argument(1);
5694 Node* src_offset = argument(2);
5695 Node* len = argument(3);
5696 Node* dest = argument(4);
5697 Node* dest_offset = argument(5);
5698
5699 src = must_be_not_null(src, false);
5700 dest = must_be_not_null(dest, false);
5701
5702 // (1) src and dest are arrays.
5703 const Type* src_type = src->Value(&_gvn);
5704 const Type* dest_type = dest->Value(&_gvn);
5705 const TypeAryPtr* top_src = src_type->isa_aryptr();
5706 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5707 assert (top_src != NULL && top_src->klass() != NULL
5708 && top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5709
5710 // checks are the responsibility of the caller
5711 Node* src_start = src;
5712 Node* dest_start = dest;
5713 if (src_offset != NULL || dest_offset != NULL) {
5714 assert(src_offset != NULL && dest_offset != NULL, "");
5715 src_start = array_element_address(src, src_offset, T_BYTE);
5716 dest_start = array_element_address(dest, dest_offset, T_BYTE);
5717 }
5718
5719 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
5720 // (because of the predicated logic executed earlier).
5721 // so we cast it here safely.
5722 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5723
5724 Node* embeddedCipherObj = load_field_from_object(cipherBlockChaining_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
5725 if (embeddedCipherObj == NULL) return false;
5726
5727 // cast it to what we know it will be at runtime
5728 const TypeInstPtr* tinst = _gvn.type(cipherBlockChaining_object)->isa_instptr();
5729 assert(tinst != NULL, "CBC obj is null");
5730 assert(tinst->klass()->is_loaded(), "CBC obj is not loaded");
5731 ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5732 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
5733
5734 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5735 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
5736 const TypeOopPtr* xtype = aklass->as_instance_type();
5737 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
5738 aescrypt_object = _gvn.transform(aescrypt_object);
5739
5740 // we need to get the start of the aescrypt_object's expanded key array
5741 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5742 if (k_start == NULL) return false;
5743
5744 // similarly, get the start address of the r vector
5745 Node* objRvec = load_field_from_object(cipherBlockChaining_object, "r", "[B");
5746 if (objRvec == NULL) return false;
5747 Node* r_start = array_element_address(objRvec, intcon(0), T_BYTE);
5748
5749 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
5750 Node* cbcCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
5751 OptoRuntime::cipherBlockChaining_aescrypt_Type(),
5752 stubAddr, stubName, TypePtr::BOTTOM,
5753 src_start, dest_start, k_start, r_start, len);
5754
5755 // return cipher length (int)
5756 Node* retvalue = _gvn.transform(new ProjNode(cbcCrypt, TypeFunc::Parms));
5757 set_result(retvalue);
5758 return true;
5759 }
5760
5761 //------------------------------inline_electronicCodeBook_AESCrypt-----------------------
inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id)5762 bool LibraryCallKit::inline_electronicCodeBook_AESCrypt(vmIntrinsics::ID id) {
5763 address stubAddr = NULL;
5764 const char *stubName = NULL;
5765
5766 assert(UseAES, "need AES instruction support");
5767
5768 switch (id) {
5769 case vmIntrinsics::_electronicCodeBook_encryptAESCrypt:
5770 stubAddr = StubRoutines::electronicCodeBook_encryptAESCrypt();
5771 stubName = "electronicCodeBook_encryptAESCrypt";
5772 break;
5773 case vmIntrinsics::_electronicCodeBook_decryptAESCrypt:
5774 stubAddr = StubRoutines::electronicCodeBook_decryptAESCrypt();
5775 stubName = "electronicCodeBook_decryptAESCrypt";
5776 break;
5777 default:
5778 break;
5779 }
5780
5781 if (stubAddr == NULL) return false;
5782
5783 Node* electronicCodeBook_object = argument(0);
5784 Node* src = argument(1);
5785 Node* src_offset = argument(2);
5786 Node* len = argument(3);
5787 Node* dest = argument(4);
5788 Node* dest_offset = argument(5);
5789
5790 // (1) src and dest are arrays.
5791 const Type* src_type = src->Value(&_gvn);
5792 const Type* dest_type = dest->Value(&_gvn);
5793 const TypeAryPtr* top_src = src_type->isa_aryptr();
5794 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5795 assert(top_src != NULL && top_src->klass() != NULL
5796 && top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5797
5798 // checks are the responsibility of the caller
5799 Node* src_start = src;
5800 Node* dest_start = dest;
5801 if (src_offset != NULL || dest_offset != NULL) {
5802 assert(src_offset != NULL && dest_offset != NULL, "");
5803 src_start = array_element_address(src, src_offset, T_BYTE);
5804 dest_start = array_element_address(dest, dest_offset, T_BYTE);
5805 }
5806
5807 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
5808 // (because of the predicated logic executed earlier).
5809 // so we cast it here safely.
5810 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5811
5812 Node* embeddedCipherObj = load_field_from_object(electronicCodeBook_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
5813 if (embeddedCipherObj == NULL) return false;
5814
5815 // cast it to what we know it will be at runtime
5816 const TypeInstPtr* tinst = _gvn.type(electronicCodeBook_object)->isa_instptr();
5817 assert(tinst != NULL, "ECB obj is null");
5818 assert(tinst->klass()->is_loaded(), "ECB obj is not loaded");
5819 ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5820 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
5821
5822 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5823 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
5824 const TypeOopPtr* xtype = aklass->as_instance_type();
5825 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
5826 aescrypt_object = _gvn.transform(aescrypt_object);
5827
5828 // we need to get the start of the aescrypt_object's expanded key array
5829 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5830 if (k_start == NULL) return false;
5831
5832 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
5833 Node* ecbCrypt = make_runtime_call(RC_LEAF | RC_NO_FP,
5834 OptoRuntime::electronicCodeBook_aescrypt_Type(),
5835 stubAddr, stubName, TypePtr::BOTTOM,
5836 src_start, dest_start, k_start, len);
5837
5838 // return cipher length (int)
5839 Node* retvalue = _gvn.transform(new ProjNode(ecbCrypt, TypeFunc::Parms));
5840 set_result(retvalue);
5841 return true;
5842 }
5843
5844 //------------------------------inline_counterMode_AESCrypt-----------------------
inline_counterMode_AESCrypt(vmIntrinsics::ID id)5845 bool LibraryCallKit::inline_counterMode_AESCrypt(vmIntrinsics::ID id) {
5846 assert(UseAES, "need AES instruction support");
5847 if (!UseAESCTRIntrinsics) return false;
5848
5849 address stubAddr = NULL;
5850 const char *stubName = NULL;
5851 if (id == vmIntrinsics::_counterMode_AESCrypt) {
5852 stubAddr = StubRoutines::counterMode_AESCrypt();
5853 stubName = "counterMode_AESCrypt";
5854 }
5855 if (stubAddr == NULL) return false;
5856
5857 Node* counterMode_object = argument(0);
5858 Node* src = argument(1);
5859 Node* src_offset = argument(2);
5860 Node* len = argument(3);
5861 Node* dest = argument(4);
5862 Node* dest_offset = argument(5);
5863
5864 // (1) src and dest are arrays.
5865 const Type* src_type = src->Value(&_gvn);
5866 const Type* dest_type = dest->Value(&_gvn);
5867 const TypeAryPtr* top_src = src_type->isa_aryptr();
5868 const TypeAryPtr* top_dest = dest_type->isa_aryptr();
5869 assert(top_src != NULL && top_src->klass() != NULL &&
5870 top_dest != NULL && top_dest->klass() != NULL, "args are strange");
5871
5872 // checks are the responsibility of the caller
5873 Node* src_start = src;
5874 Node* dest_start = dest;
5875 if (src_offset != NULL || dest_offset != NULL) {
5876 assert(src_offset != NULL && dest_offset != NULL, "");
5877 src_start = array_element_address(src, src_offset, T_BYTE);
5878 dest_start = array_element_address(dest, dest_offset, T_BYTE);
5879 }
5880
5881 // if we are in this set of code, we "know" the embeddedCipher is an AESCrypt object
5882 // (because of the predicated logic executed earlier).
5883 // so we cast it here safely.
5884 // this requires a newer class file that has this array as littleEndian ints, otherwise we revert to java
5885 Node* embeddedCipherObj = load_field_from_object(counterMode_object, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
5886 if (embeddedCipherObj == NULL) return false;
5887 // cast it to what we know it will be at runtime
5888 const TypeInstPtr* tinst = _gvn.type(counterMode_object)->isa_instptr();
5889 assert(tinst != NULL, "CTR obj is null");
5890 assert(tinst->klass()->is_loaded(), "CTR obj is not loaded");
5891 ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5892 assert(klass_AESCrypt->is_loaded(), "predicate checks that this class is loaded");
5893 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5894 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_AESCrypt);
5895 const TypeOopPtr* xtype = aklass->as_instance_type();
5896 Node* aescrypt_object = new CheckCastPPNode(control(), embeddedCipherObj, xtype);
5897 aescrypt_object = _gvn.transform(aescrypt_object);
5898 // we need to get the start of the aescrypt_object's expanded key array
5899 Node* k_start = get_key_start_from_aescrypt_object(aescrypt_object);
5900 if (k_start == NULL) return false;
5901 // similarly, get the start address of the r vector
5902 Node* obj_counter = load_field_from_object(counterMode_object, "counter", "[B");
5903 if (obj_counter == NULL) return false;
5904 Node* cnt_start = array_element_address(obj_counter, intcon(0), T_BYTE);
5905
5906 Node* saved_encCounter = load_field_from_object(counterMode_object, "encryptedCounter", "[B");
5907 if (saved_encCounter == NULL) return false;
5908 Node* saved_encCounter_start = array_element_address(saved_encCounter, intcon(0), T_BYTE);
5909 Node* used = field_address_from_object(counterMode_object, "used", "I", /*is_exact*/ false);
5910
5911 // Call the stub, passing src_start, dest_start, k_start, r_start and src_len
5912 Node* ctrCrypt = make_runtime_call(RC_LEAF|RC_NO_FP,
5913 OptoRuntime::counterMode_aescrypt_Type(),
5914 stubAddr, stubName, TypePtr::BOTTOM,
5915 src_start, dest_start, k_start, cnt_start, len, saved_encCounter_start, used);
5916
5917 // return cipher length (int)
5918 Node* retvalue = _gvn.transform(new ProjNode(ctrCrypt, TypeFunc::Parms));
5919 set_result(retvalue);
5920 return true;
5921 }
5922
5923 //------------------------------get_key_start_from_aescrypt_object-----------------------
get_key_start_from_aescrypt_object(Node * aescrypt_object)5924 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
5925 #if defined(PPC64) || defined(S390)
5926 // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
5927 // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
5928 // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
5929 // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
5930 Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I");
5931 assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
5932 if (objSessionK == NULL) {
5933 return (Node *) NULL;
5934 }
5935 Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);
5936 #else
5937 Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I");
5938 #endif // PPC64
5939 assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
5940 if (objAESCryptKey == NULL) return (Node *) NULL;
5941
5942 // now have the array, need to get the start address of the K array
5943 Node* k_start = array_element_address(objAESCryptKey, intcon(0), T_INT);
5944 return k_start;
5945 }
5946
5947 //----------------------------inline_cipherBlockChaining_AESCrypt_predicate----------------------------
5948 // Return node representing slow path of predicate check.
5949 // the pseudo code we want to emulate with this predicate is:
5950 // for encryption:
5951 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
5952 // for decryption:
5953 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
5954 // note cipher==plain is more conservative than the original java code but that's OK
5955 //
inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting)5956 Node* LibraryCallKit::inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting) {
5957 // The receiver was checked for NULL already.
5958 Node* objCBC = argument(0);
5959
5960 Node* src = argument(1);
5961 Node* dest = argument(4);
5962
5963 // Load embeddedCipher field of CipherBlockChaining object.
5964 Node* embeddedCipherObj = load_field_from_object(objCBC, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
5965
5966 // get AESCrypt klass for instanceOf check
5967 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
5968 // will have same classloader as CipherBlockChaining object
5969 const TypeInstPtr* tinst = _gvn.type(objCBC)->isa_instptr();
5970 assert(tinst != NULL, "CBCobj is null");
5971 assert(tinst->klass()->is_loaded(), "CBCobj is not loaded");
5972
5973 // we want to do an instanceof comparison against the AESCrypt class
5974 ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
5975 if (!klass_AESCrypt->is_loaded()) {
5976 // if AESCrypt is not even loaded, we never take the intrinsic fast path
5977 Node* ctrl = control();
5978 set_control(top()); // no regular fast path
5979 return ctrl;
5980 }
5981
5982 src = must_be_not_null(src, true);
5983 dest = must_be_not_null(dest, true);
5984
5985 // Resolve oops to stable for CmpP below.
5986 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
5987
5988 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
5989 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
5990 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
5991
5992 Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
5993
5994 // for encryption, we are done
5995 if (!decrypting)
5996 return instof_false; // even if it is NULL
5997
5998 // for decryption, we need to add a further check to avoid
5999 // taking the intrinsic path when cipher and plain are the same
6000 // see the original java code for why.
6001 RegionNode* region = new RegionNode(3);
6002 region->init_req(1, instof_false);
6003
6004 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6005 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6006 Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6007 region->init_req(2, src_dest_conjoint);
6008
6009 record_for_igvn(region);
6010 return _gvn.transform(region);
6011 }
6012
6013 //----------------------------inline_electronicCodeBook_AESCrypt_predicate----------------------------
6014 // Return node representing slow path of predicate check.
6015 // the pseudo code we want to emulate with this predicate is:
6016 // for encryption:
6017 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6018 // for decryption:
6019 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6020 // note cipher==plain is more conservative than the original java code but that's OK
6021 //
inline_electronicCodeBook_AESCrypt_predicate(bool decrypting)6022 Node* LibraryCallKit::inline_electronicCodeBook_AESCrypt_predicate(bool decrypting) {
6023 // The receiver was checked for NULL already.
6024 Node* objECB = argument(0);
6025
6026 // Load embeddedCipher field of ElectronicCodeBook object.
6027 Node* embeddedCipherObj = load_field_from_object(objECB, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6028
6029 // get AESCrypt klass for instanceOf check
6030 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6031 // will have same classloader as ElectronicCodeBook object
6032 const TypeInstPtr* tinst = _gvn.type(objECB)->isa_instptr();
6033 assert(tinst != NULL, "ECBobj is null");
6034 assert(tinst->klass()->is_loaded(), "ECBobj is not loaded");
6035
6036 // we want to do an instanceof comparison against the AESCrypt class
6037 ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6038 if (!klass_AESCrypt->is_loaded()) {
6039 // if AESCrypt is not even loaded, we never take the intrinsic fast path
6040 Node* ctrl = control();
6041 set_control(top()); // no regular fast path
6042 return ctrl;
6043 }
6044 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6045
6046 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6047 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6048 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6049
6050 Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6051
6052 // for encryption, we are done
6053 if (!decrypting)
6054 return instof_false; // even if it is NULL
6055
6056 // for decryption, we need to add a further check to avoid
6057 // taking the intrinsic path when cipher and plain are the same
6058 // see the original java code for why.
6059 RegionNode* region = new RegionNode(3);
6060 region->init_req(1, instof_false);
6061 Node* src = argument(1);
6062 Node* dest = argument(4);
6063 Node* cmp_src_dest = _gvn.transform(new CmpPNode(src, dest));
6064 Node* bool_src_dest = _gvn.transform(new BoolNode(cmp_src_dest, BoolTest::eq));
6065 Node* src_dest_conjoint = generate_guard(bool_src_dest, NULL, PROB_MIN);
6066 region->init_req(2, src_dest_conjoint);
6067
6068 record_for_igvn(region);
6069 return _gvn.transform(region);
6070 }
6071
6072 //----------------------------inline_counterMode_AESCrypt_predicate----------------------------
6073 // Return node representing slow path of predicate check.
6074 // the pseudo code we want to emulate with this predicate is:
6075 // for encryption:
6076 // if (embeddedCipherObj instanceof AESCrypt) do_intrinsic, else do_javapath
6077 // for decryption:
6078 // if ((embeddedCipherObj instanceof AESCrypt) && (cipher!=plain)) do_intrinsic, else do_javapath
6079 // note cipher==plain is more conservative than the original java code but that's OK
6080 //
6081
inline_counterMode_AESCrypt_predicate()6082 Node* LibraryCallKit::inline_counterMode_AESCrypt_predicate() {
6083 // The receiver was checked for NULL already.
6084 Node* objCTR = argument(0);
6085
6086 // Load embeddedCipher field of CipherBlockChaining object.
6087 Node* embeddedCipherObj = load_field_from_object(objCTR, "embeddedCipher", "Lcom/sun/crypto/provider/SymmetricCipher;");
6088
6089 // get AESCrypt klass for instanceOf check
6090 // AESCrypt might not be loaded yet if some other SymmetricCipher got us to this compile point
6091 // will have same classloader as CipherBlockChaining object
6092 const TypeInstPtr* tinst = _gvn.type(objCTR)->isa_instptr();
6093 assert(tinst != NULL, "CTRobj is null");
6094 assert(tinst->klass()->is_loaded(), "CTRobj is not loaded");
6095
6096 // we want to do an instanceof comparison against the AESCrypt class
6097 ciKlass* klass_AESCrypt = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make("com/sun/crypto/provider/AESCrypt"));
6098 if (!klass_AESCrypt->is_loaded()) {
6099 // if AESCrypt is not even loaded, we never take the intrinsic fast path
6100 Node* ctrl = control();
6101 set_control(top()); // no regular fast path
6102 return ctrl;
6103 }
6104
6105 ciInstanceKlass* instklass_AESCrypt = klass_AESCrypt->as_instance_klass();
6106 Node* instof = gen_instanceof(embeddedCipherObj, makecon(TypeKlassPtr::make(instklass_AESCrypt)));
6107 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6108 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6109 Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6110
6111 return instof_false; // even if it is NULL
6112 }
6113
6114 //------------------------------inline_ghash_processBlocks
inline_ghash_processBlocks()6115 bool LibraryCallKit::inline_ghash_processBlocks() {
6116 address stubAddr;
6117 const char *stubName;
6118 assert(UseGHASHIntrinsics, "need GHASH intrinsics support");
6119
6120 stubAddr = StubRoutines::ghash_processBlocks();
6121 stubName = "ghash_processBlocks";
6122
6123 Node* data = argument(0);
6124 Node* offset = argument(1);
6125 Node* len = argument(2);
6126 Node* state = argument(3);
6127 Node* subkeyH = argument(4);
6128
6129 state = must_be_not_null(state, true);
6130 subkeyH = must_be_not_null(subkeyH, true);
6131 data = must_be_not_null(data, true);
6132
6133 Node* state_start = array_element_address(state, intcon(0), T_LONG);
6134 assert(state_start, "state is NULL");
6135 Node* subkeyH_start = array_element_address(subkeyH, intcon(0), T_LONG);
6136 assert(subkeyH_start, "subkeyH is NULL");
6137 Node* data_start = array_element_address(data, offset, T_BYTE);
6138 assert(data_start, "data is NULL");
6139
6140 Node* ghash = make_runtime_call(RC_LEAF|RC_NO_FP,
6141 OptoRuntime::ghash_processBlocks_Type(),
6142 stubAddr, stubName, TypePtr::BOTTOM,
6143 state_start, subkeyH_start, data_start, len);
6144 return true;
6145 }
6146
inline_base64_encodeBlock()6147 bool LibraryCallKit::inline_base64_encodeBlock() {
6148 address stubAddr;
6149 const char *stubName;
6150 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
6151 assert(callee()->signature()->size() == 6, "base64_encodeBlock has 6 parameters");
6152 stubAddr = StubRoutines::base64_encodeBlock();
6153 stubName = "encodeBlock";
6154
6155 if (!stubAddr) return false;
6156 Node* base64obj = argument(0);
6157 Node* src = argument(1);
6158 Node* offset = argument(2);
6159 Node* len = argument(3);
6160 Node* dest = argument(4);
6161 Node* dp = argument(5);
6162 Node* isURL = argument(6);
6163
6164 src = must_be_not_null(src, true);
6165 dest = must_be_not_null(dest, true);
6166
6167 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
6168 assert(src_start, "source array is NULL");
6169 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
6170 assert(dest_start, "destination array is NULL");
6171
6172 Node* base64 = make_runtime_call(RC_LEAF,
6173 OptoRuntime::base64_encodeBlock_Type(),
6174 stubAddr, stubName, TypePtr::BOTTOM,
6175 src_start, offset, len, dest_start, dp, isURL);
6176 return true;
6177 }
6178
inline_base64_decodeBlock()6179 bool LibraryCallKit::inline_base64_decodeBlock() {
6180 address stubAddr;
6181 const char *stubName;
6182 assert(UseBASE64Intrinsics, "need Base64 intrinsics support");
6183 assert(callee()->signature()->size() == 6, "base64_decodeBlock has 6 parameters");
6184 stubAddr = StubRoutines::base64_decodeBlock();
6185 stubName = "decodeBlock";
6186
6187 if (!stubAddr) return false;
6188 Node* base64obj = argument(0);
6189 Node* src = argument(1);
6190 Node* src_offset = argument(2);
6191 Node* len = argument(3);
6192 Node* dest = argument(4);
6193 Node* dest_offset = argument(5);
6194 Node* isURL = argument(6);
6195
6196 src = must_be_not_null(src, true);
6197 dest = must_be_not_null(dest, true);
6198
6199 Node* src_start = array_element_address(src, intcon(0), T_BYTE);
6200 assert(src_start, "source array is NULL");
6201 Node* dest_start = array_element_address(dest, intcon(0), T_BYTE);
6202 assert(dest_start, "destination array is NULL");
6203
6204 Node* call = make_runtime_call(RC_LEAF,
6205 OptoRuntime::base64_decodeBlock_Type(),
6206 stubAddr, stubName, TypePtr::BOTTOM,
6207 src_start, src_offset, len, dest_start, dest_offset, isURL);
6208 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6209 set_result(result);
6210 return true;
6211 }
6212
6213 //------------------------------inline_digestBase_implCompress-----------------------
6214 //
6215 // Calculate MD5 for single-block byte[] array.
6216 // void com.sun.security.provider.MD5.implCompress(byte[] buf, int ofs)
6217 //
6218 // Calculate SHA (i.e., SHA-1) for single-block byte[] array.
6219 // void com.sun.security.provider.SHA.implCompress(byte[] buf, int ofs)
6220 //
6221 // Calculate SHA2 (i.e., SHA-244 or SHA-256) for single-block byte[] array.
6222 // void com.sun.security.provider.SHA2.implCompress(byte[] buf, int ofs)
6223 //
6224 // Calculate SHA5 (i.e., SHA-384 or SHA-512) for single-block byte[] array.
6225 // void com.sun.security.provider.SHA5.implCompress(byte[] buf, int ofs)
6226 //
6227 // Calculate SHA3 (i.e., SHA3-224 or SHA3-256 or SHA3-384 or SHA3-512) for single-block byte[] array.
6228 // void com.sun.security.provider.SHA3.implCompress(byte[] buf, int ofs)
6229 //
inline_digestBase_implCompress(vmIntrinsics::ID id)6230 bool LibraryCallKit::inline_digestBase_implCompress(vmIntrinsics::ID id) {
6231 assert(callee()->signature()->size() == 2, "sha_implCompress has 2 parameters");
6232
6233 Node* digestBase_obj = argument(0);
6234 Node* src = argument(1); // type oop
6235 Node* ofs = argument(2); // type int
6236
6237 const Type* src_type = src->Value(&_gvn);
6238 const TypeAryPtr* top_src = src_type->isa_aryptr();
6239 if (top_src == NULL || top_src->klass() == NULL) {
6240 // failed array check
6241 return false;
6242 }
6243 // Figure out the size and type of the elements we will be copying.
6244 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6245 if (src_elem != T_BYTE) {
6246 return false;
6247 }
6248 // 'src_start' points to src array + offset
6249 src = must_be_not_null(src, true);
6250 Node* src_start = array_element_address(src, ofs, src_elem);
6251 Node* state = NULL;
6252 Node* digest_length = NULL;
6253 address stubAddr;
6254 const char *stubName;
6255
6256 switch(id) {
6257 case vmIntrinsics::_md5_implCompress:
6258 assert(UseMD5Intrinsics, "need MD5 instruction support");
6259 state = get_state_from_digest_object(digestBase_obj, "[I");
6260 stubAddr = StubRoutines::md5_implCompress();
6261 stubName = "md5_implCompress";
6262 break;
6263 case vmIntrinsics::_sha_implCompress:
6264 assert(UseSHA1Intrinsics, "need SHA1 instruction support");
6265 state = get_state_from_digest_object(digestBase_obj, "[I");
6266 stubAddr = StubRoutines::sha1_implCompress();
6267 stubName = "sha1_implCompress";
6268 break;
6269 case vmIntrinsics::_sha2_implCompress:
6270 assert(UseSHA256Intrinsics, "need SHA256 instruction support");
6271 state = get_state_from_digest_object(digestBase_obj, "[I");
6272 stubAddr = StubRoutines::sha256_implCompress();
6273 stubName = "sha256_implCompress";
6274 break;
6275 case vmIntrinsics::_sha5_implCompress:
6276 assert(UseSHA512Intrinsics, "need SHA512 instruction support");
6277 state = get_state_from_digest_object(digestBase_obj, "[J");
6278 stubAddr = StubRoutines::sha512_implCompress();
6279 stubName = "sha512_implCompress";
6280 break;
6281 case vmIntrinsics::_sha3_implCompress:
6282 assert(UseSHA3Intrinsics, "need SHA3 instruction support");
6283 state = get_state_from_digest_object(digestBase_obj, "[B");
6284 stubAddr = StubRoutines::sha3_implCompress();
6285 stubName = "sha3_implCompress";
6286 digest_length = get_digest_length_from_digest_object(digestBase_obj);
6287 if (digest_length == NULL) return false;
6288 break;
6289 default:
6290 fatal_unexpected_iid(id);
6291 return false;
6292 }
6293 if (state == NULL) return false;
6294
6295 assert(stubAddr != NULL, "Stub is generated");
6296 if (stubAddr == NULL) return false;
6297
6298 // Call the stub.
6299 Node* call;
6300 if (digest_length == NULL) {
6301 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(false),
6302 stubAddr, stubName, TypePtr::BOTTOM,
6303 src_start, state);
6304 } else {
6305 call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::digestBase_implCompress_Type(true),
6306 stubAddr, stubName, TypePtr::BOTTOM,
6307 src_start, state, digest_length);
6308 }
6309
6310 return true;
6311 }
6312
6313 //------------------------------inline_digestBase_implCompressMB-----------------------
6314 //
6315 // Calculate MD5/SHA/SHA2/SHA5/SHA3 for multi-block byte[] array.
6316 // int com.sun.security.provider.DigestBase.implCompressMultiBlock(byte[] b, int ofs, int limit)
6317 //
inline_digestBase_implCompressMB(int predicate)6318 bool LibraryCallKit::inline_digestBase_implCompressMB(int predicate) {
6319 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
6320 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
6321 assert((uint)predicate < 5, "sanity");
6322 assert(callee()->signature()->size() == 3, "digestBase_implCompressMB has 3 parameters");
6323
6324 Node* digestBase_obj = argument(0); // The receiver was checked for NULL already.
6325 Node* src = argument(1); // byte[] array
6326 Node* ofs = argument(2); // type int
6327 Node* limit = argument(3); // type int
6328
6329 const Type* src_type = src->Value(&_gvn);
6330 const TypeAryPtr* top_src = src_type->isa_aryptr();
6331 if (top_src == NULL || top_src->klass() == NULL) {
6332 // failed array check
6333 return false;
6334 }
6335 // Figure out the size and type of the elements we will be copying.
6336 BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type();
6337 if (src_elem != T_BYTE) {
6338 return false;
6339 }
6340 // 'src_start' points to src array + offset
6341 src = must_be_not_null(src, false);
6342 Node* src_start = array_element_address(src, ofs, src_elem);
6343
6344 const char* klass_digestBase_name = NULL;
6345 const char* stub_name = NULL;
6346 address stub_addr = NULL;
6347 const char* state_type = "[I";
6348
6349 switch (predicate) {
6350 case 0:
6351 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_md5_implCompress)) {
6352 klass_digestBase_name = "sun/security/provider/MD5";
6353 stub_name = "md5_implCompressMB";
6354 stub_addr = StubRoutines::md5_implCompressMB();
6355 }
6356 break;
6357 case 1:
6358 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha_implCompress)) {
6359 klass_digestBase_name = "sun/security/provider/SHA";
6360 stub_name = "sha1_implCompressMB";
6361 stub_addr = StubRoutines::sha1_implCompressMB();
6362 }
6363 break;
6364 case 2:
6365 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha2_implCompress)) {
6366 klass_digestBase_name = "sun/security/provider/SHA2";
6367 stub_name = "sha256_implCompressMB";
6368 stub_addr = StubRoutines::sha256_implCompressMB();
6369 }
6370 break;
6371 case 3:
6372 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha5_implCompress)) {
6373 klass_digestBase_name = "sun/security/provider/SHA5";
6374 stub_name = "sha512_implCompressMB";
6375 stub_addr = StubRoutines::sha512_implCompressMB();
6376 state_type = "[J";
6377 }
6378 break;
6379 case 4:
6380 if (vmIntrinsics::is_intrinsic_available(vmIntrinsics::_sha3_implCompress)) {
6381 klass_digestBase_name = "sun/security/provider/SHA3";
6382 stub_name = "sha3_implCompressMB";
6383 stub_addr = StubRoutines::sha3_implCompressMB();
6384 state_type = "[B";
6385 }
6386 break;
6387 default:
6388 fatal("unknown DigestBase intrinsic predicate: %d", predicate);
6389 }
6390 if (klass_digestBase_name != NULL) {
6391 assert(stub_addr != NULL, "Stub is generated");
6392 if (stub_addr == NULL) return false;
6393
6394 // get DigestBase klass to lookup for SHA klass
6395 const TypeInstPtr* tinst = _gvn.type(digestBase_obj)->isa_instptr();
6396 assert(tinst != NULL, "digestBase_obj is not instance???");
6397 assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6398
6399 ciKlass* klass_digestBase = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_digestBase_name));
6400 assert(klass_digestBase->is_loaded(), "predicate checks that this class is loaded");
6401 ciInstanceKlass* instklass_digestBase = klass_digestBase->as_instance_klass();
6402 return inline_digestBase_implCompressMB(digestBase_obj, instklass_digestBase, state_type, stub_addr, stub_name, src_start, ofs, limit);
6403 }
6404 return false;
6405 }
6406
6407 //------------------------------inline_digestBase_implCompressMB-----------------------
inline_digestBase_implCompressMB(Node * digestBase_obj,ciInstanceKlass * instklass_digestBase,const char * state_type,address stubAddr,const char * stubName,Node * src_start,Node * ofs,Node * limit)6408 bool LibraryCallKit::inline_digestBase_implCompressMB(Node* digestBase_obj, ciInstanceKlass* instklass_digestBase,
6409 const char* state_type, address stubAddr, const char *stubName,
6410 Node* src_start, Node* ofs, Node* limit) {
6411 const TypeKlassPtr* aklass = TypeKlassPtr::make(instklass_digestBase);
6412 const TypeOopPtr* xtype = aklass->as_instance_type();
6413 Node* digest_obj = new CheckCastPPNode(control(), digestBase_obj, xtype);
6414 digest_obj = _gvn.transform(digest_obj);
6415
6416 Node* state = get_state_from_digest_object(digest_obj, state_type);
6417 if (state == NULL) return false;
6418
6419 Node* digest_length = NULL;
6420 if (strcmp("sha3_implCompressMB", stubName) == 0) {
6421 digest_length = get_digest_length_from_digest_object(digest_obj);
6422 if (digest_length == NULL) return false;
6423 }
6424
6425 // Call the stub.
6426 Node* call;
6427 if (digest_length == NULL) {
6428 call = make_runtime_call(RC_LEAF|RC_NO_FP,
6429 OptoRuntime::digestBase_implCompressMB_Type(false),
6430 stubAddr, stubName, TypePtr::BOTTOM,
6431 src_start, state, ofs, limit);
6432 } else {
6433 call = make_runtime_call(RC_LEAF|RC_NO_FP,
6434 OptoRuntime::digestBase_implCompressMB_Type(true),
6435 stubAddr, stubName, TypePtr::BOTTOM,
6436 src_start, state, digest_length, ofs, limit);
6437 }
6438
6439 // return ofs (int)
6440 Node* result = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
6441 set_result(result);
6442
6443 return true;
6444 }
6445
6446 //------------------------------get_state_from_digest_object-----------------------
get_state_from_digest_object(Node * digest_object,const char * state_type)6447 Node * LibraryCallKit::get_state_from_digest_object(Node *digest_object, const char *state_type) {
6448 Node* digest_state = load_field_from_object(digest_object, "state", state_type);
6449 assert (digest_state != NULL, "wrong version of sun.security.provider.MD5/SHA/SHA2/SHA5/SHA3");
6450 if (digest_state == NULL) return (Node *) NULL;
6451
6452 // now have the array, need to get the start address of the state array
6453 Node* state = array_element_address(digest_state, intcon(0), T_INT);
6454 return state;
6455 }
6456
6457 //------------------------------get_digest_length_from_sha3_object----------------------------------
get_digest_length_from_digest_object(Node * digest_object)6458 Node * LibraryCallKit::get_digest_length_from_digest_object(Node *digest_object) {
6459 Node* digest_length = load_field_from_object(digest_object, "digestLength", "I");
6460 assert (digest_length != NULL, "sanity");
6461 return digest_length;
6462 }
6463
6464 //----------------------------inline_digestBase_implCompressMB_predicate----------------------------
6465 // Return node representing slow path of predicate check.
6466 // the pseudo code we want to emulate with this predicate is:
6467 // if (digestBaseObj instanceof MD5/SHA/SHA2/SHA5/SHA3) do_intrinsic, else do_javapath
6468 //
inline_digestBase_implCompressMB_predicate(int predicate)6469 Node* LibraryCallKit::inline_digestBase_implCompressMB_predicate(int predicate) {
6470 assert(UseMD5Intrinsics || UseSHA1Intrinsics || UseSHA256Intrinsics || UseSHA512Intrinsics || UseSHA3Intrinsics,
6471 "need MD5/SHA1/SHA256/SHA512/SHA3 instruction support");
6472 assert((uint)predicate < 5, "sanity");
6473
6474 // The receiver was checked for NULL already.
6475 Node* digestBaseObj = argument(0);
6476
6477 // get DigestBase klass for instanceOf check
6478 const TypeInstPtr* tinst = _gvn.type(digestBaseObj)->isa_instptr();
6479 assert(tinst != NULL, "digestBaseObj is null");
6480 assert(tinst->klass()->is_loaded(), "DigestBase is not loaded");
6481
6482 const char* klass_name = NULL;
6483 switch (predicate) {
6484 case 0:
6485 if (UseMD5Intrinsics) {
6486 // we want to do an instanceof comparison against the MD5 class
6487 klass_name = "sun/security/provider/MD5";
6488 }
6489 break;
6490 case 1:
6491 if (UseSHA1Intrinsics) {
6492 // we want to do an instanceof comparison against the SHA class
6493 klass_name = "sun/security/provider/SHA";
6494 }
6495 break;
6496 case 2:
6497 if (UseSHA256Intrinsics) {
6498 // we want to do an instanceof comparison against the SHA2 class
6499 klass_name = "sun/security/provider/SHA2";
6500 }
6501 break;
6502 case 3:
6503 if (UseSHA512Intrinsics) {
6504 // we want to do an instanceof comparison against the SHA5 class
6505 klass_name = "sun/security/provider/SHA5";
6506 }
6507 break;
6508 case 4:
6509 if (UseSHA3Intrinsics) {
6510 // we want to do an instanceof comparison against the SHA3 class
6511 klass_name = "sun/security/provider/SHA3";
6512 }
6513 break;
6514 default:
6515 fatal("unknown SHA intrinsic predicate: %d", predicate);
6516 }
6517
6518 ciKlass* klass = NULL;
6519 if (klass_name != NULL) {
6520 klass = tinst->klass()->as_instance_klass()->find_klass(ciSymbol::make(klass_name));
6521 }
6522 if ((klass == NULL) || !klass->is_loaded()) {
6523 // if none of MD5/SHA/SHA2/SHA5 is loaded, we never take the intrinsic fast path
6524 Node* ctrl = control();
6525 set_control(top()); // no intrinsic path
6526 return ctrl;
6527 }
6528 ciInstanceKlass* instklass = klass->as_instance_klass();
6529
6530 Node* instof = gen_instanceof(digestBaseObj, makecon(TypeKlassPtr::make(instklass)));
6531 Node* cmp_instof = _gvn.transform(new CmpINode(instof, intcon(1)));
6532 Node* bool_instof = _gvn.transform(new BoolNode(cmp_instof, BoolTest::ne));
6533 Node* instof_false = generate_guard(bool_instof, NULL, PROB_MIN);
6534
6535 return instof_false; // even if it is NULL
6536 }
6537
6538 //-------------inline_fma-----------------------------------
inline_fma(vmIntrinsics::ID id)6539 bool LibraryCallKit::inline_fma(vmIntrinsics::ID id) {
6540 Node *a = NULL;
6541 Node *b = NULL;
6542 Node *c = NULL;
6543 Node* result = NULL;
6544 switch (id) {
6545 case vmIntrinsics::_fmaD:
6546 assert(callee()->signature()->size() == 6, "fma has 3 parameters of size 2 each.");
6547 // no receiver since it is static method
6548 a = round_double_node(argument(0));
6549 b = round_double_node(argument(2));
6550 c = round_double_node(argument(4));
6551 result = _gvn.transform(new FmaDNode(control(), a, b, c));
6552 break;
6553 case vmIntrinsics::_fmaF:
6554 assert(callee()->signature()->size() == 3, "fma has 3 parameters of size 1 each.");
6555 a = argument(0);
6556 b = argument(1);
6557 c = argument(2);
6558 result = _gvn.transform(new FmaFNode(control(), a, b, c));
6559 break;
6560 default:
6561 fatal_unexpected_iid(id); break;
6562 }
6563 set_result(result);
6564 return true;
6565 }
6566
inline_character_compare(vmIntrinsics::ID id)6567 bool LibraryCallKit::inline_character_compare(vmIntrinsics::ID id) {
6568 // argument(0) is receiver
6569 Node* codePoint = argument(1);
6570 Node* n = NULL;
6571
6572 switch (id) {
6573 case vmIntrinsics::_isDigit :
6574 n = new DigitNode(control(), codePoint);
6575 break;
6576 case vmIntrinsics::_isLowerCase :
6577 n = new LowerCaseNode(control(), codePoint);
6578 break;
6579 case vmIntrinsics::_isUpperCase :
6580 n = new UpperCaseNode(control(), codePoint);
6581 break;
6582 case vmIntrinsics::_isWhitespace :
6583 n = new WhitespaceNode(control(), codePoint);
6584 break;
6585 default:
6586 fatal_unexpected_iid(id);
6587 }
6588
6589 set_result(_gvn.transform(n));
6590 return true;
6591 }
6592
6593 //------------------------------inline_fp_min_max------------------------------
inline_fp_min_max(vmIntrinsics::ID id)6594 bool LibraryCallKit::inline_fp_min_max(vmIntrinsics::ID id) {
6595 /* DISABLED BECAUSE METHOD DATA ISN'T COLLECTED PER CALL-SITE, SEE JDK-8015416.
6596
6597 // The intrinsic should be used only when the API branches aren't predictable,
6598 // the last one performing the most important comparison. The following heuristic
6599 // uses the branch statistics to eventually bail out if necessary.
6600
6601 ciMethodData *md = callee()->method_data();
6602
6603 if ( md != NULL && md->is_mature() && md->invocation_count() > 0 ) {
6604 ciCallProfile cp = caller()->call_profile_at_bci(bci());
6605
6606 if ( ((double)cp.count()) / ((double)md->invocation_count()) < 0.8 ) {
6607 // Bail out if the call-site didn't contribute enough to the statistics.
6608 return false;
6609 }
6610
6611 uint taken = 0, not_taken = 0;
6612
6613 for (ciProfileData *p = md->first_data(); md->is_valid(p); p = md->next_data(p)) {
6614 if (p->is_BranchData()) {
6615 taken = ((ciBranchData*)p)->taken();
6616 not_taken = ((ciBranchData*)p)->not_taken();
6617 }
6618 }
6619
6620 double balance = (((double)taken) - ((double)not_taken)) / ((double)md->invocation_count());
6621 balance = balance < 0 ? -balance : balance;
6622 if ( balance > 0.2 ) {
6623 // Bail out if the most important branch is predictable enough.
6624 return false;
6625 }
6626 }
6627 */
6628
6629 Node *a = NULL;
6630 Node *b = NULL;
6631 Node *n = NULL;
6632 switch (id) {
6633 case vmIntrinsics::_maxF:
6634 case vmIntrinsics::_minF:
6635 assert(callee()->signature()->size() == 2, "minF/maxF has 2 parameters of size 1 each.");
6636 a = argument(0);
6637 b = argument(1);
6638 break;
6639 case vmIntrinsics::_maxD:
6640 case vmIntrinsics::_minD:
6641 assert(callee()->signature()->size() == 4, "minD/maxD has 2 parameters of size 2 each.");
6642 a = round_double_node(argument(0));
6643 b = round_double_node(argument(2));
6644 break;
6645 default:
6646 fatal_unexpected_iid(id);
6647 break;
6648 }
6649 switch (id) {
6650 case vmIntrinsics::_maxF: n = new MaxFNode(a, b); break;
6651 case vmIntrinsics::_minF: n = new MinFNode(a, b); break;
6652 case vmIntrinsics::_maxD: n = new MaxDNode(a, b); break;
6653 case vmIntrinsics::_minD: n = new MinDNode(a, b); break;
6654 default: fatal_unexpected_iid(id); break;
6655 }
6656 set_result(_gvn.transform(n));
6657 return true;
6658 }
6659
inline_profileBoolean()6660 bool LibraryCallKit::inline_profileBoolean() {
6661 Node* counts = argument(1);
6662 const TypeAryPtr* ary = NULL;
6663 ciArray* aobj = NULL;
6664 if (counts->is_Con()
6665 && (ary = counts->bottom_type()->isa_aryptr()) != NULL
6666 && (aobj = ary->const_oop()->as_array()) != NULL
6667 && (aobj->length() == 2)) {
6668 // Profile is int[2] where [0] and [1] correspond to false and true value occurrences respectively.
6669 jint false_cnt = aobj->element_value(0).as_int();
6670 jint true_cnt = aobj->element_value(1).as_int();
6671
6672 if (C->log() != NULL) {
6673 C->log()->elem("observe source='profileBoolean' false='%d' true='%d'",
6674 false_cnt, true_cnt);
6675 }
6676
6677 if (false_cnt + true_cnt == 0) {
6678 // According to profile, never executed.
6679 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6680 Deoptimization::Action_reinterpret);
6681 return true;
6682 }
6683
6684 // result is a boolean (0 or 1) and its profile (false_cnt & true_cnt)
6685 // is a number of each value occurrences.
6686 Node* result = argument(0);
6687 if (false_cnt == 0 || true_cnt == 0) {
6688 // According to profile, one value has been never seen.
6689 int expected_val = (false_cnt == 0) ? 1 : 0;
6690
6691 Node* cmp = _gvn.transform(new CmpINode(result, intcon(expected_val)));
6692 Node* test = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
6693
6694 IfNode* check = create_and_map_if(control(), test, PROB_ALWAYS, COUNT_UNKNOWN);
6695 Node* fast_path = _gvn.transform(new IfTrueNode(check));
6696 Node* slow_path = _gvn.transform(new IfFalseNode(check));
6697
6698 { // Slow path: uncommon trap for never seen value and then reexecute
6699 // MethodHandleImpl::profileBoolean() to bump the count, so JIT knows
6700 // the value has been seen at least once.
6701 PreserveJVMState pjvms(this);
6702 PreserveReexecuteState preexecs(this);
6703 jvms()->set_should_reexecute(true);
6704
6705 set_control(slow_path);
6706 set_i_o(i_o());
6707
6708 uncommon_trap_exact(Deoptimization::Reason_intrinsic,
6709 Deoptimization::Action_reinterpret);
6710 }
6711 // The guard for never seen value enables sharpening of the result and
6712 // returning a constant. It allows to eliminate branches on the same value
6713 // later on.
6714 set_control(fast_path);
6715 result = intcon(expected_val);
6716 }
6717 // Stop profiling.
6718 // MethodHandleImpl::profileBoolean() has profiling logic in its bytecode.
6719 // By replacing method body with profile data (represented as ProfileBooleanNode
6720 // on IR level) we effectively disable profiling.
6721 // It enables full speed execution once optimized code is generated.
6722 Node* profile = _gvn.transform(new ProfileBooleanNode(result, false_cnt, true_cnt));
6723 C->record_for_igvn(profile);
6724 set_result(profile);
6725 return true;
6726 } else {
6727 // Continue profiling.
6728 // Profile data isn't available at the moment. So, execute method's bytecode version.
6729 // Usually, when GWT LambdaForms are profiled it means that a stand-alone nmethod
6730 // is compiled and counters aren't available since corresponding MethodHandle
6731 // isn't a compile-time constant.
6732 return false;
6733 }
6734 }
6735
inline_isCompileConstant()6736 bool LibraryCallKit::inline_isCompileConstant() {
6737 Node* n = argument(0);
6738 set_result(n->is_Con() ? intcon(1) : intcon(0));
6739 return true;
6740 }
6741
6742 //------------------------------- inline_getObjectSize --------------------------------------
6743 //
6744 // Calculate the runtime size of the object/array.
6745 // native long sun.instrument.InstrumentationImpl.getObjectSize0(long nativeAgent, Object objectToSize);
6746 //
inline_getObjectSize()6747 bool LibraryCallKit::inline_getObjectSize() {
6748 Node* obj = argument(3);
6749 Node* klass_node = load_object_klass(obj);
6750
6751 jint layout_con = Klass::_lh_neutral_value;
6752 Node* layout_val = get_layout_helper(klass_node, layout_con);
6753 int layout_is_con = (layout_val == NULL);
6754
6755 if (layout_is_con) {
6756 // Layout helper is constant, can figure out things at compile time.
6757
6758 if (Klass::layout_helper_is_instance(layout_con)) {
6759 // Instance case: layout_con contains the size itself.
6760 Node *size = longcon(Klass::layout_helper_size_in_bytes(layout_con));
6761 set_result(size);
6762 } else {
6763 // Array case: size is round(header + element_size*arraylength).
6764 // Since arraylength is different for every array instance, we have to
6765 // compute the whole thing at runtime.
6766
6767 Node* arr_length = load_array_length(obj);
6768
6769 int round_mask = MinObjAlignmentInBytes - 1;
6770 int hsize = Klass::layout_helper_header_size(layout_con);
6771 int eshift = Klass::layout_helper_log2_element_size(layout_con);
6772
6773 if ((round_mask & ~right_n_bits(eshift)) == 0) {
6774 round_mask = 0; // strength-reduce it if it goes away completely
6775 }
6776 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
6777 Node* header_size = intcon(hsize + round_mask);
6778
6779 Node* lengthx = ConvI2X(arr_length);
6780 Node* headerx = ConvI2X(header_size);
6781
6782 Node* abody = lengthx;
6783 if (eshift != 0) {
6784 abody = _gvn.transform(new LShiftXNode(lengthx, intcon(eshift)));
6785 }
6786 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
6787 if (round_mask != 0) {
6788 size = _gvn.transform( new AndXNode(size, MakeConX(~round_mask)) );
6789 }
6790 size = ConvX2L(size);
6791 set_result(size);
6792 }
6793 } else {
6794 // Layout helper is not constant, need to test for array-ness at runtime.
6795
6796 enum { _instance_path = 1, _array_path, PATH_LIMIT };
6797 RegionNode* result_reg = new RegionNode(PATH_LIMIT);
6798 PhiNode* result_val = new PhiNode(result_reg, TypeLong::LONG);
6799 record_for_igvn(result_reg);
6800
6801 Node* array_ctl = generate_array_guard(klass_node, NULL);
6802 if (array_ctl != NULL) {
6803 // Array case: size is round(header + element_size*arraylength).
6804 // Since arraylength is different for every array instance, we have to
6805 // compute the whole thing at runtime.
6806
6807 PreserveJVMState pjvms(this);
6808 set_control(array_ctl);
6809 Node* arr_length = load_array_length(obj);
6810
6811 int round_mask = MinObjAlignmentInBytes - 1;
6812 Node* mask = intcon(round_mask);
6813
6814 Node* hss = intcon(Klass::_lh_header_size_shift);
6815 Node* hsm = intcon(Klass::_lh_header_size_mask);
6816 Node* header_size = _gvn.transform(new URShiftINode(layout_val, hss));
6817 header_size = _gvn.transform(new AndINode(header_size, hsm));
6818 header_size = _gvn.transform(new AddINode(header_size, mask));
6819
6820 // There is no need to mask or shift this value.
6821 // The semantics of LShiftINode include an implicit mask to 0x1F.
6822 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
6823 Node* elem_shift = layout_val;
6824
6825 Node* lengthx = ConvI2X(arr_length);
6826 Node* headerx = ConvI2X(header_size);
6827
6828 Node* abody = _gvn.transform(new LShiftXNode(lengthx, elem_shift));
6829 Node* size = _gvn.transform(new AddXNode(headerx, abody));
6830 if (round_mask != 0) {
6831 size = _gvn.transform(new AndXNode(size, MakeConX(~round_mask)));
6832 }
6833 size = ConvX2L(size);
6834
6835 result_reg->init_req(_array_path, control());
6836 result_val->init_req(_array_path, size);
6837 }
6838
6839 if (!stopped()) {
6840 // Instance case: the layout helper gives us instance size almost directly,
6841 // but we need to mask out the _lh_instance_slow_path_bit.
6842 Node* size = ConvI2X(layout_val);
6843 assert((int) Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
6844 Node* mask = MakeConX(~(intptr_t) right_n_bits(LogBytesPerLong));
6845 size = _gvn.transform(new AndXNode(size, mask));
6846 size = ConvX2L(size);
6847
6848 result_reg->init_req(_instance_path, control());
6849 result_val->init_req(_instance_path, size);
6850 }
6851
6852 set_result(result_reg, result_val);
6853 }
6854
6855 return true;
6856 }
6857