< prev index next >

src/hotspot/share/opto/graphKit.cpp

Print this page

   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 "compiler/compileLog.hpp"
  29 #include "gc/shared/barrierSet.hpp"
  30 #include "gc/shared/c2/barrierSetC2.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "opto/addnode.hpp"
  34 #include "opto/castnode.hpp"
  35 #include "opto/convertnode.hpp"
  36 #include "opto/graphKit.hpp"
  37 #include "opto/idealKit.hpp"

  38 #include "opto/intrinsicnode.hpp"
  39 #include "opto/locknode.hpp"
  40 #include "opto/machnode.hpp"

  41 #include "opto/opaquenode.hpp"
  42 #include "opto/parse.hpp"
  43 #include "opto/rootnode.hpp"
  44 #include "opto/runtime.hpp"
  45 #include "opto/subtypenode.hpp"
  46 #include "runtime/deoptimization.hpp"
  47 #include "runtime/sharedRuntime.hpp"
  48 #include "utilities/bitMap.inline.hpp"
  49 #include "utilities/powerOfTwo.hpp"
  50 
  51 //----------------------------GraphKit-----------------------------------------
  52 // Main utility constructor.
  53 GraphKit::GraphKit(JVMState* jvms)
  54   : Phase(Phase::Parser),
  55     _env(C->env()),
  56     _gvn(*C->initial_gvn()),
  57     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  58 {

  59   _exceptions = jvms->map()->next_exception();
  60   if (_exceptions != NULL)  jvms->map()->set_next_exception(NULL);
  61   set_jvms(jvms);







  62 }
  63 
  64 // Private constructor for parser.
  65 GraphKit::GraphKit()
  66   : Phase(Phase::Parser),
  67     _env(C->env()),
  68     _gvn(*C->initial_gvn()),
  69     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  70 {
  71   _exceptions = NULL;
  72   set_map(NULL);
  73   debug_only(_sp = -99);
  74   debug_only(set_bci(-99));
  75 }
  76 
  77 
  78 
  79 //---------------------------clean_stack---------------------------------------
  80 // Clear away rubbish from the stack area of the JVM state.
  81 // This destroys any arguments that may be waiting on the stack.

 810           tty->print_cr("Zombie local %d: ", local);
 811           jvms->dump();
 812         }
 813         return false;
 814       }
 815     }
 816   }
 817   return true;
 818 }
 819 
 820 #endif //ASSERT
 821 
 822 // Helper function for enforcing certain bytecodes to reexecute if
 823 // deoptimization happens
 824 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 825   ciMethod* cur_method = jvms->method();
 826   int       cur_bci   = jvms->bci();
 827   if (cur_method != NULL && cur_bci != InvocationEntryBci) {
 828     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 829     return Interpreter::bytecode_should_reexecute(code) ||
 830            (is_anewarray && code == Bytecodes::_multianewarray);
 831     // Reexecute _multianewarray bytecode which was replaced with
 832     // sequence of [a]newarray. See Parse::do_multianewarray().
 833     //
 834     // Note: interpreter should not have it set since this optimization
 835     // is limited by dimensions and guarded by flag so in some cases
 836     // multianewarray() runtime calls will be generated and
 837     // the bytecode should not be reexecutes (stack will not be reset).
 838   } else
 839     return false;

 840 }
 841 
 842 // Helper function for adding JVMState and debug information to node
 843 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 844   // Add the safepoint edges to the call (or other safepoint).
 845 
 846   // Make sure dead locals are set to top.  This
 847   // should help register allocation time and cut down on the size
 848   // of the deoptimization information.
 849   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
 850 
 851   // Walk the inline list to fill in the correct set of JVMState's
 852   // Also fill in the associated edges for each JVMState.
 853 
 854   // If the bytecode needs to be reexecuted we need to put
 855   // the arguments back on the stack.
 856   const bool should_reexecute = jvms()->should_reexecute();
 857   JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
 858 
 859   // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to

1063       ciSignature* declared_signature = NULL;
1064       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1065       assert(declared_signature != NULL, "cannot be null");
1066       inputs   = declared_signature->arg_size_for_bc(code);
1067       int size = declared_signature->return_type()->size();
1068       depth = size - inputs;
1069     }
1070     break;
1071 
1072   case Bytecodes::_multianewarray:
1073     {
1074       ciBytecodeStream iter(method());
1075       iter.reset_to_bci(bci());
1076       iter.next();
1077       inputs = iter.get_dimensions();
1078       assert(rsize == 1, "");
1079       depth = rsize - inputs;
1080     }
1081     break;
1082 









1083   case Bytecodes::_ireturn:
1084   case Bytecodes::_lreturn:
1085   case Bytecodes::_freturn:
1086   case Bytecodes::_dreturn:
1087   case Bytecodes::_areturn:
1088     assert(rsize == -depth, "");
1089     inputs = rsize;
1090     break;
1091 
1092   case Bytecodes::_jsr:
1093   case Bytecodes::_jsr_w:
1094     inputs = 0;
1095     depth  = 1;                  // S.B. depth=1, not zero
1096     break;
1097 
1098   default:
1099     // bytecode produces a typed result
1100     inputs = rsize - depth;
1101     assert(inputs >= 0, "");
1102     break;

1145   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1146   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1147   return _gvn.transform( new AndLNode(conv, mask) );
1148 }
1149 
1150 Node* GraphKit::ConvL2I(Node* offset) {
1151   // short-circuit a common case
1152   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1153   if (offset_con != (jlong)Type::OffsetBot) {
1154     return intcon((int) offset_con);
1155   }
1156   return _gvn.transform( new ConvL2INode(offset));
1157 }
1158 
1159 //-------------------------load_object_klass-----------------------------------
1160 Node* GraphKit::load_object_klass(Node* obj) {
1161   // Special-case a fresh allocation to avoid building nodes:
1162   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1163   if (akls != NULL)  return akls;
1164   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1165   return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS));
1166 }
1167 
1168 //-------------------------load_array_length-----------------------------------
1169 Node* GraphKit::load_array_length(Node* array) {
1170   // Special-case a fresh allocation to avoid building nodes:
1171   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1172   Node *alen;
1173   if (alloc == NULL) {
1174     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1175     alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1176   } else {
1177     alen = alloc->Ideal_length();
1178     Node* ccast = alloc->make_ideal_length(_gvn.type(array)->is_oopptr(), &_gvn);
1179     if (ccast != alen) {
1180       alen = _gvn.transform(ccast);
1181     }
1182   }
1183   return alen;
1184 }
1185 

1188 // the incoming address with NULL casted away.  You are allowed to use the
1189 // not-null value only if you are control dependent on the test.
1190 #ifndef PRODUCT
1191 extern int explicit_null_checks_inserted,
1192            explicit_null_checks_elided;
1193 #endif
1194 Node* GraphKit::null_check_common(Node* value, BasicType type,
1195                                   // optional arguments for variations:
1196                                   bool assert_null,
1197                                   Node* *null_control,
1198                                   bool speculative) {
1199   assert(!assert_null || null_control == NULL, "not both at once");
1200   if (stopped())  return top();
1201   NOT_PRODUCT(explicit_null_checks_inserted++);
1202 
1203   // Construct NULL check
1204   Node *chk = NULL;
1205   switch(type) {
1206     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1207     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;

1208     case T_ARRAY  : // fall through
1209       type = T_OBJECT;  // simplify further tests
1210     case T_OBJECT : {
1211       const Type *t = _gvn.type( value );
1212 
1213       const TypeOopPtr* tp = t->isa_oopptr();
1214       if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()
1215           // Only for do_null_check, not any of its siblings:
1216           && !assert_null && null_control == NULL) {
1217         // Usually, any field access or invocation on an unloaded oop type
1218         // will simply fail to link, since the statically linked class is
1219         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1220         // the static class is loaded but the sharper oop type is not.
1221         // Rather than checking for this obscure case in lots of places,
1222         // we simply observe that a null check on an unloaded class
1223         // will always be followed by a nonsense operation, so we
1224         // can just issue the uncommon trap here.
1225         // Our access to the unloaded class will only be correct
1226         // after it has been loaded and initialized, which requires
1227         // a trip through the interpreter.

1359   }
1360 
1361   if (assert_null) {
1362     // Cast obj to null on this path.
1363     replace_in_map(value, zerocon(type));
1364     return zerocon(type);
1365   }
1366 
1367   // Cast obj to not-null on this path, if there is no null_control.
1368   // (If there is a null_control, a non-null value may come back to haunt us.)
1369   if (type == T_OBJECT) {
1370     Node* cast = cast_not_null(value, false);
1371     if (null_control == NULL || (*null_control) == top())
1372       replace_in_map(value, cast);
1373     value = cast;
1374   }
1375 
1376   return value;
1377 }
1378 
















1379 
1380 //------------------------------cast_not_null----------------------------------
1381 // Cast obj to not-null on this path
1382 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {



1383   const Type *t = _gvn.type(obj);
1384   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1385   // Object is already not-null?
1386   if( t == t_not_null ) return obj;
1387 
1388   Node *cast = new CastPPNode(obj,t_not_null);
1389   cast->init_req(0, control());
1390   cast = _gvn.transform( cast );
1391 





1392   // Scan for instances of 'obj' in the current JVM mapping.
1393   // These instances are known to be not-null after the test.
1394   if (do_replace_in_map)
1395     replace_in_map(obj, cast);
1396 
1397   return cast;                  // Return casted value
1398 }
1399 
1400 // Sometimes in intrinsics, we implicitly know an object is not null
1401 // (there's no actual null check) so we can cast it to not null. In
1402 // the course of optimizations, the input to the cast can become null.
1403 // In that case that data path will die and we need the control path
1404 // to become dead as well to keep the graph consistent. So we have to
1405 // add a check for null for which one branch can't be taken. It uses
1406 // an Opaque4 node that will cause the check to be removed after loop
1407 // opts so the test goes away and the compiled code doesn't execute a
1408 // useless check.
1409 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1410   if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1411     return value;

1495                           MemNode::MemOrd mo,
1496                           LoadNode::ControlDependency control_dependency,
1497                           bool require_atomic_access,
1498                           bool unaligned,
1499                           bool mismatched,
1500                           bool unsafe,
1501                           uint8_t barrier_data) {
1502   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1503   const TypePtr* adr_type = NULL; // debug-mode-only argument
1504   debug_only(adr_type = C->get_adr_type(adr_idx));
1505   Node* mem = memory(adr_idx);
1506   Node* ld;
1507   if (require_atomic_access && bt == T_LONG) {
1508     ld = LoadLNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1509   } else if (require_atomic_access && bt == T_DOUBLE) {
1510     ld = LoadDNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1511   } else {
1512     ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1513   }
1514   ld = _gvn.transform(ld);
1515   if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {

1516     // Improve graph before escape analysis and boxing elimination.
1517     record_for_igvn(ld);
1518   }
1519   return ld;
1520 }
1521 
1522 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1523                                 int adr_idx,
1524                                 MemNode::MemOrd mo,
1525                                 bool require_atomic_access,
1526                                 bool unaligned,
1527                                 bool mismatched,
1528                                 bool unsafe) {
1529   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1530   const TypePtr* adr_type = NULL;
1531   debug_only(adr_type = C->get_adr_type(adr_idx));
1532   Node *mem = memory(adr_idx);
1533   Node* st;
1534   if (require_atomic_access && bt == T_LONG) {
1535     st = StoreLNode::make_atomic(ctl, mem, adr, adr_type, val, mo);

1546   }
1547   if (unsafe) {
1548     st->as_Store()->set_unsafe_access();
1549   }
1550   st = _gvn.transform(st);
1551   set_memory(st, adr_idx);
1552   // Back-to-back stores can only remove intermediate store with DU info
1553   // so push on worklist for optimizer.
1554   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1555     record_for_igvn(st);
1556 
1557   return st;
1558 }
1559 
1560 Node* GraphKit::access_store_at(Node* obj,
1561                                 Node* adr,
1562                                 const TypePtr* adr_type,
1563                                 Node* val,
1564                                 const Type* val_type,
1565                                 BasicType bt,
1566                                 DecoratorSet decorators) {

1567   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1568   // could be delayed during Parse (for example, in adjust_map_after_if()).
1569   // Execute transformation here to avoid barrier generation in such case.
1570   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1571     val = _gvn.makecon(TypePtr::NULL_PTR);
1572   }
1573 
1574   if (stopped()) {
1575     return top(); // Dead path ?
1576   }
1577 
1578   assert(val != NULL, "not dead path");







1579 
1580   C2AccessValuePtr addr(adr, adr_type);
1581   C2AccessValue value(val, val_type);
1582   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1583   if (access.is_raw()) {
1584     return _barrier_set->BarrierSetC2::store_at(access, value);
1585   } else {
1586     return _barrier_set->store_at(access, value);
1587   }
1588 }
1589 
1590 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1591                                Node* adr,   // actual adress to store val at
1592                                const TypePtr* adr_type,
1593                                const Type* val_type,
1594                                BasicType bt,
1595                                DecoratorSet decorators) {

1596   if (stopped()) {
1597     return top(); // Dead path ?
1598   }
1599 
1600   C2AccessValuePtr addr(adr, adr_type);
1601   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1602   if (access.is_raw()) {
1603     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1604   } else {
1605     return _barrier_set->load_at(access, val_type);
1606   }
1607 }
1608 
1609 Node* GraphKit::access_load(Node* adr,   // actual adress to load val at
1610                             const Type* val_type,
1611                             BasicType bt,
1612                             DecoratorSet decorators) {
1613   if (stopped()) {
1614     return top(); // Dead path ?
1615   }
1616 
1617   C2AccessValuePtr addr(adr, NULL);
1618   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1619   if (access.is_raw()) {
1620     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1621   } else {

1679   }
1680 }
1681 
1682 Node* GraphKit::access_atomic_add_at(Node* obj,
1683                                      Node* adr,
1684                                      const TypePtr* adr_type,
1685                                      int alias_idx,
1686                                      Node* new_val,
1687                                      const Type* value_type,
1688                                      BasicType bt,
1689                                      DecoratorSet decorators) {
1690   C2AccessValuePtr addr(adr, adr_type);
1691   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1692   if (access.is_raw()) {
1693     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1694   } else {
1695     return _barrier_set->atomic_add_at(access, new_val, value_type);
1696   }
1697 }
1698 
1699 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1700   return _barrier_set->clone(this, src, dst, size, is_array);
1701 }
1702 
1703 //-------------------------array_element_address-------------------------
1704 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1705                                       const TypeInt* sizetype, Node* ctrl) {
1706   uint shift  = exact_log2(type2aelembytes(elembt));





1707   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1708 
1709   // short-circuit a common case (saves lots of confusing waste motion)
1710   jint idx_con = find_int_con(idx, -1);
1711   if (idx_con >= 0) {
1712     intptr_t offset = header + ((intptr_t)idx_con << shift);
1713     return basic_plus_adr(ary, offset);
1714   }
1715 
1716   // must be correct type for alignment purposes
1717   Node* base  = basic_plus_adr(ary, header);
1718   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1719   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1720   return basic_plus_adr(ary, base, scale);
1721 }
1722 
1723 //-------------------------load_array_element-------------------------
1724 Node* GraphKit::load_array_element(Node* ctl, Node* ary, Node* idx, const TypeAryPtr* arytype) {
1725   const Type* elemtype = arytype->elem();
1726   BasicType elembt = elemtype->array_element_basic_type();

1727   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1728   if (elembt == T_NARROWOOP) {
1729     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1730   }
1731   Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);
1732   return ld;
1733 }
1734 
1735 //-------------------------set_arguments_for_java_call-------------------------
1736 // Arguments (pre-popped from the stack) are taken from the JVMS.
1737 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1738   // Add the call arguments:
1739   uint nargs = call->method()->arg_size();
1740   for (uint i = 0; i < nargs; i++) {
1741     Node* arg = argument(i);
1742     call->init_req(i + TypeFunc::Parms, arg);


































1743   }
1744 }
1745 
1746 //---------------------------set_edges_for_java_call---------------------------
1747 // Connect a newly created call into the current JVMS.
1748 // A return value node (if any) is returned from set_edges_for_java_call.
1749 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1750 
1751   // Add the predefined inputs:
1752   call->init_req( TypeFunc::Control, control() );
1753   call->init_req( TypeFunc::I_O    , i_o() );
1754   call->init_req( TypeFunc::Memory , reset_memory() );
1755   call->init_req( TypeFunc::FramePtr, frameptr() );
1756   call->init_req( TypeFunc::ReturnAdr, top() );
1757 
1758   add_safepoint_edges(call, must_throw);
1759 
1760   Node* xcall = _gvn.transform(call);
1761 
1762   if (xcall == top()) {
1763     set_control(top());
1764     return;
1765   }
1766   assert(xcall == call, "call identity is stable");
1767 
1768   // Re-use the current map to produce the result.
1769 
1770   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1771   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1772   set_all_memory_call(xcall, separate_io_proj);
1773 
1774   //return xcall;   // no need, caller already has it
1775 }
1776 
1777 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1778   if (stopped())  return top();  // maybe the call folded up?
1779 
1780   // Capture the return value, if any.
1781   Node* ret;
1782   if (call->method() == NULL ||
1783       call->method()->return_type()->basic_type() == T_VOID)
1784         ret = top();
1785   else  ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1786 
1787   // Note:  Since any out-of-line call can produce an exception,
1788   // we always insert an I_O projection from the call into the result.
1789 
1790   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1791 
1792   if (separate_io_proj) {
1793     // The caller requested separate projections be used by the fall
1794     // through and exceptional paths, so replace the projections for
1795     // the fall through path.
1796     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1797     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1798   }



















1799   return ret;
1800 }
1801 
1802 //--------------------set_predefined_input_for_runtime_call--------------------
1803 // Reading and setting the memory state is way conservative here.
1804 // The real problem is that I am not doing real Type analysis on memory,
1805 // so I cannot distinguish card mark stores from other stores.  Across a GC
1806 // point the Store Barrier and the card mark memory has to agree.  I cannot
1807 // have a card mark store and its barrier split across the GC point from
1808 // either above or below.  Here I get that to happen by reading ALL of memory.
1809 // A better answer would be to separate out card marks from other memory.
1810 // For now, return the input memory state, so that it can be reused
1811 // after the call, if this call has restricted memory effects.
1812 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1813   // Set fixed predefined input arguments
1814   Node* memory = reset_memory();
1815   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1816   call->init_req( TypeFunc::Control,   control()  );
1817   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1818   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs

