1 /*
2 * Copyright (c) 2001, 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 "ci/ciUtilities.hpp"
27 #include "compiler/compileLog.hpp"
28 #include "gc/shared/barrierSet.hpp"
29 #include "gc/shared/c2/barrierSetC2.hpp"
30 #include "interpreter/interpreter.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "opto/addnode.hpp"
33 #include "opto/castnode.hpp"
34 #include "opto/convertnode.hpp"
35 #include "opto/graphKit.hpp"
36 #include "opto/idealKit.hpp"
37 #include "opto/intrinsicnode.hpp"
38 #include "opto/locknode.hpp"
39 #include "opto/machnode.hpp"
40 #include "opto/opaquenode.hpp"
41 #include "opto/parse.hpp"
42 #include "opto/rootnode.hpp"
43 #include "opto/runtime.hpp"
44 #include "runtime/deoptimization.hpp"
45 #include "runtime/sharedRuntime.hpp"
46 #include "utilities/macros.hpp"
47 #if INCLUDE_SHENANDOAHGC
48 #include "gc/shenandoah/c2/shenandoahBarrierSetC2.hpp"
49 #endif
50
51 //----------------------------GraphKit-----------------------------------------
52 // Main utility constructor.
GraphKit(JVMState * jvms)53 GraphKit::GraphKit(JVMState* jvms)
54 : Phase(Phase::Parser),
55 _env(C->env()),
56 _gvn(*C->initial_gvn()),
57 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
58 {
59 _exceptions = jvms->map()->next_exception();
60 if (_exceptions != NULL) jvms->map()->set_next_exception(NULL);
61 set_jvms(jvms);
62 }
63
64 // Private constructor for parser.
GraphKit()65 GraphKit::GraphKit()
66 : Phase(Phase::Parser),
67 _env(C->env()),
68 _gvn(*C->initial_gvn()),
69 _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
70 {
71 _exceptions = NULL;
72 set_map(NULL);
73 debug_only(_sp = -99);
74 debug_only(set_bci(-99));
75 }
76
77
78
79 //---------------------------clean_stack---------------------------------------
80 // Clear away rubbish from the stack area of the JVM state.
81 // This destroys any arguments that may be waiting on the stack.
clean_stack(int from_sp)82 void GraphKit::clean_stack(int from_sp) {
83 SafePointNode* map = this->map();
84 JVMState* jvms = this->jvms();
85 int stk_size = jvms->stk_size();
86 int stkoff = jvms->stkoff();
87 Node* top = this->top();
88 for (int i = from_sp; i < stk_size; i++) {
89 if (map->in(stkoff + i) != top) {
90 map->set_req(stkoff + i, top);
91 }
92 }
93 }
94
95
96 //--------------------------------sync_jvms-----------------------------------
97 // Make sure our current jvms agrees with our parse state.
sync_jvms() const98 JVMState* GraphKit::sync_jvms() const {
99 JVMState* jvms = this->jvms();
100 jvms->set_bci(bci()); // Record the new bci in the JVMState
101 jvms->set_sp(sp()); // Record the new sp in the JVMState
102 assert(jvms_in_sync(), "jvms is now in sync");
103 return jvms;
104 }
105
106 //--------------------------------sync_jvms_for_reexecute---------------------
107 // Make sure our current jvms agrees with our parse state. This version
108 // uses the reexecute_sp for reexecuting bytecodes.
sync_jvms_for_reexecute()109 JVMState* GraphKit::sync_jvms_for_reexecute() {
110 JVMState* jvms = this->jvms();
111 jvms->set_bci(bci()); // Record the new bci in the JVMState
112 jvms->set_sp(reexecute_sp()); // Record the new sp in the JVMState
113 return jvms;
114 }
115
116 #ifdef ASSERT
jvms_in_sync() const117 bool GraphKit::jvms_in_sync() const {
118 Parse* parse = is_Parse();
119 if (parse == NULL) {
120 if (bci() != jvms()->bci()) return false;
121 if (sp() != (int)jvms()->sp()) return false;
122 return true;
123 }
124 if (jvms()->method() != parse->method()) return false;
125 if (jvms()->bci() != parse->bci()) return false;
126 int jvms_sp = jvms()->sp();
127 if (jvms_sp != parse->sp()) return false;
128 int jvms_depth = jvms()->depth();
129 if (jvms_depth != parse->depth()) return false;
130 return true;
131 }
132
133 // Local helper checks for special internal merge points
134 // used to accumulate and merge exception states.
135 // They are marked by the region's in(0) edge being the map itself.
136 // Such merge points must never "escape" into the parser at large,
137 // until they have been handed to gvn.transform.
is_hidden_merge(Node * reg)138 static bool is_hidden_merge(Node* reg) {
139 if (reg == NULL) return false;
140 if (reg->is_Phi()) {
141 reg = reg->in(0);
142 if (reg == NULL) return false;
143 }
144 return reg->is_Region() && reg->in(0) != NULL && reg->in(0)->is_Root();
145 }
146
verify_map() const147 void GraphKit::verify_map() const {
148 if (map() == NULL) return; // null map is OK
149 assert(map()->req() <= jvms()->endoff(), "no extra garbage on map");
150 assert(!map()->has_exceptions(), "call add_exception_states_from 1st");
151 assert(!is_hidden_merge(control()), "call use_exception_state, not set_map");
152 }
153
verify_exception_state(SafePointNode * ex_map)154 void GraphKit::verify_exception_state(SafePointNode* ex_map) {
155 assert(ex_map->next_exception() == NULL, "not already part of a chain");
156 assert(has_saved_ex_oop(ex_map), "every exception state has an ex_oop");
157 }
158 #endif
159
160 //---------------------------stop_and_kill_map---------------------------------
161 // Set _map to NULL, signalling a stop to further bytecode execution.
162 // First smash the current map's control to a constant, to mark it dead.
stop_and_kill_map()163 void GraphKit::stop_and_kill_map() {
164 SafePointNode* dead_map = stop();
165 if (dead_map != NULL) {
166 dead_map->disconnect_inputs(NULL, C); // Mark the map as killed.
167 assert(dead_map->is_killed(), "must be so marked");
168 }
169 }
170
171
172 //--------------------------------stopped--------------------------------------
173 // Tell if _map is NULL, or control is top.
stopped()174 bool GraphKit::stopped() {
175 if (map() == NULL) return true;
176 else if (control() == top()) return true;
177 else return false;
178 }
179
180
181 //-----------------------------has_ex_handler----------------------------------
182 // Tell if this method or any caller method has exception handlers.
has_ex_handler()183 bool GraphKit::has_ex_handler() {
184 for (JVMState* jvmsp = jvms(); jvmsp != NULL; jvmsp = jvmsp->caller()) {
185 if (jvmsp->has_method() && jvmsp->method()->has_exception_handlers()) {
186 return true;
187 }
188 }
189 return false;
190 }
191
192 //------------------------------save_ex_oop------------------------------------
193 // Save an exception without blowing stack contents or other JVM state.
set_saved_ex_oop(SafePointNode * ex_map,Node * ex_oop)194 void GraphKit::set_saved_ex_oop(SafePointNode* ex_map, Node* ex_oop) {
195 assert(!has_saved_ex_oop(ex_map), "clear ex-oop before setting again");
196 ex_map->add_req(ex_oop);
197 debug_only(verify_exception_state(ex_map));
198 }
199
common_saved_ex_oop(SafePointNode * ex_map,bool clear_it)200 inline static Node* common_saved_ex_oop(SafePointNode* ex_map, bool clear_it) {
201 assert(GraphKit::has_saved_ex_oop(ex_map), "ex_oop must be there");
202 Node* ex_oop = ex_map->in(ex_map->req()-1);
203 if (clear_it) ex_map->del_req(ex_map->req()-1);
204 return ex_oop;
205 }
206
207 //-----------------------------saved_ex_oop------------------------------------
208 // Recover a saved exception from its map.
saved_ex_oop(SafePointNode * ex_map)209 Node* GraphKit::saved_ex_oop(SafePointNode* ex_map) {
210 return common_saved_ex_oop(ex_map, false);
211 }
212
213 //--------------------------clear_saved_ex_oop---------------------------------
214 // Erase a previously saved exception from its map.
clear_saved_ex_oop(SafePointNode * ex_map)215 Node* GraphKit::clear_saved_ex_oop(SafePointNode* ex_map) {
216 return common_saved_ex_oop(ex_map, true);
217 }
218
219 #ifdef ASSERT
220 //---------------------------has_saved_ex_oop----------------------------------
221 // Erase a previously saved exception from its map.
has_saved_ex_oop(SafePointNode * ex_map)222 bool GraphKit::has_saved_ex_oop(SafePointNode* ex_map) {
223 return ex_map->req() == ex_map->jvms()->endoff()+1;
224 }
225 #endif
226
227 //-------------------------make_exception_state--------------------------------
228 // Turn the current JVM state into an exception state, appending the ex_oop.
make_exception_state(Node * ex_oop)229 SafePointNode* GraphKit::make_exception_state(Node* ex_oop) {
230 sync_jvms();
231 SafePointNode* ex_map = stop(); // do not manipulate this map any more
232 set_saved_ex_oop(ex_map, ex_oop);
233 return ex_map;
234 }
235
236
237 //--------------------------add_exception_state--------------------------------
238 // Add an exception to my list of exceptions.
add_exception_state(SafePointNode * ex_map)239 void GraphKit::add_exception_state(SafePointNode* ex_map) {
240 if (ex_map == NULL || ex_map->control() == top()) {
241 return;
242 }
243 #ifdef ASSERT
244 verify_exception_state(ex_map);
245 if (has_exceptions()) {
246 assert(ex_map->jvms()->same_calls_as(_exceptions->jvms()), "all collected exceptions must come from the same place");
247 }
248 #endif
249
250 // If there is already an exception of exactly this type, merge with it.
251 // In particular, null-checks and other low-level exceptions common up here.
252 Node* ex_oop = saved_ex_oop(ex_map);
253 const Type* ex_type = _gvn.type(ex_oop);
254 if (ex_oop == top()) {
255 // No action needed.
256 return;
257 }
258 assert(ex_type->isa_instptr(), "exception must be an instance");
259 for (SafePointNode* e2 = _exceptions; e2 != NULL; e2 = e2->next_exception()) {
260 const Type* ex_type2 = _gvn.type(saved_ex_oop(e2));
261 // We check sp also because call bytecodes can generate exceptions
262 // both before and after arguments are popped!
263 if (ex_type2 == ex_type
264 && e2->_jvms->sp() == ex_map->_jvms->sp()) {
265 combine_exception_states(ex_map, e2);
266 return;
267 }
268 }
269
270 // No pre-existing exception of the same type. Chain it on the list.
271 push_exception_state(ex_map);
272 }
273
274 //-----------------------add_exception_states_from-----------------------------
add_exception_states_from(JVMState * jvms)275 void GraphKit::add_exception_states_from(JVMState* jvms) {
276 SafePointNode* ex_map = jvms->map()->next_exception();
277 if (ex_map != NULL) {
278 jvms->map()->set_next_exception(NULL);
279 for (SafePointNode* next_map; ex_map != NULL; ex_map = next_map) {
280 next_map = ex_map->next_exception();
281 ex_map->set_next_exception(NULL);
282 add_exception_state(ex_map);
283 }
284 }
285 }
286
287 //-----------------------transfer_exceptions_into_jvms-------------------------
transfer_exceptions_into_jvms()288 JVMState* GraphKit::transfer_exceptions_into_jvms() {
289 if (map() == NULL) {
290 // We need a JVMS to carry the exceptions, but the map has gone away.
291 // Create a scratch JVMS, cloned from any of the exception states...
292 if (has_exceptions()) {
293 _map = _exceptions;
294 _map = clone_map();
295 _map->set_next_exception(NULL);
296 clear_saved_ex_oop(_map);
297 debug_only(verify_map());
298 } else {
299 // ...or created from scratch
300 JVMState* jvms = new (C) JVMState(_method, NULL);
301 jvms->set_bci(_bci);
302 jvms->set_sp(_sp);
303 jvms->set_map(new SafePointNode(TypeFunc::Parms, jvms));
304 set_jvms(jvms);
305 for (uint i = 0; i < map()->req(); i++) map()->init_req(i, top());
306 set_all_memory(top());
307 while (map()->req() < jvms->endoff()) map()->add_req(top());
308 }
309 // (This is a kludge, in case you didn't notice.)
310 set_control(top());
311 }
312 JVMState* jvms = sync_jvms();
313 assert(!jvms->map()->has_exceptions(), "no exceptions on this map yet");
314 jvms->map()->set_next_exception(_exceptions);
315 _exceptions = NULL; // done with this set of exceptions
316 return jvms;
317 }
318
add_n_reqs(Node * dstphi,Node * srcphi)319 static inline void add_n_reqs(Node* dstphi, Node* srcphi) {
320 assert(is_hidden_merge(dstphi), "must be a special merge node");
321 assert(is_hidden_merge(srcphi), "must be a special merge node");
322 uint limit = srcphi->req();
323 for (uint i = PhiNode::Input; i < limit; i++) {
324 dstphi->add_req(srcphi->in(i));
325 }
326 }
add_one_req(Node * dstphi,Node * src)327 static inline void add_one_req(Node* dstphi, Node* src) {
328 assert(is_hidden_merge(dstphi), "must be a special merge node");
329 assert(!is_hidden_merge(src), "must not be a special merge node");
330 dstphi->add_req(src);
331 }
332
333 //-----------------------combine_exception_states------------------------------
334 // This helper function combines exception states by building phis on a
335 // specially marked state-merging region. These regions and phis are
336 // untransformed, and can build up gradually. The region is marked by
337 // having a control input of its exception map, rather than NULL. Such
338 // regions do not appear except in this function, and in use_exception_state.
combine_exception_states(SafePointNode * ex_map,SafePointNode * phi_map)339 void GraphKit::combine_exception_states(SafePointNode* ex_map, SafePointNode* phi_map) {
340 if (failing()) return; // dying anyway...
341 JVMState* ex_jvms = ex_map->_jvms;
342 assert(ex_jvms->same_calls_as(phi_map->_jvms), "consistent call chains");
343 assert(ex_jvms->stkoff() == phi_map->_jvms->stkoff(), "matching locals");
344 assert(ex_jvms->sp() == phi_map->_jvms->sp(), "matching stack sizes");
345 assert(ex_jvms->monoff() == phi_map->_jvms->monoff(), "matching JVMS");
346 assert(ex_jvms->scloff() == phi_map->_jvms->scloff(), "matching scalar replaced objects");
347 assert(ex_map->req() == phi_map->req(), "matching maps");
348 uint tos = ex_jvms->stkoff() + ex_jvms->sp();
349 Node* hidden_merge_mark = root();
350 Node* region = phi_map->control();
351 MergeMemNode* phi_mem = phi_map->merged_memory();
352 MergeMemNode* ex_mem = ex_map->merged_memory();
353 if (region->in(0) != hidden_merge_mark) {
354 // The control input is not (yet) a specially-marked region in phi_map.
355 // Make it so, and build some phis.
356 region = new RegionNode(2);
357 _gvn.set_type(region, Type::CONTROL);
358 region->set_req(0, hidden_merge_mark); // marks an internal ex-state
359 region->init_req(1, phi_map->control());
360 phi_map->set_control(region);
361 Node* io_phi = PhiNode::make(region, phi_map->i_o(), Type::ABIO);
362 record_for_igvn(io_phi);
363 _gvn.set_type(io_phi, Type::ABIO);
364 phi_map->set_i_o(io_phi);
365 for (MergeMemStream mms(phi_mem); mms.next_non_empty(); ) {
366 Node* m = mms.memory();
367 Node* m_phi = PhiNode::make(region, m, Type::MEMORY, mms.adr_type(C));
368 record_for_igvn(m_phi);
369 _gvn.set_type(m_phi, Type::MEMORY);
370 mms.set_memory(m_phi);
371 }
372 }
373
374 // Either or both of phi_map and ex_map might already be converted into phis.
375 Node* ex_control = ex_map->control();
376 // if there is special marking on ex_map also, we add multiple edges from src
377 bool add_multiple = (ex_control->in(0) == hidden_merge_mark);
378 // how wide was the destination phi_map, originally?
379 uint orig_width = region->req();
380
381 if (add_multiple) {
382 add_n_reqs(region, ex_control);
383 add_n_reqs(phi_map->i_o(), ex_map->i_o());
384 } else {
385 // ex_map has no merges, so we just add single edges everywhere
386 add_one_req(region, ex_control);
387 add_one_req(phi_map->i_o(), ex_map->i_o());
388 }
389 for (MergeMemStream mms(phi_mem, ex_mem); mms.next_non_empty2(); ) {
390 if (mms.is_empty()) {
391 // get a copy of the base memory, and patch some inputs into it
392 const TypePtr* adr_type = mms.adr_type(C);
393 Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
394 assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
395 mms.set_memory(phi);
396 // Prepare to append interesting stuff onto the newly sliced phi:
397 while (phi->req() > orig_width) phi->del_req(phi->req()-1);
398 }
399 // Append stuff from ex_map:
400 if (add_multiple) {
401 add_n_reqs(mms.memory(), mms.memory2());
402 } else {
403 add_one_req(mms.memory(), mms.memory2());
404 }
405 }
406 uint limit = ex_map->req();
407 for (uint i = TypeFunc::Parms; i < limit; i++) {
408 // Skip everything in the JVMS after tos. (The ex_oop follows.)
409 if (i == tos) i = ex_jvms->monoff();
410 Node* src = ex_map->in(i);
411 Node* dst = phi_map->in(i);
412 if (src != dst) {
413 PhiNode* phi;
414 if (dst->in(0) != region) {
415 dst = phi = PhiNode::make(region, dst, _gvn.type(dst));
416 record_for_igvn(phi);
417 _gvn.set_type(phi, phi->type());
418 phi_map->set_req(i, dst);
419 // Prepare to append interesting stuff onto the new phi:
420 while (dst->req() > orig_width) dst->del_req(dst->req()-1);
421 } else {
422 assert(dst->is_Phi(), "nobody else uses a hidden region");
423 phi = dst->as_Phi();
424 }
425 if (add_multiple && src->in(0) == ex_control) {
426 // Both are phis.
427 add_n_reqs(dst, src);
428 } else {
429 while (dst->req() < region->req()) add_one_req(dst, src);
430 }
431 const Type* srctype = _gvn.type(src);
432 if (phi->type() != srctype) {
433 const Type* dsttype = phi->type()->meet_speculative(srctype);
434 if (phi->type() != dsttype) {
435 phi->set_type(dsttype);
436 _gvn.set_type(phi, dsttype);
437 }
438 }
439 }
440 }
441 phi_map->merge_replaced_nodes_with(ex_map);
442 }
443
444 //--------------------------use_exception_state--------------------------------
use_exception_state(SafePointNode * phi_map)445 Node* GraphKit::use_exception_state(SafePointNode* phi_map) {
446 if (failing()) { stop(); return top(); }
447 Node* region = phi_map->control();
448 Node* hidden_merge_mark = root();
449 assert(phi_map->jvms()->map() == phi_map, "sanity: 1-1 relation");
450 Node* ex_oop = clear_saved_ex_oop(phi_map);
451 if (region->in(0) == hidden_merge_mark) {
452 // Special marking for internal ex-states. Process the phis now.
453 region->set_req(0, region); // now it's an ordinary region
454 set_jvms(phi_map->jvms()); // ...so now we can use it as a map
455 // Note: Setting the jvms also sets the bci and sp.
456 set_control(_gvn.transform(region));
457 uint tos = jvms()->stkoff() + sp();
458 for (uint i = 1; i < tos; i++) {
459 Node* x = phi_map->in(i);
460 if (x->in(0) == region) {
461 assert(x->is_Phi(), "expected a special phi");
462 phi_map->set_req(i, _gvn.transform(x));
463 }
464 }
465 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
466 Node* x = mms.memory();
467 if (x->in(0) == region) {
468 assert(x->is_Phi(), "nobody else uses a hidden region");
469 mms.set_memory(_gvn.transform(x));
470 }
471 }
472 if (ex_oop->in(0) == region) {
473 assert(ex_oop->is_Phi(), "expected a special phi");
474 ex_oop = _gvn.transform(ex_oop);
475 }
476 } else {
477 set_jvms(phi_map->jvms());
478 }
479
480 assert(!is_hidden_merge(phi_map->control()), "hidden ex. states cleared");
481 assert(!is_hidden_merge(phi_map->i_o()), "hidden ex. states cleared");
482 return ex_oop;
483 }
484
485 //---------------------------------java_bc-------------------------------------
java_bc() const486 Bytecodes::Code GraphKit::java_bc() const {
487 ciMethod* method = this->method();
488 int bci = this->bci();
489 if (method != NULL && bci != InvocationEntryBci)
490 return method->java_code_at_bci(bci);
491 else
492 return Bytecodes::_illegal;
493 }
494
uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,bool must_throw)495 void GraphKit::uncommon_trap_if_should_post_on_exceptions(Deoptimization::DeoptReason reason,
496 bool must_throw) {
497 // if the exception capability is set, then we will generate code
498 // to check the JavaThread.should_post_on_exceptions flag to see
499 // if we actually need to report exception events (for this
500 // thread). If we don't need to report exception events, we will
501 // take the normal fast path provided by add_exception_events. If
502 // exception event reporting is enabled for this thread, we will
503 // take the uncommon_trap in the BuildCutout below.
504
505 // first must access the should_post_on_exceptions_flag in this thread's JavaThread
506 Node* jthread = _gvn.transform(new ThreadLocalNode());
507 Node* adr = basic_plus_adr(top(), jthread, in_bytes(JavaThread::should_post_on_exceptions_flag_offset()));
508 Node* should_post_flag = make_load(control(), adr, TypeInt::INT, T_INT, Compile::AliasIdxRaw, MemNode::unordered);
509
510 // Test the should_post_on_exceptions_flag vs. 0
511 Node* chk = _gvn.transform( new CmpINode(should_post_flag, intcon(0)) );
512 Node* tst = _gvn.transform( new BoolNode(chk, BoolTest::eq) );
513
514 // Branch to slow_path if should_post_on_exceptions_flag was true
515 { BuildCutout unless(this, tst, PROB_MAX);
516 // Do not try anything fancy if we're notifying the VM on every throw.
517 // Cf. case Bytecodes::_athrow in parse2.cpp.
518 uncommon_trap(reason, Deoptimization::Action_none,
519 (ciKlass*)NULL, (char*)NULL, must_throw);
520 }
521
522 }
523
524 //------------------------------builtin_throw----------------------------------
builtin_throw(Deoptimization::DeoptReason reason,Node * arg)525 void GraphKit::builtin_throw(Deoptimization::DeoptReason reason, Node* arg) {
526 bool must_throw = true;
527
528 if (env()->jvmti_can_post_on_exceptions()) {
529 // check if we must post exception events, take uncommon trap if so
530 uncommon_trap_if_should_post_on_exceptions(reason, must_throw);
531 // here if should_post_on_exceptions is false
532 // continue on with the normal codegen
533 }
534
535 // If this particular condition has not yet happened at this
536 // bytecode, then use the uncommon trap mechanism, and allow for
537 // a future recompilation if several traps occur here.
538 // If the throw is hot, try to use a more complicated inline mechanism
539 // which keeps execution inside the compiled code.
540 bool treat_throw_as_hot = false;
541 ciMethodData* md = method()->method_data();
542
543 if (ProfileTraps) {
544 if (too_many_traps(reason)) {
545 treat_throw_as_hot = true;
546 }
547 // (If there is no MDO at all, assume it is early in
548 // execution, and that any deopts are part of the
549 // startup transient, and don't need to be remembered.)
550
551 // Also, if there is a local exception handler, treat all throws
552 // as hot if there has been at least one in this method.
553 if (C->trap_count(reason) != 0
554 && method()->method_data()->trap_count(reason) != 0
555 && has_ex_handler()) {
556 treat_throw_as_hot = true;
557 }
558 }
559
560 // If this throw happens frequently, an uncommon trap might cause
561 // a performance pothole. If there is a local exception handler,
562 // and if this particular bytecode appears to be deoptimizing often,
563 // let us handle the throw inline, with a preconstructed instance.
564 // Note: If the deopt count has blown up, the uncommon trap
565 // runtime is going to flush this nmethod, not matter what.
566 if (treat_throw_as_hot
567 && (!StackTraceInThrowable || OmitStackTraceInFastThrow)) {
568 // If the throw is local, we use a pre-existing instance and
569 // punt on the backtrace. This would lead to a missing backtrace
570 // (a repeat of 4292742) if the backtrace object is ever asked
571 // for its backtrace.
572 // Fixing this remaining case of 4292742 requires some flavor of
573 // escape analysis. Leave that for the future.
574 ciInstance* ex_obj = NULL;
575 switch (reason) {
576 case Deoptimization::Reason_null_check:
577 ex_obj = env()->NullPointerException_instance();
578 break;
579 case Deoptimization::Reason_div0_check:
580 ex_obj = env()->ArithmeticException_instance();
581 break;
582 case Deoptimization::Reason_range_check:
583 ex_obj = env()->ArrayIndexOutOfBoundsException_instance();
584 break;
585 case Deoptimization::Reason_class_check:
586 if (java_bc() == Bytecodes::_aastore) {
587 ex_obj = env()->ArrayStoreException_instance();
588 } else {
589 ex_obj = env()->ClassCastException_instance();
590 }
591 break;
592 default:
593 break;
594 }
595 if (failing()) { stop(); return; } // exception allocation might fail
596 if (ex_obj != NULL) {
597 // Cheat with a preallocated exception object.
598 if (C->log() != NULL)
599 C->log()->elem("hot_throw preallocated='1' reason='%s'",
600 Deoptimization::trap_reason_name(reason));
601 const TypeInstPtr* ex_con = TypeInstPtr::make(ex_obj);
602 Node* ex_node = _gvn.transform(ConNode::make(ex_con));
603
604 // Clear the detail message of the preallocated exception object.
605 // Weblogic sometimes mutates the detail message of exceptions
606 // using reflection.
607 int offset = java_lang_Throwable::get_detailMessage_offset();
608 const TypePtr* adr_typ = ex_con->add_offset(offset);
609
610 Node *adr = basic_plus_adr(ex_node, ex_node, offset);
611 const TypeOopPtr* val_type = TypeOopPtr::make_from_klass(env()->String_klass());
612 Node *store = access_store_at(control(), ex_node, adr, adr_typ, null(), val_type, T_OBJECT, IN_HEAP);
613
614 add_exception_state(make_exception_state(ex_node));
615 return;
616 }
617 }
618
619 // %%% Maybe add entry to OptoRuntime which directly throws the exc.?
620 // It won't be much cheaper than bailing to the interp., since we'll
621 // have to pass up all the debug-info, and the runtime will have to
622 // create the stack trace.
623
624 // Usual case: Bail to interpreter.
625 // Reserve the right to recompile if we haven't seen anything yet.
626
627 ciMethod* m = Deoptimization::reason_is_speculate(reason) ? C->method() : NULL;
628 Deoptimization::DeoptAction action = Deoptimization::Action_maybe_recompile;
629 if (treat_throw_as_hot
630 && (method()->method_data()->trap_recompiled_at(bci(), m)
631 || C->too_many_traps(reason))) {
632 // We cannot afford to take more traps here. Suffer in the interpreter.
633 if (C->log() != NULL)
634 C->log()->elem("hot_throw preallocated='0' reason='%s' mcount='%d'",
635 Deoptimization::trap_reason_name(reason),
636 C->trap_count(reason));
637 action = Deoptimization::Action_none;
638 }
639
640 // "must_throw" prunes the JVM state to include only the stack, if there
641 // are no local exception handlers. This should cut down on register
642 // allocation time and code size, by drastically reducing the number
643 // of in-edges on the call to the uncommon trap.
644
645 uncommon_trap(reason, action, (ciKlass*)NULL, (char*)NULL, must_throw);
646 }
647
648
649 //----------------------------PreserveJVMState---------------------------------
PreserveJVMState(GraphKit * kit,bool clone_map)650 PreserveJVMState::PreserveJVMState(GraphKit* kit, bool clone_map) {
651 debug_only(kit->verify_map());
652 _kit = kit;
653 _map = kit->map(); // preserve the map
654 _sp = kit->sp();
655 kit->set_map(clone_map ? kit->clone_map() : NULL);
656 #ifdef ASSERT
657 _bci = kit->bci();
658 Parse* parser = kit->is_Parse();
659 int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
660 _block = block;
661 #endif
662 }
~PreserveJVMState()663 PreserveJVMState::~PreserveJVMState() {
664 GraphKit* kit = _kit;
665 #ifdef ASSERT
666 assert(kit->bci() == _bci, "bci must not shift");
667 Parse* parser = kit->is_Parse();
668 int block = (parser == NULL || parser->block() == NULL) ? -1 : parser->block()->rpo();
669 assert(block == _block, "block must not shift");
670 #endif
671 kit->set_map(_map);
672 kit->set_sp(_sp);
673 }
674
675
676 //-----------------------------BuildCutout-------------------------------------
BuildCutout(GraphKit * kit,Node * p,float prob,float cnt)677 BuildCutout::BuildCutout(GraphKit* kit, Node* p, float prob, float cnt)
678 : PreserveJVMState(kit)
679 {
680 assert(p->is_Con() || p->is_Bool(), "test must be a bool");
681 SafePointNode* outer_map = _map; // preserved map is caller's
682 SafePointNode* inner_map = kit->map();
683 IfNode* iff = kit->create_and_map_if(outer_map->control(), p, prob, cnt);
684 outer_map->set_control(kit->gvn().transform( new IfTrueNode(iff) ));
685 inner_map->set_control(kit->gvn().transform( new IfFalseNode(iff) ));
686 }
~BuildCutout()687 BuildCutout::~BuildCutout() {
688 GraphKit* kit = _kit;
689 assert(kit->stopped(), "cutout code must stop, throw, return, etc.");
690 }
691
692 //---------------------------PreserveReexecuteState----------------------------
PreserveReexecuteState(GraphKit * kit)693 PreserveReexecuteState::PreserveReexecuteState(GraphKit* kit) {
694 assert(!kit->stopped(), "must call stopped() before");
695 _kit = kit;
696 _sp = kit->sp();
697 _reexecute = kit->jvms()->_reexecute;
698 }
~PreserveReexecuteState()699 PreserveReexecuteState::~PreserveReexecuteState() {
700 if (_kit->stopped()) return;
701 _kit->jvms()->_reexecute = _reexecute;
702 _kit->set_sp(_sp);
703 }
704
705 //------------------------------clone_map--------------------------------------
706 // Implementation of PreserveJVMState
707 //
708 // Only clone_map(...) here. If this function is only used in the
709 // PreserveJVMState class we may want to get rid of this extra
710 // function eventually and do it all there.
711
clone_map()712 SafePointNode* GraphKit::clone_map() {
713 if (map() == NULL) return NULL;
714
715 // Clone the memory edge first
716 Node* mem = MergeMemNode::make(map()->memory());
717 gvn().set_type_bottom(mem);
718
719 SafePointNode *clonemap = (SafePointNode*)map()->clone();
720 JVMState* jvms = this->jvms();
721 JVMState* clonejvms = jvms->clone_shallow(C);
722 clonemap->set_memory(mem);
723 clonemap->set_jvms(clonejvms);
724 clonejvms->set_map(clonemap);
725 record_for_igvn(clonemap);
726 gvn().set_type_bottom(clonemap);
727 return clonemap;
728 }
729
730
731 //-----------------------------set_map_clone-----------------------------------
set_map_clone(SafePointNode * m)732 void GraphKit::set_map_clone(SafePointNode* m) {
733 _map = m;
734 _map = clone_map();
735 _map->set_next_exception(NULL);
736 debug_only(verify_map());
737 }
738
739
740 //----------------------------kill_dead_locals---------------------------------
741 // Detect any locals which are known to be dead, and force them to top.
kill_dead_locals()742 void GraphKit::kill_dead_locals() {
743 // Consult the liveness information for the locals. If any
744 // of them are unused, then they can be replaced by top(). This
745 // should help register allocation time and cut down on the size
746 // of the deoptimization information.
747
748 // This call is made from many of the bytecode handling
749 // subroutines called from the Big Switch in do_one_bytecode.
750 // Every bytecode which might include a slow path is responsible
751 // for killing its dead locals. The more consistent we
752 // are about killing deads, the fewer useless phis will be
753 // constructed for them at various merge points.
754
755 // bci can be -1 (InvocationEntryBci). We return the entry
756 // liveness for the method.
757
758 if (method() == NULL || method()->code_size() == 0) {
759 // We are building a graph for a call to a native method.
760 // All locals are live.
761 return;
762 }
763
764 ResourceMark rm;
765
766 // Consult the liveness information for the locals. If any
767 // of them are unused, then they can be replaced by top(). This
768 // should help register allocation time and cut down on the size
769 // of the deoptimization information.
770 MethodLivenessResult live_locals = method()->liveness_at_bci(bci());
771
772 int len = (int)live_locals.size();
773 assert(len <= jvms()->loc_size(), "too many live locals");
774 for (int local = 0; local < len; local++) {
775 if (!live_locals.at(local)) {
776 set_local(local, top());
777 }
778 }
779 }
780
781 #ifdef ASSERT
782 //-------------------------dead_locals_are_killed------------------------------
783 // Return true if all dead locals are set to top in the map.
784 // Used to assert "clean" debug info at various points.
dead_locals_are_killed()785 bool GraphKit::dead_locals_are_killed() {
786 if (method() == NULL || method()->code_size() == 0) {
787 // No locals need to be dead, so all is as it should be.
788 return true;
789 }
790
791 // Make sure somebody called kill_dead_locals upstream.
792 ResourceMark rm;
793 for (JVMState* jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
794 if (jvms->loc_size() == 0) continue; // no locals to consult
795 SafePointNode* map = jvms->map();
796 ciMethod* method = jvms->method();
797 int bci = jvms->bci();
798 if (jvms == this->jvms()) {
799 bci = this->bci(); // it might not yet be synched
800 }
801 MethodLivenessResult live_locals = method->liveness_at_bci(bci);
802 int len = (int)live_locals.size();
803 if (!live_locals.is_valid() || len == 0)
804 // This method is trivial, or is poisoned by a breakpoint.
805 return true;
806 assert(len == jvms->loc_size(), "live map consistent with locals map");
807 for (int local = 0; local < len; local++) {
808 if (!live_locals.at(local) && map->local(jvms, local) != top()) {
809 if (PrintMiscellaneous && (Verbose || WizardMode)) {
810 tty->print_cr("Zombie local %d: ", local);
811 jvms->dump();
812 }
813 return false;
814 }
815 }
816 }
817 return true;
818 }
819
820 #endif //ASSERT
821
822 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
should_reexecute_implied_by_bytecode(JVMState * jvms,bool is_anewarray)823 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
824 ciMethod* cur_method = jvms->method();
825 int cur_bci = jvms->bci();
826 if (cur_method != NULL && cur_bci != InvocationEntryBci) {
827 Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
828 return Interpreter::bytecode_should_reexecute(code) ||
829 (is_anewarray && code == Bytecodes::_multianewarray);
830 // Reexecute _multianewarray bytecode which was replaced with
831 // sequence of [a]newarray. See Parse::do_multianewarray().
832 //
833 // Note: interpreter should not have it set since this optimization
834 // is limited by dimensions and guarded by flag so in some cases
835 // multianewarray() runtime calls will be generated and
836 // the bytecode should not be reexecutes (stack will not be reset).
837 } else {
838 return false;
839 }
840 }
841
842 // Helper function for adding JVMState and debug information to node
add_safepoint_edges(SafePointNode * call,bool must_throw)843 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
844 // Add the safepoint edges to the call (or other safepoint).
845
846 // Make sure dead locals are set to top. This
847 // should help register allocation time and cut down on the size
848 // of the deoptimization information.
849 assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
850
851 // Walk the inline list to fill in the correct set of JVMState's
852 // Also fill in the associated edges for each JVMState.
853
854 // If the bytecode needs to be reexecuted we need to put
855 // the arguments back on the stack.
856 const bool should_reexecute = jvms()->should_reexecute();
857 JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
858
859 // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to
860 // undefined if the bci is different. This is normal for Parse but it
861 // should not happen for LibraryCallKit because only one bci is processed.
862 assert(!is_LibraryCallKit() || (jvms()->should_reexecute() == should_reexecute),
863 "in LibraryCallKit the reexecute bit should not change");
864
865 // If we are guaranteed to throw, we can prune everything but the
866 // input to the current bytecode.
867 bool can_prune_locals = false;
868 uint stack_slots_not_pruned = 0;
869 int inputs = 0, depth = 0;
870 if (must_throw) {
871 assert(method() == youngest_jvms->method(), "sanity");
872 if (compute_stack_effects(inputs, depth)) {
873 can_prune_locals = true;
874 stack_slots_not_pruned = inputs;
875 }
876 }
877
878 if (env()->should_retain_local_variables()) {
879 // At any safepoint, this method can get breakpointed, which would
880 // then require an immediate deoptimization.
881 can_prune_locals = false; // do not prune locals
882 stack_slots_not_pruned = 0;
883 }
884
885 // do not scribble on the input jvms
886 JVMState* out_jvms = youngest_jvms->clone_deep(C);
887 call->set_jvms(out_jvms); // Start jvms list for call node
888
889 // For a known set of bytecodes, the interpreter should reexecute them if
890 // deoptimization happens. We set the reexecute state for them here
891 if (out_jvms->is_reexecute_undefined() && //don't change if already specified
892 should_reexecute_implied_by_bytecode(out_jvms, call->is_AllocateArray())) {
893 #ifdef ASSERT
894 int inputs = 0, not_used; // initialized by GraphKit::compute_stack_effects()
895 assert(method() == youngest_jvms->method(), "sanity");
896 assert(compute_stack_effects(inputs, not_used), "unknown bytecode: %s", Bytecodes::name(java_bc()));
897 assert(out_jvms->sp() >= (uint)inputs, "not enough operands for reexecution");
898 #endif // ASSERT
899 out_jvms->set_should_reexecute(true); //NOTE: youngest_jvms not changed
900 }
901
902 // Presize the call:
903 DEBUG_ONLY(uint non_debug_edges = call->req());
904 call->add_req_batch(top(), youngest_jvms->debug_depth());
905 assert(call->req() == non_debug_edges + youngest_jvms->debug_depth(), "");
906
907 // Set up edges so that the call looks like this:
908 // Call [state:] ctl io mem fptr retadr
909 // [parms:] parm0 ... parmN
910 // [root:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
911 // [...mid:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN [...]
912 // [young:] loc0 ... locN stk0 ... stkSP mon0 obj0 ... monN objN
913 // Note that caller debug info precedes callee debug info.
914
915 // Fill pointer walks backwards from "young:" to "root:" in the diagram above:
916 uint debug_ptr = call->req();
917
918 // Loop over the map input edges associated with jvms, add them
919 // to the call node, & reset all offsets to match call node array.
920 for (JVMState* in_jvms = youngest_jvms; in_jvms != NULL; ) {
921 uint debug_end = debug_ptr;
922 uint debug_start = debug_ptr - in_jvms->debug_size();
923 debug_ptr = debug_start; // back up the ptr
924
925 uint p = debug_start; // walks forward in [debug_start, debug_end)
926 uint j, k, l;
927 SafePointNode* in_map = in_jvms->map();
928 out_jvms->set_map(call);
929
930 if (can_prune_locals) {
931 assert(in_jvms->method() == out_jvms->method(), "sanity");
932 // If the current throw can reach an exception handler in this JVMS,
933 // then we must keep everything live that can reach that handler.
934 // As a quick and dirty approximation, we look for any handlers at all.
935 if (in_jvms->method()->has_exception_handlers()) {
936 can_prune_locals = false;
937 }
938 }
939
940 // Add the Locals
941 k = in_jvms->locoff();
942 l = in_jvms->loc_size();
943 out_jvms->set_locoff(p);
944 if (!can_prune_locals) {
945 for (j = 0; j < l; j++)
946 call->set_req(p++, in_map->in(k+j));
947 } else {
948 p += l; // already set to top above by add_req_batch
949 }
950
951 // Add the Expression Stack
952 k = in_jvms->stkoff();
953 l = in_jvms->sp();
954 out_jvms->set_stkoff(p);
955 if (!can_prune_locals) {
956 for (j = 0; j < l; j++)
957 call->set_req(p++, in_map->in(k+j));
958 } else if (can_prune_locals && stack_slots_not_pruned != 0) {
959 // Divide stack into {S0,...,S1}, where S0 is set to top.
960 uint s1 = stack_slots_not_pruned;
961 stack_slots_not_pruned = 0; // for next iteration
962 if (s1 > l) s1 = l;
963 uint s0 = l - s1;
964 p += s0; // skip the tops preinstalled by add_req_batch
965 for (j = s0; j < l; j++)
966 call->set_req(p++, in_map->in(k+j));
967 } else {
968 p += l; // already set to top above by add_req_batch
969 }
970
971 // Add the Monitors
972 k = in_jvms->monoff();
973 l = in_jvms->mon_size();
974 out_jvms->set_monoff(p);
975 for (j = 0; j < l; j++)
976 call->set_req(p++, in_map->in(k+j));
977
978 // Copy any scalar object fields.
979 k = in_jvms->scloff();
980 l = in_jvms->scl_size();
981 out_jvms->set_scloff(p);
982 for (j = 0; j < l; j++)
983 call->set_req(p++, in_map->in(k+j));
984
985 // Finish the new jvms.
986 out_jvms->set_endoff(p);
987
988 assert(out_jvms->endoff() == debug_end, "fill ptr must match");
989 assert(out_jvms->depth() == in_jvms->depth(), "depth must match");
990 assert(out_jvms->loc_size() == in_jvms->loc_size(), "size must match");
991 assert(out_jvms->mon_size() == in_jvms->mon_size(), "size must match");
992 assert(out_jvms->scl_size() == in_jvms->scl_size(), "size must match");
993 assert(out_jvms->debug_size() == in_jvms->debug_size(), "size must match");
994
995 // Update the two tail pointers in parallel.
996 out_jvms = out_jvms->caller();
997 in_jvms = in_jvms->caller();
998 }
999
1000 assert(debug_ptr == non_debug_edges, "debug info must fit exactly");
1001
1002 // Test the correctness of JVMState::debug_xxx accessors:
1003 assert(call->jvms()->debug_start() == non_debug_edges, "");
1004 assert(call->jvms()->debug_end() == call->req(), "");
1005 assert(call->jvms()->debug_depth() == call->req() - non_debug_edges, "");
1006 }
1007
compute_stack_effects(int & inputs,int & depth)1008 bool GraphKit::compute_stack_effects(int& inputs, int& depth) {
1009 Bytecodes::Code code = java_bc();
1010 if (code == Bytecodes::_wide) {
1011 code = method()->java_code_at_bci(bci() + 1);
1012 }
1013
1014 BasicType rtype = T_ILLEGAL;
1015 int rsize = 0;
1016
1017 if (code != Bytecodes::_illegal) {
1018 depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1019 rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V
1020 if (rtype < T_CONFLICT)
1021 rsize = type2size[rtype];
1022 }
1023
1024 switch (code) {
1025 case Bytecodes::_illegal:
1026 return false;
1027
1028 case Bytecodes::_ldc:
1029 case Bytecodes::_ldc_w:
1030 case Bytecodes::_ldc2_w:
1031 inputs = 0;
1032 break;
1033
1034 case Bytecodes::_dup: inputs = 1; break;
1035 case Bytecodes::_dup_x1: inputs = 2; break;
1036 case Bytecodes::_dup_x2: inputs = 3; break;
1037 case Bytecodes::_dup2: inputs = 2; break;
1038 case Bytecodes::_dup2_x1: inputs = 3; break;
1039 case Bytecodes::_dup2_x2: inputs = 4; break;
1040 case Bytecodes::_swap: inputs = 2; break;
1041 case Bytecodes::_arraylength: inputs = 1; break;
1042
1043 case Bytecodes::_getstatic:
1044 case Bytecodes::_putstatic:
1045 case Bytecodes::_getfield:
1046 case Bytecodes::_putfield:
1047 {
1048 bool ignored_will_link;
1049 ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1050 int size = field->type()->size();
1051 bool is_get = (depth >= 0), is_static = (depth & 1);
1052 inputs = (is_static ? 0 : 1);
1053 if (is_get) {
1054 depth = size - inputs;
1055 } else {
1056 inputs += size; // putxxx pops the value from the stack
1057 depth = - inputs;
1058 }
1059 }
1060 break;
1061
1062 case Bytecodes::_invokevirtual:
1063 case Bytecodes::_invokespecial:
1064 case Bytecodes::_invokestatic:
1065 case Bytecodes::_invokedynamic:
1066 case Bytecodes::_invokeinterface:
1067 {
1068 bool ignored_will_link;
1069 ciSignature* declared_signature = NULL;
1070 ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1071 assert(declared_signature != NULL, "cannot be null");
1072 inputs = declared_signature->arg_size_for_bc(code);
1073 int size = declared_signature->return_type()->size();
1074 depth = size - inputs;
1075 }
1076 break;
1077
1078 case Bytecodes::_multianewarray:
1079 {
1080 ciBytecodeStream iter(method());
1081 iter.reset_to_bci(bci());
1082 iter.next();
1083 inputs = iter.get_dimensions();
1084 assert(rsize == 1, "");
1085 depth = rsize - inputs;
1086 }
1087 break;
1088
1089 case Bytecodes::_ireturn:
1090 case Bytecodes::_lreturn:
1091 case Bytecodes::_freturn:
1092 case Bytecodes::_dreturn:
1093 case Bytecodes::_areturn:
1094 assert(rsize == -depth, "");
1095 inputs = rsize;
1096 break;
1097
1098 case Bytecodes::_jsr:
1099 case Bytecodes::_jsr_w:
1100 inputs = 0;
1101 depth = 1; // S.B. depth=1, not zero
1102 break;
1103
1104 default:
1105 // bytecode produces a typed result
1106 inputs = rsize - depth;
1107 assert(inputs >= 0, "");
1108 break;
1109 }
1110
1111 #ifdef ASSERT
1112 // spot check
1113 int outputs = depth + inputs;
1114 assert(outputs >= 0, "sanity");
1115 switch (code) {
1116 case Bytecodes::_checkcast: assert(inputs == 1 && outputs == 1, ""); break;
1117 case Bytecodes::_athrow: assert(inputs == 1 && outputs == 0, ""); break;
1118 case Bytecodes::_aload_0: assert(inputs == 0 && outputs == 1, ""); break;
1119 case Bytecodes::_return: assert(inputs == 0 && outputs == 0, ""); break;
1120 case Bytecodes::_drem: assert(inputs == 4 && outputs == 2, ""); break;
1121 default: break;
1122 }
1123 #endif //ASSERT
1124
1125 return true;
1126 }
1127
1128
1129
1130 //------------------------------basic_plus_adr---------------------------------
basic_plus_adr(Node * base,Node * ptr,Node * offset)1131 Node* GraphKit::basic_plus_adr(Node* base, Node* ptr, Node* offset) {
1132 // short-circuit a common case
1133 if (offset == intcon(0)) return ptr;
1134 return _gvn.transform( new AddPNode(base, ptr, offset) );
1135 }
1136
ConvI2L(Node * offset)1137 Node* GraphKit::ConvI2L(Node* offset) {
1138 // short-circuit a common case
1139 jint offset_con = find_int_con(offset, Type::OffsetBot);
1140 if (offset_con != Type::OffsetBot) {
1141 return longcon((jlong) offset_con);
1142 }
1143 return _gvn.transform( new ConvI2LNode(offset));
1144 }
1145
ConvI2UL(Node * offset)1146 Node* GraphKit::ConvI2UL(Node* offset) {
1147 juint offset_con = (juint) find_int_con(offset, Type::OffsetBot);
1148 if (offset_con != (juint) Type::OffsetBot) {
1149 return longcon((julong) offset_con);
1150 }
1151 Node* conv = _gvn.transform( new ConvI2LNode(offset));
1152 Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1153 return _gvn.transform( new AndLNode(conv, mask) );
1154 }
1155
ConvL2I(Node * offset)1156 Node* GraphKit::ConvL2I(Node* offset) {
1157 // short-circuit a common case
1158 jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1159 if (offset_con != (jlong)Type::OffsetBot) {
1160 return intcon((int) offset_con);
1161 }
1162 return _gvn.transform( new ConvL2INode(offset));
1163 }
1164
1165 //-------------------------load_object_klass-----------------------------------
load_object_klass(Node * obj)1166 Node* GraphKit::load_object_klass(Node* obj) {
1167 // Special-case a fresh allocation to avoid building nodes:
1168 Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1169 if (akls != NULL) return akls;
1170 Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1171 return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1172 }
1173
1174 //-------------------------load_array_length-----------------------------------
load_array_length(Node * array)1175 Node* GraphKit::load_array_length(Node* array) {
1176 // Special-case a fresh allocation to avoid building nodes:
1177 AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1178 Node *alen;
1179 if (alloc == NULL) {
1180 Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1181 alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1182 } else {
1183 alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1184 }
1185 return alen;
1186 }
1187
array_ideal_length(AllocateArrayNode * alloc,const TypeOopPtr * oop_type,bool replace_length_in_map)1188 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1189 const TypeOopPtr* oop_type,
1190 bool replace_length_in_map) {
1191 Node* length = alloc->Ideal_length();
1192 if (replace_length_in_map == false || map()->find_edge(length) >= 0) {
1193 Node* ccast = alloc->make_ideal_length(oop_type, &_gvn);
1194 if (ccast != length) {
1195 // do not transfrom ccast here, it might convert to top node for
1196 // negative array length and break assumptions in parsing stage.
1197 _gvn.set_type_bottom(ccast);
1198 record_for_igvn(ccast);
1199 if (replace_length_in_map) {
1200 replace_in_map(length, ccast);
1201 }
1202 return ccast;
1203 }
1204 }
1205 return length;
1206 }
1207
1208 //------------------------------do_null_check----------------------------------
1209 // Helper function to do a NULL pointer check. Returned value is
1210 // the incoming address with NULL casted away. You are allowed to use the
1211 // not-null value only if you are control dependent on the test.
1212 #ifndef PRODUCT
1213 extern int explicit_null_checks_inserted,
1214 explicit_null_checks_elided;
1215 #endif
null_check_common(Node * value,BasicType type,bool assert_null,Node ** null_control,bool speculative)1216 Node* GraphKit::null_check_common(Node* value, BasicType type,
1217 // optional arguments for variations:
1218 bool assert_null,
1219 Node* *null_control,
1220 bool speculative) {
1221 assert(!assert_null || null_control == NULL, "not both at once");
1222 if (stopped()) return top();
1223 NOT_PRODUCT(explicit_null_checks_inserted++);
1224
1225 // Construct NULL check
1226 Node *chk = NULL;
1227 switch(type) {
1228 case T_LONG : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1229 case T_INT : chk = new CmpINode(value, _gvn.intcon(0)); break;
1230 case T_ARRAY : // fall through
1231 type = T_OBJECT; // simplify further tests
1232 case T_OBJECT : {
1233 const Type *t = _gvn.type( value );
1234
1235 const TypeOopPtr* tp = t->isa_oopptr();
1236 if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()
1237 // Only for do_null_check, not any of its siblings:
1238 && !assert_null && null_control == NULL) {
1239 // Usually, any field access or invocation on an unloaded oop type
1240 // will simply fail to link, since the statically linked class is
1241 // likely also to be unloaded. However, in -Xcomp mode, sometimes
1242 // the static class is loaded but the sharper oop type is not.
1243 // Rather than checking for this obscure case in lots of places,
1244 // we simply observe that a null check on an unloaded class
1245 // will always be followed by a nonsense operation, so we
1246 // can just issue the uncommon trap here.
1247 // Our access to the unloaded class will only be correct
1248 // after it has been loaded and initialized, which requires
1249 // a trip through the interpreter.
1250 #ifndef PRODUCT
1251 if (WizardMode) { tty->print("Null check of unloaded "); tp->klass()->print(); tty->cr(); }
1252 #endif
1253 uncommon_trap(Deoptimization::Reason_unloaded,
1254 Deoptimization::Action_reinterpret,
1255 tp->klass(), "!loaded");
1256 return top();
1257 }
1258
1259 if (assert_null) {
1260 // See if the type is contained in NULL_PTR.
1261 // If so, then the value is already null.
1262 if (t->higher_equal(TypePtr::NULL_PTR)) {
1263 NOT_PRODUCT(explicit_null_checks_elided++);
1264 return value; // Elided null assert quickly!
1265 }
1266 } else {
1267 // See if mixing in the NULL pointer changes type.
1268 // If so, then the NULL pointer was not allowed in the original
1269 // type. In other words, "value" was not-null.
1270 if (t->meet(TypePtr::NULL_PTR) != t->remove_speculative()) {
1271 // same as: if (!TypePtr::NULL_PTR->higher_equal(t)) ...
1272 NOT_PRODUCT(explicit_null_checks_elided++);
1273 return value; // Elided null check quickly!
1274 }
1275 }
1276 chk = new CmpPNode( value, null() );
1277 break;
1278 }
1279
1280 default:
1281 fatal("unexpected type: %s", type2name(type));
1282 }
1283 assert(chk != NULL, "sanity check");
1284 chk = _gvn.transform(chk);
1285
1286 BoolTest::mask btest = assert_null ? BoolTest::eq : BoolTest::ne;
1287 BoolNode *btst = new BoolNode( chk, btest);
1288 Node *tst = _gvn.transform( btst );
1289
1290 //-----------
1291 // if peephole optimizations occurred, a prior test existed.
1292 // If a prior test existed, maybe it dominates as we can avoid this test.
1293 if (tst != btst && type == T_OBJECT) {
1294 // At this point we want to scan up the CFG to see if we can
1295 // find an identical test (and so avoid this test altogether).
1296 Node *cfg = control();
1297 int depth = 0;
1298 while( depth < 16 ) { // Limit search depth for speed
1299 if( cfg->Opcode() == Op_IfTrue &&
1300 cfg->in(0)->in(1) == tst ) {
1301 // Found prior test. Use "cast_not_null" to construct an identical
1302 // CastPP (and hence hash to) as already exists for the prior test.
1303 // Return that casted value.
1304 if (assert_null) {
1305 replace_in_map(value, null());
1306 return null(); // do not issue the redundant test
1307 }
1308 Node *oldcontrol = control();
1309 set_control(cfg);
1310 Node *res = cast_not_null(value);
1311 set_control(oldcontrol);
1312 NOT_PRODUCT(explicit_null_checks_elided++);
1313 return res;
1314 }
1315 cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1316 if (cfg == NULL) break; // Quit at region nodes
1317 depth++;
1318 }
1319 }
1320
1321 //-----------
1322 // Branch to failure if null
1323 float ok_prob = PROB_MAX; // a priori estimate: nulls never happen
1324 Deoptimization::DeoptReason reason;
1325 if (assert_null) {
1326 reason = Deoptimization::reason_null_assert(speculative);
1327 } else if (type == T_OBJECT) {
1328 reason = Deoptimization::reason_null_check(speculative);
1329 } else {
1330 reason = Deoptimization::Reason_div0_check;
1331 }
1332 // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1333 // ciMethodData::has_trap_at will return a conservative -1 if any
1334 // must-be-null assertion has failed. This could cause performance
1335 // problems for a method after its first do_null_assert failure.
1336 // Consider using 'Reason_class_check' instead?
1337
1338 // To cause an implicit null check, we set the not-null probability
1339 // to the maximum (PROB_MAX). For an explicit check the probability
1340 // is set to a smaller value.
1341 if (null_control != NULL || too_many_traps(reason)) {
1342 // probability is less likely
1343 ok_prob = PROB_LIKELY_MAG(3);
1344 } else if (!assert_null &&
1345 (ImplicitNullCheckThreshold > 0) &&
1346 method() != NULL &&
1347 (method()->method_data()->trap_count(reason)
1348 >= (uint)ImplicitNullCheckThreshold)) {
1349 ok_prob = PROB_LIKELY_MAG(3);
1350 }
1351
1352 if (null_control != NULL) {
1353 IfNode* iff = create_and_map_if(control(), tst, ok_prob, COUNT_UNKNOWN);
1354 Node* null_true = _gvn.transform( new IfFalseNode(iff));
1355 set_control( _gvn.transform( new IfTrueNode(iff)));
1356 #ifndef PRODUCT
1357 if (null_true == top()) {
1358 explicit_null_checks_elided++;
1359 }
1360 #endif
1361 (*null_control) = null_true;
1362 } else {
1363 BuildCutout unless(this, tst, ok_prob);
1364 // Check for optimizer eliding test at parse time
1365 if (stopped()) {
1366 // Failure not possible; do not bother making uncommon trap.
1367 NOT_PRODUCT(explicit_null_checks_elided++);
1368 } else if (assert_null) {
1369 uncommon_trap(reason,
1370 Deoptimization::Action_make_not_entrant,
1371 NULL, "assert_null");
1372 } else {
1373 replace_in_map(value, zerocon(type));
1374 builtin_throw(reason);
1375 }
1376 }
1377
1378 // Must throw exception, fall-thru not possible?
1379 if (stopped()) {
1380 return top(); // No result
1381 }
1382
1383 if (assert_null) {
1384 // Cast obj to null on this path.
1385 replace_in_map(value, zerocon(type));
1386 return zerocon(type);
1387 }
1388
1389 // Cast obj to not-null on this path, if there is no null_control.
1390 // (If there is a null_control, a non-null value may come back to haunt us.)
1391 if (type == T_OBJECT) {
1392 Node* cast = cast_not_null(value, false);
1393 if (null_control == NULL || (*null_control) == top())
1394 replace_in_map(value, cast);
1395 value = cast;
1396 }
1397
1398 return value;
1399 }
1400
1401
1402 //------------------------------cast_not_null----------------------------------
1403 // Cast obj to not-null on this path
cast_not_null(Node * obj,bool do_replace_in_map)1404 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1405 const Type *t = _gvn.type(obj);
1406 const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1407 // Object is already not-null?
1408 if( t == t_not_null ) return obj;
1409
1410 Node *cast = new CastPPNode(obj,t_not_null);
1411 cast->init_req(0, control());
1412 cast = _gvn.transform( cast );
1413
1414 // Scan for instances of 'obj' in the current JVM mapping.
1415 // These instances are known to be not-null after the test.
1416 if (do_replace_in_map)
1417 replace_in_map(obj, cast);
1418
1419 return cast; // Return casted value
1420 }
1421
1422 // Sometimes in intrinsics, we implicitly know an object is not null
1423 // (there's no actual null check) so we can cast it to not null. In
1424 // the course of optimizations, the input to the cast can become null.
1425 // In that case that data path will die and we need the control path
1426 // to become dead as well to keep the graph consistent. So we have to
1427 // add a check for null for which one branch can't be taken. It uses
1428 // an Opaque4 node that will cause the check to be removed after loop
1429 // opts so the test goes away and the compiled code doesn't execute a
1430 // useless check.
must_be_not_null(Node * value,bool do_replace_in_map)1431 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1432 if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1433 return value;
1434 }
1435 Node* chk = _gvn.transform(new CmpPNode(value, null()));
1436 Node *tst = _gvn.transform(new BoolNode(chk, BoolTest::ne));
1437 Node* opaq = _gvn.transform(new Opaque4Node(C, tst, intcon(1)));
1438 IfNode *iff = new IfNode(control(), opaq, PROB_MAX, COUNT_UNKNOWN);
1439 _gvn.set_type(iff, iff->Value(&_gvn));
1440 Node *if_f = _gvn.transform(new IfFalseNode(iff));
1441 Node *frame = _gvn.transform(new ParmNode(C->start(), TypeFunc::FramePtr));
1442 Node* halt = _gvn.transform(new HaltNode(if_f, frame, "unexpected null in intrinsic"));
1443 C->root()->add_req(halt);
1444 Node *if_t = _gvn.transform(new IfTrueNode(iff));
1445 set_control(if_t);
1446 return cast_not_null(value, do_replace_in_map);
1447 }
1448
1449
1450 //--------------------------replace_in_map-------------------------------------
replace_in_map(Node * old,Node * neww)1451 void GraphKit::replace_in_map(Node* old, Node* neww) {
1452 if (old == neww) {
1453 return;
1454 }
1455
1456 map()->replace_edge(old, neww);
1457
1458 // Note: This operation potentially replaces any edge
1459 // on the map. This includes locals, stack, and monitors
1460 // of the current (innermost) JVM state.
1461
1462 // don't let inconsistent types from profiling escape this
1463 // method
1464
1465 const Type* told = _gvn.type(old);
1466 const Type* tnew = _gvn.type(neww);
1467
1468 if (!tnew->higher_equal(told)) {
1469 return;
1470 }
1471
1472 map()->record_replaced_node(old, neww);
1473 }
1474
1475
1476 //=============================================================================
1477 //--------------------------------memory---------------------------------------
memory(uint alias_idx)1478 Node* GraphKit::memory(uint alias_idx) {
1479 MergeMemNode* mem = merged_memory();
1480 Node* p = mem->memory_at(alias_idx);
1481 _gvn.set_type(p, Type::MEMORY); // must be mapped
1482 return p;
1483 }
1484
1485 //-----------------------------reset_memory------------------------------------
reset_memory()1486 Node* GraphKit::reset_memory() {
1487 Node* mem = map()->memory();
1488 // do not use this node for any more parsing!
1489 debug_only( map()->set_memory((Node*)NULL) );
1490 return _gvn.transform( mem );
1491 }
1492
1493 //------------------------------set_all_memory---------------------------------
set_all_memory(Node * newmem)1494 void GraphKit::set_all_memory(Node* newmem) {
1495 Node* mergemem = MergeMemNode::make(newmem);
1496 gvn().set_type_bottom(mergemem);
1497 map()->set_memory(mergemem);
1498 }
1499
1500 //------------------------------set_all_memory_call----------------------------
set_all_memory_call(Node * call,bool separate_io_proj)1501 void GraphKit::set_all_memory_call(Node* call, bool separate_io_proj) {
1502 Node* newmem = _gvn.transform( new ProjNode(call, TypeFunc::Memory, separate_io_proj) );
1503 set_all_memory(newmem);
1504 }
1505
1506 //=============================================================================
1507 //
1508 // parser factory methods for MemNodes
1509 //
1510 // These are layered on top of the factory methods in LoadNode and StoreNode,
1511 // and integrate with the parser's memory state and _gvn engine.
1512 //
1513
1514 // factory methods in "int adr_idx"
make_load(Node * ctl,Node * adr,const Type * t,BasicType bt,int adr_idx,MemNode::MemOrd mo,LoadNode::ControlDependency control_dependency,bool require_atomic_access,bool unaligned,bool mismatched,bool unsafe)1515 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1516 int adr_idx,
1517 MemNode::MemOrd mo,
1518 LoadNode::ControlDependency control_dependency,
1519 bool require_atomic_access,
1520 bool unaligned,
1521 bool mismatched,
1522 bool unsafe) {
1523 assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1524 const TypePtr* adr_type = NULL; // debug-mode-only argument
1525 debug_only(adr_type = C->get_adr_type(adr_idx));
1526 Node* mem = memory(adr_idx);
1527 Node* ld;
1528 if (require_atomic_access && bt == T_LONG) {
1529 ld = LoadLNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe);
1530 } else if (require_atomic_access && bt == T_DOUBLE) {
1531 ld = LoadDNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe);
1532 } else {
1533 ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, unaligned, mismatched, unsafe);
1534 }
1535 ld = _gvn.transform(ld);
1536 if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1537 // Improve graph before escape analysis and boxing elimination.
1538 record_for_igvn(ld);
1539 }
1540 return ld;
1541 }
1542
store_to_memory(Node * ctl,Node * adr,Node * val,BasicType bt,int adr_idx,MemNode::MemOrd mo,bool require_atomic_access,bool unaligned,bool mismatched,bool unsafe)1543 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1544 int adr_idx,
1545 MemNode::MemOrd mo,
1546 bool require_atomic_access,
1547 bool unaligned,
1548 bool mismatched,
1549 bool unsafe) {
1550 assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1551 const TypePtr* adr_type = NULL;
1552 debug_only(adr_type = C->get_adr_type(adr_idx));
1553 Node *mem = memory(adr_idx);
1554 Node* st;
1555 if (require_atomic_access && bt == T_LONG) {
1556 st = StoreLNode::make_atomic(ctl, mem, adr, adr_type, val, mo);
1557 } else if (require_atomic_access && bt == T_DOUBLE) {
1558 st = StoreDNode::make_atomic(ctl, mem, adr, adr_type, val, mo);
1559 } else {
1560 st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo);
1561 }
1562 if (unaligned) {
1563 st->as_Store()->set_unaligned_access();
1564 }
1565 if (mismatched) {
1566 st->as_Store()->set_mismatched_access();
1567 }
1568 if (unsafe) {
1569 st->as_Store()->set_unsafe_access();
1570 }
1571 st = _gvn.transform(st);
1572 set_memory(st, adr_idx);
1573 // Back-to-back stores can only remove intermediate store with DU info
1574 // so push on worklist for optimizer.
1575 if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1576 record_for_igvn(st);
1577
1578 return st;
1579 }
1580
access_store_at(Node * ctl,Node * obj,Node * adr,const TypePtr * adr_type,Node * val,const Type * val_type,BasicType bt,DecoratorSet decorators)1581 Node* GraphKit::access_store_at(Node* ctl,
1582 Node* obj,
1583 Node* adr,
1584 const TypePtr* adr_type,
1585 Node* val,
1586 const Type* val_type,
1587 BasicType bt,
1588 DecoratorSet decorators) {
1589 // Transformation of a value which could be NULL pointer (CastPP #NULL)
1590 // could be delayed during Parse (for example, in adjust_map_after_if()).
1591 // Execute transformation here to avoid barrier generation in such case.
1592 if (_gvn.type(val) == TypePtr::NULL_PTR) {
1593 val = _gvn.makecon(TypePtr::NULL_PTR);
1594 }
1595
1596 set_control(ctl);
1597 if (stopped()) {
1598 return top(); // Dead path ?
1599 }
1600
1601 assert(val != NULL, "not dead path");
1602
1603 C2AccessValuePtr addr(adr, adr_type);
1604 C2AccessValue value(val, val_type);
1605 C2Access access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1606 if (access.is_raw()) {
1607 return _barrier_set->BarrierSetC2::store_at(access, value);
1608 } else {
1609 return _barrier_set->store_at(access, value);
1610 }
1611 }
1612
access_load_at(Node * obj,Node * adr,const TypePtr * adr_type,const Type * val_type,BasicType bt,DecoratorSet decorators)1613 Node* GraphKit::access_load_at(Node* obj, // containing obj
1614 Node* adr, // actual adress to store val at
1615 const TypePtr* adr_type,
1616 const Type* val_type,
1617 BasicType bt,
1618 DecoratorSet decorators) {
1619 if (stopped()) {
1620 return top(); // Dead path ?
1621 }
1622
1623 C2AccessValuePtr addr(adr, adr_type);
1624 C2Access access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1625 if (access.is_raw()) {
1626 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1627 } else {
1628 return _barrier_set->load_at(access, val_type);
1629 }
1630 }
1631
access_load(Node * adr,const Type * val_type,BasicType bt,DecoratorSet decorators)1632 Node* GraphKit::access_load(Node* adr, // actual adress to load val at
1633 const Type* val_type,
1634 BasicType bt,
1635 DecoratorSet decorators) {
1636 if (stopped()) {
1637 return top(); // Dead path ?
1638 }
1639
1640 C2AccessValuePtr addr(adr, NULL);
1641 C2Access access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1642 if (access.is_raw()) {
1643 return _barrier_set->BarrierSetC2::load_at(access, val_type);
1644 } else {
1645 return _barrier_set->load_at(access, val_type);
1646 }
1647 }
1648
access_atomic_cmpxchg_val_at(Node * ctl,Node * obj,Node * adr,const TypePtr * adr_type,int alias_idx,Node * expected_val,Node * new_val,const Type * value_type,BasicType bt,DecoratorSet decorators)1649 Node* GraphKit::access_atomic_cmpxchg_val_at(Node* ctl,
1650 Node* obj,
1651 Node* adr,
1652 const TypePtr* adr_type,
1653 int alias_idx,
1654 Node* expected_val,
1655 Node* new_val,
1656 const Type* value_type,
1657 BasicType bt,
1658 DecoratorSet decorators) {
1659 set_control(ctl);
1660 C2AccessValuePtr addr(adr, adr_type);
1661 C2AtomicAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1662 bt, obj, addr, alias_idx);
1663 if (access.is_raw()) {
1664 return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1665 } else {
1666 return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1667 }
1668 }
1669
access_atomic_cmpxchg_bool_at(Node * ctl,Node * obj,Node * adr,const TypePtr * adr_type,int alias_idx,Node * expected_val,Node * new_val,const Type * value_type,BasicType bt,DecoratorSet decorators)1670 Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* ctl,
1671 Node* obj,
1672 Node* adr,
1673 const TypePtr* adr_type,
1674 int alias_idx,
1675 Node* expected_val,
1676 Node* new_val,
1677 const Type* value_type,
1678 BasicType bt,
1679 DecoratorSet decorators) {
1680 set_control(ctl);
1681 C2AccessValuePtr addr(adr, adr_type);
1682 C2AtomicAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1683 bt, obj, addr, alias_idx);
1684 if (access.is_raw()) {
1685 return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1686 } else {
1687 return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1688 }
1689 }
1690
access_atomic_xchg_at(Node * ctl,Node * obj,Node * adr,const TypePtr * adr_type,int alias_idx,Node * new_val,const Type * value_type,BasicType bt,DecoratorSet decorators)1691 Node* GraphKit::access_atomic_xchg_at(Node* ctl,
1692 Node* obj,
1693 Node* adr,
1694 const TypePtr* adr_type,
1695 int alias_idx,
1696 Node* new_val,
1697 const Type* value_type,
1698 BasicType bt,
1699 DecoratorSet decorators) {
1700 set_control(ctl);
1701 C2AccessValuePtr addr(adr, adr_type);
1702 C2AtomicAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1703 bt, obj, addr, alias_idx);
1704 if (access.is_raw()) {
1705 return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type);
1706 } else {
1707 return _barrier_set->atomic_xchg_at(access, new_val, value_type);
1708 }
1709 }
1710
access_atomic_add_at(Node * ctl,Node * obj,Node * adr,const TypePtr * adr_type,int alias_idx,Node * new_val,const Type * value_type,BasicType bt,DecoratorSet decorators)1711 Node* GraphKit::access_atomic_add_at(Node* ctl,
1712 Node* obj,
1713 Node* adr,
1714 const TypePtr* adr_type,
1715 int alias_idx,
1716 Node* new_val,
1717 const Type* value_type,
1718 BasicType bt,
1719 DecoratorSet decorators) {
1720 set_control(ctl);
1721 C2AccessValuePtr addr(adr, adr_type);
1722 C2AtomicAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1723 if (access.is_raw()) {
1724 return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1725 } else {
1726 return _barrier_set->atomic_add_at(access, new_val, value_type);
1727 }
1728 }
1729
access_clone(Node * ctl,Node * src,Node * dst,Node * size,bool is_array)1730 void GraphKit::access_clone(Node* ctl, Node* src, Node* dst, Node* size, bool is_array) {
1731 set_control(ctl);
1732 return _barrier_set->clone(this, src, dst, size, is_array);
1733 }
1734
1735 //-------------------------array_element_address-------------------------
array_element_address(Node * ary,Node * idx,BasicType elembt,const TypeInt * sizetype,Node * ctrl)1736 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1737 const TypeInt* sizetype, Node* ctrl) {
1738 uint shift = exact_log2(type2aelembytes(elembt));
1739 uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1740
1741 // short-circuit a common case (saves lots of confusing waste motion)
1742 jint idx_con = find_int_con(idx, -1);
1743 if (idx_con >= 0) {
1744 intptr_t offset = header + ((intptr_t)idx_con << shift);
1745 return basic_plus_adr(ary, offset);
1746 }
1747
1748 // must be correct type for alignment purposes
1749 Node* base = basic_plus_adr(ary, header);
1750 idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1751 Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1752 return basic_plus_adr(ary, base, scale);
1753 }
1754
1755 //-------------------------load_array_element-------------------------
load_array_element(Node * ctl,Node * ary,Node * idx,const TypeAryPtr * arytype)1756 Node* GraphKit::load_array_element(Node* ctl, Node* ary, Node* idx, const TypeAryPtr* arytype) {
1757 const Type* elemtype = arytype->elem();
1758 BasicType elembt = elemtype->array_element_basic_type();
1759 Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1760 if (elembt == T_NARROWOOP) {
1761 elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1762 }
1763 Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);
1764 return ld;
1765 }
1766
1767 //-------------------------set_arguments_for_java_call-------------------------
1768 // Arguments (pre-popped from the stack) are taken from the JVMS.
set_arguments_for_java_call(CallJavaNode * call)1769 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1770 // Add the call arguments:
1771 uint nargs = call->method()->arg_size();
1772 for (uint i = 0; i < nargs; i++) {
1773 Node* arg = argument(i);
1774 call->init_req(i + TypeFunc::Parms, arg);
1775 }
1776 }
1777
1778 //---------------------------set_edges_for_java_call---------------------------
1779 // Connect a newly created call into the current JVMS.
1780 // A return value node (if any) is returned from set_edges_for_java_call.
set_edges_for_java_call(CallJavaNode * call,bool must_throw,bool separate_io_proj)1781 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1782
1783 // Add the predefined inputs:
1784 call->init_req( TypeFunc::Control, control() );
1785 call->init_req( TypeFunc::I_O , i_o() );
1786 call->init_req( TypeFunc::Memory , reset_memory() );
1787 call->init_req( TypeFunc::FramePtr, frameptr() );
1788 call->init_req( TypeFunc::ReturnAdr, top() );
1789
1790 add_safepoint_edges(call, must_throw);
1791
1792 Node* xcall = _gvn.transform(call);
1793
1794 if (xcall == top()) {
1795 set_control(top());
1796 return;
1797 }
1798 assert(xcall == call, "call identity is stable");
1799
1800 // Re-use the current map to produce the result.
1801
1802 set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1803 set_i_o( _gvn.transform(new ProjNode(call, TypeFunc::I_O , separate_io_proj)));
1804 set_all_memory_call(xcall, separate_io_proj);
1805
1806 //return xcall; // no need, caller already has it
1807 }
1808
set_results_for_java_call(CallJavaNode * call,bool separate_io_proj,bool deoptimize)1809 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1810 if (stopped()) return top(); // maybe the call folded up?
1811
1812 // Capture the return value, if any.
1813 Node* ret;
1814 if (call->method() == NULL ||
1815 call->method()->return_type()->basic_type() == T_VOID)
1816 ret = top();
1817 else ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1818
1819 // Note: Since any out-of-line call can produce an exception,
1820 // we always insert an I_O projection from the call into the result.
1821
1822 make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1823
1824 if (separate_io_proj) {
1825 // The caller requested separate projections be used by the fall
1826 // through and exceptional paths, so replace the projections for
1827 // the fall through path.
1828 set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1829 set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1830 }
1831 return ret;
1832 }
1833
1834 //--------------------set_predefined_input_for_runtime_call--------------------
1835 // Reading and setting the memory state is way conservative here.
1836 // The real problem is that I am not doing real Type analysis on memory,
1837 // so I cannot distinguish card mark stores from other stores. Across a GC
1838 // point the Store Barrier and the card mark memory has to agree. I cannot
1839 // have a card mark store and its barrier split across the GC point from
1840 // either above or below. Here I get that to happen by reading ALL of memory.
1841 // A better answer would be to separate out card marks from other memory.
1842 // For now, return the input memory state, so that it can be reused
1843 // after the call, if this call has restricted memory effects.
set_predefined_input_for_runtime_call(SafePointNode * call,Node * narrow_mem)1844 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1845 // Set fixed predefined input arguments
1846 Node* memory = reset_memory();
1847 Node* m = narrow_mem == NULL ? memory : narrow_mem;
1848 call->init_req( TypeFunc::Control, control() );
1849 call->init_req( TypeFunc::I_O, top() ); // does no i/o
1850 call->init_req( TypeFunc::Memory, m ); // may gc ptrs
1851 call->init_req( TypeFunc::FramePtr, frameptr() );
1852 call->init_req( TypeFunc::ReturnAdr, top() );
1853 return memory;
1854 }
1855
1856 //-------------------set_predefined_output_for_runtime_call--------------------
1857 // Set control and memory (not i_o) from the call.
1858 // If keep_mem is not NULL, use it for the output state,
1859 // except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.
1860 // If hook_mem is NULL, this call produces no memory effects at all.
1861 // If hook_mem is a Java-visible memory slice (such as arraycopy operands),
1862 // then only that memory slice is taken from the call.
1863 // In the last case, we must put an appropriate memory barrier before
1864 // the call, so as to create the correct anti-dependencies on loads
1865 // preceding the call.
set_predefined_output_for_runtime_call(Node * call,Node * keep_mem,const TypePtr * hook_mem)1866 void GraphKit::set_predefined_output_for_runtime_call(Node* call,
1867 Node* keep_mem,
1868 const TypePtr* hook_mem) {
1869 // no i/o
1870 set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));
1871 if (keep_mem) {
1872 // First clone the existing memory state
1873 set_all_memory(keep_mem);
1874 if (hook_mem != NULL) {
1875 // Make memory for the call
1876 Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );
1877 // Set the RawPtr memory state only. This covers all the heap top/GC stuff
1878 // We also use hook_mem to extract specific effects from arraycopy stubs.
1879 set_memory(mem, hook_mem);
1880 }
1881 // ...else the call has NO memory effects.
1882
1883 // Make sure the call advertises its memory effects precisely.
1884 // This lets us build accurate anti-dependences in gcm.cpp.
1885 assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),
1886 "call node must be constructed correctly");
1887 } else {
1888 assert(hook_mem == NULL, "");
1889 // This is not a "slow path" call; all memory comes from the call.
1890 set_all_memory_call(call);
1891 }
1892 }
1893
1894
1895 // Replace the call with the current state of the kit.
replace_call(CallNode * call,Node * result,bool do_replaced_nodes)1896 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1897 JVMState* ejvms = NULL;
1898 if (has_exceptions()) {
1899 ejvms = transfer_exceptions_into_jvms();
1900 }
1901
1902 ReplacedNodes replaced_nodes = map()->replaced_nodes();
1903 ReplacedNodes replaced_nodes_exception;
1904 Node* ex_ctl = top();
1905
1906 SafePointNode* final_state = stop();
1907
1908 // Find all the needed outputs of this call
1909 CallProjections callprojs;
1910 call->extract_projections(&callprojs, true);
1911
1912 Node* init_mem = call->in(TypeFunc::Memory);
1913 Node* final_mem = final_state->in(TypeFunc::Memory);
1914 Node* final_ctl = final_state->in(TypeFunc::Control);
1915 Node* final_io = final_state->in(TypeFunc::I_O);
1916
1917 // Replace all the old call edges with the edges from the inlining result
1918 if (callprojs.fallthrough_catchproj != NULL) {
1919 C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1920 }
1921 if (callprojs.fallthrough_memproj != NULL) {
1922 if (final_mem->is_MergeMem()) {
1923 // Parser's exits MergeMem was not transformed but may be optimized
1924 final_mem = _gvn.transform(final_mem);
1925 }
1926 C->gvn_replace_by(callprojs.fallthrough_memproj, final_mem);
1927 }
1928 if (callprojs.fallthrough_ioproj != NULL) {
1929 C->gvn_replace_by(callprojs.fallthrough_ioproj, final_io);
1930 }
1931
1932 // Replace the result with the new result if it exists and is used
1933 if (callprojs.resproj != NULL && result != NULL) {
1934 C->gvn_replace_by(callprojs.resproj, result);
1935 }
1936
1937 if (ejvms == NULL) {
1938 // No exception edges to simply kill off those paths
1939 if (callprojs.catchall_catchproj != NULL) {
1940 C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1941 }
1942 if (callprojs.catchall_memproj != NULL) {
1943 C->gvn_replace_by(callprojs.catchall_memproj, C->top());
1944 }
1945 if (callprojs.catchall_ioproj != NULL) {
1946 C->gvn_replace_by(callprojs.catchall_ioproj, C->top());
1947 }
1948 // Replace the old exception object with top
1949 if (callprojs.exobj != NULL) {
1950 C->gvn_replace_by(callprojs.exobj, C->top());
1951 }
1952 } else {
1953 GraphKit ekit(ejvms);
1954
1955 // Load my combined exception state into the kit, with all phis transformed:
1956 SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1957 replaced_nodes_exception = ex_map->replaced_nodes();
1958
1959 Node* ex_oop = ekit.use_exception_state(ex_map);
1960
1961 if (callprojs.catchall_catchproj != NULL) {
1962 C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1963 ex_ctl = ekit.control();
1964 }
1965 if (callprojs.catchall_memproj != NULL) {
1966 C->gvn_replace_by(callprojs.catchall_memproj, ekit.reset_memory());
1967 }
1968 if (callprojs.catchall_ioproj != NULL) {
1969 C->gvn_replace_by(callprojs.catchall_ioproj, ekit.i_o());
1970 }
1971
1972 // Replace the old exception object with the newly created one
1973 if (callprojs.exobj != NULL) {
1974 C->gvn_replace_by(callprojs.exobj, ex_oop);
1975 }
1976 }
1977
1978 // Disconnect the call from the graph
1979 call->disconnect_inputs(NULL, C);
1980 C->gvn_replace_by(call, C->top());
1981
1982 // Clean up any MergeMems that feed other MergeMems since the
1983 // optimizer doesn't like that.
1984 if (final_mem->is_MergeMem()) {
1985 Node_List wl;
1986 for (SimpleDUIterator i(final_mem); i.has_next(); i.next()) {
1987 Node* m = i.get();
1988 if (m->is_MergeMem() && !wl.contains(m)) {
1989 wl.push(m);
1990 }
1991 }
1992 while (wl.size() > 0) {
1993 _gvn.transform(wl.pop());
1994 }
1995 }
1996
1997 if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
1998 replaced_nodes.apply(C, final_ctl);
1999 }
2000 if (!ex_ctl->is_top() && do_replaced_nodes) {
2001 replaced_nodes_exception.apply(C, ex_ctl);
2002 }
2003 }
2004
2005
2006 //------------------------------increment_counter------------------------------
2007 // for statistics: increment a VM counter by 1
2008
increment_counter(address counter_addr)2009 void GraphKit::increment_counter(address counter_addr) {
2010 Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2011 increment_counter(adr1);
2012 }
2013
increment_counter(Node * counter_addr)2014 void GraphKit::increment_counter(Node* counter_addr) {
2015 int adr_type = Compile::AliasIdxRaw;
2016 Node* ctrl = control();
2017 Node* cnt = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);
2018 Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2019 store_to_memory(ctrl, counter_addr, incr, T_LONG, adr_type, MemNode::unordered);
2020 }
2021
2022
2023 //------------------------------uncommon_trap----------------------------------
2024 // Bail out to the interpreter in mid-method. Implemented by calling the
2025 // uncommon_trap blob. This helper function inserts a runtime call with the
2026 // right debug info.
uncommon_trap(int trap_request,ciKlass * klass,const char * comment,bool must_throw,bool keep_exact_action)2027 void GraphKit::uncommon_trap(int trap_request,
2028 ciKlass* klass, const char* comment,
2029 bool must_throw,
2030 bool keep_exact_action) {
2031 if (failing()) stop();
2032 if (stopped()) return; // trap reachable?
2033
2034 // Note: If ProfileTraps is true, and if a deopt. actually
2035 // occurs here, the runtime will make sure an MDO exists. There is
2036 // no need to call method()->ensure_method_data() at this point.
2037
2038 // Set the stack pointer to the right value for reexecution:
2039 set_sp(reexecute_sp());
2040
2041 #ifdef ASSERT
2042 if (!must_throw) {
2043 // Make sure the stack has at least enough depth to execute
2044 // the current bytecode.
2045 int inputs, ignored_depth;
2046 if (compute_stack_effects(inputs, ignored_depth)) {
2047 assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d",
2048 Bytecodes::name(java_bc()), sp(), inputs);
2049 }
2050 }
2051 #endif
2052
2053 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
2054 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
2055
2056 switch (action) {
2057 case Deoptimization::Action_maybe_recompile:
2058 case Deoptimization::Action_reinterpret:
2059 // Temporary fix for 6529811 to allow virtual calls to be sure they
2060 // get the chance to go from mono->bi->mega
2061 if (!keep_exact_action &&
2062 Deoptimization::trap_request_index(trap_request) < 0 &&
2063 too_many_recompiles(reason)) {
2064 // This BCI is causing too many recompilations.
2065 if (C->log() != NULL) {
2066 C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",
2067 Deoptimization::trap_reason_name(reason),
2068 Deoptimization::trap_action_name(action));
2069 }
2070 action = Deoptimization::Action_none;
2071 trap_request = Deoptimization::make_trap_request(reason, action);
2072 } else {
2073 C->set_trap_can_recompile(true);
2074 }
2075 break;
2076 case Deoptimization::Action_make_not_entrant:
2077 C->set_trap_can_recompile(true);
2078 break;
2079 case Deoptimization::Action_none:
2080 case Deoptimization::Action_make_not_compilable:
2081 break;
2082 default:
2083 #ifdef ASSERT
2084 fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action));
2085 #endif
2086 break;
2087 }
2088
2089 if (TraceOptoParse) {
2090 char buf[100];
2091 tty->print_cr("Uncommon trap %s at bci:%d",
2092 Deoptimization::format_trap_request(buf, sizeof(buf),
2093 trap_request), bci());
2094 }
2095
2096 CompileLog* log = C->log();
2097 if (log != NULL) {
2098 int kid = (klass == NULL)? -1: log->identify(klass);
2099 log->begin_elem("uncommon_trap bci='%d'", bci());
2100 char buf[100];
2101 log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
2102 trap_request));
2103 if (kid >= 0) log->print(" klass='%d'", kid);
2104 if (comment != NULL) log->print(" comment='%s'", comment);
2105 log->end_elem();
2106 }
2107
2108 // Make sure any guarding test views this path as very unlikely
2109 Node *i0 = control()->in(0);
2110 if (i0 != NULL && i0->is_If()) { // Found a guarding if test?
2111 IfNode *iff = i0->as_If();
2112 float f = iff->_prob; // Get prob
2113 if (control()->Opcode() == Op_IfTrue) {
2114 if (f > PROB_UNLIKELY_MAG(4))
2115 iff->_prob = PROB_MIN;
2116 } else {
2117 if (f < PROB_LIKELY_MAG(4))
2118 iff->_prob = PROB_MAX;
2119 }
2120 }
2121
2122 // Clear out dead values from the debug info.
2123 kill_dead_locals();
2124
2125 // Now insert the uncommon trap subroutine call
2126 address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2127 const TypePtr* no_memory_effects = NULL;
2128 // Pass the index of the class to be loaded
2129 Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |
2130 (must_throw ? RC_MUST_THROW : 0),
2131 OptoRuntime::uncommon_trap_Type(),
2132 call_addr, "uncommon_trap", no_memory_effects,
2133 intcon(trap_request));
2134 assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,
2135 "must extract request correctly from the graph");
2136 assert(trap_request != 0, "zero value reserved by uncommon_trap_request");
2137
2138 call->set_req(TypeFunc::ReturnAdr, returnadr());
2139 // The debug info is the only real input to this call.
2140
2141 // Halt-and-catch fire here. The above call should never return!
2142 HaltNode* halt = new HaltNode(control(), frameptr(), "uncommon trap returned which should never happen"
2143 PRODUCT_ONLY(COMMA /*reachable*/false));
2144 _gvn.set_type_bottom(halt);
2145 root()->add_req(halt);
2146
2147 stop_and_kill_map();
2148 }
2149
2150
2151 //--------------------------just_allocated_object------------------------------
2152 // Report the object that was just allocated.
2153 // It must be the case that there are no intervening safepoints.
2154 // We use this to determine if an object is so "fresh" that
2155 // it does not require card marks.
just_allocated_object(Node * current_control)2156 Node* GraphKit::just_allocated_object(Node* current_control) {
2157 if (C->recent_alloc_ctl() == current_control)
2158 return C->recent_alloc_obj();
2159 return NULL;
2160 }
2161
2162
round_double_arguments(ciMethod * dest_method)2163 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2164 // (Note: TypeFunc::make has a cache that makes this fast.)
2165 const TypeFunc* tf = TypeFunc::make(dest_method);
2166 int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2167 for (int j = 0; j < nargs; j++) {
2168 const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2169 if( targ->basic_type() == T_DOUBLE ) {
2170 // If any parameters are doubles, they must be rounded before
2171 // the call, dstore_rounding does gvn.transform
2172 Node *arg = argument(j);
2173 arg = dstore_rounding(arg);
2174 set_argument(j, arg);
2175 }
2176 }
2177 }
2178
2179 /**
2180 * Record profiling data exact_kls for Node n with the type system so
2181 * that it can propagate it (speculation)
2182 *
2183 * @param n node that the type applies to
2184 * @param exact_kls type from profiling
2185 * @param maybe_null did profiling see null?
2186 *
2187 * @return node with improved type
2188 */
record_profile_for_speculation(Node * n,ciKlass * exact_kls,ProfilePtrKind ptr_kind)2189 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2190 const Type* current_type = _gvn.type(n);
2191 assert(UseTypeSpeculation, "type speculation must be on");
2192
2193 const TypePtr* speculative = current_type->speculative();
2194
2195 // Should the klass from the profile be recorded in the speculative type?
2196 if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2197 const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2198 const TypeOopPtr* xtype = tklass->as_instance_type();
2199 assert(xtype->klass_is_exact(), "Should be exact");
2200 // Any reason to believe n is not null (from this profiling or a previous one)?
2201 assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2202 const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2203 // record the new speculative type's depth
2204 speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2205 speculative = speculative->with_inline_depth(jvms()->depth());
2206 } else if (current_type->would_improve_ptr(ptr_kind)) {
2207 // Profiling report that null was never seen so we can change the
2208 // speculative type to non null ptr.
2209 if (ptr_kind == ProfileAlwaysNull) {
2210 speculative = TypePtr::NULL_PTR;
2211 } else {
2212 assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2213 const TypePtr* ptr = TypePtr::NOTNULL;
2214 if (speculative != NULL) {
2215 speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2216 } else {
2217 speculative = ptr;
2218 }
2219 }
2220 }
2221
2222 if (speculative != current_type->speculative()) {
2223 // Build a type with a speculative type (what we think we know
2224 // about the type but will need a guard when we use it)
2225 const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2226 // We're changing the type, we need a new CheckCast node to carry
2227 // the new type. The new type depends on the control: what
2228 // profiling tells us is only valid from here as far as we can
2229 // tell.
2230 Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2231 cast = _gvn.transform(cast);
2232 replace_in_map(n, cast);
2233 n = cast;
2234 }
2235
2236 return n;
2237 }
2238
2239 /**
2240 * Record profiling data from receiver profiling at an invoke with the
2241 * type system so that it can propagate it (speculation)
2242 *
2243 * @param n receiver node
2244 *
2245 * @return node with improved type
2246 */
record_profiled_receiver_for_speculation(Node * n)2247 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2248 if (!UseTypeSpeculation) {
2249 return n;
2250 }
2251 ciKlass* exact_kls = profile_has_unique_klass();
2252 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2253 if ((java_bc() == Bytecodes::_checkcast ||
2254 java_bc() == Bytecodes::_instanceof ||
2255 java_bc() == Bytecodes::_aastore) &&
2256 method()->method_data()->is_mature()) {
2257 ciProfileData* data = method()->method_data()->bci_to_data(bci());
2258 if (data != NULL) {
2259 if (!data->as_BitData()->null_seen()) {
2260 ptr_kind = ProfileNeverNull;
2261 } else {
2262 assert(data->is_ReceiverTypeData(), "bad profile data type");
2263 ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2264 uint i = 0;
2265 for (; i < call->row_limit(); i++) {
2266 ciKlass* receiver = call->receiver(i);
2267 if (receiver != NULL) {
2268 break;
2269 }
2270 }
2271 ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2272 }
2273 }
2274 }
2275 return record_profile_for_speculation(n, exact_kls, ptr_kind);
2276 }
2277
2278 /**
2279 * Record profiling data from argument profiling at an invoke with the
2280 * type system so that it can propagate it (speculation)
2281 *
2282 * @param dest_method target method for the call
2283 * @param bc what invoke bytecode is this?
2284 */
record_profiled_arguments_for_speculation(ciMethod * dest_method,Bytecodes::Code bc)2285 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2286 if (!UseTypeSpeculation) {
2287 return;
2288 }
2289 const TypeFunc* tf = TypeFunc::make(dest_method);
2290 int nargs = tf->domain()->cnt() - TypeFunc::Parms;
2291 int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2292 for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2293 const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2294 if (targ->basic_type() == T_OBJECT || targ->basic_type() == T_ARRAY) {
2295 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2296 ciKlass* better_type = NULL;
2297 if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2298 record_profile_for_speculation(argument(j), better_type, ptr_kind);
2299 }
2300 i++;
2301 }
2302 }
2303 }
2304
2305 /**
2306 * Record profiling data from parameter profiling at an invoke with
2307 * the type system so that it can propagate it (speculation)
2308 */
record_profiled_parameters_for_speculation()2309 void GraphKit::record_profiled_parameters_for_speculation() {
2310 if (!UseTypeSpeculation) {
2311 return;
2312 }
2313 for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2314 if (_gvn.type(local(i))->isa_oopptr()) {
2315 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2316 ciKlass* better_type = NULL;
2317 if (method()->parameter_profiled_type(j, better_type, ptr_kind)) {
2318 record_profile_for_speculation(local(i), better_type, ptr_kind);
2319 }
2320 j++;
2321 }
2322 }
2323 }
2324
2325 /**
2326 * Record profiling data from return value profiling at an invoke with
2327 * the type system so that it can propagate it (speculation)
2328 */
record_profiled_return_for_speculation()2329 void GraphKit::record_profiled_return_for_speculation() {
2330 if (!UseTypeSpeculation) {
2331 return;
2332 }
2333 ProfilePtrKind ptr_kind = ProfileMaybeNull;
2334 ciKlass* better_type = NULL;
2335 if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2336 // If profiling reports a single type for the return value,
2337 // feed it to the type system so it can propagate it as a
2338 // speculative type
2339 record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2340 }
2341 }
2342
round_double_result(ciMethod * dest_method)2343 void GraphKit::round_double_result(ciMethod* dest_method) {
2344 // A non-strict method may return a double value which has an extended
2345 // exponent, but this must not be visible in a caller which is 'strict'
2346 // If a strict caller invokes a non-strict callee, round a double result
2347
2348 BasicType result_type = dest_method->return_type()->basic_type();
2349 assert( method() != NULL, "must have caller context");
2350 if( result_type == T_DOUBLE && method()->is_strict() && !dest_method->is_strict() ) {
2351 // Destination method's return value is on top of stack
2352 // dstore_rounding() does gvn.transform
2353 Node *result = pop_pair();
2354 result = dstore_rounding(result);
2355 push_pair(result);
2356 }
2357 }
2358
2359 // rounding for strict float precision conformance
precision_rounding(Node * n)2360 Node* GraphKit::precision_rounding(Node* n) {
2361 return UseStrictFP && _method->flags().is_strict()
2362 && UseSSE == 0 && Matcher::strict_fp_requires_explicit_rounding
2363 ? _gvn.transform( new RoundFloatNode(0, n) )
2364 : n;
2365 }
2366
2367 // rounding for strict double precision conformance
dprecision_rounding(Node * n)2368 Node* GraphKit::dprecision_rounding(Node *n) {
2369 return UseStrictFP && _method->flags().is_strict()
2370 && UseSSE <= 1 && Matcher::strict_fp_requires_explicit_rounding
2371 ? _gvn.transform( new RoundDoubleNode(0, n) )
2372 : n;
2373 }
2374
2375 // rounding for non-strict double stores
dstore_rounding(Node * n)2376 Node* GraphKit::dstore_rounding(Node* n) {
2377 return Matcher::strict_fp_requires_explicit_rounding
2378 && UseSSE <= 1
2379 ? _gvn.transform( new RoundDoubleNode(0, n) )
2380 : n;
2381 }
2382
2383 //=============================================================================
2384 // Generate a fast path/slow path idiom. Graph looks like:
2385 // [foo] indicates that 'foo' is a parameter
2386 //
2387 // [in] NULL
2388 // \ /
2389 // CmpP
2390 // Bool ne
2391 // If
2392 // / \
2393 // True False-<2>
2394 // / |
2395 // / cast_not_null
2396 // Load | | ^
2397 // [fast_test] | |
2398 // gvn to opt_test | |
2399 // / \ | <1>
2400 // True False |
2401 // | \\ |
2402 // [slow_call] \[fast_result]
2403 // Ctl Val \ \
2404 // | \ \
2405 // Catch <1> \ \
2406 // / \ ^ \ \
2407 // Ex No_Ex | \ \
2408 // | \ \ | \ <2> \
2409 // ... \ [slow_res] | | \ [null_result]
2410 // \ \--+--+--- | |
2411 // \ | / \ | /
2412 // --------Region Phi
2413 //
2414 //=============================================================================
2415 // Code is structured as a series of driver functions all called 'do_XXX' that
2416 // call a set of helper functions. Helper functions first, then drivers.
2417
2418 //------------------------------null_check_oop---------------------------------
2419 // Null check oop. Set null-path control into Region in slot 3.
2420 // Make a cast-not-nullness use the other not-null control. Return cast.
null_check_oop(Node * value,Node ** null_control,bool never_see_null,bool safe_for_replace,bool speculative)2421 Node* GraphKit::null_check_oop(Node* value, Node* *null_control,
2422 bool never_see_null,
2423 bool safe_for_replace,
2424 bool speculative) {
2425 // Initial NULL check taken path
2426 (*null_control) = top();
2427 Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);
2428
2429 // Generate uncommon_trap:
2430 if (never_see_null && (*null_control) != top()) {
2431 // If we see an unexpected null at a check-cast we record it and force a
2432 // recompile; the offending check-cast will be compiled to handle NULLs.
2433 // If we see more than one offending BCI, then all checkcasts in the
2434 // method will be compiled to handle NULLs.
2435 PreserveJVMState pjvms(this);
2436 set_control(*null_control);
2437 replace_in_map(value, null());
2438 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);
2439 uncommon_trap(reason,
2440 Deoptimization::Action_make_not_entrant);
2441 (*null_control) = top(); // NULL path is dead
2442 }
2443 if ((*null_control) == top() && safe_for_replace) {
2444 replace_in_map(value, cast);
2445 }
2446
2447 // Cast away null-ness on the result
2448 return cast;
2449 }
2450
2451 //------------------------------opt_iff----------------------------------------
2452 // Optimize the fast-check IfNode. Set the fast-path region slot 2.
2453 // Return slow-path control.
opt_iff(Node * region,Node * iff)2454 Node* GraphKit::opt_iff(Node* region, Node* iff) {
2455 IfNode *opt_iff = _gvn.transform(iff)->as_If();
2456
2457 // Fast path taken; set region slot 2
2458 Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );
2459 region->init_req(2,fast_taken); // Capture fast-control
2460
2461 // Fast path not-taken, i.e. slow path
2462 Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );
2463 return slow_taken;
2464 }
2465
2466 //-----------------------------make_runtime_call-------------------------------
make_runtime_call(int flags,const TypeFunc * call_type,address call_addr,const char * call_name,const TypePtr * adr_type,Node * parm0,Node * parm1,Node * parm2,Node * parm3,Node * parm4,Node * parm5,Node * parm6,Node * parm7)2467 Node* GraphKit::make_runtime_call(int flags,
2468 const TypeFunc* call_type, address call_addr,
2469 const char* call_name,
2470 const TypePtr* adr_type,
2471 // The following parms are all optional.
2472 // The first NULL ends the list.
2473 Node* parm0, Node* parm1,
2474 Node* parm2, Node* parm3,
2475 Node* parm4, Node* parm5,
2476 Node* parm6, Node* parm7) {
2477 assert(call_addr != NULL, "must not call NULL targets");
2478
2479 // Slow-path call
2480 bool is_leaf = !(flags & RC_NO_LEAF);
2481 bool has_io = (!is_leaf && !(flags & RC_NO_IO));
2482 if (call_name == NULL) {
2483 assert(!is_leaf, "must supply name for leaf");
2484 call_name = OptoRuntime::stub_name(call_addr);
2485 }
2486 CallNode* call;
2487 if (!is_leaf) {
2488 call = new CallStaticJavaNode(call_type, call_addr, call_name,
2489 bci(), adr_type);
2490 } else if (flags & RC_NO_FP) {
2491 call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2492 } else {
2493 call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2494 }
2495
2496 // The following is similar to set_edges_for_java_call,
2497 // except that the memory effects of the call are restricted to AliasIdxRaw.
2498
2499 // Slow path call has no side-effects, uses few values
2500 bool wide_in = !(flags & RC_NARROW_MEM);
2501 bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2502
2503 Node* prev_mem = NULL;
2504 if (wide_in) {
2505 prev_mem = set_predefined_input_for_runtime_call(call);
2506 } else {
2507 assert(!wide_out, "narrow in => narrow out");
2508 Node* narrow_mem = memory(adr_type);
2509 prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2510 }
2511
2512 // Hook each parm in order. Stop looking at the first NULL.
2513 if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
2514 if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
2515 if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
2516 if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
2517 if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
2518 if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
2519 if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
2520 if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
2521 /* close each nested if ===> */ } } } } } } } }
2522 assert(call->in(call->req()-1) != NULL, "must initialize all parms");
2523
2524 if (!is_leaf) {
2525 // Non-leaves can block and take safepoints:
2526 add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2527 }
2528 // Non-leaves can throw exceptions:
2529 if (has_io) {
2530 call->set_req(TypeFunc::I_O, i_o());
2531 }
2532
2533 if (flags & RC_UNCOMMON) {
2534 // Set the count to a tiny probability. Cf. Estimate_Block_Frequency.
2535 // (An "if" probability corresponds roughly to an unconditional count.
2536 // Sort of.)
2537 call->set_cnt(PROB_UNLIKELY_MAG(4));
2538 }
2539
2540 Node* c = _gvn.transform(call);
2541 assert(c == call, "cannot disappear");
2542
2543 if (wide_out) {
2544 // Slow path call has full side-effects.
2545 set_predefined_output_for_runtime_call(call);
2546 } else {
2547 // Slow path call has few side-effects, and/or sets few values.
2548 set_predefined_output_for_runtime_call(call, prev_mem, adr_type);
2549 }
2550
2551 if (has_io) {
2552 set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2553 }
2554 return call;
2555
2556 }
2557
2558 //------------------------------merge_memory-----------------------------------
2559 // Merge memory from one path into the current memory state.
merge_memory(Node * new_mem,Node * region,int new_path)2560 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2561 for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2562 Node* old_slice = mms.force_memory();
2563 Node* new_slice = mms.memory2();
2564 if (old_slice != new_slice) {
2565 PhiNode* phi;
2566 if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2567 if (mms.is_empty()) {
2568 // clone base memory Phi's inputs for this memory slice
2569 assert(old_slice == mms.base_memory(), "sanity");
2570 phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2571 _gvn.set_type(phi, Type::MEMORY);
2572 for (uint i = 1; i < phi->req(); i++) {
2573 phi->init_req(i, old_slice->in(i));
2574 }
2575 } else {
2576 phi = old_slice->as_Phi(); // Phi was generated already
2577 }
2578 } else {
2579 phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));
2580 _gvn.set_type(phi, Type::MEMORY);
2581 }
2582 phi->set_req(new_path, new_slice);
2583 mms.set_memory(phi);
2584 }
2585 }
2586 }
2587
2588 //------------------------------make_slow_call_ex------------------------------
2589 // Make the exception handler hookups for the slow call
make_slow_call_ex(Node * call,ciInstanceKlass * ex_klass,bool separate_io_proj,bool deoptimize)2590 void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {
2591 if (stopped()) return;
2592
2593 // Make a catch node with just two handlers: fall-through and catch-all
2594 Node* i_o = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );
2595 Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );
2596 Node* norm = _gvn.transform( new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci) );
2597 Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index, CatchProjNode::no_handler_bci) );
2598
2599 { PreserveJVMState pjvms(this);
2600 set_control(excp);
2601 set_i_o(i_o);
2602
2603 if (excp != top()) {
2604 if (deoptimize) {
2605 // Deoptimize if an exception is caught. Don't construct exception state in this case.
2606 uncommon_trap(Deoptimization::Reason_unhandled,
2607 Deoptimization::Action_none);
2608 } else {
2609 // Create an exception state also.
2610 // Use an exact type if the caller has a specific exception.
2611 const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);
2612 Node* ex_oop = new CreateExNode(ex_type, control(), i_o);
2613 add_exception_state(make_exception_state(_gvn.transform(ex_oop)));
2614 }
2615 }
2616 }
2617
2618 // Get the no-exception control from the CatchNode.
2619 set_control(norm);
2620 }
2621
gen_subtype_check_compare(Node * ctrl,Node * in1,Node * in2,BoolTest::mask test,float p,PhaseGVN * gvn,BasicType bt)2622 static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN* gvn, BasicType bt) {
2623 Node* cmp = NULL;
2624 switch(bt) {
2625 case T_INT: cmp = new CmpINode(in1, in2); break;
2626 case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;
2627 default: fatal("unexpected comparison type %s", type2name(bt));
2628 }
2629 gvn->transform(cmp);
2630 Node* bol = gvn->transform(new BoolNode(cmp, test));
2631 IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);
2632 gvn->transform(iff);
2633 if (!bol->is_Con()) gvn->record_for_igvn(iff);
2634 return iff;
2635 }
2636
2637
2638 //-------------------------------gen_subtype_check-----------------------------
2639 // Generate a subtyping check. Takes as input the subtype and supertype.
2640 // Returns 2 values: sets the default control() to the true path and returns
2641 // the false path. Only reads invariant memory; sets no (visible) memory.
2642 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2643 // but that's not exposed to the optimizer. This call also doesn't take in an
2644 // Object; if you wish to check an Object you need to load the Object's class
2645 // prior to coming here.
gen_subtype_check(Node * subklass,Node * superklass,Node ** ctrl,MergeMemNode * mem,PhaseGVN * gvn)2646 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, MergeMemNode* mem, PhaseGVN* gvn) {
2647 Compile* C = gvn->C;
2648
2649 if ((*ctrl)->is_top()) {
2650 return C->top();
2651 }
2652
2653 // Fast check for identical types, perhaps identical constants.
2654 // The types can even be identical non-constants, in cases
2655 // involving Array.newInstance, Object.clone, etc.
2656 if (subklass == superklass)
2657 return C->top(); // false path is dead; no test needed.
2658
2659 if (gvn->type(superklass)->singleton()) {
2660 ciKlass* superk = gvn->type(superklass)->is_klassptr()->klass();
2661 ciKlass* subk = gvn->type(subklass)->is_klassptr()->klass();
2662
2663 // In the common case of an exact superklass, try to fold up the
2664 // test before generating code. You may ask, why not just generate
2665 // the code and then let it fold up? The answer is that the generated
2666 // code will necessarily include null checks, which do not always
2667 // completely fold away. If they are also needless, then they turn
2668 // into a performance loss. Example:
2669 // Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2670 // Here, the type of 'fa' is often exact, so the store check
2671 // of fa[1]=x will fold up, without testing the nullness of x.
2672 switch (C->static_subtype_check(superk, subk)) {
2673 case Compile::SSC_always_false:
2674 {
2675 Node* always_fail = *ctrl;
2676 *ctrl = gvn->C->top();
2677 return always_fail;
2678 }
2679 case Compile::SSC_always_true:
2680 return C->top();
2681 case Compile::SSC_easy_test:
2682 {
2683 // Just do a direct pointer compare and be done.
2684 IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2685 *ctrl = gvn->transform(new IfTrueNode(iff));
2686 return gvn->transform(new IfFalseNode(iff));
2687 }
2688 case Compile::SSC_full_test:
2689 break;
2690 default:
2691 ShouldNotReachHere();
2692 }
2693 }
2694
2695 // %%% Possible further optimization: Even if the superklass is not exact,
2696 // if the subklass is the unique subtype of the superklass, the check
2697 // will always succeed. We could leave a dependency behind to ensure this.
2698
2699 // First load the super-klass's check-offset
2700 Node *p1 = gvn->transform(new AddPNode(superklass, superklass, gvn->MakeConX(in_bytes(Klass::super_check_offset_offset()))));
2701 Node* m = mem->memory_at(C->get_alias_index(gvn->type(p1)->is_ptr()));
2702 Node *chk_off = gvn->transform(new LoadINode(NULL, m, p1, gvn->type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
2703 int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
2704 bool might_be_cache = (gvn->find_int_con(chk_off, cacheoff_con) == cacheoff_con);
2705
2706 // Load from the sub-klass's super-class display list, or a 1-word cache of
2707 // the secondary superclass list, or a failing value with a sentinel offset
2708 // if the super-klass is an interface or exceptionally deep in the Java
2709 // hierarchy and we have to scan the secondary superclass list the hard way.
2710 // Worst-case type is a little odd: NULL is allowed as a result (usually
2711 // klass loads can never produce a NULL).
2712 Node *chk_off_X = chk_off;
2713 #ifdef _LP64
2714 chk_off_X = gvn->transform(new ConvI2LNode(chk_off_X));
2715 #endif
2716 Node *p2 = gvn->transform(new AddPNode(subklass,subklass,chk_off_X));
2717 // For some types like interfaces the following loadKlass is from a 1-word
2718 // cache which is mutable so can't use immutable memory. Other
2719 // types load from the super-class display table which is immutable.
2720 m = mem->memory_at(C->get_alias_index(gvn->type(p2)->is_ptr()));
2721 Node *kmem = might_be_cache ? m : C->immutable_memory();
2722 Node *nkls = gvn->transform(LoadKlassNode::make(*gvn, NULL, kmem, p2, gvn->type(p2)->is_ptr(), TypeKlassPtr::OBJECT_OR_NULL));
2723
2724 // Compile speed common case: ARE a subtype and we canNOT fail
2725 if( superklass == nkls )
2726 return C->top(); // false path is dead; no test needed.
2727
2728 // See if we get an immediate positive hit. Happens roughly 83% of the
2729 // time. Test to see if the value loaded just previously from the subklass
2730 // is exactly the superklass.
2731 IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
2732 Node *iftrue1 = gvn->transform( new IfTrueNode (iff1));
2733 *ctrl = gvn->transform(new IfFalseNode(iff1));
2734
2735 // Compile speed common case: Check for being deterministic right now. If
2736 // chk_off is a constant and not equal to cacheoff then we are NOT a
2737 // subklass. In this case we need exactly the 1 test above and we can
2738 // return those results immediately.
2739 if (!might_be_cache) {
2740 Node* not_subtype_ctrl = *ctrl;
2741 *ctrl = iftrue1; // We need exactly the 1 test above
2742 return not_subtype_ctrl;
2743 }
2744
2745 // Gather the various success & failures here
2746 RegionNode *r_ok_subtype = new RegionNode(4);
2747 gvn->record_for_igvn(r_ok_subtype);
2748 RegionNode *r_not_subtype = new RegionNode(3);
2749 gvn->record_for_igvn(r_not_subtype);
2750
2751 r_ok_subtype->init_req(1, iftrue1);
2752
2753 // Check for immediate negative hit. Happens roughly 11% of the time (which
2754 // is roughly 63% of the remaining cases). Test to see if the loaded
2755 // check-offset points into the subklass display list or the 1-element
2756 // cache. If it points to the display (and NOT the cache) and the display
2757 // missed then it's not a subtype.
2758 Node *cacheoff = gvn->intcon(cacheoff_con);
2759 IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
2760 r_not_subtype->init_req(1, gvn->transform(new IfTrueNode (iff2)));
2761 *ctrl = gvn->transform(new IfFalseNode(iff2));
2762
2763 // Check for self. Very rare to get here, but it is taken 1/3 the time.
2764 // No performance impact (too rare) but allows sharing of secondary arrays
2765 // which has some footprint reduction.
2766 IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
2767 r_ok_subtype->init_req(2, gvn->transform(new IfTrueNode(iff3)));
2768 *ctrl = gvn->transform(new IfFalseNode(iff3));
2769
2770 // -- Roads not taken here: --
2771 // We could also have chosen to perform the self-check at the beginning
2772 // of this code sequence, as the assembler does. This would not pay off
2773 // the same way, since the optimizer, unlike the assembler, can perform
2774 // static type analysis to fold away many successful self-checks.
2775 // Non-foldable self checks work better here in second position, because
2776 // the initial primary superclass check subsumes a self-check for most
2777 // types. An exception would be a secondary type like array-of-interface,
2778 // which does not appear in its own primary supertype display.
2779 // Finally, we could have chosen to move the self-check into the
2780 // PartialSubtypeCheckNode, and from there out-of-line in a platform
2781 // dependent manner. But it is worthwhile to have the check here,
2782 // where it can be perhaps be optimized. The cost in code space is
2783 // small (register compare, branch).
2784
2785 // Now do a linear scan of the secondary super-klass array. Again, no real
2786 // performance impact (too rare) but it's gotta be done.
2787 // Since the code is rarely used, there is no penalty for moving it
2788 // out of line, and it can only improve I-cache density.
2789 // The decision to inline or out-of-line this final check is platform
2790 // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2791 Node* psc = gvn->transform(
2792 new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2793
2794 IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn->zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2795 r_not_subtype->init_req(2, gvn->transform(new IfTrueNode (iff4)));
2796 r_ok_subtype ->init_req(3, gvn->transform(new IfFalseNode(iff4)));
2797
2798 // Return false path; set default control to true path.
2799 *ctrl = gvn->transform(r_ok_subtype);
2800 return gvn->transform(r_not_subtype);
2801 }
2802
2803 // Profile-driven exact type check:
type_check_receiver(Node * receiver,ciKlass * klass,float prob,Node ** casted_receiver)2804 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2805 float prob,
2806 Node* *casted_receiver) {
2807 const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2808 Node* recv_klass = load_object_klass(receiver);
2809 Node* want_klass = makecon(tklass);
2810 Node* cmp = _gvn.transform( new CmpPNode(recv_klass, want_klass) );
2811 Node* bol = _gvn.transform( new BoolNode(cmp, BoolTest::eq) );
2812 IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2813 set_control( _gvn.transform( new IfTrueNode (iff) ));
2814 Node* fail = _gvn.transform( new IfFalseNode(iff) );
2815
2816 const TypeOopPtr* recv_xtype = tklass->as_instance_type();
2817 assert(recv_xtype->klass_is_exact(), "");
2818
2819 // Subsume downstream occurrences of receiver with a cast to
2820 // recv_xtype, since now we know what the type will be.
2821 Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
2822 (*casted_receiver) = _gvn.transform(cast);
2823 // (User must make the replace_in_map call.)
2824
2825 return fail;
2826 }
2827
2828
2829 //------------------------------seems_never_null-------------------------------
2830 // Use null_seen information if it is available from the profile.
2831 // If we see an unexpected null at a type check we record it and force a
2832 // recompile; the offending check will be recompiled to handle NULLs.
2833 // If we see several offending BCIs, then all checks in the
2834 // method will be recompiled.
seems_never_null(Node * obj,ciProfileData * data,bool & speculating)2835 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2836 speculating = !_gvn.type(obj)->speculative_maybe_null();
2837 Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2838 if (UncommonNullCast // Cutout for this technique
2839 && obj != null() // And not the -Xcomp stupid case?
2840 && !too_many_traps(reason)
2841 ) {
2842 if (speculating) {
2843 return true;
2844 }
2845 if (data == NULL)
2846 // Edge case: no mature data. Be optimistic here.
2847 return true;
2848 // If the profile has not seen a null, assume it won't happen.
2849 assert(java_bc() == Bytecodes::_checkcast ||
2850 java_bc() == Bytecodes::_instanceof ||
2851 java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
2852 return !data->as_BitData()->null_seen();
2853 }
2854 speculating = false;
2855 return false;
2856 }
2857
2858 //------------------------maybe_cast_profiled_receiver-------------------------
2859 // If the profile has seen exactly one type, narrow to exactly that type.
2860 // Subsequent type checks will always fold up.
maybe_cast_profiled_receiver(Node * not_null_obj,ciKlass * require_klass,ciKlass * spec_klass,bool safe_for_replace)2861 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
2862 ciKlass* require_klass,
2863 ciKlass* spec_klass,
2864 bool safe_for_replace) {
2865 if (!UseTypeProfile || !TypeProfileCasts) return NULL;
2866
2867 Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
2868
2869 // Make sure we haven't already deoptimized from this tactic.
2870 if (too_many_traps_or_recompiles(reason))
2871 return NULL;
2872
2873 // (No, this isn't a call, but it's enough like a virtual call
2874 // to use the same ciMethod accessor to get the profile info...)
2875 // If we have a speculative type use it instead of profiling (which
2876 // may not help us)
2877 ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;
2878 if (exact_kls != NULL) {// no cast failures here
2879 if (require_klass == NULL ||
2880 C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {
2881 // If we narrow the type to match what the type profile sees or
2882 // the speculative type, we can then remove the rest of the
2883 // cast.
2884 // This is a win, even if the exact_kls is very specific,
2885 // because downstream operations, such as method calls,
2886 // will often benefit from the sharper type.
2887 Node* exact_obj = not_null_obj; // will get updated in place...
2888 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
2889 &exact_obj);
2890 { PreserveJVMState pjvms(this);
2891 set_control(slow_ctl);
2892 uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
2893 }
2894 if (safe_for_replace) {
2895 replace_in_map(not_null_obj, exact_obj);
2896 }
2897 return exact_obj;
2898 }
2899 // assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.
2900 }
2901
2902 return NULL;
2903 }
2904
2905 /**
2906 * Cast obj to type and emit guard unless we had too many traps here
2907 * already
2908 *
2909 * @param obj node being casted
2910 * @param type type to cast the node to
2911 * @param not_null true if we know node cannot be null
2912 */
maybe_cast_profiled_obj(Node * obj,ciKlass * type,bool not_null)2913 Node* GraphKit::maybe_cast_profiled_obj(Node* obj,
2914 ciKlass* type,
2915 bool not_null) {
2916 if (stopped()) {
2917 return obj;
2918 }
2919
2920 // type == NULL if profiling tells us this object is always null
2921 if (type != NULL) {
2922 Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;
2923 Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;
2924
2925 if (!too_many_traps_or_recompiles(null_reason) &&
2926 !too_many_traps_or_recompiles(class_reason)) {
2927 Node* not_null_obj = NULL;
2928 // not_null is true if we know the object is not null and
2929 // there's no need for a null check
2930 if (!not_null) {
2931 Node* null_ctl = top();
2932 not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);
2933 assert(null_ctl->is_top(), "no null control here");
2934 } else {
2935 not_null_obj = obj;
2936 }
2937
2938 Node* exact_obj = not_null_obj;
2939 ciKlass* exact_kls = type;
2940 Node* slow_ctl = type_check_receiver(exact_obj, exact_kls, 1.0,
2941 &exact_obj);
2942 {
2943 PreserveJVMState pjvms(this);
2944 set_control(slow_ctl);
2945 uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);
2946 }
2947 replace_in_map(not_null_obj, exact_obj);
2948 obj = exact_obj;
2949 }
2950 } else {
2951 if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
2952 Node* exact_obj = null_assert(obj);
2953 replace_in_map(obj, exact_obj);
2954 obj = exact_obj;
2955 }
2956 }
2957 return obj;
2958 }
2959
2960 //-------------------------------gen_instanceof--------------------------------
2961 // Generate an instance-of idiom. Used by both the instance-of bytecode
2962 // and the reflective instance-of call.
gen_instanceof(Node * obj,Node * superklass,bool safe_for_replace)2963 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
2964 kill_dead_locals(); // Benefit all the uncommon traps
2965 assert( !stopped(), "dead parse path should be checked in callers" );
2966 assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
2967 "must check for not-null not-dead klass in callers");
2968
2969 // Make the merge point
2970 enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
2971 RegionNode* region = new RegionNode(PATH_LIMIT);
2972 Node* phi = new PhiNode(region, TypeInt::BOOL);
2973 C->set_has_split_ifs(true); // Has chance for split-if optimization
2974
2975 ciProfileData* data = NULL;
2976 if (java_bc() == Bytecodes::_instanceof) { // Only for the bytecode
2977 data = method()->method_data()->bci_to_data(bci());
2978 }
2979 bool speculative_not_null = false;
2980 bool never_see_null = (ProfileDynamicTypes // aggressive use of profile
2981 && seems_never_null(obj, data, speculative_not_null));
2982
2983 // Null check; get casted pointer; set region slot 3
2984 Node* null_ctl = top();
2985 Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
2986
2987 // If not_null_obj is dead, only null-path is taken
2988 if (stopped()) { // Doing instance-of on a NULL?
2989 set_control(null_ctl);
2990 return intcon(0);
2991 }
2992 region->init_req(_null_path, null_ctl);
2993 phi ->init_req(_null_path, intcon(0)); // Set null path value
2994 if (null_ctl == top()) {
2995 // Do this eagerly, so that pattern matches like is_diamond_phi
2996 // will work even during parsing.
2997 assert(_null_path == PATH_LIMIT-1, "delete last");
2998 region->del_req(_null_path);
2999 phi ->del_req(_null_path);
3000 }
3001
3002 // Do we know the type check always succeed?
3003 bool known_statically = false;
3004 if (_gvn.type(superklass)->singleton()) {
3005 ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();
3006 ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();
3007 if (subk != NULL && subk->is_loaded()) {
3008 int static_res = C->static_subtype_check(superk, subk);
3009 known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3010 }
3011 }
3012
3013 if (!known_statically) {
3014 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3015 // We may not have profiling here or it may not help us. If we
3016 // have a speculative type use it to perform an exact cast.
3017 ciKlass* spec_obj_type = obj_type->speculative_type();
3018 if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3019 Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3020 if (stopped()) { // Profile disagrees with this path.
3021 set_control(null_ctl); // Null is the only remaining possibility.
3022 return intcon(0);
3023 }
3024 if (cast_obj != NULL) {
3025 not_null_obj = cast_obj;
3026 }
3027 }
3028 }
3029
3030 // Load the object's klass
3031 Node* obj_klass = load_object_klass(not_null_obj);
3032
3033 // Generate the subtype check
3034 Node* not_subtype_ctrl = gen_subtype_check(obj_klass, superklass);
3035
3036 // Plug in the success path to the general merge in slot 1.
3037 region->init_req(_obj_path, control());
3038 phi ->init_req(_obj_path, intcon(1));
3039
3040 // Plug in the failing path to the general merge in slot 2.
3041 region->init_req(_fail_path, not_subtype_ctrl);
3042 phi ->init_req(_fail_path, intcon(0));
3043
3044 // Return final merged results
3045 set_control( _gvn.transform(region) );
3046 record_for_igvn(region);
3047
3048 // If we know the type check always succeeds then we don't use the
3049 // profiling data at this bytecode. Don't lose it, feed it to the
3050 // type system as a speculative type.
3051 if (safe_for_replace) {
3052 Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3053 replace_in_map(obj, casted_obj);
3054 }
3055
3056 return _gvn.transform(phi);
3057 }
3058
3059 //-------------------------------gen_checkcast---------------------------------
3060 // Generate a checkcast idiom. Used by both the checkcast bytecode and the
3061 // array store bytecode. Stack must be as-if BEFORE doing the bytecode so the
3062 // uncommon-trap paths work. Adjust stack after this call.
3063 // If failure_control is supplied and not null, it is filled in with
3064 // the control edge for the cast failure. Otherwise, an appropriate
3065 // uncommon trap or exception is thrown.
gen_checkcast(Node * obj,Node * superklass,Node ** failure_control)3066 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3067 Node* *failure_control) {
3068 kill_dead_locals(); // Benefit all the uncommon traps
3069 const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
3070 const Type *toop = TypeOopPtr::make_from_klass(tk->klass());
3071
3072 // Fast cutout: Check the case that the cast is vacuously true.
3073 // This detects the common cases where the test will short-circuit
3074 // away completely. We do this before we perform the null check,
3075 // because if the test is going to turn into zero code, we don't
3076 // want a residual null check left around. (Causes a slowdown,
3077 // for example, in some objArray manipulations, such as a[i]=a[j].)
3078 if (tk->singleton()) {
3079 const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3080 if (objtp != NULL && objtp->klass() != NULL) {
3081 switch (C->static_subtype_check(tk->klass(), objtp->klass())) {
3082 case Compile::SSC_always_true:
3083 // If we know the type check always succeed then we don't use
3084 // the profiling data at this bytecode. Don't lose it, feed it
3085 // to the type system as a speculative type.
3086 return record_profiled_receiver_for_speculation(obj);
3087 case Compile::SSC_always_false:
3088 // It needs a null check because a null will *pass* the cast check.
3089 // A non-null value will always produce an exception.
3090 if (!objtp->maybe_null()) {
3091 builtin_throw(Deoptimization::Reason_class_check, makecon(TypeKlassPtr::make(objtp->klass())));
3092 return top();
3093 } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3094 return null_assert(obj);
3095 }
3096 break; // Fall through to full check
3097 }
3098 }
3099 }
3100
3101 ciProfileData* data = NULL;
3102 bool safe_for_replace = false;
3103 if (failure_control == NULL) { // use MDO in regular case only
3104 assert(java_bc() == Bytecodes::_aastore ||
3105 java_bc() == Bytecodes::_checkcast,
3106 "interpreter profiles type checks only for these BCs");
3107 data = method()->method_data()->bci_to_data(bci());
3108 safe_for_replace = true;
3109 }
3110
3111 // Make the merge point
3112 enum { _obj_path = 1, _null_path, PATH_LIMIT };
3113 RegionNode* region = new RegionNode(PATH_LIMIT);
3114 Node* phi = new PhiNode(region, toop);
3115 C->set_has_split_ifs(true); // Has chance for split-if optimization
3116
3117 // Use null-cast information if it is available
3118 bool speculative_not_null = false;
3119 bool never_see_null = ((failure_control == NULL) // regular case only
3120 && seems_never_null(obj, data, speculative_not_null));
3121
3122 // Null check; get casted pointer; set region slot 3
3123 Node* null_ctl = top();
3124 Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3125
3126 // If not_null_obj is dead, only null-path is taken
3127 if (stopped()) { // Doing instance-of on a NULL?
3128 set_control(null_ctl);
3129 return null();
3130 }
3131 region->init_req(_null_path, null_ctl);
3132 phi ->init_req(_null_path, null()); // Set null path value
3133 if (null_ctl == top()) {
3134 // Do this eagerly, so that pattern matches like is_diamond_phi
3135 // will work even during parsing.
3136 assert(_null_path == PATH_LIMIT-1, "delete last");
3137 region->del_req(_null_path);
3138 phi ->del_req(_null_path);
3139 }
3140
3141 Node* cast_obj = NULL;
3142 if (tk->klass_is_exact()) {
3143 // The following optimization tries to statically cast the speculative type of the object
3144 // (for example obtained during profiling) to the type of the superklass and then do a
3145 // dynamic check that the type of the object is what we expect. To work correctly
3146 // for checkcast and aastore the type of superklass should be exact.
3147 const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3148 // We may not have profiling here or it may not help us. If we have
3149 // a speculative type use it to perform an exact cast.
3150 ciKlass* spec_obj_type = obj_type->speculative_type();
3151 if (spec_obj_type != NULL || data != NULL) {
3152 cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
3153 if (cast_obj != NULL) {
3154 if (failure_control != NULL) // failure is now impossible
3155 (*failure_control) = top();
3156 // adjust the type of the phi to the exact klass:
3157 phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3158 }
3159 }
3160 }
3161
3162 if (cast_obj == NULL) {
3163 // Load the object's klass
3164 Node* obj_klass = load_object_klass(not_null_obj);
3165
3166 // Generate the subtype check
3167 Node* not_subtype_ctrl = gen_subtype_check( obj_klass, superklass );
3168
3169 // Plug in success path into the merge
3170 cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3171 // Failure path ends in uncommon trap (or may be dead - failure impossible)
3172 if (failure_control == NULL) {
3173 if (not_subtype_ctrl != top()) { // If failure is possible
3174 PreserveJVMState pjvms(this);
3175 set_control(not_subtype_ctrl);
3176 builtin_throw(Deoptimization::Reason_class_check, obj_klass);
3177 }
3178 } else {
3179 (*failure_control) = not_subtype_ctrl;
3180 }
3181 }
3182
3183 region->init_req(_obj_path, control());
3184 phi ->init_req(_obj_path, cast_obj);
3185
3186 // A merge of NULL or Casted-NotNull obj
3187 Node* res = _gvn.transform(phi);
3188
3189 // Note I do NOT always 'replace_in_map(obj,result)' here.
3190 // if( tk->klass()->can_be_primary_super() )
3191 // This means that if I successfully store an Object into an array-of-String
3192 // I 'forget' that the Object is really now known to be a String. I have to
3193 // do this because we don't have true union types for interfaces - if I store
3194 // a Baz into an array-of-Interface and then tell the optimizer it's an
3195 // Interface, I forget that it's also a Baz and cannot do Baz-like field
3196 // references to it. FIX THIS WHEN UNION TYPES APPEAR!
3197 // replace_in_map( obj, res );
3198
3199 // Return final merged results
3200 set_control( _gvn.transform(region) );
3201 record_for_igvn(region);
3202
3203 return record_profiled_receiver_for_speculation(res);
3204 }
3205
3206 //------------------------------next_monitor-----------------------------------
3207 // What number should be given to the next monitor?
next_monitor()3208 int GraphKit::next_monitor() {
3209 int current = jvms()->monitor_depth()* C->sync_stack_slots();
3210 int next = current + C->sync_stack_slots();
3211 // Keep the toplevel high water mark current:
3212 if (C->fixed_slots() < next) C->set_fixed_slots(next);
3213 return current;
3214 }
3215
3216 //------------------------------insert_mem_bar---------------------------------
3217 // Memory barrier to avoid floating things around
3218 // The membar serves as a pinch point between both control and all memory slices.
insert_mem_bar(int opcode,Node * precedent)3219 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3220 MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3221 mb->init_req(TypeFunc::Control, control());
3222 mb->init_req(TypeFunc::Memory, reset_memory());
3223 Node* membar = _gvn.transform(mb);
3224 set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3225 set_all_memory_call(membar);
3226 return membar;
3227 }
3228
3229 //-------------------------insert_mem_bar_volatile----------------------------
3230 // Memory barrier to avoid floating things around
3231 // The membar serves as a pinch point between both control and memory(alias_idx).
3232 // If you want to make a pinch point on all memory slices, do not use this
3233 // function (even with AliasIdxBot); use insert_mem_bar() instead.
insert_mem_bar_volatile(int opcode,int alias_idx,Node * precedent)3234 Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {
3235 // When Parse::do_put_xxx updates a volatile field, it appends a series
3236 // of MemBarVolatile nodes, one for *each* volatile field alias category.
3237 // The first membar is on the same memory slice as the field store opcode.
3238 // This forces the membar to follow the store. (Bug 6500685 broke this.)
3239 // All the other membars (for other volatile slices, including AliasIdxBot,
3240 // which stands for all unknown volatile slices) are control-dependent
3241 // on the first membar. This prevents later volatile loads or stores
3242 // from sliding up past the just-emitted store.
3243
3244 MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);
3245 mb->set_req(TypeFunc::Control,control());
3246 if (alias_idx == Compile::AliasIdxBot) {
3247 mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());
3248 } else {
3249 assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");
3250 mb->set_req(TypeFunc::Memory, memory(alias_idx));
3251 }
3252 Node* membar = _gvn.transform(mb);
3253 set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3254 if (alias_idx == Compile::AliasIdxBot) {
3255 merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3256 } else {
3257 set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3258 }
3259 return membar;
3260 }
3261
3262 //------------------------------shared_lock------------------------------------
3263 // Emit locking code.
shared_lock(Node * obj)3264 FastLockNode* GraphKit::shared_lock(Node* obj) {
3265 // bci is either a monitorenter bc or InvocationEntryBci
3266 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3267 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3268
3269 if( !GenerateSynchronizationCode )
3270 return NULL; // Not locking things?
3271 if (stopped()) // Dead monitor?
3272 return NULL;
3273
3274 assert(dead_locals_are_killed(), "should kill locals before sync. point");
3275
3276 // Box the stack location
3277 Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3278 Node* mem = reset_memory();
3279
3280 FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3281 if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {
3282 // Create the counters for this fast lock.
3283 flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3284 }
3285
3286 // Create the rtm counters for this fast lock if needed.
3287 flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3288
3289 // Add monitor to debug info for the slow path. If we block inside the
3290 // slow path and de-opt, we need the monitor hanging around
3291 map()->push_monitor( flock );
3292
3293 const TypeFunc *tf = LockNode::lock_type();
3294 LockNode *lock = new LockNode(C, tf);
3295
3296 lock->init_req( TypeFunc::Control, control() );
3297 lock->init_req( TypeFunc::Memory , mem );
3298 lock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3299 lock->init_req( TypeFunc::FramePtr, frameptr() );
3300 lock->init_req( TypeFunc::ReturnAdr, top() );
3301
3302 lock->init_req(TypeFunc::Parms + 0, obj);
3303 lock->init_req(TypeFunc::Parms + 1, box);
3304 lock->init_req(TypeFunc::Parms + 2, flock);
3305 add_safepoint_edges(lock);
3306
3307 lock = _gvn.transform( lock )->as_Lock();
3308
3309 // lock has no side-effects, sets few values
3310 set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);
3311
3312 insert_mem_bar(Op_MemBarAcquireLock);
3313
3314 // Add this to the worklist so that the lock can be eliminated
3315 record_for_igvn(lock);
3316
3317 #ifndef PRODUCT
3318 if (PrintLockStatistics) {
3319 // Update the counter for this lock. Don't bother using an atomic
3320 // operation since we don't require absolute accuracy.
3321 lock->create_lock_counter(map()->jvms());
3322 increment_counter(lock->counter()->addr());
3323 }
3324 #endif
3325
3326 return flock;
3327 }
3328
3329
3330 //------------------------------shared_unlock----------------------------------
3331 // Emit unlocking code.
shared_unlock(Node * box,Node * obj)3332 void GraphKit::shared_unlock(Node* box, Node* obj) {
3333 // bci is either a monitorenter bc or InvocationEntryBci
3334 // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3335 assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3336
3337 if( !GenerateSynchronizationCode )
3338 return;
3339 if (stopped()) { // Dead monitor?
3340 map()->pop_monitor(); // Kill monitor from debug info
3341 return;
3342 }
3343
3344 // Memory barrier to avoid floating things down past the locked region
3345 insert_mem_bar(Op_MemBarReleaseLock);
3346
3347 const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3348 UnlockNode *unlock = new UnlockNode(C, tf);
3349 #ifdef ASSERT
3350 unlock->set_dbg_jvms(sync_jvms());
3351 #endif
3352 uint raw_idx = Compile::AliasIdxRaw;
3353 unlock->init_req( TypeFunc::Control, control() );
3354 unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3355 unlock->init_req( TypeFunc::I_O , top() ) ; // does no i/o
3356 unlock->init_req( TypeFunc::FramePtr, frameptr() );
3357 unlock->init_req( TypeFunc::ReturnAdr, top() );
3358
3359 unlock->init_req(TypeFunc::Parms + 0, obj);
3360 unlock->init_req(TypeFunc::Parms + 1, box);
3361 unlock = _gvn.transform(unlock)->as_Unlock();
3362
3363 Node* mem = reset_memory();
3364
3365 // unlock has no side-effects, sets few values
3366 set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3367
3368 // Kill monitor from debug info
3369 map()->pop_monitor( );
3370 }
3371
3372 //-------------------------------get_layout_helper-----------------------------
3373 // If the given klass is a constant or known to be an array,
3374 // fetch the constant layout helper value into constant_value
3375 // and return (Node*)NULL. Otherwise, load the non-constant
3376 // layout helper value, and return the node which represents it.
3377 // This two-faced routine is useful because allocation sites
3378 // almost always feature constant types.
get_layout_helper(Node * klass_node,jint & constant_value)3379 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3380 const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3381 if (!StressReflectiveCode && inst_klass != NULL) {
3382 ciKlass* klass = inst_klass->klass();
3383 bool xklass = inst_klass->klass_is_exact();
3384 if (xklass || klass->is_array_klass()) {
3385 jint lhelper = klass->layout_helper();
3386 if (lhelper != Klass::_lh_neutral_value) {
3387 constant_value = lhelper;
3388 return (Node*) NULL;
3389 }
3390 }
3391 }
3392 constant_value = Klass::_lh_neutral_value; // put in a known value
3393 Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3394 return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3395 }
3396
3397 // We just put in an allocate/initialize with a big raw-memory effect.
3398 // Hook selected additional alias categories on the initialization.
hook_memory_on_init(GraphKit & kit,int alias_idx,MergeMemNode * init_in_merge,Node * init_out_raw)3399 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3400 MergeMemNode* init_in_merge,
3401 Node* init_out_raw) {
3402 DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3403 assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3404
3405 Node* prevmem = kit.memory(alias_idx);
3406 init_in_merge->set_memory_at(alias_idx, prevmem);
3407 kit.set_memory(init_out_raw, alias_idx);
3408 }
3409
3410 //---------------------------set_output_for_allocation-------------------------
set_output_for_allocation(AllocateNode * alloc,const TypeOopPtr * oop_type,bool deoptimize_on_exception)3411 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3412 const TypeOopPtr* oop_type,
3413 bool deoptimize_on_exception) {
3414 int rawidx = Compile::AliasIdxRaw;
3415 alloc->set_req( TypeFunc::FramePtr, frameptr() );
3416 add_safepoint_edges(alloc);
3417 Node* allocx = _gvn.transform(alloc);
3418 set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3419 // create memory projection for i_o
3420 set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3421 make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3422
3423 // create a memory projection as for the normal control path
3424 Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3425 set_memory(malloc, rawidx);
3426
3427 // a normal slow-call doesn't change i_o, but an allocation does
3428 // we create a separate i_o projection for the normal control path
3429 set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3430 Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3431
3432 // put in an initialization barrier
3433 InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3434 rawoop)->as_Initialize();
3435 assert(alloc->initialization() == init, "2-way macro link must work");
3436 assert(init ->allocation() == alloc, "2-way macro link must work");
3437 {
3438 // Extract memory strands which may participate in the new object's
3439 // initialization, and source them from the new InitializeNode.
3440 // This will allow us to observe initializations when they occur,
3441 // and link them properly (as a group) to the InitializeNode.
3442 assert(init->in(InitializeNode::Memory) == malloc, "");
3443 MergeMemNode* minit_in = MergeMemNode::make(malloc);
3444 init->set_req(InitializeNode::Memory, minit_in);
3445 record_for_igvn(minit_in); // fold it up later, if possible
3446 Node* minit_out = memory(rawidx);
3447 assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3448 // Add an edge in the MergeMem for the header fields so an access
3449 // to one of those has correct memory state
3450 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3451 set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3452 if (oop_type->isa_aryptr()) {
3453 const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3454 int elemidx = C->get_alias_index(telemref);
3455 hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3456 } else if (oop_type->isa_instptr()) {
3457 ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();
3458 for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3459 ciField* field = ik->nonstatic_field_at(i);
3460 if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3461 continue; // do not bother to track really large numbers of fields
3462 // Find (or create) the alias category for this field:
3463 int fieldidx = C->alias_type(field)->index();
3464 hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3465 }
3466 }
3467 }
3468
3469 // Cast raw oop to the real thing...
3470 Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3471 javaoop = _gvn.transform(javaoop);
3472 C->set_recent_alloc(control(), javaoop);
3473 assert(just_allocated_object(control()) == javaoop, "just allocated");
3474
3475 #ifdef ASSERT
3476 { // Verify that the AllocateNode::Ideal_allocation recognizers work:
3477 assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,
3478 "Ideal_allocation works");
3479 assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,
3480 "Ideal_allocation works");
3481 if (alloc->is_AllocateArray()) {
3482 assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),
3483 "Ideal_allocation works");
3484 assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),
3485 "Ideal_allocation works");
3486 } else {
3487 assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3488 }
3489 }
3490 #endif //ASSERT
3491
3492 return javaoop;
3493 }
3494
3495 //---------------------------new_instance--------------------------------------
3496 // This routine takes a klass_node which may be constant (for a static type)
3497 // or may be non-constant (for reflective code). It will work equally well
3498 // for either, and the graph will fold nicely if the optimizer later reduces
3499 // the type to a constant.
3500 // The optional arguments are for specialized use by intrinsics:
3501 // - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3502 // - If 'return_size_val', report the the total object size to the caller.
3503 // - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
new_instance(Node * klass_node,Node * extra_slow_test,Node ** return_size_val,bool deoptimize_on_exception)3504 Node* GraphKit::new_instance(Node* klass_node,
3505 Node* extra_slow_test,
3506 Node* *return_size_val,
3507 bool deoptimize_on_exception) {
3508 // Compute size in doublewords
3509 // The size is always an integral number of doublewords, represented
3510 // as a positive bytewise size stored in the klass's layout_helper.
3511 // The layout_helper also encodes (in a low bit) the need for a slow path.
3512 jint layout_con = Klass::_lh_neutral_value;
3513 Node* layout_val = get_layout_helper(klass_node, layout_con);
3514 int layout_is_con = (layout_val == NULL);
3515
3516 if (extra_slow_test == NULL) extra_slow_test = intcon(0);
3517 // Generate the initial go-slow test. It's either ALWAYS (return a
3518 // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3519 // case) a computed value derived from the layout_helper.
3520 Node* initial_slow_test = NULL;
3521 if (layout_is_con) {
3522 assert(!StressReflectiveCode, "stress mode does not use these paths");
3523 bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3524 initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3525 } else { // reflective case
3526 // This reflective path is used by Unsafe.allocateInstance.
3527 // (It may be stress-tested by specifying StressReflectiveCode.)
3528 // Basically, we want to get into the VM is there's an illegal argument.
3529 Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3530 initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3531 if (extra_slow_test != intcon(0)) {
3532 initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3533 }
3534 // (Macro-expander will further convert this to a Bool, if necessary.)
3535 }
3536
3537 // Find the size in bytes. This is easy; it's the layout_helper.
3538 // The size value must be valid even if the slow path is taken.
3539 Node* size = NULL;
3540 if (layout_is_con) {
3541 size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));
3542 } else { // reflective case
3543 // This reflective path is used by clone and Unsafe.allocateInstance.
3544 size = ConvI2X(layout_val);
3545
3546 // Clear the low bits to extract layout_helper_size_in_bytes:
3547 assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3548 Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3549 size = _gvn.transform( new AndXNode(size, mask) );
3550 }
3551 if (return_size_val != NULL) {
3552 (*return_size_val) = size;
3553 }
3554
3555 // This is a precise notnull oop of the klass.
3556 // (Actually, it need not be precise if this is a reflective allocation.)
3557 // It's what we cast the result to.
3558 const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3559 if (!tklass) tklass = TypeKlassPtr::OBJECT;
3560 const TypeOopPtr* oop_type = tklass->as_instance_type();
3561
3562 // Now generate allocation code
3563
3564 // The entire memory state is needed for slow path of the allocation
3565 // since GC and deoptimization can happened.
3566 Node *mem = reset_memory();
3567 set_all_memory(mem); // Create new memory state
3568
3569 AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3570 control(), mem, i_o(),
3571 size, klass_node,
3572 initial_slow_test);
3573
3574 return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3575 }
3576
3577 //-------------------------------new_array-------------------------------------
3578 // helper for both newarray and anewarray
3579 // The 'length' parameter is (obviously) the length of the array.
3580 // See comments on new_instance for the meaning of the other arguments.
new_array(Node * klass_node,Node * length,int nargs,Node ** return_size_val,bool deoptimize_on_exception)3581 Node* GraphKit::new_array(Node* klass_node, // array klass (maybe variable)
3582 Node* length, // number of array elements
3583 int nargs, // number of arguments to push back for uncommon trap
3584 Node* *return_size_val,
3585 bool deoptimize_on_exception) {
3586 jint layout_con = Klass::_lh_neutral_value;
3587 Node* layout_val = get_layout_helper(klass_node, layout_con);
3588 int layout_is_con = (layout_val == NULL);
3589
3590 if (!layout_is_con && !StressReflectiveCode &&
3591 !too_many_traps(Deoptimization::Reason_class_check)) {
3592 // This is a reflective array creation site.
3593 // Optimistically assume that it is a subtype of Object[],
3594 // so that we can fold up all the address arithmetic.
3595 layout_con = Klass::array_layout_helper(T_OBJECT);
3596 Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3597 Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3598 { BuildCutout unless(this, bol_lh, PROB_MAX);
3599 inc_sp(nargs);
3600 uncommon_trap(Deoptimization::Reason_class_check,
3601 Deoptimization::Action_maybe_recompile);
3602 }
3603 layout_val = NULL;
3604 layout_is_con = true;
3605 }
3606
3607 // Generate the initial go-slow test. Make sure we do not overflow
3608 // if length is huge (near 2Gig) or negative! We do not need
3609 // exact double-words here, just a close approximation of needed
3610 // double-words. We can't add any offset or rounding bits, lest we
3611 // take a size -1 of bytes and make it positive. Use an unsigned
3612 // compare, so negative sizes look hugely positive.
3613 int fast_size_limit = FastAllocateSizeLimit;
3614 if (layout_is_con) {
3615 assert(!StressReflectiveCode, "stress mode does not use these paths");
3616 // Increase the size limit if we have exact knowledge of array type.
3617 int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3618 fast_size_limit <<= (LogBytesPerLong - log2_esize);
3619 }
3620
3621 Node* initial_slow_cmp = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3622 Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3623
3624 // --- Size Computation ---
3625 // array_size = round_to_heap(array_header + (length << elem_shift));
3626 // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3627 // and align_to(x, y) == ((x + y-1) & ~(y-1))
3628 // The rounding mask is strength-reduced, if possible.
3629 int round_mask = MinObjAlignmentInBytes - 1;
3630 Node* header_size = NULL;
3631 int header_size_min = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3632 // (T_BYTE has the weakest alignment and size restrictions...)
3633 if (layout_is_con) {
3634 int hsize = Klass::layout_helper_header_size(layout_con);
3635 int eshift = Klass::layout_helper_log2_element_size(layout_con);
3636 BasicType etype = Klass::layout_helper_element_type(layout_con);
3637 if ((round_mask & ~right_n_bits(eshift)) == 0)
3638 round_mask = 0; // strength-reduce it if it goes away completely
3639 assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3640 assert(header_size_min <= hsize, "generic minimum is smallest");
3641 header_size_min = hsize;
3642 header_size = intcon(hsize + round_mask);
3643 } else {
3644 Node* hss = intcon(Klass::_lh_header_size_shift);
3645 Node* hsm = intcon(Klass::_lh_header_size_mask);
3646 Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3647 hsize = _gvn.transform( new AndINode(hsize, hsm) );
3648 Node* mask = intcon(round_mask);
3649 header_size = _gvn.transform( new AddINode(hsize, mask) );
3650 }
3651
3652 Node* elem_shift = NULL;
3653 if (layout_is_con) {
3654 int eshift = Klass::layout_helper_log2_element_size(layout_con);
3655 if (eshift != 0)
3656 elem_shift = intcon(eshift);
3657 } else {
3658 // There is no need to mask or shift this value.
3659 // The semantics of LShiftINode include an implicit mask to 0x1F.
3660 assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
3661 elem_shift = layout_val;
3662 }
3663
3664 // Transition to native address size for all offset calculations:
3665 Node* lengthx = ConvI2X(length);
3666 Node* headerx = ConvI2X(header_size);
3667 #ifdef _LP64
3668 { const TypeInt* tilen = _gvn.find_int_type(length);
3669 if (tilen != NULL && tilen->_lo < 0) {
3670 // Add a manual constraint to a positive range. Cf. array_element_address.
3671 jint size_max = fast_size_limit;
3672 if (size_max > tilen->_hi) size_max = tilen->_hi;
3673 const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);
3674
3675 // Only do a narrow I2L conversion if the range check passed.
3676 IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
3677 _gvn.transform(iff);
3678 RegionNode* region = new RegionNode(3);
3679 _gvn.set_type(region, Type::CONTROL);
3680 lengthx = new PhiNode(region, TypeLong::LONG);
3681 _gvn.set_type(lengthx, TypeLong::LONG);
3682
3683 // Range check passed. Use ConvI2L node with narrow type.
3684 Node* passed = IfFalse(iff);
3685 region->init_req(1, passed);
3686 // Make I2L conversion control dependent to prevent it from
3687 // floating above the range check during loop optimizations.
3688 lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));
3689
3690 // Range check failed. Use ConvI2L with wide type because length may be invalid.
3691 region->init_req(2, IfTrue(iff));
3692 lengthx->init_req(2, ConvI2X(length));
3693
3694 set_control(region);
3695 record_for_igvn(region);
3696 record_for_igvn(lengthx);
3697 }
3698 }
3699 #endif
3700
3701 // Combine header size (plus rounding) and body size. Then round down.
3702 // This computation cannot overflow, because it is used only in two
3703 // places, one where the length is sharply limited, and the other
3704 // after a successful allocation.
3705 Node* abody = lengthx;
3706 if (elem_shift != NULL)
3707 abody = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3708 Node* size = _gvn.transform( new AddXNode(headerx, abody) );
3709 if (round_mask != 0) {
3710 Node* mask = MakeConX(~round_mask);
3711 size = _gvn.transform( new AndXNode(size, mask) );
3712 }
3713 // else if round_mask == 0, the size computation is self-rounding
3714
3715 if (return_size_val != NULL) {
3716 // This is the size
3717 (*return_size_val) = size;
3718 }
3719
3720 // Now generate allocation code
3721
3722 // The entire memory state is needed for slow path of the allocation
3723 // since GC and deoptimization can happened.
3724 Node *mem = reset_memory();
3725 set_all_memory(mem); // Create new memory state
3726
3727 if (initial_slow_test->is_Bool()) {
3728 // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3729 initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3730 }
3731
3732 // Create the AllocateArrayNode and its result projections
3733 AllocateArrayNode* alloc
3734 = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3735 control(), mem, i_o(),
3736 size, klass_node,
3737 initial_slow_test,
3738 length);
3739
3740 // Cast to correct type. Note that the klass_node may be constant or not,
3741 // and in the latter case the actual array type will be inexact also.
3742 // (This happens via a non-constant argument to inline_native_newArray.)
3743 // In any case, the value of klass_node provides the desired array type.
3744 const TypeInt* length_type = _gvn.find_int_type(length);
3745 const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3746 if (ary_type->isa_aryptr() && length_type != NULL) {
3747 // Try to get a better type than POS for the size
3748 ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3749 }
3750
3751 Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3752
3753 array_ideal_length(alloc, ary_type, true);
3754 return javaoop;
3755 }
3756
3757 // The following "Ideal_foo" functions are placed here because they recognize
3758 // the graph shapes created by the functions immediately above.
3759
3760 //---------------------------Ideal_allocation----------------------------------
3761 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
Ideal_allocation(Node * ptr,PhaseTransform * phase)3762 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
3763 if (ptr == NULL) { // reduce dumb test in callers
3764 return NULL;
3765 }
3766
3767 #if INCLUDE_SHENANDOAHGC
3768 if (UseShenandoahGC) {
3769 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
3770 ptr = bs->step_over_gc_barrier(ptr);
3771 }
3772 #endif
3773
3774 if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast
3775 ptr = ptr->in(1);
3776 if (ptr == NULL) return NULL;
3777 }
3778 // Return NULL for allocations with several casts:
3779 // j.l.reflect.Array.newInstance(jobject, jint)
3780 // Object.clone()
3781 // to keep more precise type from last cast.
3782 if (ptr->is_Proj()) {
3783 Node* allo = ptr->in(0);
3784 if (allo != NULL && allo->is_Allocate()) {
3785 return allo->as_Allocate();
3786 }
3787 }
3788 // Report failure to match.
3789 return NULL;
3790 }
3791
3792 // Fancy version which also strips off an offset (and reports it to caller).
Ideal_allocation(Node * ptr,PhaseTransform * phase,intptr_t & offset)3793 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,
3794 intptr_t& offset) {
3795 Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);
3796 if (base == NULL) return NULL;
3797 return Ideal_allocation(base, phase);
3798 }
3799
3800 // Trace Initialize <- Proj[Parm] <- Allocate
allocation()3801 AllocateNode* InitializeNode::allocation() {
3802 Node* rawoop = in(InitializeNode::RawAddress);
3803 if (rawoop->is_Proj()) {
3804 Node* alloc = rawoop->in(0);
3805 if (alloc->is_Allocate()) {
3806 return alloc->as_Allocate();
3807 }
3808 }
3809 return NULL;
3810 }
3811
3812 // Trace Allocate -> Proj[Parm] -> Initialize
initialization()3813 InitializeNode* AllocateNode::initialization() {
3814 ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);
3815 if (rawoop == NULL) return NULL;
3816 for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
3817 Node* init = rawoop->fast_out(i);
3818 if (init->is_Initialize()) {
3819 assert(init->as_Initialize()->allocation() == this, "2-way link");
3820 return init->as_Initialize();
3821 }
3822 }
3823 return NULL;
3824 }
3825
3826 //----------------------------- loop predicates ---------------------------
3827
3828 //------------------------------add_predicate_impl----------------------------
add_empty_predicate_impl(Deoptimization::DeoptReason reason,int nargs)3829 void GraphKit::add_empty_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {
3830 // Too many traps seen?
3831 if (too_many_traps(reason)) {
3832 #ifdef ASSERT
3833 if (TraceLoopPredicate) {
3834 int tc = C->trap_count(reason);
3835 tty->print("too many traps=%s tcount=%d in ",
3836 Deoptimization::trap_reason_name(reason), tc);
3837 method()->print(); // which method has too many predicate traps
3838 tty->cr();
3839 }
3840 #endif
3841 // We cannot afford to take more traps here,
3842 // do not generate predicate.
3843 return;
3844 }
3845
3846 Node *cont = _gvn.intcon(1);
3847 Node* opq = _gvn.transform(new Opaque1Node(C, cont));
3848 Node *bol = _gvn.transform(new Conv2BNode(opq));
3849 IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
3850 Node* iffalse = _gvn.transform(new IfFalseNode(iff));
3851 C->add_predicate_opaq(opq);
3852 {
3853 PreserveJVMState pjvms(this);
3854 set_control(iffalse);
3855 inc_sp(nargs);
3856 uncommon_trap(reason, Deoptimization::Action_maybe_recompile);
3857 }
3858 Node* iftrue = _gvn.transform(new IfTrueNode(iff));
3859 set_control(iftrue);
3860 }
3861
3862 //------------------------------add_predicate---------------------------------
add_empty_predicates(int nargs)3863 void GraphKit::add_empty_predicates(int nargs) {
3864 // These loop predicates remain empty. All concrete loop predicates are inserted above the corresponding
3865 // empty loop predicate later by 'PhaseIdealLoop::create_new_if_for_predicate'. All concrete loop predicates of
3866 // a specific kind (normal, profile or limit check) share the same uncommon trap as the empty loop predicate.
3867 if (UseLoopPredicate) {
3868 add_empty_predicate_impl(Deoptimization::Reason_predicate, nargs);
3869 }
3870 if (UseProfiledLoopPredicate) {
3871 add_empty_predicate_impl(Deoptimization::Reason_profile_predicate, nargs);
3872 }
3873 // loop's limit check predicate should be near the loop.
3874 add_empty_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);
3875 }
3876
sync_kit(IdealKit & ideal)3877 void GraphKit::sync_kit(IdealKit& ideal) {
3878 set_all_memory(ideal.merged_memory());
3879 set_i_o(ideal.i_o());
3880 set_control(ideal.ctrl());
3881 }
3882
final_sync(IdealKit & ideal)3883 void GraphKit::final_sync(IdealKit& ideal) {
3884 // Final sync IdealKit and graphKit.
3885 sync_kit(ideal);
3886 }
3887
load_String_length(Node * ctrl,Node * str)3888 Node* GraphKit::load_String_length(Node* ctrl, Node* str) {
3889 Node* len = load_array_length(load_String_value(ctrl, str));
3890 Node* coder = load_String_coder(ctrl, str);
3891 // Divide length by 2 if coder is UTF16
3892 return _gvn.transform(new RShiftINode(len, coder));
3893 }
3894
load_String_value(Node * ctrl,Node * str)3895 Node* GraphKit::load_String_value(Node* ctrl, Node* str) {
3896 int value_offset = java_lang_String::value_offset_in_bytes();
3897 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
3898 false, NULL, 0);
3899 const TypePtr* value_field_type = string_type->add_offset(value_offset);
3900 const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
3901 TypeAry::make(TypeInt::BYTE, TypeInt::POS),
3902 ciTypeArrayKlass::make(T_BYTE), true, 0);
3903 Node* p = basic_plus_adr(str, str, value_offset);
3904 Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
3905 IN_HEAP | C2_CONTROL_DEPENDENT_LOAD);
3906 // String.value field is known to be @Stable.
3907 if (UseImplicitStableValues) {
3908 load = cast_array_to_stable(load, value_type);
3909 }
3910 return load;
3911 }
3912
load_String_coder(Node * ctrl,Node * str)3913 Node* GraphKit::load_String_coder(Node* ctrl, Node* str) {
3914 if (!CompactStrings) {
3915 return intcon(java_lang_String::CODER_UTF16);
3916 }
3917 int coder_offset = java_lang_String::coder_offset_in_bytes();
3918 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
3919 false, NULL, 0);
3920 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
3921 int coder_field_idx = C->get_alias_index(coder_field_type);
3922 return make_load(ctrl, basic_plus_adr(str, str, coder_offset),
3923 TypeInt::BYTE, T_BYTE, coder_field_idx, MemNode::unordered);
3924 }
3925
store_String_value(Node * ctrl,Node * str,Node * value)3926 void GraphKit::store_String_value(Node* ctrl, Node* str, Node* value) {
3927 int value_offset = java_lang_String::value_offset_in_bytes();
3928 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
3929 false, NULL, 0);
3930 const TypePtr* value_field_type = string_type->add_offset(value_offset);
3931 access_store_at(ctrl, str, basic_plus_adr(str, value_offset), value_field_type,
3932 value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP);
3933 }
3934
store_String_coder(Node * ctrl,Node * str,Node * value)3935 void GraphKit::store_String_coder(Node* ctrl, Node* str, Node* value) {
3936 int coder_offset = java_lang_String::coder_offset_in_bytes();
3937 const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
3938 false, NULL, 0);
3939 const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
3940 int coder_field_idx = C->get_alias_index(coder_field_type);
3941 store_to_memory(ctrl, basic_plus_adr(str, coder_offset),
3942 value, T_BYTE, coder_field_idx, MemNode::unordered);
3943 }
3944
3945 // Capture src and dst memory state with a MergeMemNode
capture_memory(const TypePtr * src_type,const TypePtr * dst_type)3946 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
3947 if (src_type == dst_type) {
3948 // Types are equal, we don't need a MergeMemNode
3949 return memory(src_type);
3950 }
3951 MergeMemNode* merge = MergeMemNode::make(map()->memory());
3952 record_for_igvn(merge); // fold it up later, if possible
3953 int src_idx = C->get_alias_index(src_type);
3954 int dst_idx = C->get_alias_index(dst_type);
3955 merge->set_memory_at(src_idx, memory(src_idx));
3956 merge->set_memory_at(dst_idx, memory(dst_idx));
3957 return merge;
3958 }
3959
compress_string(Node * src,const TypeAryPtr * src_type,Node * dst,Node * count)3960 Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) {
3961 assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported");
3962 assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type");
3963 // If input and output memory types differ, capture both states to preserve
3964 // the dependency between preceding and subsequent loads/stores.
3965 // For example, the following program:
3966 // StoreB
3967 // compress_string
3968 // LoadB
3969 // has this memory graph (use->def):
3970 // LoadB -> compress_string -> CharMem
3971 // ... -> StoreB -> ByteMem
3972 // The intrinsic hides the dependency between LoadB and StoreB, causing
3973 // the load to read from memory not containing the result of the StoreB.
3974 // The correct memory graph should look like this:
3975 // LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem))
3976 Node* mem = capture_memory(src_type, TypeAryPtr::BYTES);
3977 StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count);
3978 Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str)));
3979 set_memory(res_mem, TypeAryPtr::BYTES);
3980 return str;
3981 }
3982
inflate_string(Node * src,Node * dst,const TypeAryPtr * dst_type,Node * count)3983 void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) {
3984 assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported");
3985 assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type");
3986 // Capture src and dst memory (see comment in 'compress_string').
3987 Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type);
3988 StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count);
3989 set_memory(_gvn.transform(str), dst_type);
3990 }
3991
inflate_string_slow(Node * src,Node * dst,Node * start,Node * count)3992 void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) {
3993 /**
3994 * int i_char = start;
3995 * for (int i_byte = 0; i_byte < count; i_byte++) {
3996 * dst[i_char++] = (char)(src[i_byte] & 0xff);
3997 * }
3998 */
3999 add_empty_predicates();
4000 C->set_has_loops(true);
4001
4002 RegionNode* head = new RegionNode(3);
4003 head->init_req(1, control());
4004 gvn().set_type(head, Type::CONTROL);
4005 record_for_igvn(head);
4006
4007 Node* i_byte = new PhiNode(head, TypeInt::INT);
4008 i_byte->init_req(1, intcon(0));
4009 gvn().set_type(i_byte, TypeInt::INT);
4010 record_for_igvn(i_byte);
4011
4012 Node* i_char = new PhiNode(head, TypeInt::INT);
4013 i_char->init_req(1, start);
4014 gvn().set_type(i_char, TypeInt::INT);
4015 record_for_igvn(i_char);
4016
4017 Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES);
4018 gvn().set_type(mem, Type::MEMORY);
4019 record_for_igvn(mem);
4020 set_control(head);
4021 set_memory(mem, TypeAryPtr::BYTES);
4022 Node* ch = load_array_element(control(), src, i_byte, TypeAryPtr::BYTES);
4023 Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE),
4024 AndI(ch, intcon(0xff)), T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,
4025 false, false, true /* mismatched */);
4026
4027 IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN);
4028 head->init_req(2, IfTrue(iff));
4029 mem->init_req(2, st);
4030 i_byte->init_req(2, AddI(i_byte, intcon(1)));
4031 i_char->init_req(2, AddI(i_char, intcon(2)));
4032
4033 set_control(IfFalse(iff));
4034 set_memory(st, TypeAryPtr::BYTES);
4035 }
4036
make_constant_from_field(ciField * field,Node * obj)4037 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4038 if (!field->is_constant()) {
4039 return NULL; // Field not marked as constant.
4040 }
4041 ciInstance* holder = NULL;
4042 if (!field->is_static()) {
4043 ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4044 if (const_oop != NULL && const_oop->is_instance()) {
4045 holder = const_oop->as_instance();
4046 }
4047 }
4048 const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4049 /*is_unsigned_load=*/false);
4050 if (con_type != NULL) {
4051 return makecon(con_type);
4052 }
4053 return NULL;
4054 }
4055
cast_array_to_stable(Node * ary,const TypeAryPtr * ary_type)4056 Node* GraphKit::cast_array_to_stable(Node* ary, const TypeAryPtr* ary_type) {
4057 // Reify the property as a CastPP node in Ideal graph to comply with monotonicity
4058 // assumption of CCP analysis.
4059 return _gvn.transform(new CastPPNode(ary, ary_type->cast_to_stable(true)));
4060 }
4061