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