1869     if (use->is_MergeMem()) {
1870       wl.push(use);
1871     }
1872   }
1873 }
1874 
1875 // Replace the call with the current state of the kit.
1876 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1877   JVMState* ejvms = NULL;
1878   if (has_exceptions()) {
1879     ejvms = transfer_exceptions_into_jvms();
1880   }
1881 
1882   ReplacedNodes replaced_nodes = map()->replaced_nodes();
1883   ReplacedNodes replaced_nodes_exception;
1884   Node* ex_ctl = top();
1885 
1886   SafePointNode* final_state = stop();
1887 
1888   // Find all the needed outputs of this call
1889   CallProjections callprojs;
1890   call->extract_projections(&callprojs, true);
1891 
1892   Unique_Node_List wl;
1893   Node* init_mem = call->in(TypeFunc::Memory);
1894   Node* final_mem = final_state->in(TypeFunc::Memory);
1895   Node* final_ctl = final_state->in(TypeFunc::Control);
1896   Node* final_io = final_state->in(TypeFunc::I_O);
1897 
1898   // Replace all the old call edges with the edges from the inlining result
1899   if (callprojs.fallthrough_catchproj != NULL) {
1900     C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1901   }
1902   if (callprojs.fallthrough_memproj != NULL) {
1903     if (final_mem->is_MergeMem()) {
1904       // Parser's exits MergeMem was not transformed but may be optimized
1905       final_mem = _gvn.transform(final_mem);
1906     }
1907     C->gvn_replace_by(callprojs.fallthrough_memproj,   final_mem);
1908     add_mergemem_users_to_worklist(wl, final_mem);
1909   }
1910   if (callprojs.fallthrough_ioproj != NULL) {
1911     C->gvn_replace_by(callprojs.fallthrough_ioproj,    final_io);
1912   }
1913 
1914   // Replace the result with the new result if it exists and is used
1915   if (callprojs.resproj != NULL && result != NULL) {
1916     C->gvn_replace_by(callprojs.resproj, result);

1917   }
1918 
1919   if (ejvms == NULL) {
1920     // No exception edges to simply kill off those paths
1921     if (callprojs.catchall_catchproj != NULL) {
1922       C->gvn_replace_by(callprojs.catchall_catchproj, C->top());
1923     }
1924     if (callprojs.catchall_memproj != NULL) {
1925       C->gvn_replace_by(callprojs.catchall_memproj,   C->top());
1926     }
1927     if (callprojs.catchall_ioproj != NULL) {
1928       C->gvn_replace_by(callprojs.catchall_ioproj,    C->top());
1929     }
1930     // Replace the old exception object with top
1931     if (callprojs.exobj != NULL) {
1932       C->gvn_replace_by(callprojs.exobj, C->top());
1933     }
1934   } else {
1935     GraphKit ekit(ejvms);
1936 
1937     // Load my combined exception state into the kit, with all phis transformed:
1938     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
1939     replaced_nodes_exception = ex_map->replaced_nodes();
1940 
1941     Node* ex_oop = ekit.use_exception_state(ex_map);
1942 
1943     if (callprojs.catchall_catchproj != NULL) {
1944       C->gvn_replace_by(callprojs.catchall_catchproj, ekit.control());
1945       ex_ctl = ekit.control();
1946     }
1947     if (callprojs.catchall_memproj != NULL) {
1948       Node* ex_mem = ekit.reset_memory();
1949       C->gvn_replace_by(callprojs.catchall_memproj,   ex_mem);
1950       add_mergemem_users_to_worklist(wl, ex_mem);
1951     }
1952     if (callprojs.catchall_ioproj != NULL) {
1953       C->gvn_replace_by(callprojs.catchall_ioproj,    ekit.i_o());
1954     }
1955 
1956     // Replace the old exception object with the newly created one
1957     if (callprojs.exobj != NULL) {
1958       C->gvn_replace_by(callprojs.exobj, ex_oop);
1959     }
1960   }
1961 
1962   // Disconnect the call from the graph
1963   call->disconnect_inputs(NULL, C);
1964   C->gvn_replace_by(call, C->top());
1965 
1966   // Clean up any MergeMems that feed other MergeMems since the
1967   // optimizer doesn't like that.
1968   while (wl.size() > 0) {
1969     _gvn.transform(wl.pop());
1970   }
1971 
1972   if (callprojs.fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
1973     replaced_nodes.apply(C, final_ctl);
1974   }
1975   if (!ex_ctl->is_top() && do_replaced_nodes) {
1976     replaced_nodes_exception.apply(C, ex_ctl);
1977   }
1978 }
1979 
1980 
1981 //------------------------------increment_counter------------------------------
1982 // for statistics: increment a VM counter by 1
1983 
1984 void GraphKit::increment_counter(address counter_addr) {
1985   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
1986   increment_counter(adr1);
1987 }
1988 
1989 void GraphKit::increment_counter(Node* counter_addr) {
1990   int adr_type = Compile::AliasIdxRaw;
1991   Node* ctrl = control();
1992   Node* cnt  = make_load(ctrl, counter_addr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);

2173     speculative = speculative->with_inline_depth(jvms()->depth());
2174   } else if (current_type->would_improve_ptr(ptr_kind)) {
2175     // Profiling report that null was never seen so we can change the
2176     // speculative type to non null ptr.
2177     if (ptr_kind == ProfileAlwaysNull) {
2178       speculative = TypePtr::NULL_PTR;
2179     } else {
2180       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2181       const TypePtr* ptr = TypePtr::NOTNULL;
2182       if (speculative != NULL) {
2183         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2184       } else {
2185         speculative = ptr;
2186       }
2187     }
2188   }
2189 
2190   if (speculative != current_type->speculative()) {
2191     // Build a type with a speculative type (what we think we know
2192     // about the type but will need a guard when we use it)
2193     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2194     // We're changing the type, we need a new CheckCast node to carry
2195     // the new type. The new type depends on the control: what
2196     // profiling tells us is only valid from here as far as we can
2197     // tell.
2198     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2199     cast = _gvn.transform(cast);
2200     replace_in_map(n, cast);
2201     n = cast;
2202   }
2203 
2204   return n;
2205 }
2206 
2207 /**
2208  * Record profiling data from receiver profiling at an invoke with the
2209  * type system so that it can propagate it (speculation)
2210  *
2211  * @param n  receiver node
2212  *
2213  * @return   node with improved type
2214  */
2215 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2216   if (!UseTypeSpeculation) {
2217     return n;
2218   }
2219   ciKlass* exact_kls = profile_has_unique_klass();
2220   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2221   if ((java_bc() == Bytecodes::_checkcast ||
2222        java_bc() == Bytecodes::_instanceof ||
2223        java_bc() == Bytecodes::_aastore) &&
2224       method()->method_data()->is_mature()) {
2225     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2226     if (data != NULL) {
2227       if (!data->as_BitData()->null_seen()) {
2228         ptr_kind = ProfileNeverNull;







2229       } else {
2230         assert(data->is_ReceiverTypeData(), "bad profile data type");
2231         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2232         uint i = 0;
2233         for (; i < call->row_limit(); i++) {
2234           ciKlass* receiver = call->receiver(i);
2235           if (receiver != NULL) {
2236             break;




2237           }

2238         }
2239         ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2240       }
2241     }
2242   }
2243   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2244 }
2245 
2246 /**
2247  * Record profiling data from argument profiling at an invoke with the
2248  * type system so that it can propagate it (speculation)
2249  *
2250  * @param dest_method  target method for the call
2251  * @param bc           what invoke bytecode is this?
2252  */
2253 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2254   if (!UseTypeSpeculation) {
2255     return;
2256   }
2257   const TypeFunc* tf    = TypeFunc::make(dest_method);
2258   int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2259   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2260   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2261     const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2262     if (is_reference_type(targ->basic_type())) {
2263       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2264       ciKlass* better_type = NULL;
2265       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2266         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2267       }
2268       i++;
2269     }
2270   }
2271 }
2272 
2273 /**
2274  * Record profiling data from parameter profiling at an invoke with
2275  * the type system so that it can propagate it (speculation)
2276  */
2277 void GraphKit::record_profiled_parameters_for_speculation() {
2278   if (!UseTypeSpeculation) {
2279     return;
2280   }
2281   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {

2312   if (Matcher::strict_fp_requires_explicit_rounding) {
2313     // If a strict caller invokes a non-strict callee, round a double result.
2314     // A non-strict method may return a double value which has an extended exponent,
2315     // but this must not be visible in a caller which is strict.
2316     BasicType result_type = dest_method->return_type()->basic_type();
2317     assert(method() != NULL, "must have caller context");
2318     if( result_type == T_DOUBLE && method()->is_strict() && !dest_method->is_strict() ) {
2319       // Destination method's return value is on top of stack
2320       // dstore_rounding() does gvn.transform
2321       Node *result = pop_pair();
2322       result = dstore_rounding(result);
2323       push_pair(result);
2324     }
2325   }
2326 }
2327 
2328 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2329   if (Matcher::strict_fp_requires_explicit_rounding) {
2330     // (Note:  TypeFunc::make has a cache that makes this fast.)
2331     const TypeFunc* tf    = TypeFunc::make(dest_method);
2332     int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2333     for (int j = 0; j < nargs; j++) {
2334       const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2335       if (targ->basic_type() == T_DOUBLE) {
2336         // If any parameters are doubles, they must be rounded before
2337         // the call, dstore_rounding does gvn.transform
2338         Node *arg = argument(j);
2339         arg = dstore_rounding(arg);
2340         set_argument(j, arg);
2341       }
2342     }
2343   }
2344 }
2345 
2346 // rounding for strict float precision conformance
2347 Node* GraphKit::precision_rounding(Node* n) {
2348   if (Matcher::strict_fp_requires_explicit_rounding) {
2349 #ifdef IA32
2350     if (_method->flags().is_strict() && UseSSE == 0) {
2351       return _gvn.transform(new RoundFloatNode(0, n));
2352     }
2353 #else
2354     Unimplemented();

2794 
2795   // Now do a linear scan of the secondary super-klass array.  Again, no real
2796   // performance impact (too rare) but it's gotta be done.
2797   // Since the code is rarely used, there is no penalty for moving it
2798   // out of line, and it can only improve I-cache density.
2799   // The decision to inline or out-of-line this final check is platform
2800   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2801   Node* psc = gvn.transform(
2802     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2803 
2804   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2805   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2806   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2807 
2808   // Return false path; set default control to true path.
2809   *ctrl = gvn.transform(r_ok_subtype);
2810   return gvn.transform(r_not_subtype);
2811 }
2812 
2813 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {




2814   if (ExpandSubTypeCheckAtParseTime) {
2815     MergeMemNode* mem = merged_memory();
2816     Node* ctrl = control();
2817     Node* subklass = obj_or_subklass;
2818     if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2819       subklass = load_object_klass(obj_or_subklass);
2820     }
2821 
2822     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2823     set_control(ctrl);
2824     return n;
2825   }
2826 
2827   const TypePtr* adr_type = TypeKlassPtr::make(TypePtr::NotNull, C->env()->Object_klass(), Type::OffsetBot);
2828   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2829   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2830   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2831   set_control(_gvn.transform(new IfTrueNode(iff)));
2832   return _gvn.transform(new IfFalseNode(iff));
2833 }
2834 
2835 // Profile-driven exact type check:
2836 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2837                                     float prob,
2838                                     Node* *casted_receiver) {











2839   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2840   Node* recv_klass = load_object_klass(receiver);
2841   Node* want_klass = makecon(tklass);
2842   Node* cmp = _gvn.transform( new CmpPNode(recv_klass, want_klass) );
2843   Node* bol = _gvn.transform( new BoolNode(cmp, BoolTest::eq) );
2844   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2845   set_control( _gvn.transform( new IfTrueNode (iff) ));
2846   Node* fail = _gvn.transform( new IfFalseNode(iff) );
2847 
2848   const TypeOopPtr* recv_xtype = tklass->as_instance_type();
2849   assert(recv_xtype->klass_is_exact(), "");
2850 
2851   // Subsume downstream occurrences of receiver with a cast to
2852   // recv_xtype, since now we know what the type will be.
2853   Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
2854   (*casted_receiver) = _gvn.transform(cast);






2855   // (User must make the replace_in_map call.)
2856 
2857   return fail;
2858 }
2859 











2860 //------------------------------subtype_check_receiver-------------------------
2861 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
2862                                        Node** casted_receiver) {
2863   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2864   Node* want_klass = makecon(tklass);
2865 
2866   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
2867 
2868   // Cast receiver after successful check
2869   const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
2870   Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
2871   (*casted_receiver) = _gvn.transform(cast);
2872 
2873   return slow_ctl;
2874 }
2875 
2876 //------------------------------seems_never_null-------------------------------
2877 // Use null_seen information if it is available from the profile.
2878 // If we see an unexpected null at a type check we record it and force a
2879 // recompile; the offending check will be recompiled to handle NULLs.
2880 // If we see several offending BCIs, then all checks in the
2881 // method will be recompiled.
2882 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2883   speculating = !_gvn.type(obj)->speculative_maybe_null();
2884   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2885   if (UncommonNullCast               // Cutout for this technique
2886       && obj != null()               // And not the -Xcomp stupid case?
2887       && !too_many_traps(reason)
2888       ) {
2889     if (speculating) {
2890       return true;
2891     }
2892     if (data == NULL)
2893       // Edge case:  no mature data.  Be optimistic here.
2894       return true;
2895     // If the profile has not seen a null, assume it won't happen.
2896     assert(java_bc() == Bytecodes::_checkcast ||
2897            java_bc() == Bytecodes::_instanceof ||
2898            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");



2899     return !data->as_BitData()->null_seen();
2900   }
2901   speculating = false;
2902   return false;
2903 }
2904 
2905 void GraphKit::guard_klass_being_initialized(Node* klass) {
2906   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
2907   Node* adr = basic_plus_adr(top(), klass, init_state_off);
2908   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
2909                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
2910                                     T_BYTE, MemNode::unordered);
2911   init_state = _gvn.transform(init_state);
2912 
2913   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
2914 
2915   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
2916   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
2917 
2918   { BuildCutout unless(this, tst, PROB_MAX);

2958 
2959 //------------------------maybe_cast_profiled_receiver-------------------------
2960 // If the profile has seen exactly one type, narrow to exactly that type.
2961 // Subsequent type checks will always fold up.
2962 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
2963                                              ciKlass* require_klass,
2964                                              ciKlass* spec_klass,
2965                                              bool safe_for_replace) {
2966   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
2967 
2968   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
2969 
2970   // Make sure we haven't already deoptimized from this tactic.
2971   if (too_many_traps_or_recompiles(reason))
2972     return NULL;
2973 
2974   // (No, this isn't a call, but it's enough like a virtual call
2975   // to use the same ciMethod accessor to get the profile info...)
2976   // If we have a speculative type use it instead of profiling (which
2977   // may not help us)
2978   ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;













2979   if (exact_kls != NULL) {// no cast failures here
2980     if (require_klass == NULL ||
2981         C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {
2982       // If we narrow the type to match what the type profile sees or
2983       // the speculative type, we can then remove the rest of the
2984       // cast.
2985       // This is a win, even if the exact_kls is very specific,
2986       // because downstream operations, such as method calls,
2987       // will often benefit from the sharper type.
2988       Node* exact_obj = not_null_obj; // will get updated in place...
2989       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
2990                                             &exact_obj);
2991       { PreserveJVMState pjvms(this);
2992         set_control(slow_ctl);
2993         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
2994       }
2995       if (safe_for_replace) {
2996         replace_in_map(not_null_obj, exact_obj);
2997       }
2998       return exact_obj;

3063 // and the reflective instance-of call.
3064 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3065   kill_dead_locals();           // Benefit all the uncommon traps
3066   assert( !stopped(), "dead parse path should be checked in callers" );
3067   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3068          "must check for not-null not-dead klass in callers");
3069 
3070   // Make the merge point
3071   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3072   RegionNode* region = new RegionNode(PATH_LIMIT);
3073   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3074   C->set_has_split_ifs(true); // Has chance for split-if optimization
3075 
3076   ciProfileData* data = NULL;
3077   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3078     data = method()->method_data()->bci_to_data(bci());
3079   }
3080   bool speculative_not_null = false;
3081   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3082                          && seems_never_null(obj, data, speculative_not_null));

3083 
3084   // Null check; get casted pointer; set region slot 3
3085   Node* null_ctl = top();
3086   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3087 
3088   // If not_null_obj is dead, only null-path is taken
3089   if (stopped()) {              // Doing instance-of on a NULL?
3090     set_control(null_ctl);
3091     return intcon(0);
3092   }
3093   region->init_req(_null_path, null_ctl);
3094   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3095   if (null_ctl == top()) {
3096     // Do this eagerly, so that pattern matches like is_diamond_phi
3097     // will work even during parsing.
3098     assert(_null_path == PATH_LIMIT-1, "delete last");
3099     region->del_req(_null_path);
3100     phi   ->del_req(_null_path);
3101   }
3102 
3103   // Do we know the type check always succeed?
3104   bool known_statically = false;
3105   if (_gvn.type(superklass)->singleton()) {
3106     ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();
3107     ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();
3108     if (subk != NULL && subk->is_loaded()) {
3109       int static_res = C->static_subtype_check(superk, subk);
3110       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);


3111     }
3112   }
3113 
3114   if (!known_statically) {
3115     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3116     // We may not have profiling here or it may not help us. If we
3117     // have a speculative type use it to perform an exact cast.
3118     ciKlass* spec_obj_type = obj_type->speculative_type();
3119     if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3120       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3121       if (stopped()) {            // Profile disagrees with this path.
3122         set_control(null_ctl);    // Null is the only remaining possibility.
3123         return intcon(0);
3124       }
3125       if (cast_obj != NULL) {



3126         not_null_obj = cast_obj;
3127       }
3128     }
3129   }
3130 
3131   // Generate the subtype check
3132   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3133 
3134   // Plug in the success path to the general merge in slot 1.
3135   region->init_req(_obj_path, control());
3136   phi   ->init_req(_obj_path, intcon(1));
3137 
3138   // Plug in the failing path to the general merge in slot 2.
3139   region->init_req(_fail_path, not_subtype_ctrl);
3140   phi   ->init_req(_fail_path, intcon(0));
3141 
3142   // Return final merged results
3143   set_control( _gvn.transform(region) );
3144   record_for_igvn(region);
3145 
3146   // If we know the type check always succeeds then we don't use the
3147   // profiling data at this bytecode. Don't lose it, feed it to the
3148   // type system as a speculative type.
3149   if (safe_for_replace) {
3150     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3151     replace_in_map(obj, casted_obj);
3152   }
3153 
3154   return _gvn.transform(phi);
3155 }
3156 
3157 //-------------------------------gen_checkcast---------------------------------
3158 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3159 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3160 // uncommon-trap paths work.  Adjust stack after this call.
3161 // If failure_control is supplied and not null, it is filled in with
3162 // the control edge for the cast failure.  Otherwise, an appropriate
3163 // uncommon trap or exception is thrown.
3164 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3165                               Node* *failure_control) {
3166   kill_dead_locals();           // Benefit all the uncommon traps
3167   const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
3168   const Type *toop = TypeOopPtr::make_from_klass(tk->klass());




3169 
3170   // Fast cutout:  Check the case that the cast is vacuously true.
3171   // This detects the common cases where the test will short-circuit
3172   // away completely.  We do this before we perform the null check,
3173   // because if the test is going to turn into zero code, we don't
3174   // want a residual null check left around.  (Causes a slowdown,
3175   // for example, in some objArray manipulations, such as a[i]=a[j].)
3176   if (tk->singleton()) {
3177     const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3178     if (objtp != NULL && objtp->klass() != NULL) {
3179       switch (C->static_subtype_check(tk->klass(), objtp->klass())) {








3180       case Compile::SSC_always_true:
3181         // If we know the type check always succeed then we don't use
3182         // the profiling data at this bytecode. Don't lose it, feed it
3183         // to the type system as a speculative type.
3184         return record_profiled_receiver_for_speculation(obj);









3185       case Compile::SSC_always_false:
3186         // It needs a null check because a null will *pass* the cast check.
3187         // A non-null value will always produce an exception.
3188         return null_assert(obj);








3189       }
3190     }
3191   }
3192 
3193   ciProfileData* data = NULL;
3194   bool safe_for_replace = false;
3195   if (failure_control == NULL) {        // use MDO in regular case only
3196     assert(java_bc() == Bytecodes::_aastore ||
3197            java_bc() == Bytecodes::_checkcast,
3198            "interpreter profiles type checks only for these BCs");
3199     data = method()->method_data()->bci_to_data(bci());


3200     safe_for_replace = true;
3201   }
3202 
3203   // Make the merge point
3204   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3205   RegionNode* region = new RegionNode(PATH_LIMIT);
3206   Node*       phi    = new PhiNode(region, toop);



3207   C->set_has_split_ifs(true); // Has chance for split-if optimization
3208 
3209   // Use null-cast information if it is available
3210   bool speculative_not_null = false;
3211   bool never_see_null = ((failure_control == NULL)  // regular case only
3212                          && seems_never_null(obj, data, speculative_not_null));
3213 
3214   // Null check; get casted pointer; set region slot 3
3215   Node* null_ctl = top();
3216   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);







3217 
3218   // If not_null_obj is dead, only null-path is taken
3219   if (stopped()) {              // Doing instance-of on a NULL?
3220     set_control(null_ctl);
3221     return null();
3222   }
3223   region->init_req(_null_path, null_ctl);
3224   phi   ->init_req(_null_path, null());  // Set null path value
3225   if (null_ctl == top()) {
3226     // Do this eagerly, so that pattern matches like is_diamond_phi
3227     // will work even during parsing.
3228     assert(_null_path == PATH_LIMIT-1, "delete last");
3229     region->del_req(_null_path);
3230     phi   ->del_req(_null_path);
3231   }
3232 
3233   Node* cast_obj = NULL;
3234   if (tk->klass_is_exact()) {
3235     // The following optimization tries to statically cast the speculative type of the object
3236     // (for example obtained during profiling) to the type of the superklass and then do a
3237     // dynamic check that the type of the object is what we expect. To work correctly
3238     // for checkcast and aastore the type of superklass should be exact.
3239     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3240     // We may not have profiling here or it may not help us. If we have
3241     // a speculative type use it to perform an exact cast.
3242     ciKlass* spec_obj_type = obj_type->speculative_type();
3243     if (spec_obj_type != NULL || data != NULL) {
3244       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);







3245       if (cast_obj != NULL) {
3246         if (failure_control != NULL) // failure is now impossible
3247           (*failure_control) = top();
3248         // adjust the type of the phi to the exact klass:
3249         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3250       }
3251     }
3252   }
3253 
3254   if (cast_obj == NULL) {
3255     // Generate the subtype check
3256     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );
3257 
3258     // Plug in success path into the merge
3259     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3260     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3261     if (failure_control == NULL) {
3262       if (not_subtype_ctrl != top()) { // If failure is possible
3263         PreserveJVMState pjvms(this);
3264         set_control(not_subtype_ctrl);
3265         builtin_throw(Deoptimization::Reason_class_check, load_object_klass(not_null_obj));






3266       }
3267     } else {
3268       (*failure_control) = not_subtype_ctrl;
3269     }
3270   }
3271 
3272   region->init_req(_obj_path, control());
3273   phi   ->init_req(_obj_path, cast_obj);
3274 
3275   // A merge of NULL or Casted-NotNull obj
3276   Node* res = _gvn.transform(phi);
3277 
3278   // Note I do NOT always 'replace_in_map(obj,result)' here.
3279   //  if( tk->klass()->can_be_primary_super()  )
3280     // This means that if I successfully store an Object into an array-of-String
3281     // I 'forget' that the Object is really now known to be a String.  I have to
3282     // do this because we don't have true union types for interfaces - if I store
3283     // a Baz into an array-of-Interface and then tell the optimizer it's an
3284     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3285     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3286   //  replace_in_map( obj, res );
3287 
3288   // Return final merged results
3289   set_control( _gvn.transform(region) );
3290   record_for_igvn(region);
3291 
3292   return record_profiled_receiver_for_speculation(res);


























































































































3293 }
3294 
3295 //------------------------------next_monitor-----------------------------------
3296 // What number should be given to the next monitor?
3297 int GraphKit::next_monitor() {
3298   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3299   int next = current + C->sync_stack_slots();
3300   // Keep the toplevel high water mark current:
3301   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3302   return current;
3303 }
3304 
3305 //------------------------------insert_mem_bar---------------------------------
3306 // Memory barrier to avoid floating things around
3307 // The membar serves as a pinch point between both control and all memory slices.
3308 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3309   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3310   mb->init_req(TypeFunc::Control, control());
3311   mb->init_req(TypeFunc::Memory,  reset_memory());
3312   Node* membar = _gvn.transform(mb);

3340   }
3341   Node* membar = _gvn.transform(mb);
3342   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3343   if (alias_idx == Compile::AliasIdxBot) {
3344     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3345   } else {
3346     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3347   }
3348   return membar;
3349 }
3350 
3351 //------------------------------shared_lock------------------------------------
3352 // Emit locking code.
3353 FastLockNode* GraphKit::shared_lock(Node* obj) {
3354   // bci is either a monitorenter bc or InvocationEntryBci
3355   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3356   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3357 
3358   if( !GenerateSynchronizationCode )
3359     return NULL;                // Not locking things?

3360   if (stopped())                // Dead monitor?
3361     return NULL;
3362 
3363   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3364 
3365   // Box the stack location
3366   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3367   Node* mem = reset_memory();
3368 
3369   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3370   if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {
3371     // Create the counters for this fast lock.
3372     flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3373   }
3374 
3375   // Create the rtm counters for this fast lock if needed.
3376   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3377 
3378   // Add monitor to debug info for the slow path.  If we block inside the
3379   // slow path and de-opt, we need the monitor hanging around

3412   }
3413 #endif
3414 
3415   return flock;
3416 }
3417 
3418 
3419 //------------------------------shared_unlock----------------------------------
3420 // Emit unlocking code.
3421 void GraphKit::shared_unlock(Node* box, Node* obj) {
3422   // bci is either a monitorenter bc or InvocationEntryBci
3423   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3424   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3425 
3426   if( !GenerateSynchronizationCode )
3427     return;
3428   if (stopped()) {               // Dead monitor?
3429     map()->pop_monitor();        // Kill monitor from debug info
3430     return;
3431   }

3432 
3433   // Memory barrier to avoid floating things down past the locked region
3434   insert_mem_bar(Op_MemBarReleaseLock);
3435 
3436   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3437   UnlockNode *unlock = new UnlockNode(C, tf);
3438 #ifdef ASSERT
3439   unlock->set_dbg_jvms(sync_jvms());
3440 #endif
3441   uint raw_idx = Compile::AliasIdxRaw;
3442   unlock->init_req( TypeFunc::Control, control() );
3443   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3444   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3445   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3446   unlock->init_req( TypeFunc::ReturnAdr, top() );
3447 
3448   unlock->init_req(TypeFunc::Parms + 0, obj);
3449   unlock->init_req(TypeFunc::Parms + 1, box);
3450   unlock = _gvn.transform(unlock)->as_Unlock();
3451 
3452   Node* mem = reset_memory();
3453 
3454   // unlock has no side-effects, sets few values
3455   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3456 
3457   // Kill monitor from debug info
3458   map()->pop_monitor( );
3459 }
3460 
3461 //-------------------------------get_layout_helper-----------------------------
3462 // If the given klass is a constant or known to be an array,
3463 // fetch the constant layout helper value into constant_value
3464 // and return (Node*)NULL.  Otherwise, load the non-constant
3465 // layout helper value, and return the node which represents it.
3466 // This two-faced routine is useful because allocation sites
3467 // almost always feature constant types.
3468 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3469   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3470   if (!StressReflectiveCode && inst_klass != NULL) {
3471     ciKlass* klass = inst_klass->klass();

3472     bool    xklass = inst_klass->klass_is_exact();
3473     if (xklass || klass->is_array_klass()) {





3474       jint lhelper = klass->layout_helper();
3475       if (lhelper != Klass::_lh_neutral_value) {
3476         constant_value = lhelper;
3477         return (Node*) NULL;
3478       }
3479     }
3480   }
3481   constant_value = Klass::_lh_neutral_value;  // put in a known value
3482   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3483   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3484 }
3485 
3486 // We just put in an allocate/initialize with a big raw-memory effect.
3487 // Hook selected additional alias categories on the initialization.
3488 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3489                                 MergeMemNode* init_in_merge,
3490                                 Node* init_out_raw) {
3491   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3492   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3493 

3515 
3516   // a normal slow-call doesn't change i_o, but an allocation does
3517   // we create a separate i_o projection for the normal control path
3518   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3519   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3520 
3521   // put in an initialization barrier
3522   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3523                                                  rawoop)->as_Initialize();
3524   assert(alloc->initialization() == init,  "2-way macro link must work");
3525   assert(init ->allocation()     == alloc, "2-way macro link must work");
3526   {
3527     // Extract memory strands which may participate in the new object's
3528     // initialization, and source them from the new InitializeNode.
3529     // This will allow us to observe initializations when they occur,
3530     // and link them properly (as a group) to the InitializeNode.
3531     assert(init->in(InitializeNode::Memory) == malloc, "");
3532     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3533     init->set_req(InitializeNode::Memory, minit_in);
3534     record_for_igvn(minit_in); // fold it up later, if possible

3535     Node* minit_out = memory(rawidx);
3536     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3537     // Add an edge in the MergeMem for the header fields so an access
3538     // to one of those has correct memory state
3539     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3540     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3541     if (oop_type->isa_aryptr()) {
3542       const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3543       int            elemidx  = C->get_alias_index(telemref);
3544       hook_memory_on_init(*this, elemidx, minit_in, minit_out);























3545     } else if (oop_type->isa_instptr()) {

3546       ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();
3547       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3548         ciField* field = ik->nonstatic_field_at(i);
3549         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3550           continue;  // do not bother to track really large numbers of fields
3551         // Find (or create) the alias category for this field:
3552         int fieldidx = C->alias_type(field)->index();
3553         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3554       }
3555     }
3556   }
3557 
3558   // Cast raw oop to the real thing...
3559   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3560   javaoop = _gvn.transform(javaoop);
3561   C->set_recent_alloc(control(), javaoop);
3562   assert(just_allocated_object(control()) == javaoop, "just allocated");
3563 
3564 #ifdef ASSERT
3565   { // Verify that the AllocateNode::Ideal_allocation recognizers work:

3576       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3577     }
3578   }
3579 #endif //ASSERT
3580 
3581   return javaoop;
3582 }
3583 
3584 //---------------------------new_instance--------------------------------------
3585 // This routine takes a klass_node which may be constant (for a static type)
3586 // or may be non-constant (for reflective code).  It will work equally well
3587 // for either, and the graph will fold nicely if the optimizer later reduces
3588 // the type to a constant.
3589 // The optional arguments are for specialized use by intrinsics:
3590 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3591 //  - If 'return_size_val', report the the total object size to the caller.
3592 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3593 Node* GraphKit::new_instance(Node* klass_node,
3594                              Node* extra_slow_test,
3595                              Node* *return_size_val,
3596                              bool deoptimize_on_exception) {

3597   // Compute size in doublewords
3598   // The size is always an integral number of doublewords, represented
3599   // as a positive bytewise size stored in the klass's layout_helper.
3600   // The layout_helper also encodes (in a low bit) the need for a slow path.
3601   jint  layout_con = Klass::_lh_neutral_value;
3602   Node* layout_val = get_layout_helper(klass_node, layout_con);
3603   int   layout_is_con = (layout_val == NULL);
3604 
3605   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
3606   // Generate the initial go-slow test.  It's either ALWAYS (return a
3607   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3608   // case) a computed value derived from the layout_helper.
3609   Node* initial_slow_test = NULL;
3610   if (layout_is_con) {
3611     assert(!StressReflectiveCode, "stress mode does not use these paths");
3612     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3613     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3614   } else {   // reflective case
3615     // This reflective path is used by Unsafe.allocateInstance.
3616     // (It may be stress-tested by specifying StressReflectiveCode.)
3617     // Basically, we want to get into the VM is there's an illegal argument.
3618     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3619     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3620     if (extra_slow_test != intcon(0)) {
3621       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3622     }
3623     // (Macro-expander will further convert this to a Bool, if necessary.)

3634 
3635     // Clear the low bits to extract layout_helper_size_in_bytes:
3636     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3637     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3638     size = _gvn.transform( new AndXNode(size, mask) );
3639   }
3640   if (return_size_val != NULL) {
3641     (*return_size_val) = size;
3642   }
3643 
3644   // This is a precise notnull oop of the klass.
3645   // (Actually, it need not be precise if this is a reflective allocation.)
3646   // It's what we cast the result to.
3647   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3648   if (!tklass)  tklass = TypeKlassPtr::OBJECT;
3649   const TypeOopPtr* oop_type = tklass->as_instance_type();
3650 
3651   // Now generate allocation code
3652 
3653   // The entire memory state is needed for slow path of the allocation
3654   // since GC and deoptimization can happened.
3655   Node *mem = reset_memory();
3656   set_all_memory(mem); // Create new memory state
3657 
3658   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3659                                          control(), mem, i_o(),
3660                                          size, klass_node,
3661                                          initial_slow_test);
3662 
3663   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3664 }
3665 








3666 //-------------------------------new_array-------------------------------------
3667 // helper for both newarray and anewarray
3668 // The 'length' parameter is (obviously) the length of the array.
3669 // See comments on new_instance for the meaning of the other arguments.
3670 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
3671                           Node* length,         // number of array elements
3672                           int   nargs,          // number of arguments to push back for uncommon trap
3673                           Node* *return_size_val,
3674                           bool deoptimize_on_exception) {
3675   jint  layout_con = Klass::_lh_neutral_value;
3676   Node* layout_val = get_layout_helper(klass_node, layout_con);
3677   int   layout_is_con = (layout_val == NULL);
3678 
3679   if (!layout_is_con && !StressReflectiveCode &&
3680       !too_many_traps(Deoptimization::Reason_class_check)) {
3681     // This is a reflective array creation site.
3682     // Optimistically assume that it is a subtype of Object[],
3683     // so that we can fold up all the address arithmetic.
3684     layout_con = Klass::array_layout_helper(T_OBJECT);
3685     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3686     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3687     { BuildCutout unless(this, bol_lh, PROB_MAX);
3688       inc_sp(nargs);
3689       uncommon_trap(Deoptimization::Reason_class_check,
3690                     Deoptimization::Action_maybe_recompile);
3691     }
3692     layout_val = NULL;
3693     layout_is_con = true;
3694   }
3695 
3696   // Generate the initial go-slow test.  Make sure we do not overflow
3697   // if length is huge (near 2Gig) or negative!  We do not need
3698   // exact double-words here, just a close approximation of needed
3699   // double-words.  We can't add any offset or rounding bits, lest we
3700   // take a size -1 of bytes and make it positive.  Use an unsigned
3701   // compare, so negative sizes look hugely positive.
3702   int fast_size_limit = FastAllocateSizeLimit;
3703   if (layout_is_con) {
3704     assert(!StressReflectiveCode, "stress mode does not use these paths");
3705     // Increase the size limit if we have exact knowledge of array type.
3706     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3707     fast_size_limit <<= (LogBytesPerLong - log2_esize);
3708   }
3709 
3710   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3711   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3712 
3713   // --- Size Computation ---
3714   // array_size = round_to_heap(array_header + (length << elem_shift));
3715   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3716   // and align_to(x, y) == ((x + y-1) & ~(y-1))
3717   // The rounding mask is strength-reduced, if possible.
3718   int round_mask = MinObjAlignmentInBytes - 1;
3719   Node* header_size = NULL;
3720   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3721   // (T_BYTE has the weakest alignment and size restrictions...)
3722   if (layout_is_con) {
3723     int       hsize  = Klass::layout_helper_header_size(layout_con);
3724     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
3725     BasicType etype  = Klass::layout_helper_element_type(layout_con);
3726     if ((round_mask & ~right_n_bits(eshift)) == 0)
3727       round_mask = 0;  // strength-reduce it if it goes away completely
3728     assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3729     assert(header_size_min <= hsize, "generic minimum is smallest");
3730     header_size_min = hsize;
3731     header_size = intcon(hsize + round_mask);
3732   } else {
3733     Node* hss   = intcon(Klass::_lh_header_size_shift);
3734     Node* hsm   = intcon(Klass::_lh_header_size_mask);
3735     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3736     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
3737     Node* mask  = intcon(round_mask);
3738     header_size = _gvn.transform( new AddINode(hsize, mask) );
3739   }
3740 
3741   Node* elem_shift = NULL;
3742   if (layout_is_con) {
3743     int eshift = Klass::layout_helper_log2_element_size(layout_con);
3744     if (eshift != 0)
3745       elem_shift = intcon(eshift);
3746   } else {
3747     // There is no need to mask or shift this value.
3748     // The semantics of LShiftINode include an implicit mask to 0x1F.

3792   // places, one where the length is sharply limited, and the other
3793   // after a successful allocation.
3794   Node* abody = lengthx;
3795   if (elem_shift != NULL)
3796     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3797   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
3798   if (round_mask != 0) {
3799     Node* mask = MakeConX(~round_mask);
3800     size       = _gvn.transform( new AndXNode(size, mask) );
3801   }
3802   // else if round_mask == 0, the size computation is self-rounding
3803 
3804   if (return_size_val != NULL) {
3805     // This is the size
3806     (*return_size_val) = size;
3807   }
3808 
3809   // Now generate allocation code
3810 
3811   // The entire memory state is needed for slow path of the allocation
3812   // since GC and deoptimization can happened.
3813   Node *mem = reset_memory();
3814   set_all_memory(mem); // Create new memory state
3815 
3816   if (initial_slow_test->is_Bool()) {
3817     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3818     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3819   }
3820 
















































































3821   // Create the AllocateArrayNode and its result projections
3822   AllocateArrayNode* alloc
3823     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3824                             control(), mem, i_o(),
3825                             size, klass_node,
3826                             initial_slow_test,
3827                             length);
3828 
3829   // Cast to correct type.  Note that the klass_node may be constant or not,
3830   // and in the latter case the actual array type will be inexact also.
3831   // (This happens via a non-constant argument to inline_native_newArray.)
3832   // In any case, the value of klass_node provides the desired array type.
3833   const TypeInt* length_type = _gvn.find_int_type(length);
3834   const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3835   if (ary_type->isa_aryptr() && length_type != NULL) {
3836     // Try to get a better type than POS for the size
3837     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3838   }
3839 
3840   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3841 
3842   // Cast length on remaining path to be as narrow as possible
3843   if (map()->find_edge(length) >= 0) {
3844     Node* ccast = alloc->make_ideal_length(ary_type, &_gvn);
3845     if (ccast != length) {
3846       _gvn.set_type_bottom(ccast);
3847       record_for_igvn(ccast);
3848       replace_in_map(length, ccast);
3849     }
3850   }
3851 
3852   return javaoop;
3853 }
3854 

3972   set_all_memory(ideal.merged_memory());
3973   set_i_o(ideal.i_o());
3974   set_control(ideal.ctrl());
3975 }
3976 
3977 void GraphKit::final_sync(IdealKit& ideal) {
3978   // Final sync IdealKit and graphKit.
3979   sync_kit(ideal);
3980 }
3981 
3982 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
3983   Node* len = load_array_length(load_String_value(str, set_ctrl));
3984   Node* coder = load_String_coder(str, set_ctrl);
3985   // Divide length by 2 if coder is UTF16
3986   return _gvn.transform(new RShiftINode(len, coder));
3987 }
3988 
3989 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
3990   int value_offset = java_lang_String::value_offset();
3991   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
3992                                                      false, NULL, 0);
3993   const TypePtr* value_field_type = string_type->add_offset(value_offset);
3994   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
3995                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS),
3996                                                   ciTypeArrayKlass::make(T_BYTE), true, 0);
3997   Node* p = basic_plus_adr(str, str, value_offset);
3998   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
3999                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4000   return load;
4001 }
4002 
4003 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4004   if (!CompactStrings) {
4005     return intcon(java_lang_String::CODER_UTF16);
4006   }
4007   int coder_offset = java_lang_String::coder_offset();
4008   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4009                                                      false, NULL, 0);
4010   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4011 
4012   Node* p = basic_plus_adr(str, str, coder_offset);
4013   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4014                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4015   return load;
4016 }
4017 
4018 void GraphKit::store_String_value(Node* str, Node* value) {
4019   int value_offset = java_lang_String::value_offset();
4020   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4021                                                      false, NULL, 0);
4022   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4023 
4024   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4025                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4026 }
4027 
4028 void GraphKit::store_String_coder(Node* str, Node* value) {
4029   int coder_offset = java_lang_String::coder_offset();
4030   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4031                                                      false, NULL, 0);
4032   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4033 
4034   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4035                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4036 }
4037 
4038 // Capture src and dst memory state with a MergeMemNode
4039 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4040   if (src_type == dst_type) {
4041     // Types are equal, we don't need a MergeMemNode
4042     return memory(src_type);
4043   }
4044   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4045   record_for_igvn(merge); // fold it up later, if possible
4046   int src_idx = C->get_alias_index(src_type);
4047   int dst_idx = C->get_alias_index(dst_type);
4048   merge->set_memory_at(src_idx, memory(src_idx));
4049   merge->set_memory_at(dst_idx, memory(dst_idx));
4050   return merge;
4051 }

4122   i_char->init_req(2, AddI(i_char, intcon(2)));
4123 
4124   set_control(IfFalse(iff));
4125   set_memory(st, TypeAryPtr::BYTES);
4126 }
4127 
4128 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4129   if (!field->is_constant()) {
4130     return NULL; // Field not marked as constant.
4131   }
4132   ciInstance* holder = NULL;
4133   if (!field->is_static()) {
4134     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4135     if (const_oop != NULL && const_oop->is_instance()) {
4136       holder = const_oop->as_instance();
4137     }
4138   }
4139   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4140                                                         /*is_unsigned_load=*/false);
4141   if (con_type != NULL) {
4142     return makecon(con_type);







4143   }
4144   return NULL;
4145 }










   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/ciFlatArrayKlass.hpp"
  27 #include "ci/ciInlineKlass.hpp"
  28 #include "ci/ciUtilities.hpp"
  29 #include "classfile/javaClasses.hpp"
  30 #include "compiler/compileLog.hpp"
  31 #include "gc/shared/barrierSet.hpp"
  32 #include "gc/shared/c2/barrierSetC2.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "opto/addnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/convertnode.hpp"
  38 #include "opto/graphKit.hpp"
  39 #include "opto/idealKit.hpp"
  40 #include "opto/inlinetypenode.hpp"
  41 #include "opto/intrinsicnode.hpp"
  42 #include "opto/locknode.hpp"
  43 #include "opto/machnode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/opaquenode.hpp"
  46 #include "opto/parse.hpp"
  47 #include "opto/rootnode.hpp"
  48 #include "opto/runtime.hpp"
  49 #include "opto/subtypenode.hpp"
  50 #include "runtime/deoptimization.hpp"
  51 #include "runtime/sharedRuntime.hpp"
  52 #include "utilities/bitMap.inline.hpp"
  53 #include "utilities/powerOfTwo.hpp"
  54 
  55 //----------------------------GraphKit-----------------------------------------
  56 // Main utility constructor.
  57 GraphKit::GraphKit(JVMState* jvms, PhaseGVN* gvn)
  58   : Phase(Phase::Parser),
  59     _env(C->env()),
  60     _gvn((gvn != NULL) ? *gvn : *C->initial_gvn()),
  61     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  62 {
  63   assert(gvn == NULL || !gvn->is_IterGVN() || gvn->is_IterGVN()->delay_transform(), "delay transform should be enabled");
  64   _exceptions = jvms->map()->next_exception();
  65   if (_exceptions != NULL)  jvms->map()->set_next_exception(NULL);
  66   set_jvms(jvms);
  67 #ifdef ASSERT
  68   if (_gvn.is_IterGVN() != NULL) {
  69     assert(_gvn.is_IterGVN()->delay_transform(), "Transformation must be delayed if IterGVN is used");
  70     // Save the initial size of _for_igvn worklist for verification (see ~GraphKit)
  71     _worklist_size = _gvn.C->for_igvn()->size();
  72   }
  73 #endif
  74 }
  75 
  76 // Private constructor for parser.
  77 GraphKit::GraphKit()
  78   : Phase(Phase::Parser),
  79     _env(C->env()),
  80     _gvn(*C->initial_gvn()),
  81     _barrier_set(BarrierSet::barrier_set()->barrier_set_c2())
  82 {
  83   _exceptions = NULL;
  84   set_map(NULL);
  85   debug_only(_sp = -99);
  86   debug_only(set_bci(-99));
  87 }
  88 
  89 
  90 
  91 //---------------------------clean_stack---------------------------------------
  92 // Clear away rubbish from the stack area of the JVM state.
  93 // This destroys any arguments that may be waiting on the stack.

 822           tty->print_cr("Zombie local %d: ", local);
 823           jvms->dump();
 824         }
 825         return false;
 826       }
 827     }
 828   }
 829   return true;
 830 }
 831 
 832 #endif //ASSERT
 833 
 834 // Helper function for enforcing certain bytecodes to reexecute if
 835 // deoptimization happens
 836 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 837   ciMethod* cur_method = jvms->method();
 838   int       cur_bci   = jvms->bci();
 839   if (cur_method != NULL && cur_bci != InvocationEntryBci) {
 840     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 841     return Interpreter::bytecode_should_reexecute(code) ||
 842            (is_anewarray && (code == Bytecodes::_multianewarray));
 843     // Reexecute _multianewarray bytecode which was replaced with
 844     // sequence of [a]newarray. See Parse::do_multianewarray().
 845     //
 846     // Note: interpreter should not have it set since this optimization
 847     // is limited by dimensions and guarded by flag so in some cases
 848     // multianewarray() runtime calls will be generated and
 849     // the bytecode should not be reexecutes (stack will not be reset).
 850   } else {
 851     return false;
 852   }
 853 }
 854 
 855 // Helper function for adding JVMState and debug information to node
 856 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 857   // Add the safepoint edges to the call (or other safepoint).
 858 
 859   // Make sure dead locals are set to top.  This
 860   // should help register allocation time and cut down on the size
 861   // of the deoptimization information.
 862   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");
 863 
 864   // Walk the inline list to fill in the correct set of JVMState's
 865   // Also fill in the associated edges for each JVMState.
 866 
 867   // If the bytecode needs to be reexecuted we need to put
 868   // the arguments back on the stack.
 869   const bool should_reexecute = jvms()->should_reexecute();
 870   JVMState* youngest_jvms = should_reexecute ? sync_jvms_for_reexecute() : sync_jvms();
 871 
 872   // NOTE: set_bci (called from sync_jvms) might reset the reexecute bit to

1076       ciSignature* declared_signature = NULL;
1077       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1078       assert(declared_signature != NULL, "cannot be null");
1079       inputs   = declared_signature->arg_size_for_bc(code);
1080       int size = declared_signature->return_type()->size();
1081       depth = size - inputs;
1082     }
1083     break;
1084 
1085   case Bytecodes::_multianewarray:
1086     {
1087       ciBytecodeStream iter(method());
1088       iter.reset_to_bci(bci());
1089       iter.next();
1090       inputs = iter.get_dimensions();
1091       assert(rsize == 1, "");
1092       depth = rsize - inputs;
1093     }
1094     break;
1095 
1096   case Bytecodes::_withfield: {
1097     bool ignored_will_link;
1098     ciField* field = method()->get_field_at_bci(bci(), ignored_will_link);
1099     int      size  = field->type()->size();
1100     inputs = size+1;
1101     depth = rsize - inputs;
1102     break;
1103   }
1104 
1105   case Bytecodes::_ireturn:
1106   case Bytecodes::_lreturn:
1107   case Bytecodes::_freturn:
1108   case Bytecodes::_dreturn:
1109   case Bytecodes::_areturn:
1110     assert(rsize == -depth, "");
1111     inputs = rsize;
1112     break;
1113 
1114   case Bytecodes::_jsr:
1115   case Bytecodes::_jsr_w:
1116     inputs = 0;
1117     depth  = 1;                  // S.B. depth=1, not zero
1118     break;
1119 
1120   default:
1121     // bytecode produces a typed result
1122     inputs = rsize - depth;
1123     assert(inputs >= 0, "");
1124     break;

1167   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1168   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1169   return _gvn.transform( new AndLNode(conv, mask) );
1170 }
1171 
1172 Node* GraphKit::ConvL2I(Node* offset) {
1173   // short-circuit a common case
1174   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1175   if (offset_con != (jlong)Type::OffsetBot) {
1176     return intcon((int) offset_con);
1177   }
1178   return _gvn.transform( new ConvL2INode(offset));
1179 }
1180 
1181 //-------------------------load_object_klass-----------------------------------
1182 Node* GraphKit::load_object_klass(Node* obj) {
1183   // Special-case a fresh allocation to avoid building nodes:
1184   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1185   if (akls != NULL)  return akls;
1186   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1187   return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeKlassPtr::OBJECT));
1188 }
1189 
1190 //-------------------------load_array_length-----------------------------------
1191 Node* GraphKit::load_array_length(Node* array) {
1192   // Special-case a fresh allocation to avoid building nodes:
1193   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1194   Node *alen;
1195   if (alloc == NULL) {
1196     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1197     alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1198   } else {
1199     alen = alloc->Ideal_length();
1200     Node* ccast = alloc->make_ideal_length(_gvn.type(array)->is_oopptr(), &_gvn);
1201     if (ccast != alen) {
1202       alen = _gvn.transform(ccast);
1203     }
1204   }
1205   return alen;
1206 }
1207 

1210 // the incoming address with NULL casted away.  You are allowed to use the
1211 // not-null value only if you are control dependent on the test.
1212 #ifndef PRODUCT
1213 extern int explicit_null_checks_inserted,
1214            explicit_null_checks_elided;
1215 #endif
1216 Node* GraphKit::null_check_common(Node* value, BasicType type,
1217                                   // optional arguments for variations:
1218                                   bool assert_null,
1219                                   Node* *null_control,
1220                                   bool speculative) {
1221   assert(!assert_null || null_control == NULL, "not both at once");
1222   if (stopped())  return top();
1223   NOT_PRODUCT(explicit_null_checks_inserted++);
1224 
1225   // Construct NULL check
1226   Node *chk = NULL;
1227   switch(type) {
1228     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1229     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;
1230     case T_INLINE_TYPE : // fall through
1231     case T_ARRAY  : // fall through
1232       type = T_OBJECT;  // simplify further tests
1233     case T_OBJECT : {
1234       const Type *t = _gvn.type( value );
1235 
1236       const TypeOopPtr* tp = t->isa_oopptr();
1237       if (tp != NULL && tp->klass() != NULL && !tp->klass()->is_loaded()
1238           // Only for do_null_check, not any of its siblings:
1239           && !assert_null && null_control == NULL) {
1240         // Usually, any field access or invocation on an unloaded oop type
1241         // will simply fail to link, since the statically linked class is
1242         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1243         // the static class is loaded but the sharper oop type is not.
1244         // Rather than checking for this obscure case in lots of places,
1245         // we simply observe that a null check on an unloaded class
1246         // will always be followed by a nonsense operation, so we
1247         // can just issue the uncommon trap here.
1248         // Our access to the unloaded class will only be correct
1249         // after it has been loaded and initialized, which requires
1250         // a trip through the interpreter.

1382   }
1383 
1384   if (assert_null) {
1385     // Cast obj to null on this path.
1386     replace_in_map(value, zerocon(type));
1387     return zerocon(type);
1388   }
1389 
1390   // Cast obj to not-null on this path, if there is no null_control.
1391   // (If there is a null_control, a non-null value may come back to haunt us.)
1392   if (type == T_OBJECT) {
1393     Node* cast = cast_not_null(value, false);
1394     if (null_control == NULL || (*null_control) == top())
1395       replace_in_map(value, cast);
1396     value = cast;
1397   }
1398 
1399   return value;
1400 }
1401 
1402 Node* GraphKit::null2default(Node* value, ciInlineKlass* vk) {
1403   assert(!vk->is_scalarizable(), "Should only be used for non scalarizable inline klasses");
1404   Node* null_ctl = top();
1405   value = null_check_oop(value, &null_ctl);
1406   if (!null_ctl->is_top()) {
1407     // Return default value if oop is null
1408     Node* region = new RegionNode(3);
1409     region->init_req(1, control());
1410     region->init_req(2, null_ctl);
1411     value = PhiNode::make(region, value, TypeInstPtr::make(TypePtr::BotPTR, vk));
1412     value->set_req(2, InlineTypeNode::default_oop(gvn(), vk));
1413     set_control(gvn().transform(region));
1414     value = gvn().transform(value);
1415   }
1416   return value;
1417 }
1418 
1419 //------------------------------cast_not_null----------------------------------
1420 // Cast obj to not-null on this path
1421 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1422   if (obj->is_InlineType()) {
1423     return obj;
1424   }
1425   const Type *t = _gvn.type(obj);
1426   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1427   // Object is already not-null?
1428   if( t == t_not_null ) return obj;
1429 
1430   Node *cast = new CastPPNode(obj,t_not_null);
1431   cast->init_req(0, control());
1432   cast = _gvn.transform( cast );
1433 
1434   if (t->is_inlinetypeptr() && t->inline_klass()->is_scalarizable()) {
1435     // Scalarize inline type now that we know it's non-null
1436     cast = InlineTypeNode::make_from_oop(this, cast, t->inline_klass())->as_ptr(&gvn());
1437   }
1438 
1439   // Scan for instances of 'obj' in the current JVM mapping.
1440   // These instances are known to be not-null after the test.
1441   if (do_replace_in_map)
1442     replace_in_map(obj, cast);
1443 
1444   return cast;                  // Return casted value
1445 }
1446 
1447 // Sometimes in intrinsics, we implicitly know an object is not null
1448 // (there's no actual null check) so we can cast it to not null. In
1449 // the course of optimizations, the input to the cast can become null.
1450 // In that case that data path will die and we need the control path
1451 // to become dead as well to keep the graph consistent. So we have to
1452 // add a check for null for which one branch can't be taken. It uses
1453 // an Opaque4 node that will cause the check to be removed after loop
1454 // opts so the test goes away and the compiled code doesn't execute a
1455 // useless check.
1456 Node* GraphKit::must_be_not_null(Node* value, bool do_replace_in_map) {
1457   if (!TypePtr::NULL_PTR->higher_equal(_gvn.type(value))) {
1458     return value;

1542                           MemNode::MemOrd mo,
1543                           LoadNode::ControlDependency control_dependency,
1544                           bool require_atomic_access,
1545                           bool unaligned,
1546                           bool mismatched,
1547                           bool unsafe,
1548                           uint8_t barrier_data) {
1549   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1550   const TypePtr* adr_type = NULL; // debug-mode-only argument
1551   debug_only(adr_type = C->get_adr_type(adr_idx));
1552   Node* mem = memory(adr_idx);
1553   Node* ld;
1554   if (require_atomic_access && bt == T_LONG) {
1555     ld = LoadLNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1556   } else if (require_atomic_access && bt == T_DOUBLE) {
1557     ld = LoadDNode::make_atomic(ctl, mem, adr, adr_type, t, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1558   } else {
1559     ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, unaligned, mismatched, unsafe, barrier_data);
1560   }
1561   ld = _gvn.transform(ld);
1562 
1563   if (((bt == T_OBJECT || bt == T_INLINE_TYPE) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1564     // Improve graph before escape analysis and boxing elimination.
1565     record_for_igvn(ld);
1566   }
1567   return ld;
1568 }
1569 
1570 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1571                                 int adr_idx,
1572                                 MemNode::MemOrd mo,
1573                                 bool require_atomic_access,
1574                                 bool unaligned,
1575                                 bool mismatched,
1576                                 bool unsafe) {
1577   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1578   const TypePtr* adr_type = NULL;
1579   debug_only(adr_type = C->get_adr_type(adr_idx));
1580   Node *mem = memory(adr_idx);
1581   Node* st;
1582   if (require_atomic_access && bt == T_LONG) {
1583     st = StoreLNode::make_atomic(ctl, mem, adr, adr_type, val, mo);

1594   }
1595   if (unsafe) {
1596     st->as_Store()->set_unsafe_access();
1597   }
1598   st = _gvn.transform(st);
1599   set_memory(st, adr_idx);
1600   // Back-to-back stores can only remove intermediate store with DU info
1601   // so push on worklist for optimizer.
1602   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1603     record_for_igvn(st);
1604 
1605   return st;
1606 }
1607 
1608 Node* GraphKit::access_store_at(Node* obj,
1609                                 Node* adr,
1610                                 const TypePtr* adr_type,
1611                                 Node* val,
1612                                 const Type* val_type,
1613                                 BasicType bt,
1614                                 DecoratorSet decorators,
1615                                 bool safe_for_replace) {
1616   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1617   // could be delayed during Parse (for example, in adjust_map_after_if()).
1618   // Execute transformation here to avoid barrier generation in such case.
1619   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1620     val = _gvn.makecon(TypePtr::NULL_PTR);
1621   }
1622 
1623   if (stopped()) {
1624     return top(); // Dead path ?
1625   }
1626 
1627   assert(val != NULL, "not dead path");
1628   if (val->is_InlineType()) {
1629     // Store to non-flattened field. Buffer the inline type and make sure
1630     // the store is re-executed if the allocation triggers deoptimization.
1631     PreserveReexecuteState preexecs(this);
1632     jvms()->set_should_reexecute(true);
1633     val = val->as_InlineType()->buffer(this, safe_for_replace);
1634   }
1635 
1636   C2AccessValuePtr addr(adr, adr_type);
1637   C2AccessValue value(val, val_type);
1638   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1639   if (access.is_raw()) {
1640     return _barrier_set->BarrierSetC2::store_at(access, value);
1641   } else {
1642     return _barrier_set->store_at(access, value);
1643   }
1644 }
1645 
1646 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1647                                Node* adr,   // actual adress to store val at
1648                                const TypePtr* adr_type,
1649                                const Type* val_type,
1650                                BasicType bt,
1651                                DecoratorSet decorators,
1652                                Node* ctl) {
1653   if (stopped()) {
1654     return top(); // Dead path ?
1655   }
1656 
1657   C2AccessValuePtr addr(adr, adr_type);
1658   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1659   if (access.is_raw()) {
1660     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1661   } else {
1662     return _barrier_set->load_at(access, val_type);
1663   }
1664 }
1665 
1666 Node* GraphKit::access_load(Node* adr,   // actual adress to load val at
1667                             const Type* val_type,
1668                             BasicType bt,
1669                             DecoratorSet decorators) {
1670   if (stopped()) {
1671     return top(); // Dead path ?
1672   }
1673 
1674   C2AccessValuePtr addr(adr, NULL);
1675   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1676   if (access.is_raw()) {
1677     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1678   } else {

1736   }
1737 }
1738 
1739 Node* GraphKit::access_atomic_add_at(Node* obj,
1740                                      Node* adr,
1741                                      const TypePtr* adr_type,
1742                                      int alias_idx,
1743                                      Node* new_val,
1744                                      const Type* value_type,
1745                                      BasicType bt,
1746                                      DecoratorSet decorators) {
1747   C2AccessValuePtr addr(adr, adr_type);
1748   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1749   if (access.is_raw()) {
1750     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1751   } else {
1752     return _barrier_set->atomic_add_at(access, new_val, value_type);
1753   }
1754 }
1755 
1756 void GraphKit::access_clone(Node* src_base, Node* dst_base, Node* countx, bool is_array) {
1757   return _barrier_set->clone(this, src_base, dst_base, countx, is_array);
1758 }
1759 
1760 //-------------------------array_element_address-------------------------
1761 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1762                                       const TypeInt* sizetype, Node* ctrl) {
1763   uint shift  = exact_log2(type2aelembytes(elembt));
1764   ciKlass* arytype_klass = _gvn.type(ary)->is_aryptr()->klass();
1765   if (arytype_klass != NULL && arytype_klass->is_flat_array_klass()) {
1766     ciFlatArrayKlass* vak = arytype_klass->as_flat_array_klass();
1767     shift = vak->log2_element_size();
1768   }
1769   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1770 
1771   // short-circuit a common case (saves lots of confusing waste motion)
1772   jint idx_con = find_int_con(idx, -1);
1773   if (idx_con >= 0) {
1774     intptr_t offset = header + ((intptr_t)idx_con << shift);
1775     return basic_plus_adr(ary, offset);
1776   }
1777 
1778   // must be correct type for alignment purposes
1779   Node* base  = basic_plus_adr(ary, header);
1780   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1781   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1782   return basic_plus_adr(ary, base, scale);
1783 }
1784 
1785 //-------------------------load_array_element-------------------------
1786 Node* GraphKit::load_array_element(Node* ctl, Node* ary, Node* idx, const TypeAryPtr* arytype) {
1787   const Type* elemtype = arytype->elem();
1788   BasicType elembt = elemtype->array_element_basic_type();
1789   assert(elembt != T_INLINE_TYPE, "inline types are not supported by this method");
1790   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1791   if (elembt == T_NARROWOOP) {
1792     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1793   }
1794   Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);
1795   return ld;
1796 }
1797 
1798 //-------------------------set_arguments_for_java_call-------------------------
1799 // Arguments (pre-popped from the stack) are taken from the JVMS.
1800 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1801   PreserveReexecuteState preexecs(this);
1802   if (EnableValhalla) {
1803     // Make sure the call is re-executed, if buffering of inline type arguments triggers deoptimization
1804     jvms()->set_should_reexecute(true);
1805     int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1806     inc_sp(arg_size);
1807   }
1808   // Add the call arguments
1809   const TypeTuple* domain = call->tf()->domain_sig();
1810   ExtendedSignature sig_cc = ExtendedSignature(call->method()->get_sig_cc(), SigEntryFilter());
1811   uint nargs = domain->cnt();
1812   for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1813     Node* arg = argument(i-TypeFunc::Parms);
1814     const Type* t = domain->field_at(i);
1815     if (call->method()->has_scalarized_args() && t->is_inlinetypeptr() && !t->maybe_null()) {
1816       // We don't pass inline type arguments by reference but instead pass each field of the inline type
1817       InlineTypeNode* vt = arg->as_InlineType();
1818       vt->pass_fields(this, call, sig_cc, idx);
1819       // If an inline type argument is passed as fields, attach the Method* to the call site
1820       // to be able to access the extended signature later via attached_method_before_pc().
1821       // For example, see CompiledMethod::preserve_callee_argument_oops().
1822       call->set_override_symbolic_info(true);
1823       continue;
1824     } else if (arg->is_InlineType()) {
1825       // Pass inline type argument via oop to callee
1826       arg = arg->as_InlineType()->buffer(this);
1827       if (!is_late_inline) {
1828         arg = arg->as_InlineTypePtr()->get_oop();
1829       }
1830     }
1831     call->init_req(idx++, arg);
1832     // Skip reserved arguments
1833     BasicType bt = t->basic_type();
1834     while (SigEntry::next_is_reserved(sig_cc, bt, true)) {
1835       call->init_req(idx++, top());
1836       if (type2size[bt] == 2) {
1837         call->init_req(idx++, top());
1838       }
1839     }
1840   }
1841 }
1842 
1843 //---------------------------set_edges_for_java_call---------------------------
1844 // Connect a newly created call into the current JVMS.
1845 // A return value node (if any) is returned from set_edges_for_java_call.
1846 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1847 
1848   // Add the predefined inputs:
1849   call->init_req( TypeFunc::Control, control() );
1850   call->init_req( TypeFunc::I_O    , i_o() );
1851   call->init_req( TypeFunc::Memory , reset_memory() );
1852   call->init_req( TypeFunc::FramePtr, frameptr() );
1853   call->init_req( TypeFunc::ReturnAdr, top() );
1854 
1855   add_safepoint_edges(call, must_throw);
1856 
1857   Node* xcall = _gvn.transform(call);
1858 
1859   if (xcall == top()) {
1860     set_control(top());
1861     return;
1862   }
1863   assert(xcall == call, "call identity is stable");
1864 
1865   // Re-use the current map to produce the result.
1866 
1867   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1868   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1869   set_all_memory_call(xcall, separate_io_proj);
1870 
1871   //return xcall;   // no need, caller already has it
1872 }
1873 
1874 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1875   if (stopped())  return top();  // maybe the call folded up?
1876 







1877   // Note:  Since any out-of-line call can produce an exception,
1878   // we always insert an I_O projection from the call into the result.
1879 
1880   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1881 
1882   if (separate_io_proj) {
1883     // The caller requested separate projections be used by the fall
1884     // through and exceptional paths, so replace the projections for
1885     // the fall through path.
1886     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1887     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1888   }
1889 
1890   // Capture the return value, if any.
1891   Node* ret;
1892   if (call->method() == NULL || call->method()->return_type()->basic_type() == T_VOID) {
1893     ret = top();
1894   } else if (call->tf()->returns_inline_type_as_fields()) {
1895     // Return of multiple values (inline type fields): we create a
1896     // InlineType node, each field is a projection from the call.
1897     ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
1898     const Array<SigEntry>* sig_array = vk->extended_sig();
1899     GrowableArray<SigEntry> sig = GrowableArray<SigEntry>(sig_array->length());
1900     sig.appendAll(sig_array);
1901     ExtendedSignature sig_cc = ExtendedSignature(&sig, SigEntryFilter());
1902     uint base_input = TypeFunc::Parms + 1;
1903     ret = InlineTypeNode::make_from_multi(this, call, sig_cc, vk, base_input, false);
1904   } else {
1905     ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1906   }
1907 
1908   return ret;
1909 }
1910 
1911 //--------------------set_predefined_input_for_runtime_call--------------------
1912 // Reading and setting the memory state is way conservative here.
1913 // The real problem is that I am not doing real Type analysis on memory,
1914 // so I cannot distinguish card mark stores from other stores.  Across a GC
1915 // point the Store Barrier and the card mark memory has to agree.  I cannot
1916 // have a card mark store and its barrier split across the GC point from
1917 // either above or below.  Here I get that to happen by reading ALL of memory.
1918 // A better answer would be to separate out card marks from other memory.
1919 // For now, return the input memory state, so that it can be reused
1920 // after the call, if this call has restricted memory effects.
1921 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1922   // Set fixed predefined input arguments
1923   Node* memory = reset_memory();
1924   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1925   call->init_req( TypeFunc::Control,   control()  );
1926   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1927   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs

1978     if (use->is_MergeMem()) {
1979       wl.push(use);
1980     }
1981   }
1982 }
1983 
1984 // Replace the call with the current state of the kit.
1985 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1986   JVMState* ejvms = NULL;
1987   if (has_exceptions()) {
1988     ejvms = transfer_exceptions_into_jvms();
1989   }
1990 
1991   ReplacedNodes replaced_nodes = map()->replaced_nodes();
1992   ReplacedNodes replaced_nodes_exception;
1993   Node* ex_ctl = top();
1994 
1995   SafePointNode* final_state = stop();
1996 
1997   // Find all the needed outputs of this call
1998   CallProjections* callprojs = call->extract_projections(true);

1999 
2000   Unique_Node_List wl;
2001   Node* init_mem = call->in(TypeFunc::Memory);
2002   Node* final_mem = final_state->in(TypeFunc::Memory);
2003   Node* final_ctl = final_state->in(TypeFunc::Control);
2004   Node* final_io = final_state->in(TypeFunc::I_O);
2005 
2006   // Replace all the old call edges with the edges from the inlining result
2007   if (callprojs->fallthrough_catchproj != NULL) {
2008     C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2009   }
2010   if (callprojs->fallthrough_memproj != NULL) {
2011     if (final_mem->is_MergeMem()) {
2012       // Parser's exits MergeMem was not transformed but may be optimized
2013       final_mem = _gvn.transform(final_mem);
2014     }
2015     C->gvn_replace_by(callprojs->fallthrough_memproj,   final_mem);
2016     add_mergemem_users_to_worklist(wl, final_mem);
2017   }
2018   if (callprojs->fallthrough_ioproj != NULL) {
2019     C->gvn_replace_by(callprojs->fallthrough_ioproj,    final_io);
2020   }
2021 
2022   // Replace the result with the new result if it exists and is used
2023   if (callprojs->resproj[0] != NULL && result != NULL) {
2024     assert(callprojs->nb_resproj == 1, "unexpected number of results");
2025     C->gvn_replace_by(callprojs->resproj[0], result);
2026   }
2027 
2028   if (ejvms == NULL) {
2029     // No exception edges to simply kill off those paths
2030     if (callprojs->catchall_catchproj != NULL) {
2031       C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2032     }
2033     if (callprojs->catchall_memproj != NULL) {
2034       C->gvn_replace_by(callprojs->catchall_memproj,   C->top());
2035     }
2036     if (callprojs->catchall_ioproj != NULL) {
2037       C->gvn_replace_by(callprojs->catchall_ioproj,    C->top());
2038     }
2039     // Replace the old exception object with top
2040     if (callprojs->exobj != NULL) {
2041       C->gvn_replace_by(callprojs->exobj, C->top());
2042     }
2043   } else {
2044     GraphKit ekit(ejvms);
2045 
2046     // Load my combined exception state into the kit, with all phis transformed:
2047     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2048     replaced_nodes_exception = ex_map->replaced_nodes();
2049 
2050     Node* ex_oop = ekit.use_exception_state(ex_map);
2051 
2052     if (callprojs->catchall_catchproj != NULL) {
2053       C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2054       ex_ctl = ekit.control();
2055     }
2056     if (callprojs->catchall_memproj != NULL) {
2057       Node* ex_mem = ekit.reset_memory();
2058       C->gvn_replace_by(callprojs->catchall_memproj,   ex_mem);
2059       add_mergemem_users_to_worklist(wl, ex_mem);
2060     }
2061     if (callprojs->catchall_ioproj != NULL) {
2062       C->gvn_replace_by(callprojs->catchall_ioproj,    ekit.i_o());
2063     }
2064 
2065     // Replace the old exception object with the newly created one
2066     if (callprojs->exobj != NULL) {
2067       C->gvn_replace_by(callprojs->exobj, ex_oop);
2068     }
2069   }
2070 
2071   // Disconnect the call from the graph
2072   call->disconnect_inputs(NULL, C);
2073   C->gvn_replace_by(call, C->top());
2074 
2075   // Clean up any MergeMems that feed other MergeMems since the
2076   // optimizer doesn't like that.
2077   while (wl.size() > 0) {
2078     _gvn.transform(wl.pop());
2079   }
2080 
2081   if (callprojs->fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
2082     replaced_nodes.apply(C, final_ctl);
2083   }
2084   if (!ex_ctl->is_top() && do_replaced_nodes) {
2085     replaced_nodes_exception.apply(C, ex_ctl);
2086   }
2087 }
2088 
2089 
2090 //------------------------------increment_counter------------------------------
2091 // for statistics: increment a VM counter by 1
2092 
2093 void GraphKit::increment_counter(address counter_addr) {
2094   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2095   increment_counter(adr1);
2096 }
2097 
2098 void GraphKit::increment_counter(Node* counter_addr) {
2099   int adr_type = Compile::AliasIdxRaw;
2100   Node* ctrl = control();
2101   Node* cnt  = make_load(ctrl, counter_addr, TypeInt::INT, T_INT, adr_type, MemNode::unordered);

2282     speculative = speculative->with_inline_depth(jvms()->depth());
2283   } else if (current_type->would_improve_ptr(ptr_kind)) {
2284     // Profiling report that null was never seen so we can change the
2285     // speculative type to non null ptr.
2286     if (ptr_kind == ProfileAlwaysNull) {
2287       speculative = TypePtr::NULL_PTR;
2288     } else {
2289       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2290       const TypePtr* ptr = TypePtr::NOTNULL;
2291       if (speculative != NULL) {
2292         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2293       } else {
2294         speculative = ptr;
2295       }
2296     }
2297   }
2298 
2299   if (speculative != current_type->speculative()) {
2300     // Build a type with a speculative type (what we think we know
2301     // about the type but will need a guard when we use it)
2302     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2303     // We're changing the type, we need a new CheckCast node to carry
2304     // the new type. The new type depends on the control: what
2305     // profiling tells us is only valid from here as far as we can
2306     // tell.
2307     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2308     cast = _gvn.transform(cast);
2309     replace_in_map(n, cast);
2310     n = cast;
2311   }
2312 
2313   return n;
2314 }
2315 
2316 /**
2317  * Record profiling data from receiver profiling at an invoke with the
2318  * type system so that it can propagate it (speculation)
2319  *
2320  * @param n  receiver node
2321  *
2322  * @return   node with improved type
2323  */
2324 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2325   if (!UseTypeSpeculation) {
2326     return n;
2327   }
2328   ciKlass* exact_kls = profile_has_unique_klass();
2329   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2330   if ((java_bc() == Bytecodes::_checkcast ||
2331        java_bc() == Bytecodes::_instanceof ||
2332        java_bc() == Bytecodes::_aastore) &&
2333       method()->method_data()->is_mature()) {
2334     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2335     if (data != NULL) {
2336       if (java_bc() == Bytecodes::_aastore) {
2337         ciKlass* array_type = NULL;
2338         ciKlass* element_type = NULL;
2339         ProfilePtrKind element_ptr = ProfileMaybeNull;
2340         bool flat_array = true;
2341         bool null_free_array = true;
2342         method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2343         exact_kls = element_type;
2344         ptr_kind = element_ptr;
2345       } else {
2346         if (!data->as_BitData()->null_seen()) {
2347           ptr_kind = ProfileNeverNull;
2348         } else {
2349           assert(data->is_ReceiverTypeData(), "bad profile data type");
2350           ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2351           uint i = 0;
2352           for (; i < call->row_limit(); i++) {
2353             ciKlass* receiver = call->receiver(i);
2354             if (receiver != NULL) {
2355               break;
2356             }
2357           }
2358           ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2359         }

2360       }
2361     }
2362   }
2363   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2364 }
2365 
2366 /**
2367  * Record profiling data from argument profiling at an invoke with the
2368  * type system so that it can propagate it (speculation)
2369  *
2370  * @param dest_method  target method for the call
2371  * @param bc           what invoke bytecode is this?
2372  */
2373 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2374   if (!UseTypeSpeculation) {
2375     return;
2376   }
2377   const TypeFunc* tf    = TypeFunc::make(dest_method);
2378   int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2379   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2380   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2381     const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2382     if (is_reference_type(targ->basic_type())) {
2383       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2384       ciKlass* better_type = NULL;
2385       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2386         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2387       }
2388       i++;
2389     }
2390   }
2391 }
2392 
2393 /**
2394  * Record profiling data from parameter profiling at an invoke with
2395  * the type system so that it can propagate it (speculation)
2396  */
2397 void GraphKit::record_profiled_parameters_for_speculation() {
2398   if (!UseTypeSpeculation) {
2399     return;
2400   }
2401   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {

2432   if (Matcher::strict_fp_requires_explicit_rounding) {
2433     // If a strict caller invokes a non-strict callee, round a double result.
2434     // A non-strict method may return a double value which has an extended exponent,
2435     // but this must not be visible in a caller which is strict.
2436     BasicType result_type = dest_method->return_type()->basic_type();
2437     assert(method() != NULL, "must have caller context");
2438     if( result_type == T_DOUBLE && method()->is_strict() && !dest_method->is_strict() ) {
2439       // Destination method's return value is on top of stack
2440       // dstore_rounding() does gvn.transform
2441       Node *result = pop_pair();
2442       result = dstore_rounding(result);
2443       push_pair(result);
2444     }
2445   }
2446 }
2447 
2448 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2449   if (Matcher::strict_fp_requires_explicit_rounding) {
2450     // (Note:  TypeFunc::make has a cache that makes this fast.)
2451     const TypeFunc* tf    = TypeFunc::make(dest_method);
2452     int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2453     for (int j = 0; j < nargs; j++) {
2454       const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2455       if (targ->basic_type() == T_DOUBLE) {
2456         // If any parameters are doubles, they must be rounded before
2457         // the call, dstore_rounding does gvn.transform
2458         Node *arg = argument(j);
2459         arg = dstore_rounding(arg);
2460         set_argument(j, arg);
2461       }
2462     }
2463   }
2464 }
2465 
2466 // rounding for strict float precision conformance
2467 Node* GraphKit::precision_rounding(Node* n) {
2468   if (Matcher::strict_fp_requires_explicit_rounding) {
2469 #ifdef IA32
2470     if (_method->flags().is_strict() && UseSSE == 0) {
2471       return _gvn.transform(new RoundFloatNode(0, n));
2472     }
2473 #else
2474     Unimplemented();

2914 
2915   // Now do a linear scan of the secondary super-klass array.  Again, no real
2916   // performance impact (too rare) but it's gotta be done.
2917   // Since the code is rarely used, there is no penalty for moving it
2918   // out of line, and it can only improve I-cache density.
2919   // The decision to inline or out-of-line this final check is platform
2920   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2921   Node* psc = gvn.transform(
2922     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2923 
2924   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2925   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2926   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2927 
2928   // Return false path; set default control to true path.
2929   *ctrl = gvn.transform(r_ok_subtype);
2930   return gvn.transform(r_not_subtype);
2931 }
2932 
2933 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2934   const Type* sub_t = _gvn.type(obj_or_subklass);
2935   if (sub_t->isa_inlinetype()) {
2936     obj_or_subklass = makecon(TypeKlassPtr::make(sub_t->inline_klass()));
2937   }
2938   if (ExpandSubTypeCheckAtParseTime) {
2939     MergeMemNode* mem = merged_memory();
2940     Node* ctrl = control();
2941     Node* subklass = obj_or_subklass;
2942     if (!sub_t->isa_klassptr()) {
2943       subklass = load_object_klass(obj_or_subklass);
2944     }

2945     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2946     set_control(ctrl);
2947     return n;
2948   }
2949 

2950   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2951   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2952   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2953   set_control(_gvn.transform(new IfTrueNode(iff)));
2954   return _gvn.transform(new IfFalseNode(iff));
2955 }
2956 
2957 // Profile-driven exact type check:
2958 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2959                                     float prob, Node* *casted_receiver) {
2960   Node* fail = top();
2961   const Type* rec_t = _gvn.type(receiver);
2962   if (false && rec_t->isa_inlinetype()) {
2963     if (klass->equals(rec_t->inline_klass())) {
2964       (*casted_receiver) = receiver; // Always passes
2965     } else {
2966       (*casted_receiver) = top();    // Always fails
2967       fail = control();
2968       set_control(top());
2969     }
2970     return fail;
2971   }
2972   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2973   Node* recv_klass = load_object_klass(receiver);
2974   fail = type_check(recv_klass, tklass, prob);






2975   const TypeOopPtr* recv_xtype = tklass->as_instance_type();
2976   assert(recv_xtype->klass_is_exact(), "");
2977 
2978   // Subsume downstream occurrences of receiver with a cast to
2979   // recv_xtype, since now we know what the type will be.
2980   Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
2981   Node* res = _gvn.transform(cast);
2982   if (recv_xtype->is_inlinetypeptr() && recv_xtype->inline_klass()->is_scalarizable()) {
2983     assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
2984     res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass());
2985   }
2986 
2987   (*casted_receiver) = res;
2988   // (User must make the replace_in_map call.)
2989 
2990   return fail;
2991 }
2992 
2993 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
2994                            float prob) {
2995   Node* want_klass = makecon(tklass);
2996   Node* cmp = _gvn.transform( new CmpPNode(recv_klass, want_klass));
2997   Node* bol = _gvn.transform( new BoolNode(cmp, BoolTest::eq) );
2998   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2999   set_control(  _gvn.transform( new IfTrueNode (iff)));
3000   Node* fail = _gvn.transform( new IfFalseNode(iff));
3001   return fail;
3002 }
3003 
3004 //------------------------------subtype_check_receiver-------------------------
3005 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3006                                        Node** casted_receiver) {
3007   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
3008   Node* want_klass = makecon(tklass);
3009 
3010   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3011 
3012   // Cast receiver after successful check
3013   const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3014   Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
3015   (*casted_receiver) = _gvn.transform(cast);
3016 
3017   return slow_ctl;
3018 }
3019 
3020 //------------------------------seems_never_null-------------------------------
3021 // Use null_seen information if it is available from the profile.
3022 // If we see an unexpected null at a type check we record it and force a
3023 // recompile; the offending check will be recompiled to handle NULLs.
3024 // If we see several offending BCIs, then all checks in the
3025 // method will be recompiled.
3026 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3027   speculating = !_gvn.type(obj)->speculative_maybe_null();
3028   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3029   if (UncommonNullCast               // Cutout for this technique
3030       && obj != null()               // And not the -Xcomp stupid case?
3031       && !too_many_traps(reason)
3032       ) {
3033     if (speculating) {
3034       return true;
3035     }
3036     if (data == NULL)
3037       // Edge case:  no mature data.  Be optimistic here.
3038       return true;
3039     // If the profile has not seen a null, assume it won't happen.
3040     assert(java_bc() == Bytecodes::_checkcast ||
3041            java_bc() == Bytecodes::_instanceof ||
3042            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3043     if (java_bc() == Bytecodes::_aastore) {
3044       return ((ciArrayLoadStoreData*)data->as_ArrayLoadStoreData())->element()->ptr_kind() == ProfileNeverNull;
3045     }
3046     return !data->as_BitData()->null_seen();
3047   }
3048   speculating = false;
3049   return false;
3050 }
3051 
3052 void GraphKit::guard_klass_being_initialized(Node* klass) {
3053   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3054   Node* adr = basic_plus_adr(top(), klass, init_state_off);
3055   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3056                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3057                                     T_BYTE, MemNode::unordered);
3058   init_state = _gvn.transform(init_state);
3059 
3060   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3061 
3062   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3063   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3064 
3065   { BuildCutout unless(this, tst, PROB_MAX);

3105 
3106 //------------------------maybe_cast_profiled_receiver-------------------------
3107 // If the profile has seen exactly one type, narrow to exactly that type.
3108 // Subsequent type checks will always fold up.
3109 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3110                                              ciKlass* require_klass,
3111                                              ciKlass* spec_klass,
3112                                              bool safe_for_replace) {
3113   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
3114 
3115   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
3116 
3117   // Make sure we haven't already deoptimized from this tactic.
3118   if (too_many_traps_or_recompiles(reason))
3119     return NULL;
3120 
3121   // (No, this isn't a call, but it's enough like a virtual call
3122   // to use the same ciMethod accessor to get the profile info...)
3123   // If we have a speculative type use it instead of profiling (which
3124   // may not help us)
3125   ciKlass* exact_kls = spec_klass;
3126   if (exact_kls == NULL) {
3127     if (java_bc() == Bytecodes::_aastore) {
3128       ciKlass* array_type = NULL;
3129       ciKlass* element_type = NULL;
3130       ProfilePtrKind element_ptr = ProfileMaybeNull;
3131       bool flat_array = true;
3132       bool null_free_array = true;
3133       method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3134       exact_kls = element_type;
3135     } else {
3136       exact_kls = profile_has_unique_klass();
3137     }
3138   }
3139   if (exact_kls != NULL) {// no cast failures here
3140     if (require_klass == NULL ||
3141         C->static_subtype_check(require_klass, exact_kls) == Compile::SSC_always_true) {
3142       // If we narrow the type to match what the type profile sees or
3143       // the speculative type, we can then remove the rest of the
3144       // cast.
3145       // This is a win, even if the exact_kls is very specific,
3146       // because downstream operations, such as method calls,
3147       // will often benefit from the sharper type.
3148       Node* exact_obj = not_null_obj; // will get updated in place...
3149       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3150                                             &exact_obj);
3151       { PreserveJVMState pjvms(this);
3152         set_control(slow_ctl);
3153         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3154       }
3155       if (safe_for_replace) {
3156         replace_in_map(not_null_obj, exact_obj);
3157       }
3158       return exact_obj;

3223 // and the reflective instance-of call.
3224 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3225   kill_dead_locals();           // Benefit all the uncommon traps
3226   assert( !stopped(), "dead parse path should be checked in callers" );
3227   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3228          "must check for not-null not-dead klass in callers");
3229 
3230   // Make the merge point
3231   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3232   RegionNode* region = new RegionNode(PATH_LIMIT);
3233   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3234   C->set_has_split_ifs(true); // Has chance for split-if optimization
3235 
3236   ciProfileData* data = NULL;
3237   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3238     data = method()->method_data()->bci_to_data(bci());
3239   }
3240   bool speculative_not_null = false;
3241   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3242                          && seems_never_null(obj, data, speculative_not_null));
3243   bool is_value = obj->is_InlineType();
3244 
3245   // Null check; get casted pointer; set region slot 3
3246   Node* null_ctl = top();
3247   Node* not_null_obj = is_value ? obj : null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3248 
3249   // If not_null_obj is dead, only null-path is taken
3250   if (stopped()) {              // Doing instance-of on a NULL?
3251     set_control(null_ctl);
3252     return intcon(0);
3253   }
3254   region->init_req(_null_path, null_ctl);
3255   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3256   if (null_ctl == top()) {
3257     // Do this eagerly, so that pattern matches like is_diamond_phi
3258     // will work even during parsing.
3259     assert(_null_path == PATH_LIMIT-1, "delete last");
3260     region->del_req(_null_path);
3261     phi   ->del_req(_null_path);
3262   }
3263 
3264   // Do we know the type check always succeed?
3265   if (!is_value) {
3266     bool known_statically = false;
3267     if (_gvn.type(superklass)->singleton()) {
3268       ciKlass* superk = _gvn.type(superklass)->is_klassptr()->klass();
3269       ciKlass* subk = _gvn.type(obj)->is_oopptr()->klass();
3270       if (subk != NULL && subk->is_loaded()) {
3271         int static_res = C->static_subtype_check(superk, subk);
3272         known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3273       }
3274     }
3275 
3276     if (!known_statically) {
3277       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3278       // We may not have profiling here or it may not help us. If we
3279       // have a speculative type use it to perform an exact cast.
3280       ciKlass* spec_obj_type = obj_type->speculative_type();
3281       if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3282         Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3283         if (stopped()) {            // Profile disagrees with this path.
3284           set_control(null_ctl);    // Null is the only remaining possibility.
3285           return intcon(0);
3286         }
3287         if (cast_obj != NULL &&
3288             // A value that's sometimes null is not something we can optimize well
3289             !(cast_obj->is_InlineType() && null_ctl != top())) {
3290           not_null_obj = cast_obj;
3291           is_value = not_null_obj->is_InlineType();
3292         }
3293       }
3294     }
3295   }
3296 
3297   // Generate the subtype check
3298   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3299 
3300   // Plug in the success path to the general merge in slot 1.
3301   region->init_req(_obj_path, control());
3302   phi   ->init_req(_obj_path, intcon(1));
3303 
3304   // Plug in the failing path to the general merge in slot 2.
3305   region->init_req(_fail_path, not_subtype_ctrl);
3306   phi   ->init_req(_fail_path, intcon(0));
3307 
3308   // Return final merged results
3309   set_control( _gvn.transform(region) );
3310   record_for_igvn(region);
3311 
3312   // If we know the type check always succeeds then we don't use the
3313   // profiling data at this bytecode. Don't lose it, feed it to the
3314   // type system as a speculative type.
3315   if (safe_for_replace && !is_value) {
3316     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3317     replace_in_map(obj, casted_obj);
3318   }
3319 
3320   return _gvn.transform(phi);
3321 }
3322 
3323 //-------------------------------gen_checkcast---------------------------------
3324 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3325 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3326 // uncommon-trap paths work.  Adjust stack after this call.
3327 // If failure_control is supplied and not null, it is filled in with
3328 // the control edge for the cast failure.  Otherwise, an appropriate
3329 // uncommon trap or exception is thrown.
3330 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass, Node* *failure_control) {

3331   kill_dead_locals();           // Benefit all the uncommon traps
3332   const TypeKlassPtr* tk = _gvn.type(superklass)->is_klassptr();
3333   const TypeOopPtr* toop = TypeOopPtr::make_from_klass(tk->klass());
3334 
3335   // Check if inline types are involved
3336   bool from_inline = obj->is_InlineType();
3337   bool to_inline = tk->klass()->is_inlinetype();
3338 
3339   // Fast cutout:  Check the case that the cast is vacuously true.
3340   // This detects the common cases where the test will short-circuit
3341   // away completely.  We do this before we perform the null check,
3342   // because if the test is going to turn into zero code, we don't
3343   // want a residual null check left around.  (Causes a slowdown,
3344   // for example, in some objArray manipulations, such as a[i]=a[j].)
3345   if (tk->singleton()) {
3346     ciKlass* klass = NULL;
3347     if (from_inline) {
3348       klass = _gvn.type(obj)->inline_klass();
3349     } else {
3350       const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3351       if (objtp != NULL) {
3352         klass = objtp->klass();
3353       }
3354     }
3355     if (klass != NULL) {
3356       switch (C->static_subtype_check(tk->klass(), klass)) {
3357       case Compile::SSC_always_true:
3358         // If we know the type check always succeed then we don't use
3359         // the profiling data at this bytecode. Don't lose it, feed it
3360         // to the type system as a speculative type.
3361         if (!from_inline) {
3362           obj = record_profiled_receiver_for_speculation(obj);
3363           if (to_inline) {
3364             obj = null_check(obj);
3365             if (toop->inline_klass()->is_scalarizable()) {
3366               obj = InlineTypeNode::make_from_oop(this, obj, toop->inline_klass());
3367             }
3368           }
3369         }
3370         return obj;
3371       case Compile::SSC_always_false:
3372         if (from_inline || to_inline) {
3373           if (!from_inline) {
3374             null_check(obj);
3375           }
3376           // Inline type is never null. Always throw an exception.
3377           builtin_throw(Deoptimization::Reason_class_check, makecon(TypeKlassPtr::make(klass)));
3378           return top();
3379         } else {
3380           // It needs a null check because a null will *pass* the cast check.
3381           return null_assert(obj);
3382         }
3383       }
3384     }
3385   }
3386 
3387   ciProfileData* data = NULL;
3388   bool safe_for_replace = false;
3389   if (failure_control == NULL) {        // use MDO in regular case only
3390     assert(java_bc() == Bytecodes::_aastore ||
3391            java_bc() == Bytecodes::_checkcast,
3392            "interpreter profiles type checks only for these BCs");
3393     if (method()->method_data()->is_mature()) {
3394       data = method()->method_data()->bci_to_data(bci());
3395     }
3396     safe_for_replace = true;
3397   }
3398 
3399   // Make the merge point
3400   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3401   RegionNode* region = new RegionNode(PATH_LIMIT);
3402   Node*       phi    = new PhiNode(region, toop);
3403   _gvn.set_type(region, Type::CONTROL);
3404   _gvn.set_type(phi, toop);
3405 
3406   C->set_has_split_ifs(true); // Has chance for split-if optimization
3407 
3408   // Use null-cast information if it is available
3409   bool speculative_not_null = false;
3410   bool never_see_null = ((failure_control == NULL)  // regular case only
3411                          && seems_never_null(obj, data, speculative_not_null));
3412 
3413   // Null check; get casted pointer; set region slot 3
3414   Node* null_ctl = top();
3415   Node* not_null_obj = NULL;
3416   if (from_inline) {
3417     not_null_obj = obj;
3418   } else if (to_inline) {
3419     not_null_obj = null_check(obj);
3420   } else {
3421     not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3422   }
3423 
3424   // If not_null_obj is dead, only null-path is taken
3425   if (stopped()) {              // Doing instance-of on a NULL?
3426     set_control(null_ctl);
3427     return null();
3428   }
3429   region->init_req(_null_path, null_ctl);
3430   phi   ->init_req(_null_path, null());  // Set null path value
3431   if (null_ctl == top()) {
3432     // Do this eagerly, so that pattern matches like is_diamond_phi
3433     // will work even during parsing.
3434     assert(_null_path == PATH_LIMIT-1, "delete last");
3435     region->del_req(_null_path);
3436     phi   ->del_req(_null_path);
3437   }
3438 
3439   Node* cast_obj = NULL;
3440   if (!from_inline && tk->klass_is_exact()) {
3441     // The following optimization tries to statically cast the speculative type of the object
3442     // (for example obtained during profiling) to the type of the superklass and then do a
3443     // dynamic check that the type of the object is what we expect. To work correctly
3444     // for checkcast and aastore the type of superklass should be exact.
3445     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3446     // We may not have profiling here or it may not help us. If we have
3447     // a speculative type use it to perform an exact cast.
3448     ciKlass* spec_obj_type = obj_type->speculative_type();
3449     if (spec_obj_type != NULL || data != NULL) {
3450       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk->klass(), spec_obj_type, safe_for_replace);
3451       if (cast_obj != NULL && cast_obj->is_InlineType()) {
3452         if (null_ctl != top()) {
3453           cast_obj = NULL; // A value that's sometimes null is not something we can optimize well
3454         } else {
3455           return cast_obj;
3456         }
3457       }
3458       if (cast_obj != NULL) {
3459         if (failure_control != NULL) // failure is now impossible
3460           (*failure_control) = top();
3461         // adjust the type of the phi to the exact klass:
3462         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3463       }
3464     }
3465   }
3466 
3467   if (cast_obj == NULL) {
3468     // Generate the subtype check
3469     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3470 
3471     // Plug in success path into the merge
3472     cast_obj = from_inline ? not_null_obj : _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3473     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3474     if (failure_control == NULL) {
3475       if (not_subtype_ctrl != top()) { // If failure is possible
3476         PreserveJVMState pjvms(this);
3477         set_control(not_subtype_ctrl);
3478         Node* obj_klass = NULL;
3479         if (from_inline) {
3480           obj_klass = makecon(TypeKlassPtr::make(_gvn.type(not_null_obj)->inline_klass()));
3481         } else {
3482           obj_klass = load_object_klass(not_null_obj);
3483         }
3484         builtin_throw(Deoptimization::Reason_class_check, obj_klass);
3485       }
3486     } else {
3487       (*failure_control) = not_subtype_ctrl;
3488     }
3489   }
3490 
3491   region->init_req(_obj_path, control());
3492   phi   ->init_req(_obj_path, cast_obj);
3493 
3494   // A merge of NULL or Casted-NotNull obj
3495   Node* res = _gvn.transform(phi);
3496 
3497   // Note I do NOT always 'replace_in_map(obj,result)' here.
3498   //  if( tk->klass()->can_be_primary_super()  )
3499     // This means that if I successfully store an Object into an array-of-String
3500     // I 'forget' that the Object is really now known to be a String.  I have to
3501     // do this because we don't have true union types for interfaces - if I store
3502     // a Baz into an array-of-Interface and then tell the optimizer it's an
3503     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3504     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3505   //  replace_in_map( obj, res );
3506 
3507   // Return final merged results
3508   set_control( _gvn.transform(region) );
3509   record_for_igvn(region);
3510 
3511   bool not_inline = !toop->can_be_inline_type();
3512   bool not_flattened = !UseFlatArray || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->flatten_array());
3513   if (EnableValhalla && not_flattened) {
3514     // Check if obj has been loaded from an array
3515     obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3516     Node* array = NULL;
3517     if (obj->isa_Load()) {
3518       Node* address = obj->in(MemNode::Address);
3519       if (address->isa_AddP()) {
3520         array = address->as_AddP()->in(AddPNode::Base);
3521       }
3522     } else if (obj->is_Phi()) {
3523       Node* region = obj->in(0);
3524       // TODO make this more robust (see JDK-8231346)
3525       if (region->req() == 3 && region->in(2) != NULL && region->in(2)->in(0) != NULL) {
3526         IfNode* iff = region->in(2)->in(0)->isa_If();
3527         if (iff != NULL) {
3528           iff->is_non_flattened_array_check(&_gvn, &array);
3529         }
3530       }
3531     }
3532     if (array != NULL) {
3533       const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3534       if (ary_t != NULL) {
3535         if (!ary_t->is_not_null_free() && not_inline) {
3536           // Casting array element to a non-inline-type, mark array as not null-free.
3537           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3538           replace_in_map(array, cast);
3539         } else if (!ary_t->is_not_flat()) {
3540           // Casting array element to a non-flattened type, mark array as not flat.
3541           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3542           replace_in_map(array, cast);
3543         }
3544       }
3545     }
3546   }
3547 
3548   if (!from_inline) {
3549     res = record_profiled_receiver_for_speculation(res);
3550     if (to_inline && toop->inline_klass()->is_scalarizable()) {
3551       assert(!gvn().type(res)->maybe_null(), "Inline types are null-free");
3552       res = InlineTypeNode::make_from_oop(this, res, toop->inline_klass());
3553     }
3554   }
3555   return res;
3556 }
3557 
3558 // Check if 'obj' is an inline type by checking if it has the always_locked markWord pattern set.
3559 Node* GraphKit::is_inline_type(Node* obj) {
3560   Node* mark_addr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3561   Node* mark = make_load(NULL, mark_addr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3562   Node* mask = _gvn.MakeConX(markWord::always_locked_pattern);
3563   Node* andx = _gvn.transform(new AndXNode(mark, mask));
3564   Node* cmp = _gvn.transform(new CmpXNode(andx, mask));
3565   return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3566 }
3567 
3568 // Check if 'ary' is a non-flattened array
3569 Node* GraphKit::is_non_flattened_array(Node* ary) {
3570   Node* kls = load_object_klass(ary);
3571   Node* tag = load_lh_array_tag(kls);
3572   Node* cmp = gen_lh_array_test(kls, Klass::_lh_array_tag_vt_value);
3573   return _gvn.transform(new BoolNode(cmp, BoolTest::ne));
3574 }
3575 
3576 // Check if 'ary' is a nullable array
3577 Node* GraphKit::is_nullable_array(Node* ary) {
3578   Node* kls = load_object_klass(ary);
3579   Node* lhp = basic_plus_adr(kls, in_bytes(Klass::layout_helper_offset()));
3580   Node* layout_val = _gvn.transform(LoadNode::make(_gvn, NULL, immutable_memory(), lhp, lhp->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
3581   Node* null_free = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_null_free_shift)));
3582   null_free = _gvn.transform(new AndINode(null_free, intcon(Klass::_lh_null_free_mask)));
3583   Node* cmp = _gvn.transform(new CmpINode(null_free, intcon(0)));
3584   return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3585 }
3586 
3587 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3588 Node* GraphKit::gen_inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3589   const Type* val_t = _gvn.type(val);
3590   if (val->is_InlineType() || !TypePtr::NULL_PTR->higher_equal(val_t)) {
3591     return ary; // Never null
3592   }
3593   RegionNode* region = new RegionNode(3);
3594   Node* null_ctl = top();
3595   null_check_oop(val, &null_ctl);
3596   if (null_ctl != top()) {
3597     PreserveJVMState pjvms(this);
3598     set_control(null_ctl);
3599     {
3600       // Deoptimize if null-free array
3601       BuildCutout unless(this, is_nullable_array(ary), PROB_MAX);
3602       inc_sp(nargs);
3603       uncommon_trap(Deoptimization::Reason_null_check,
3604                     Deoptimization::Action_none);
3605     }
3606     region->init_req(1, control());
3607   }
3608   region->init_req(2, control());
3609   set_control(_gvn.transform(region));
3610   record_for_igvn(region);
3611   const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3612   if (val_t == TypePtr::NULL_PTR && !ary_t->is_not_null_free()) {
3613     // Since we were just successfully storing null, the array can't be null free.
3614     ary_t = ary_t->cast_to_not_null_free();
3615     Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3616     if (safe_for_replace) {
3617       replace_in_map(ary, cast);
3618     }
3619     ary = cast;
3620   }
3621   return ary;
3622 }
3623 
3624 Node* GraphKit::load_lh_array_tag(Node* kls) {
3625   Node* lhp = basic_plus_adr(kls, in_bytes(Klass::layout_helper_offset()));
3626   Node* layout_val = _gvn.transform(LoadNode::make(_gvn, NULL, immutable_memory(), lhp, lhp->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
3627   return _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_array_tag_shift)));
3628 }
3629 
3630 Node* GraphKit::gen_lh_array_test(Node* kls, unsigned int lh_value) {
3631   Node* layout_val = load_lh_array_tag(kls);
3632   Node* cmp = _gvn.transform(new CmpINode(layout_val, intcon(lh_value)));
3633   return cmp;
3634 }
3635 
3636 //------------------------------next_monitor-----------------------------------
3637 // What number should be given to the next monitor?
3638 int GraphKit::next_monitor() {
3639   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3640   int next = current + C->sync_stack_slots();
3641   // Keep the toplevel high water mark current:
3642   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3643   return current;
3644 }
3645 
3646 //------------------------------insert_mem_bar---------------------------------
3647 // Memory barrier to avoid floating things around
3648 // The membar serves as a pinch point between both control and all memory slices.
3649 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3650   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3651   mb->init_req(TypeFunc::Control, control());
3652   mb->init_req(TypeFunc::Memory,  reset_memory());
3653   Node* membar = _gvn.transform(mb);

3681   }
3682   Node* membar = _gvn.transform(mb);
3683   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3684   if (alias_idx == Compile::AliasIdxBot) {
3685     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3686   } else {
3687     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3688   }
3689   return membar;
3690 }
3691 
3692 //------------------------------shared_lock------------------------------------
3693 // Emit locking code.
3694 FastLockNode* GraphKit::shared_lock(Node* obj) {
3695   // bci is either a monitorenter bc or InvocationEntryBci
3696   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3697   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3698 
3699   if( !GenerateSynchronizationCode )
3700     return NULL;                // Not locking things?
3701 
3702   if (stopped())                // Dead monitor?
3703     return NULL;
3704 
3705   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3706 
3707   // Box the stack location
3708   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3709   Node* mem = reset_memory();
3710 
3711   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3712   if (UseBiasedLocking && PrintPreciseBiasedLockingStatistics) {
3713     // Create the counters for this fast lock.
3714     flock->create_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3715   }
3716 
3717   // Create the rtm counters for this fast lock if needed.
3718   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3719 
3720   // Add monitor to debug info for the slow path.  If we block inside the
3721   // slow path and de-opt, we need the monitor hanging around

3754   }
3755 #endif
3756 
3757   return flock;
3758 }
3759 
3760 
3761 //------------------------------shared_unlock----------------------------------
3762 // Emit unlocking code.
3763 void GraphKit::shared_unlock(Node* box, Node* obj) {
3764   // bci is either a monitorenter bc or InvocationEntryBci
3765   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3766   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3767 
3768   if( !GenerateSynchronizationCode )
3769     return;
3770   if (stopped()) {               // Dead monitor?
3771     map()->pop_monitor();        // Kill monitor from debug info
3772     return;
3773   }
3774   assert(!obj->is_InlineTypeBase(), "should not unlock on inline type");
3775 
3776   // Memory barrier to avoid floating things down past the locked region
3777   insert_mem_bar(Op_MemBarReleaseLock);
3778 
3779   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3780   UnlockNode *unlock = new UnlockNode(C, tf);
3781 #ifdef ASSERT
3782   unlock->set_dbg_jvms(sync_jvms());
3783 #endif
3784   uint raw_idx = Compile::AliasIdxRaw;
3785   unlock->init_req( TypeFunc::Control, control() );
3786   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3787   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3788   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3789   unlock->init_req( TypeFunc::ReturnAdr, top() );
3790 
3791   unlock->init_req(TypeFunc::Parms + 0, obj);
3792   unlock->init_req(TypeFunc::Parms + 1, box);
3793   unlock = _gvn.transform(unlock)->as_Unlock();
3794 
3795   Node* mem = reset_memory();
3796 
3797   // unlock has no side-effects, sets few values
3798   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3799 
3800   // Kill monitor from debug info
3801   map()->pop_monitor( );
3802 }
3803 
3804 //-------------------------------get_layout_helper-----------------------------
3805 // If the given klass is a constant or known to be an array,
3806 // fetch the constant layout helper value into constant_value
3807 // and return (Node*)NULL.  Otherwise, load the non-constant
3808 // layout helper value, and return the node which represents it.
3809 // This two-faced routine is useful because allocation sites
3810 // almost always feature constant types.
3811 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3812   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3813   if (!StressReflectiveCode && inst_klass != NULL) {
3814     ciKlass* klass = inst_klass->klass();
3815     assert(klass != NULL, "klass should not be NULL");
3816     bool    xklass = inst_klass->klass_is_exact();
3817     bool can_be_flattened = false;
3818     if (UseFlatArray && klass->is_obj_array_klass()) {
3819       ciKlass* elem = klass->as_obj_array_klass()->element_klass();
3820       can_be_flattened = elem->can_be_inline_klass() && (!elem->is_inlinetype() || elem->flatten_array());
3821     }
3822     if (xklass || (klass->is_array_klass() && !can_be_flattened)) {
3823       jint lhelper = klass->layout_helper();
3824       if (lhelper != Klass::_lh_neutral_value) {
3825         constant_value = lhelper;
3826         return (Node*) NULL;
3827       }
3828     }
3829   }
3830   constant_value = Klass::_lh_neutral_value;  // put in a known value
3831   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3832   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3833 }
3834 
3835 // We just put in an allocate/initialize with a big raw-memory effect.
3836 // Hook selected additional alias categories on the initialization.
3837 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3838                                 MergeMemNode* init_in_merge,
3839                                 Node* init_out_raw) {
3840   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3841   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3842 

3864 
3865   // a normal slow-call doesn't change i_o, but an allocation does
3866   // we create a separate i_o projection for the normal control path
3867   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3868   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3869 
3870   // put in an initialization barrier
3871   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3872                                                  rawoop)->as_Initialize();
3873   assert(alloc->initialization() == init,  "2-way macro link must work");
3874   assert(init ->allocation()     == alloc, "2-way macro link must work");
3875   {
3876     // Extract memory strands which may participate in the new object's
3877     // initialization, and source them from the new InitializeNode.
3878     // This will allow us to observe initializations when they occur,
3879     // and link them properly (as a group) to the InitializeNode.
3880     assert(init->in(InitializeNode::Memory) == malloc, "");
3881     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3882     init->set_req(InitializeNode::Memory, minit_in);
3883     record_for_igvn(minit_in); // fold it up later, if possible
3884     _gvn.set_type(minit_in, Type::MEMORY);
3885     Node* minit_out = memory(rawidx);
3886     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3887     // Add an edge in the MergeMem for the header fields so an access
3888     // to one of those has correct memory state
3889     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3890     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3891     if (oop_type->isa_aryptr()) {
3892       const TypeAryPtr* arytype = oop_type->is_aryptr();
3893       if (arytype->klass()->is_flat_array_klass()) {
3894         // Initially all flattened array accesses share a single slice
3895         // but that changes after parsing. Prepare the memory graph so
3896         // it can optimize flattened array accesses properly once they
3897         // don't share a single slice.
3898         assert(C->flattened_accesses_share_alias(), "should be set at parse time");
3899         C->set_flattened_accesses_share_alias(false);
3900         ciFlatArrayKlass* vak = arytype->klass()->as_flat_array_klass();
3901         ciInlineKlass* vk = vak->element_klass()->as_inline_klass();
3902         for (int i = 0, len = vk->nof_nonstatic_fields(); i < len; i++) {
3903           ciField* field = vk->nonstatic_field_at(i);
3904           if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3905             continue;  // do not bother to track really large numbers of fields
3906           int off_in_vt = field->offset() - vk->first_field_offset();
3907           const TypePtr* adr_type = arytype->with_field_offset(off_in_vt)->add_offset(Type::OffsetBot);
3908           int fieldidx = C->get_alias_index(adr_type, true);
3909           hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3910         }
3911         C->set_flattened_accesses_share_alias(true);
3912         hook_memory_on_init(*this, C->get_alias_index(TypeAryPtr::INLINES), minit_in, minit_out);
3913       } else {
3914         const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3915         int            elemidx  = C->get_alias_index(telemref);
3916         hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3917       }
3918     } else if (oop_type->isa_instptr()) {
3919       set_memory(minit_out, C->get_alias_index(oop_type)); // mark word
3920       ciInstanceKlass* ik = oop_type->klass()->as_instance_klass();
3921       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3922         ciField* field = ik->nonstatic_field_at(i);
3923         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3924           continue;  // do not bother to track really large numbers of fields
3925         // Find (or create) the alias category for this field:
3926         int fieldidx = C->alias_type(field)->index();
3927         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3928       }
3929     }
3930   }
3931 
3932   // Cast raw oop to the real thing...
3933   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3934   javaoop = _gvn.transform(javaoop);
3935   C->set_recent_alloc(control(), javaoop);
3936   assert(just_allocated_object(control()) == javaoop, "just allocated");
3937 
3938 #ifdef ASSERT
3939   { // Verify that the AllocateNode::Ideal_allocation recognizers work:

3950       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3951     }
3952   }
3953 #endif //ASSERT
3954 
3955   return javaoop;
3956 }
3957 
3958 //---------------------------new_instance--------------------------------------
3959 // This routine takes a klass_node which may be constant (for a static type)
3960 // or may be non-constant (for reflective code).  It will work equally well
3961 // for either, and the graph will fold nicely if the optimizer later reduces
3962 // the type to a constant.
3963 // The optional arguments are for specialized use by intrinsics:
3964 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3965 //  - If 'return_size_val', report the the total object size to the caller.
3966 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3967 Node* GraphKit::new_instance(Node* klass_node,
3968                              Node* extra_slow_test,
3969                              Node* *return_size_val,
3970                              bool deoptimize_on_exception,
3971                              InlineTypeBaseNode* inline_type_node) {
3972   // Compute size in doublewords
3973   // The size is always an integral number of doublewords, represented
3974   // as a positive bytewise size stored in the klass's layout_helper.
3975   // The layout_helper also encodes (in a low bit) the need for a slow path.
3976   jint  layout_con = Klass::_lh_neutral_value;
3977   Node* layout_val = get_layout_helper(klass_node, layout_con);
3978   bool  layout_is_con = (layout_val == NULL);
3979 
3980   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
3981   // Generate the initial go-slow test.  It's either ALWAYS (return a
3982   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3983   // case) a computed value derived from the layout_helper.
3984   Node* initial_slow_test = NULL;
3985   if (layout_is_con) {
3986     assert(!StressReflectiveCode, "stress mode does not use these paths");
3987     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3988     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3989   } else {   // reflective case
3990     // This reflective path is used by Unsafe.allocateInstance.
3991     // (It may be stress-tested by specifying StressReflectiveCode.)
3992     // Basically, we want to get into the VM is there's an illegal argument.
3993     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3994     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3995     if (extra_slow_test != intcon(0)) {
3996       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3997     }
3998     // (Macro-expander will further convert this to a Bool, if necessary.)

4009 
4010     // Clear the low bits to extract layout_helper_size_in_bytes:
4011     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4012     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4013     size = _gvn.transform( new AndXNode(size, mask) );
4014   }
4015   if (return_size_val != NULL) {
4016     (*return_size_val) = size;
4017   }
4018 
4019   // This is a precise notnull oop of the klass.
4020   // (Actually, it need not be precise if this is a reflective allocation.)
4021   // It's what we cast the result to.
4022   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4023   if (!tklass)  tklass = TypeKlassPtr::OBJECT;
4024   const TypeOopPtr* oop_type = tklass->as_instance_type();
4025 
4026   // Now generate allocation code
4027 
4028   // The entire memory state is needed for slow path of the allocation
4029   // since GC and deoptimization can happen.
4030   Node *mem = reset_memory();
4031   set_all_memory(mem); // Create new memory state
4032 
4033   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4034                                          control(), mem, i_o(),
4035                                          size, klass_node,
4036                                          initial_slow_test, inline_type_node);
4037 
4038   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4039 }
4040 
4041 // With compressed oops, the 64 bit init value for non flattened value
4042 // arrays is built from 2 32 bit compressed oops
4043 static Node* raw_default_for_coops(Node* default_value, GraphKit& kit) {
4044   Node* lower = kit.gvn().transform(new CastP2XNode(kit.control(), default_value));
4045   Node* upper = kit.gvn().transform(new LShiftLNode(lower, kit.intcon(32)));
4046   return kit.gvn().transform(new OrLNode(lower, upper));
4047 }
4048 
4049 //-------------------------------new_array-------------------------------------
4050 // helper for newarray and anewarray
4051 // The 'length' parameter is (obviously) the length of the array.
4052 // See comments on new_instance for the meaning of the other arguments.
4053 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
4054                           Node* length,         // number of array elements
4055                           int   nargs,          // number of arguments to push back for uncommon trap
4056                           Node* *return_size_val,
4057                           bool deoptimize_on_exception) {
4058   jint  layout_con = Klass::_lh_neutral_value;
4059   Node* layout_val = get_layout_helper(klass_node, layout_con);
4060   bool  layout_is_con = (layout_val == NULL);
4061 
4062   if (!layout_is_con && !StressReflectiveCode &&
4063       !too_many_traps(Deoptimization::Reason_class_check)) {
4064     // This is a reflective array creation site.
4065     // Optimistically assume that it is a subtype of Object[],
4066     // so that we can fold up all the address arithmetic.
4067     layout_con = Klass::array_layout_helper(T_OBJECT);
4068     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4069     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4070     { BuildCutout unless(this, bol_lh, PROB_MAX);
4071       inc_sp(nargs);
4072       uncommon_trap(Deoptimization::Reason_class_check,
4073                     Deoptimization::Action_maybe_recompile);
4074     }
4075     layout_val = NULL;
4076     layout_is_con = true;
4077   }
4078 
4079   // Generate the initial go-slow test.  Make sure we do not overflow
4080   // if length is huge (near 2Gig) or negative!  We do not need
4081   // exact double-words here, just a close approximation of needed
4082   // double-words.  We can't add any offset or rounding bits, lest we
4083   // take a size -1 of bytes and make it positive.  Use an unsigned
4084   // compare, so negative sizes look hugely positive.
4085   int fast_size_limit = FastAllocateSizeLimit;
4086   if (layout_is_con) {
4087     assert(!StressReflectiveCode, "stress mode does not use these paths");
4088     // Increase the size limit if we have exact knowledge of array type.
4089     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4090     fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4091   }
4092 
4093   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4094   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4095 
4096   // --- Size Computation ---
4097   // array_size = round_to_heap(array_header + (length << elem_shift));
4098   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4099   // and align_to(x, y) == ((x + y-1) & ~(y-1))
4100   // The rounding mask is strength-reduced, if possible.
4101   int round_mask = MinObjAlignmentInBytes - 1;
4102   Node* header_size = NULL;
4103   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4104   // (T_BYTE has the weakest alignment and size restrictions...)
4105   if (layout_is_con) {
4106     int       hsize  = Klass::layout_helper_header_size(layout_con);
4107     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
4108     bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4109     if ((round_mask & ~right_n_bits(eshift)) == 0)
4110       round_mask = 0;  // strength-reduce it if it goes away completely
4111     assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4112     assert(header_size_min <= hsize, "generic minimum is smallest");
4113     header_size_min = hsize;
4114     header_size = intcon(hsize + round_mask);
4115   } else {
4116     Node* hss   = intcon(Klass::_lh_header_size_shift);
4117     Node* hsm   = intcon(Klass::_lh_header_size_mask);
4118     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
4119     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
4120     Node* mask  = intcon(round_mask);
4121     header_size = _gvn.transform( new AddINode(hsize, mask) );
4122   }
4123 
4124   Node* elem_shift = NULL;
4125   if (layout_is_con) {
4126     int eshift = Klass::layout_helper_log2_element_size(layout_con);
4127     if (eshift != 0)
4128       elem_shift = intcon(eshift);
4129   } else {
4130     // There is no need to mask or shift this value.
4131     // The semantics of LShiftINode include an implicit mask to 0x1F.

4175   // places, one where the length is sharply limited, and the other
4176   // after a successful allocation.
4177   Node* abody = lengthx;
4178   if (elem_shift != NULL)
4179     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
4180   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
4181   if (round_mask != 0) {
4182     Node* mask = MakeConX(~round_mask);
4183     size       = _gvn.transform( new AndXNode(size, mask) );
4184   }
4185   // else if round_mask == 0, the size computation is self-rounding
4186 
4187   if (return_size_val != NULL) {
4188     // This is the size
4189     (*return_size_val) = size;
4190   }
4191 
4192   // Now generate allocation code
4193 
4194   // The entire memory state is needed for slow path of the allocation
4195   // since GC and deoptimization can happen.
4196   Node *mem = reset_memory();
4197   set_all_memory(mem); // Create new memory state
4198 
4199   if (initial_slow_test->is_Bool()) {
4200     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4201     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4202   }
4203 
4204   const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4205   const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4206   const TypeAryPtr* ary_ptr = ary_type->isa_aryptr();
4207 
4208   // Inline type array variants:
4209   // - null-ok:              MyValue.ref[] (ciObjArrayKlass "[LMyValue$ref")
4210   // - null-free:            MyValue.val[] (ciObjArrayKlass "[QMyValue$val")
4211   // - null-free, flattened: MyValue.val[] (ciFlatArrayKlass "[QMyValue$val")
4212   // Check if array is a null-free, non-flattened inline type array
4213   // that needs to be initialized with the default inline type.
4214   Node* default_value = NULL;
4215   Node* raw_default_value = NULL;
4216   if (ary_ptr != NULL && ary_ptr->klass_is_exact()) {
4217     // Array type is known
4218     ciKlass* elem_klass = ary_ptr->klass()->as_array_klass()->element_klass();
4219     if (elem_klass != NULL && elem_klass->is_inlinetype()) {
4220       ciInlineKlass* vk = elem_klass->as_inline_klass();
4221       if (!vk->flatten_array()) {
4222         default_value = InlineTypeNode::default_oop(gvn(), vk);
4223         if (UseCompressedOops) {
4224           default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop()));
4225           raw_default_value = raw_default_for_coops(default_value, *this);
4226         } else {
4227           raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value));
4228         }
4229       }
4230     }
4231   } else if (ary_klass->klass()->can_be_inline_array_klass()) {
4232     // Array type is not known, add runtime checks
4233     assert(!ary_klass->klass_is_exact(), "unexpected exact type");
4234     Node* r = new RegionNode(4);
4235     default_value = new PhiNode(r, TypeInstPtr::BOTTOM);
4236 
4237     // Check if array is an object array
4238     Node* cmp = gen_lh_array_test(klass_node, Klass::_lh_array_tag_obj_value);
4239     Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
4240     IfNode* iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4241 
4242     // Not an object array, initialize with all zero
4243     r->init_req(1, _gvn.transform(new IfFalseNode(iff)));
4244     default_value->init_req(1, null());
4245 
4246     // Object array, check if null-free
4247     set_control(_gvn.transform(new IfTrueNode(iff)));
4248     Node* lhp = basic_plus_adr(klass_node, in_bytes(Klass::layout_helper_offset()));
4249     Node* layout_val = _gvn.transform(LoadNode::make(_gvn, NULL, immutable_memory(), lhp, lhp->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
4250     Node* null_free = _gvn.transform(new RShiftINode(layout_val, intcon(Klass::_lh_null_free_shift)));
4251     null_free = _gvn.transform(new AndINode(null_free, intcon(Klass::_lh_null_free_mask)));
4252     cmp = _gvn.transform(new CmpINode(null_free, intcon(0)));
4253     bol = _gvn.transform(new BoolNode(cmp, BoolTest::ne));
4254     iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4255 
4256     // Not null-free, initialize with all zero
4257     r->init_req(2, _gvn.transform(new IfFalseNode(iff)));
4258     default_value->init_req(2, null());
4259 
4260     // Null-free, non-flattened inline type array, initialize with the default value
4261     set_control(_gvn.transform(new IfTrueNode(iff)));
4262     Node* p = basic_plus_adr(klass_node, in_bytes(ArrayKlass::element_klass_offset()));
4263     Node* eklass = _gvn.transform(LoadKlassNode::make(_gvn, control(), immutable_memory(), p, TypeInstPtr::KLASS));
4264     Node* adr_fixed_block_addr = basic_plus_adr(eklass, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()));
4265     Node* adr_fixed_block = make_load(control(), adr_fixed_block_addr, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4266     Node* default_value_offset_addr = basic_plus_adr(adr_fixed_block, in_bytes(InlineKlass::default_value_offset_offset()));
4267     Node* default_value_offset = make_load(control(), default_value_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
4268     Node* elem_mirror = load_mirror_from_klass(eklass);
4269     Node* default_value_addr = basic_plus_adr(elem_mirror, ConvI2X(default_value_offset));
4270     Node* val = access_load_at(elem_mirror, default_value_addr, _gvn.type(default_value_addr)->is_ptr(), TypeInstPtr::BOTTOM, T_OBJECT, IN_HEAP);
4271     r->init_req(3, control());
4272     default_value->init_req(3, val);
4273 
4274     set_control(_gvn.transform(r));
4275     default_value = _gvn.transform(default_value);
4276     if (UseCompressedOops) {
4277       default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop()));
4278       raw_default_value = raw_default_for_coops(default_value, *this);
4279     } else {
4280       raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value));
4281     }
4282   }
4283 
4284   // Create the AllocateArrayNode and its result projections
4285   AllocateArrayNode* alloc = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4286                                                    control(), mem, i_o(),
4287                                                    size, klass_node,
4288                                                    initial_slow_test,
4289                                                    length, default_value,
4290                                                    raw_default_value);
4291 
4292   // Cast to correct type.  Note that the klass_node may be constant or not,
4293   // and in the latter case the actual array type will be inexact also.
4294   // (This happens via a non-constant argument to inline_native_newArray.)
4295   // In any case, the value of klass_node provides the desired array type.
4296   const TypeInt* length_type = _gvn.find_int_type(length);

4297   if (ary_type->isa_aryptr() && length_type != NULL) {
4298     // Try to get a better type than POS for the size
4299     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4300   }
4301 
4302   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4303 
4304   // Cast length on remaining path to be as narrow as possible
4305   if (map()->find_edge(length) >= 0) {
4306     Node* ccast = alloc->make_ideal_length(ary_type, &_gvn);
4307     if (ccast != length) {
4308       _gvn.set_type_bottom(ccast);
4309       record_for_igvn(ccast);
4310       replace_in_map(length, ccast);
4311     }
4312   }
4313 
4314   return javaoop;
4315 }
4316 

4434   set_all_memory(ideal.merged_memory());
4435   set_i_o(ideal.i_o());
4436   set_control(ideal.ctrl());
4437 }
4438 
4439 void GraphKit::final_sync(IdealKit& ideal) {
4440   // Final sync IdealKit and graphKit.
4441   sync_kit(ideal);
4442 }
4443 
4444 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4445   Node* len = load_array_length(load_String_value(str, set_ctrl));
4446   Node* coder = load_String_coder(str, set_ctrl);
4447   // Divide length by 2 if coder is UTF16
4448   return _gvn.transform(new RShiftINode(len, coder));
4449 }
4450 
4451 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4452   int value_offset = java_lang_String::value_offset();
4453   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4454                                                      false, NULL, Type::Offset(0));
4455   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4456   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4457                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, true, true),
4458                                                   ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4459   Node* p = basic_plus_adr(str, str, value_offset);
4460   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4461                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4462   return load;
4463 }
4464 
4465 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4466   if (!CompactStrings) {
4467     return intcon(java_lang_String::CODER_UTF16);
4468   }
4469   int coder_offset = java_lang_String::coder_offset();
4470   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4471                                                      false, NULL, Type::Offset(0));
4472   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4473 
4474   Node* p = basic_plus_adr(str, str, coder_offset);
4475   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4476                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4477   return load;
4478 }
4479 
4480 void GraphKit::store_String_value(Node* str, Node* value) {
4481   int value_offset = java_lang_String::value_offset();
4482   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4483                                                      false, NULL, Type::Offset(0));
4484   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4485 
4486   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4487                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4488 }
4489 
4490 void GraphKit::store_String_coder(Node* str, Node* value) {
4491   int coder_offset = java_lang_String::coder_offset();
4492   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4493                                                      false, NULL, Type::Offset(0));
4494   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4495 
4496   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4497                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4498 }
4499 
4500 // Capture src and dst memory state with a MergeMemNode
4501 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4502   if (src_type == dst_type) {
4503     // Types are equal, we don't need a MergeMemNode
4504     return memory(src_type);
4505   }
4506   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4507   record_for_igvn(merge); // fold it up later, if possible
4508   int src_idx = C->get_alias_index(src_type);
4509   int dst_idx = C->get_alias_index(dst_type);
4510   merge->set_memory_at(src_idx, memory(src_idx));
4511   merge->set_memory_at(dst_idx, memory(dst_idx));
4512   return merge;
4513 }

4584   i_char->init_req(2, AddI(i_char, intcon(2)));
4585 
4586   set_control(IfFalse(iff));
4587   set_memory(st, TypeAryPtr::BYTES);
4588 }
4589 
4590 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4591   if (!field->is_constant()) {
4592     return NULL; // Field not marked as constant.
4593   }
4594   ciInstance* holder = NULL;
4595   if (!field->is_static()) {
4596     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4597     if (const_oop != NULL && const_oop->is_instance()) {
4598       holder = const_oop->as_instance();
4599     }
4600   }
4601   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4602                                                         /*is_unsigned_load=*/false);
4603   if (con_type != NULL) {
4604     Node* con = makecon(con_type);
4605     assert(!field->type()->is_inlinetype() || (field->is_static() && !con_type->is_zero_type()), "sanity");
4606     // Check type of constant which might be more precise
4607     if (con_type->is_inlinetypeptr() && con_type->inline_klass()->is_scalarizable()) {
4608       // Load inline type from constant oop
4609       con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass());
4610     }
4611     return con;
4612   }
4613   return NULL;
4614 }
4615 
4616 //---------------------------load_mirror_from_klass----------------------------
4617 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4618 Node* GraphKit::load_mirror_from_klass(Node* klass) {
4619   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4620   Node* load = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4621   // mirror = ((OopHandle)mirror)->resolve();
4622   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4623 }
< prev index next >