< 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 "ci/ciObjArray.hpp"
  29 #include "asm/register.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/intrinsicnode.hpp"
  41 #include "opto/locknode.hpp"
  42 #include "opto/machnode.hpp"

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

  62   _exceptions = jvms->map()->next_exception();
  63   if (_exceptions != NULL)  jvms->map()->set_next_exception(NULL);
  64   set_jvms(jvms);







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

 817         if (PrintMiscellaneous && (Verbose || WizardMode)) {
 818           tty->print_cr("Zombie local %d: ", local);
 819           jvms->dump();
 820         }
 821         return false;
 822       }
 823     }
 824   }
 825   return true;
 826 }
 827 
 828 #endif //ASSERT
 829 
 830 // Helper function for enforcing certain bytecodes to reexecute if deoptimization happens.
 831 static bool should_reexecute_implied_by_bytecode(JVMState *jvms, bool is_anewarray) {
 832   ciMethod* cur_method = jvms->method();
 833   int       cur_bci   = jvms->bci();
 834   if (cur_method != NULL && cur_bci != InvocationEntryBci) {
 835     Bytecodes::Code code = cur_method->java_code_at_bci(cur_bci);
 836     return Interpreter::bytecode_should_reexecute(code) ||
 837            (is_anewarray && code == Bytecodes::_multianewarray);
 838     // Reexecute _multianewarray bytecode which was replaced with
 839     // sequence of [a]newarray. See Parse::do_multianewarray().
 840     //
 841     // Note: interpreter should not have it set since this optimization
 842     // is limited by dimensions and guarded by flag so in some cases
 843     // multianewarray() runtime calls will be generated and
 844     // the bytecode should not be reexecutes (stack will not be reset).
 845   } else {
 846     return false;
 847   }
 848 }
 849 
 850 // Helper function for adding JVMState and debug information to node
 851 void GraphKit::add_safepoint_edges(SafePointNode* call, bool must_throw) {
 852   // Add the safepoint edges to the call (or other safepoint).
 853 
 854   // Make sure dead locals are set to top.  This
 855   // should help register allocation time and cut down on the size
 856   // of the deoptimization information.
 857   assert(dead_locals_are_killed(), "garbage in debug info before safepoint");

1077       ciSignature* declared_signature = NULL;
1078       ciMethod* ignored_callee = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
1079       assert(declared_signature != NULL, "cannot be null");
1080       inputs   = declared_signature->arg_size_for_bc(code);
1081       int size = declared_signature->return_type()->size();
1082       depth = size - inputs;
1083     }
1084     break;
1085 
1086   case Bytecodes::_multianewarray:
1087     {
1088       ciBytecodeStream iter(method());
1089       iter.reset_to_bci(bci());
1090       iter.next();
1091       inputs = iter.get_dimensions();
1092       assert(rsize == 1, "");
1093       depth = rsize - inputs;
1094     }
1095     break;
1096 









1097   case Bytecodes::_ireturn:
1098   case Bytecodes::_lreturn:
1099   case Bytecodes::_freturn:
1100   case Bytecodes::_dreturn:
1101   case Bytecodes::_areturn:
1102     assert(rsize == -depth, "");
1103     inputs = rsize;
1104     break;
1105 
1106   case Bytecodes::_jsr:
1107   case Bytecodes::_jsr_w:
1108     inputs = 0;
1109     depth  = 1;                  // S.B. depth=1, not zero
1110     break;
1111 
1112   default:
1113     // bytecode produces a typed result
1114     inputs = rsize - depth;
1115     assert(inputs >= 0, "");
1116     break;

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

1208         replace_in_map(length, ccast);
1209       }
1210       return ccast;
1211     }
1212   }
1213   return length;
1214 }
1215 
1216 //------------------------------do_null_check----------------------------------
1217 // Helper function to do a NULL pointer check.  Returned value is
1218 // the incoming address with NULL casted away.  You are allowed to use the
1219 // not-null value only if you are control dependent on the test.
1220 #ifndef PRODUCT
1221 extern int explicit_null_checks_inserted,
1222            explicit_null_checks_elided;
1223 #endif
1224 Node* GraphKit::null_check_common(Node* value, BasicType type,
1225                                   // optional arguments for variations:
1226                                   bool assert_null,
1227                                   Node* *null_control,
1228                                   bool speculative) {

1229   assert(!assert_null || null_control == NULL, "not both at once");
1230   if (stopped())  return top();
1231   NOT_PRODUCT(explicit_null_checks_inserted++);
1232 





































1233   // Construct NULL check
1234   Node *chk = NULL;
1235   switch(type) {
1236     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1237     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;

1238     case T_ARRAY  : // fall through
1239       type = T_OBJECT;  // simplify further tests
1240     case T_OBJECT : {
1241       const Type *t = _gvn.type( value );
1242 
1243       const TypeOopPtr* tp = t->isa_oopptr();
1244       if (tp != NULL && !tp->is_loaded()
1245           // Only for do_null_check, not any of its siblings:
1246           && !assert_null && null_control == NULL) {
1247         // Usually, any field access or invocation on an unloaded oop type
1248         // will simply fail to link, since the statically linked class is
1249         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1250         // the static class is loaded but the sharper oop type is not.
1251         // Rather than checking for this obscure case in lots of places,
1252         // we simply observe that a null check on an unloaded class
1253         // will always be followed by a nonsense operation, so we
1254         // can just issue the uncommon trap here.
1255         // Our access to the unloaded class will only be correct
1256         // after it has been loaded and initialized, which requires
1257         // a trip through the interpreter.

1316         }
1317         Node *oldcontrol = control();
1318         set_control(cfg);
1319         Node *res = cast_not_null(value);
1320         set_control(oldcontrol);
1321         NOT_PRODUCT(explicit_null_checks_elided++);
1322         return res;
1323       }
1324       cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1325       if (cfg == NULL)  break;  // Quit at region nodes
1326       depth++;
1327     }
1328   }
1329 
1330   //-----------
1331   // Branch to failure if null
1332   float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1333   Deoptimization::DeoptReason reason;
1334   if (assert_null) {
1335     reason = Deoptimization::reason_null_assert(speculative);
1336   } else if (type == T_OBJECT) {
1337     reason = Deoptimization::reason_null_check(speculative);
1338   } else {
1339     reason = Deoptimization::Reason_div0_check;
1340   }
1341   // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1342   // ciMethodData::has_trap_at will return a conservative -1 if any
1343   // must-be-null assertion has failed.  This could cause performance
1344   // problems for a method after its first do_null_assert failure.
1345   // Consider using 'Reason_class_check' instead?
1346 
1347   // To cause an implicit null check, we set the not-null probability
1348   // to the maximum (PROB_MAX).  For an explicit check the probability
1349   // is set to a smaller value.
1350   if (null_control != NULL || too_many_traps(reason)) {
1351     // probability is less likely
1352     ok_prob =  PROB_LIKELY_MAG(3);
1353   } else if (!assert_null &&
1354              (ImplicitNullCheckThreshold > 0) &&
1355              method() != NULL &&
1356              (method()->method_data()->trap_count(reason)

1390   }
1391 
1392   if (assert_null) {
1393     // Cast obj to null on this path.
1394     replace_in_map(value, zerocon(type));
1395     return zerocon(type);
1396   }
1397 
1398   // Cast obj to not-null on this path, if there is no null_control.
1399   // (If there is a null_control, a non-null value may come back to haunt us.)
1400   if (type == T_OBJECT) {
1401     Node* cast = cast_not_null(value, false);
1402     if (null_control == NULL || (*null_control) == top())
1403       replace_in_map(value, cast);
1404     value = cast;
1405   }
1406 
1407   return value;
1408 }
1409 
1410 
1411 //------------------------------cast_not_null----------------------------------
1412 // Cast obj to not-null on this path
1413 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {

























1414   const Type *t = _gvn.type(obj);
1415   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1416   // Object is already not-null?
1417   if( t == t_not_null ) return obj;
1418 
1419   Node *cast = new CastPPNode(obj,t_not_null);
1420   cast->init_req(0, control());
1421   cast = _gvn.transform( cast );
1422 
1423   // Scan for instances of 'obj' in the current JVM mapping.
1424   // These instances are known to be not-null after the test.
1425   if (do_replace_in_map)
1426     replace_in_map(obj, cast);
1427 
1428   return cast;                  // Return casted value
1429 }
1430 
1431 // Sometimes in intrinsics, we implicitly know an object is not null
1432 // (there's no actual null check) so we can cast it to not null. In
1433 // the course of optimizations, the input to the cast can become null.

1520 // These are layered on top of the factory methods in LoadNode and StoreNode,
1521 // and integrate with the parser's memory state and _gvn engine.
1522 //
1523 
1524 // factory methods in "int adr_idx"
1525 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1526                           int adr_idx,
1527                           MemNode::MemOrd mo,
1528                           LoadNode::ControlDependency control_dependency,
1529                           bool require_atomic_access,
1530                           bool unaligned,
1531                           bool mismatched,
1532                           bool unsafe,
1533                           uint8_t barrier_data) {
1534   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1535   const TypePtr* adr_type = NULL; // debug-mode-only argument
1536   debug_only(adr_type = C->get_adr_type(adr_idx));
1537   Node* mem = memory(adr_idx);
1538   Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1539   ld = _gvn.transform(ld);
1540   if (((bt == T_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {

1541     // Improve graph before escape analysis and boxing elimination.
1542     record_for_igvn(ld);
1543   }
1544   return ld;
1545 }
1546 
1547 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1548                                 int adr_idx,
1549                                 MemNode::MemOrd mo,
1550                                 bool require_atomic_access,
1551                                 bool unaligned,
1552                                 bool mismatched,
1553                                 bool unsafe) {
1554   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1555   const TypePtr* adr_type = NULL;
1556   debug_only(adr_type = C->get_adr_type(adr_idx));
1557   Node *mem = memory(adr_idx);
1558   Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1559   if (unaligned) {
1560     st->as_Store()->set_unaligned_access();

1564   }
1565   if (unsafe) {
1566     st->as_Store()->set_unsafe_access();
1567   }
1568   st = _gvn.transform(st);
1569   set_memory(st, adr_idx);
1570   // Back-to-back stores can only remove intermediate store with DU info
1571   // so push on worklist for optimizer.
1572   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1573     record_for_igvn(st);
1574 
1575   return st;
1576 }
1577 
1578 Node* GraphKit::access_store_at(Node* obj,
1579                                 Node* adr,
1580                                 const TypePtr* adr_type,
1581                                 Node* val,
1582                                 const Type* val_type,
1583                                 BasicType bt,
1584                                 DecoratorSet decorators) {

1585   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1586   // could be delayed during Parse (for example, in adjust_map_after_if()).
1587   // Execute transformation here to avoid barrier generation in such case.
1588   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1589     val = _gvn.makecon(TypePtr::NULL_PTR);
1590   }
1591 
1592   if (stopped()) {
1593     return top(); // Dead path ?
1594   }
1595 
1596   assert(val != NULL, "not dead path");







1597 
1598   C2AccessValuePtr addr(adr, adr_type);
1599   C2AccessValue value(val, val_type);
1600   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1601   if (access.is_raw()) {
1602     return _barrier_set->BarrierSetC2::store_at(access, value);
1603   } else {
1604     return _barrier_set->store_at(access, value);
1605   }
1606 }
1607 
1608 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1609                                Node* adr,   // actual address to store val at
1610                                const TypePtr* adr_type,
1611                                const Type* val_type,
1612                                BasicType bt,
1613                                DecoratorSet decorators) {

1614   if (stopped()) {
1615     return top(); // Dead path ?
1616   }
1617 
1618   C2AccessValuePtr addr(adr, adr_type);
1619   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr);
1620   if (access.is_raw()) {
1621     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1622   } else {
1623     return _barrier_set->load_at(access, val_type);
1624   }
1625 }
1626 
1627 Node* GraphKit::access_load(Node* adr,   // actual address to load val at
1628                             const Type* val_type,
1629                             BasicType bt,
1630                             DecoratorSet decorators) {
1631   if (stopped()) {
1632     return top(); // Dead path ?
1633   }
1634 
1635   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1636   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1637   if (access.is_raw()) {
1638     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1639   } else {

1704                                      Node* new_val,
1705                                      const Type* value_type,
1706                                      BasicType bt,
1707                                      DecoratorSet decorators) {
1708   C2AccessValuePtr addr(adr, adr_type);
1709   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1710   if (access.is_raw()) {
1711     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1712   } else {
1713     return _barrier_set->atomic_add_at(access, new_val, value_type);
1714   }
1715 }
1716 
1717 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1718   return _barrier_set->clone(this, src, dst, size, is_array);
1719 }
1720 
1721 //-------------------------array_element_address-------------------------
1722 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1723                                       const TypeInt* sizetype, Node* ctrl) {
1724   uint shift  = exact_log2(type2aelembytes(elembt));

1725   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1726 
1727   // short-circuit a common case (saves lots of confusing waste motion)
1728   jint idx_con = find_int_con(idx, -1);
1729   if (idx_con >= 0) {
1730     intptr_t offset = header + ((intptr_t)idx_con << shift);
1731     return basic_plus_adr(ary, offset);
1732   }
1733 
1734   // must be correct type for alignment purposes
1735   Node* base  = basic_plus_adr(ary, header);
1736   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1737   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1738   return basic_plus_adr(ary, base, scale);
1739 }
1740 
1741 //-------------------------load_array_element-------------------------
1742 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1743   const Type* elemtype = arytype->elem();
1744   BasicType elembt = elemtype->array_element_basic_type();

1745   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1746   if (elembt == T_NARROWOOP) {
1747     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1748   }
1749   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1750                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1751   return ld;
1752 }
1753 
1754 //-------------------------set_arguments_for_java_call-------------------------
1755 // Arguments (pre-popped from the stack) are taken from the JVMS.
1756 void GraphKit::set_arguments_for_java_call(CallJavaNode* call) {
1757   // Add the call arguments:
1758   uint nargs = call->method()->arg_size();
1759   for (uint i = 0; i < nargs; i++) {
1760     Node* arg = argument(i);
1761     call->init_req(i + TypeFunc::Parms, arg);



































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















1818   return ret;
1819 }
1820 
1821 //--------------------set_predefined_input_for_runtime_call--------------------
1822 // Reading and setting the memory state is way conservative here.
1823 // The real problem is that I am not doing real Type analysis on memory,
1824 // so I cannot distinguish card mark stores from other stores.  Across a GC
1825 // point the Store Barrier and the card mark memory has to agree.  I cannot
1826 // have a card mark store and its barrier split across the GC point from
1827 // either above or below.  Here I get that to happen by reading ALL of memory.
1828 // A better answer would be to separate out card marks from other memory.
1829 // For now, return the input memory state, so that it can be reused
1830 // after the call, if this call has restricted memory effects.
1831 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1832   // Set fixed predefined input arguments
1833   Node* memory = reset_memory();
1834   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1835   call->init_req( TypeFunc::Control,   control()  );
1836   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1837   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs

1888     if (use->is_MergeMem()) {
1889       wl.push(use);
1890     }
1891   }
1892 }
1893 
1894 // Replace the call with the current state of the kit.
1895 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
1896   JVMState* ejvms = NULL;
1897   if (has_exceptions()) {
1898     ejvms = transfer_exceptions_into_jvms();
1899   }
1900 
1901   ReplacedNodes replaced_nodes = map()->replaced_nodes();
1902   ReplacedNodes replaced_nodes_exception;
1903   Node* ex_ctl = top();
1904 
1905   SafePointNode* final_state = stop();
1906 
1907   // Find all the needed outputs of this call
1908   CallProjections callprojs;
1909   call->extract_projections(&callprojs, true);
1910 
1911   Unique_Node_List wl;
1912   Node* init_mem = call->in(TypeFunc::Memory);
1913   Node* final_mem = final_state->in(TypeFunc::Memory);
1914   Node* final_ctl = final_state->in(TypeFunc::Control);
1915   Node* final_io = final_state->in(TypeFunc::I_O);
1916 
1917   // Replace all the old call edges with the edges from the inlining result
1918   if (callprojs.fallthrough_catchproj != NULL) {
1919     C->gvn_replace_by(callprojs.fallthrough_catchproj, final_ctl);
1920   }
1921   if (callprojs.fallthrough_memproj != NULL) {
1922     if (final_mem->is_MergeMem()) {
1923       // Parser's exits MergeMem was not transformed but may be optimized
1924       final_mem = _gvn.transform(final_mem);
1925     }
1926     C->gvn_replace_by(callprojs.fallthrough_memproj,   final_mem);
1927     add_mergemem_users_to_worklist(wl, final_mem);
1928   }
1929   if (callprojs.fallthrough_ioproj != NULL) {
1930     C->gvn_replace_by(callprojs.fallthrough_ioproj,    final_io);
1931   }
1932 
1933   // Replace the result with the new result if it exists and is used
1934   if (callprojs.resproj != NULL && result != NULL) {
1935     C->gvn_replace_by(callprojs.resproj, result);




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

2170  *
2171  * @param n          node that the type applies to
2172  * @param exact_kls  type from profiling
2173  * @param maybe_null did profiling see null?
2174  *
2175  * @return           node with improved type
2176  */
2177 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2178   const Type* current_type = _gvn.type(n);
2179   assert(UseTypeSpeculation, "type speculation must be on");
2180 
2181   const TypePtr* speculative = current_type->speculative();
2182 
2183   // Should the klass from the profile be recorded in the speculative type?
2184   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2185     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2186     const TypeOopPtr* xtype = tklass->as_instance_type();
2187     assert(xtype->klass_is_exact(), "Should be exact");
2188     // Any reason to believe n is not null (from this profiling or a previous one)?
2189     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2190     const TypePtr* ptr = (ptr_kind == ProfileMaybeNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2191     // record the new speculative type's depth
2192     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2193     speculative = speculative->with_inline_depth(jvms()->depth());
2194   } else if (current_type->would_improve_ptr(ptr_kind)) {
2195     // Profiling report that null was never seen so we can change the
2196     // speculative type to non null ptr.
2197     if (ptr_kind == ProfileAlwaysNull) {
2198       speculative = TypePtr::NULL_PTR;
2199     } else {
2200       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2201       const TypePtr* ptr = TypePtr::NOTNULL;
2202       if (speculative != NULL) {
2203         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2204       } else {
2205         speculative = ptr;
2206       }
2207     }
2208   }
2209 
2210   if (speculative != current_type->speculative()) {
2211     // Build a type with a speculative type (what we think we know
2212     // about the type but will need a guard when we use it)
2213     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::OffsetBot, TypeOopPtr::InstanceBot, speculative);
2214     // We're changing the type, we need a new CheckCast node to carry
2215     // the new type. The new type depends on the control: what
2216     // profiling tells us is only valid from here as far as we can
2217     // tell.
2218     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2219     cast = _gvn.transform(cast);
2220     replace_in_map(n, cast);
2221     n = cast;
2222   }
2223 
2224   return n;
2225 }
2226 
2227 /**
2228  * Record profiling data from receiver profiling at an invoke with the
2229  * type system so that it can propagate it (speculation)
2230  *
2231  * @param n  receiver node
2232  *
2233  * @return   node with improved type
2234  */
2235 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2236   if (!UseTypeSpeculation) {
2237     return n;
2238   }
2239   ciKlass* exact_kls = profile_has_unique_klass();
2240   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2241   if ((java_bc() == Bytecodes::_checkcast ||
2242        java_bc() == Bytecodes::_instanceof ||
2243        java_bc() == Bytecodes::_aastore) &&
2244       method()->method_data()->is_mature()) {
2245     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2246     if (data != NULL) {
2247       if (!data->as_BitData()->null_seen()) {
2248         ptr_kind = ProfileNeverNull;







2249       } else {
2250         assert(data->is_ReceiverTypeData(), "bad profile data type");
2251         ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2252         uint i = 0;
2253         for (; i < call->row_limit(); i++) {
2254           ciKlass* receiver = call->receiver(i);
2255           if (receiver != NULL) {
2256             break;




2257           }

2258         }
2259         ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2260       }
2261     }
2262   }
2263   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2264 }
2265 
2266 /**
2267  * Record profiling data from argument profiling at an invoke with the
2268  * type system so that it can propagate it (speculation)
2269  *
2270  * @param dest_method  target method for the call
2271  * @param bc           what invoke bytecode is this?
2272  */
2273 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2274   if (!UseTypeSpeculation) {
2275     return;
2276   }
2277   const TypeFunc* tf    = TypeFunc::make(dest_method);
2278   int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2279   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2280   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2281     const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2282     if (is_reference_type(targ->basic_type())) {
2283       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2284       ciKlass* better_type = NULL;
2285       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2286         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2287       }
2288       i++;
2289     }
2290   }
2291 }
2292 
2293 /**
2294  * Record profiling data from parameter profiling at an invoke with
2295  * the type system so that it can propagate it (speculation)
2296  */
2297 void GraphKit::record_profiled_parameters_for_speculation() {
2298   if (!UseTypeSpeculation) {
2299     return;
2300   }
2301   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {

2315  * the type system so that it can propagate it (speculation)
2316  */
2317 void GraphKit::record_profiled_return_for_speculation() {
2318   if (!UseTypeSpeculation) {
2319     return;
2320   }
2321   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2322   ciKlass* better_type = NULL;
2323   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2324     // If profiling reports a single type for the return value,
2325     // feed it to the type system so it can propagate it as a
2326     // speculative type
2327     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2328   }
2329 }
2330 
2331 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2332   if (Matcher::strict_fp_requires_explicit_rounding) {
2333     // (Note:  TypeFunc::make has a cache that makes this fast.)
2334     const TypeFunc* tf    = TypeFunc::make(dest_method);
2335     int             nargs = tf->domain()->cnt() - TypeFunc::Parms;
2336     for (int j = 0; j < nargs; j++) {
2337       const Type *targ = tf->domain()->field_at(j + TypeFunc::Parms);
2338       if (targ->basic_type() == T_DOUBLE) {
2339         // If any parameters are doubles, they must be rounded before
2340         // the call, dprecision_rounding does gvn.transform
2341         Node *arg = argument(j);
2342         arg = dprecision_rounding(arg);
2343         set_argument(j, arg);
2344       }
2345     }
2346   }
2347 }
2348 
2349 // rounding for strict float precision conformance
2350 Node* GraphKit::precision_rounding(Node* n) {
2351   if (Matcher::strict_fp_requires_explicit_rounding) {
2352 #ifdef IA32
2353     if (UseSSE == 0) {
2354       return _gvn.transform(new RoundFloatNode(0, n));
2355     }
2356 #else
2357     Unimplemented();

2466                                   // The first NULL ends the list.
2467                                   Node* parm0, Node* parm1,
2468                                   Node* parm2, Node* parm3,
2469                                   Node* parm4, Node* parm5,
2470                                   Node* parm6, Node* parm7) {
2471   assert(call_addr != NULL, "must not call NULL targets");
2472 
2473   // Slow-path call
2474   bool is_leaf = !(flags & RC_NO_LEAF);
2475   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2476   if (call_name == NULL) {
2477     assert(!is_leaf, "must supply name for leaf");
2478     call_name = OptoRuntime::stub_name(call_addr);
2479   }
2480   CallNode* call;
2481   if (!is_leaf) {
2482     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2483   } else if (flags & RC_NO_FP) {
2484     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2485   } else  if (flags & RC_VECTOR){
2486     uint num_bits = call_type->range()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2487     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2488   } else {
2489     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2490   }
2491 
2492   // The following is similar to set_edges_for_java_call,
2493   // except that the memory effects of the call are restricted to AliasIdxRaw.
2494 
2495   // Slow path call has no side-effects, uses few values
2496   bool wide_in  = !(flags & RC_NARROW_MEM);
2497   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2498 
2499   Node* prev_mem = NULL;
2500   if (wide_in) {
2501     prev_mem = set_predefined_input_for_runtime_call(call);
2502   } else {
2503     assert(!wide_out, "narrow in => narrow out");
2504     Node* narrow_mem = memory(adr_type);
2505     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2506   }

2546 
2547   if (has_io) {
2548     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2549   }
2550   return call;
2551 
2552 }
2553 
2554 // i2b
2555 Node* GraphKit::sign_extend_byte(Node* in) {
2556   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2557   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2558 }
2559 
2560 // i2s
2561 Node* GraphKit::sign_extend_short(Node* in) {
2562   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2563   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2564 }
2565 

2566 //------------------------------merge_memory-----------------------------------
2567 // Merge memory from one path into the current memory state.
2568 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2569   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2570     Node* old_slice = mms.force_memory();
2571     Node* new_slice = mms.memory2();
2572     if (old_slice != new_slice) {
2573       PhiNode* phi;
2574       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2575         if (mms.is_empty()) {
2576           // clone base memory Phi's inputs for this memory slice
2577           assert(old_slice == mms.base_memory(), "sanity");
2578           phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2579           _gvn.set_type(phi, Type::MEMORY);
2580           for (uint i = 1; i < phi->req(); i++) {
2581             phi->init_req(i, old_slice->in(i));
2582           }
2583         } else {
2584           phi = old_slice->as_Phi(); // Phi was generated already
2585         }

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




2817   bool expand_subtype_check = C->post_loop_opts_phase() ||   // macro node expansion is over
2818                               ExpandSubTypeCheckAtParseTime; // forced expansion
2819   if (expand_subtype_check) {
2820     MergeMemNode* mem = merged_memory();
2821     Node* ctrl = control();
2822     Node* subklass = obj_or_subklass;
2823     if (!_gvn.type(obj_or_subklass)->isa_klassptr()) {
2824       subklass = load_object_klass(obj_or_subklass);
2825     }
2826 
2827     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2828     set_control(ctrl);
2829     return n;
2830   }
2831 
2832   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2833   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2834   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2835   set_control(_gvn.transform(new IfTrueNode(iff)));
2836   return _gvn.transform(new IfFalseNode(iff));
2837 }
2838 
2839 // Profile-driven exact type check:
2840 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2841                                     float prob,
2842                                     Node* *casted_receiver) {
2843   assert(!klass->is_interface(), "no exact type check on interfaces");
2844 











2845   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2846   Node* recv_klass = load_object_klass(receiver);
2847   Node* want_klass = makecon(tklass);
2848   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
2849   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
2850   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
2851   set_control( _gvn.transform(new IfTrueNode (iff)));
2852   Node* fail = _gvn.transform(new IfFalseNode(iff));
2853 
2854   if (!stopped()) {
2855     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2856     const TypeOopPtr* recvx_type = tklass->as_instance_type();
2857     assert(recvx_type->klass_is_exact(), "");
2858 
2859     if (!receiver_type->higher_equal(recvx_type)) { // ignore redundant casts
2860       // Subsume downstream occurrences of receiver with a cast to
2861       // recv_xtype, since now we know what the type will be.
2862       Node* cast = new CheckCastPPNode(control(), receiver, recvx_type);
2863       (*casted_receiver) = _gvn.transform(cast);





2864       // (User must make the replace_in_map call.)
2865     }
2866   }
2867 
2868   return fail;
2869 }
2870 











2871 //------------------------------subtype_check_receiver-------------------------
2872 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
2873                                        Node** casted_receiver) {
2874   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
2875   Node* want_klass = makecon(tklass);
2876 
2877   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
2878 
2879   // Ignore interface type information until interface types are properly tracked.
2880   if (!stopped() && !klass->is_interface()) {
2881     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2882     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
2883     if (!receiver_type->higher_equal(recv_type)) { // ignore redundant casts
2884       Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
2885       (*casted_receiver) = _gvn.transform(cast);
2886     }
2887   }
2888 
2889   return slow_ctl;
2890 }
2891 
2892 //------------------------------seems_never_null-------------------------------
2893 // Use null_seen information if it is available from the profile.
2894 // If we see an unexpected null at a type check we record it and force a
2895 // recompile; the offending check will be recompiled to handle NULLs.
2896 // If we see several offending BCIs, then all checks in the
2897 // method will be recompiled.
2898 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
2899   speculating = !_gvn.type(obj)->speculative_maybe_null();
2900   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
2901   if (UncommonNullCast               // Cutout for this technique
2902       && obj != null()               // And not the -Xcomp stupid case?
2903       && !too_many_traps(reason)
2904       ) {
2905     if (speculating) {
2906       return true;
2907     }
2908     if (data == NULL)
2909       // Edge case:  no mature data.  Be optimistic here.
2910       return true;
2911     // If the profile has not seen a null, assume it won't happen.
2912     assert(java_bc() == Bytecodes::_checkcast ||
2913            java_bc() == Bytecodes::_instanceof ||
2914            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");



2915     return !data->as_BitData()->null_seen();
2916   }
2917   speculating = false;
2918   return false;
2919 }
2920 
2921 void GraphKit::guard_klass_being_initialized(Node* klass) {
2922   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
2923   Node* adr = basic_plus_adr(top(), klass, init_state_off);
2924   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
2925                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
2926                                     T_BYTE, MemNode::unordered);
2927   init_state = _gvn.transform(init_state);
2928 
2929   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
2930 
2931   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
2932   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
2933 
2934   { BuildCutout unless(this, tst, PROB_MAX);

2974 
2975 //------------------------maybe_cast_profiled_receiver-------------------------
2976 // If the profile has seen exactly one type, narrow to exactly that type.
2977 // Subsequent type checks will always fold up.
2978 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
2979                                              const TypeKlassPtr* require_klass,
2980                                              ciKlass* spec_klass,
2981                                              bool safe_for_replace) {
2982   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
2983 
2984   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
2985 
2986   // Make sure we haven't already deoptimized from this tactic.
2987   if (too_many_traps_or_recompiles(reason))
2988     return NULL;
2989 
2990   // (No, this isn't a call, but it's enough like a virtual call
2991   // to use the same ciMethod accessor to get the profile info...)
2992   // If we have a speculative type use it instead of profiling (which
2993   // may not help us)
2994   ciKlass* exact_kls = spec_klass == NULL ? profile_has_unique_klass() : spec_klass;













2995   if (exact_kls != NULL) {// no cast failures here
2996     if (require_klass == NULL ||
2997         C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls)) == Compile::SSC_always_true) {
2998       // If we narrow the type to match what the type profile sees or
2999       // the speculative type, we can then remove the rest of the
3000       // cast.
3001       // This is a win, even if the exact_kls is very specific,
3002       // because downstream operations, such as method calls,
3003       // will often benefit from the sharper type.
3004       Node* exact_obj = not_null_obj; // will get updated in place...
3005       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3006                                             &exact_obj);
3007       { PreserveJVMState pjvms(this);
3008         set_control(slow_ctl);
3009         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3010       }
3011       if (safe_for_replace) {
3012         replace_in_map(not_null_obj, exact_obj);
3013       }
3014       return exact_obj;

3079 // and the reflective instance-of call.
3080 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3081   kill_dead_locals();           // Benefit all the uncommon traps
3082   assert( !stopped(), "dead parse path should be checked in callers" );
3083   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3084          "must check for not-null not-dead klass in callers");
3085 
3086   // Make the merge point
3087   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3088   RegionNode* region = new RegionNode(PATH_LIMIT);
3089   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3090   C->set_has_split_ifs(true); // Has chance for split-if optimization
3091 
3092   ciProfileData* data = NULL;
3093   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3094     data = method()->method_data()->bci_to_data(bci());
3095   }
3096   bool speculative_not_null = false;
3097   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3098                          && seems_never_null(obj, data, speculative_not_null));

3099 
3100   // Null check; get casted pointer; set region slot 3
3101   Node* null_ctl = top();





3102   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3103 
3104   // If not_null_obj is dead, only null-path is taken
3105   if (stopped()) {              // Doing instance-of on a NULL?
3106     set_control(null_ctl);
3107     return intcon(0);
3108   }
3109   region->init_req(_null_path, null_ctl);
3110   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3111   if (null_ctl == top()) {
3112     // Do this eagerly, so that pattern matches like is_diamond_phi
3113     // will work even during parsing.
3114     assert(_null_path == PATH_LIMIT-1, "delete last");
3115     region->del_req(_null_path);
3116     phi   ->del_req(_null_path);
3117   }
3118 
3119   // Do we know the type check always succeed?
3120   bool known_statically = false;
3121   if (_gvn.type(superklass)->singleton()) {
3122     const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3123     const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3124     if (subk->is_loaded()) {
3125       int static_res = C->static_subtype_check(superk, subk);
3126       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);


3127     }
3128   }
3129 
3130   if (!known_statically) {
3131     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3132     // We may not have profiling here or it may not help us. If we
3133     // have a speculative type use it to perform an exact cast.
3134     ciKlass* spec_obj_type = obj_type->speculative_type();
3135     if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3136       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3137       if (stopped()) {            // Profile disagrees with this path.
3138         set_control(null_ctl);    // Null is the only remaining possibility.
3139         return intcon(0);
3140       }
3141       if (cast_obj != NULL) {
3142         not_null_obj = cast_obj;


3143       }
3144     }
3145   }
3146 
3147   // Generate the subtype check
3148   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3149 
3150   // Plug in the success path to the general merge in slot 1.
3151   region->init_req(_obj_path, control());
3152   phi   ->init_req(_obj_path, intcon(1));
3153 
3154   // Plug in the failing path to the general merge in slot 2.
3155   region->init_req(_fail_path, not_subtype_ctrl);
3156   phi   ->init_req(_fail_path, intcon(0));
3157 
3158   // Return final merged results
3159   set_control( _gvn.transform(region) );
3160   record_for_igvn(region);
3161 
3162   // If we know the type check always succeeds then we don't use the
3163   // profiling data at this bytecode. Don't lose it, feed it to the
3164   // type system as a speculative type.
3165   if (safe_for_replace) {
3166     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3167     replace_in_map(obj, casted_obj);
3168   }
3169 
3170   return _gvn.transform(phi);
3171 }
3172 
3173 //-------------------------------gen_checkcast---------------------------------
3174 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3175 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3176 // uncommon-trap paths work.  Adjust stack after this call.
3177 // If failure_control is supplied and not null, it is filled in with
3178 // the control edge for the cast failure.  Otherwise, an appropriate
3179 // uncommon trap or exception is thrown.
3180 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass,
3181                               Node* *failure_control) {
3182   kill_dead_locals();           // Benefit all the uncommon traps
3183   const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr();
3184   const Type *toop = tk->cast_to_exactness(false)->as_instance_type();



3185 
3186   // Fast cutout:  Check the case that the cast is vacuously true.
3187   // This detects the common cases where the test will short-circuit
3188   // away completely.  We do this before we perform the null check,
3189   // because if the test is going to turn into zero code, we don't
3190   // want a residual null check left around.  (Causes a slowdown,
3191   // for example, in some objArray manipulations, such as a[i]=a[j].)
3192   if (tk->singleton()) {
3193     const TypeOopPtr* objtp = _gvn.type(obj)->isa_oopptr();
3194     if (objtp != NULL) {
3195       switch (C->static_subtype_check(tk, objtp->as_klass_type())) {







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








3201       case Compile::SSC_always_false:




3202         // It needs a null check because a null will *pass* the cast check.
3203         // A non-null value will always produce an exception.
3204         if (!objtp->maybe_null()) {
3205           bool is_aastore = (java_bc() == Bytecodes::_aastore);
3206           Deoptimization::DeoptReason reason = is_aastore ?
3207             Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3208           builtin_throw(reason);
3209           return top();
3210         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3211           return null_assert(obj);
3212         }
3213         break; // Fall through to full check
3214       default:
3215         break;
3216       }
3217     }
3218   }
3219 
3220   ciProfileData* data = NULL;
3221   bool safe_for_replace = false;
3222   if (failure_control == NULL) {        // use MDO in regular case only
3223     assert(java_bc() == Bytecodes::_aastore ||
3224            java_bc() == Bytecodes::_checkcast,
3225            "interpreter profiles type checks only for these BCs");
3226     data = method()->method_data()->bci_to_data(bci());
3227     safe_for_replace = true;

3228   }
3229 
3230   // Make the merge point
3231   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3232   RegionNode* region = new RegionNode(PATH_LIMIT);
3233   Node*       phi    = new PhiNode(region, toop);



3234   C->set_has_split_ifs(true); // Has chance for split-if optimization
3235 
3236   // Use null-cast information if it is available
3237   bool speculative_not_null = false;
3238   bool never_see_null = ((failure_control == NULL)  // regular case only
3239                          && seems_never_null(obj, data, speculative_not_null));
3240 
3241   // Null check; get casted pointer; set region slot 3
3242   Node* null_ctl = top();
3243   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);









3244 
3245   // If not_null_obj is dead, only null-path is taken
3246   if (stopped()) {              // Doing instance-of on a NULL?
3247     set_control(null_ctl);



3248     return null();
3249   }
3250   region->init_req(_null_path, null_ctl);
3251   phi   ->init_req(_null_path, null());  // Set null path value
3252   if (null_ctl == top()) {
3253     // Do this eagerly, so that pattern matches like is_diamond_phi
3254     // will work even during parsing.
3255     assert(_null_path == PATH_LIMIT-1, "delete last");
3256     region->del_req(_null_path);
3257     phi   ->del_req(_null_path);
3258   }
3259 
3260   Node* cast_obj = NULL;
3261   if (tk->klass_is_exact()) {
3262     // The following optimization tries to statically cast the speculative type of the object
3263     // (for example obtained during profiling) to the type of the superklass and then do a
3264     // dynamic check that the type of the object is what we expect. To work correctly
3265     // for checkcast and aastore the type of superklass should be exact.
3266     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3267     // We may not have profiling here or it may not help us. If we have
3268     // a speculative type use it to perform an exact cast.
3269     ciKlass* spec_obj_type = obj_type->speculative_type();
3270     if (spec_obj_type != NULL || data != NULL) {
3271       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3272       if (cast_obj != NULL) {
3273         if (failure_control != NULL) // failure is now impossible
3274           (*failure_control) = top();
3275         // adjust the type of the phi to the exact klass:
3276         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3277       }
3278     }
3279   }
3280 
3281   if (cast_obj == NULL) {
3282     // Generate the subtype check
3283     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass );
3284 
3285     // Plug in success path into the merge
3286     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3287     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3288     if (failure_control == NULL) {
3289       if (not_subtype_ctrl != top()) { // If failure is possible
3290         PreserveJVMState pjvms(this);
3291         set_control(not_subtype_ctrl);






3292         bool is_aastore = (java_bc() == Bytecodes::_aastore);
3293         Deoptimization::DeoptReason reason = is_aastore ?
3294           Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3295         builtin_throw(reason);
3296       }
3297     } else {
3298       (*failure_control) = not_subtype_ctrl;
3299     }
3300   }
3301 
3302   region->init_req(_obj_path, control());
3303   phi   ->init_req(_obj_path, cast_obj);
3304 
3305   // A merge of NULL or Casted-NotNull obj
3306   Node* res = _gvn.transform(phi);
3307 
3308   // Note I do NOT always 'replace_in_map(obj,result)' here.
3309   //  if( tk->klass()->can_be_primary_super()  )
3310     // This means that if I successfully store an Object into an array-of-String
3311     // I 'forget' that the Object is really now known to be a String.  I have to
3312     // do this because we don't have true union types for interfaces - if I store
3313     // a Baz into an array-of-Interface and then tell the optimizer it's an
3314     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3315     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3316   //  replace_in_map( obj, res );
3317 
3318   // Return final merged results
3319   set_control( _gvn.transform(region) );
3320   record_for_igvn(region);
3321 
3322   return record_profiled_receiver_for_speculation(res);




























































































































3323 }
3324 
3325 //------------------------------next_monitor-----------------------------------
3326 // What number should be given to the next monitor?
3327 int GraphKit::next_monitor() {
3328   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3329   int next = current + C->sync_stack_slots();
3330   // Keep the toplevel high water mark current:
3331   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3332   return current;
3333 }
3334 
3335 //------------------------------insert_mem_bar---------------------------------
3336 // Memory barrier to avoid floating things around
3337 // The membar serves as a pinch point between both control and all memory slices.
3338 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3339   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3340   mb->init_req(TypeFunc::Control, control());
3341   mb->init_req(TypeFunc::Memory,  reset_memory());
3342   Node* membar = _gvn.transform(mb);

3370   }
3371   Node* membar = _gvn.transform(mb);
3372   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3373   if (alias_idx == Compile::AliasIdxBot) {
3374     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3375   } else {
3376     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3377   }
3378   return membar;
3379 }
3380 
3381 //------------------------------shared_lock------------------------------------
3382 // Emit locking code.
3383 FastLockNode* GraphKit::shared_lock(Node* obj) {
3384   // bci is either a monitorenter bc or InvocationEntryBci
3385   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3386   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3387 
3388   if( !GenerateSynchronizationCode )
3389     return NULL;                // Not locking things?

3390   if (stopped())                // Dead monitor?
3391     return NULL;
3392 
3393   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3394 
3395   // Box the stack location
3396   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3397   Node* mem = reset_memory();
3398 
3399   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3400 
3401   // Create the rtm counters for this fast lock if needed.
3402   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3403 
3404   // Add monitor to debug info for the slow path.  If we block inside the
3405   // slow path and de-opt, we need the monitor hanging around
3406   map()->push_monitor( flock );
3407 
3408   const TypeFunc *tf = LockNode::lock_type();
3409   LockNode *lock = new LockNode(C, tf);

3438   }
3439 #endif
3440 
3441   return flock;
3442 }
3443 
3444 
3445 //------------------------------shared_unlock----------------------------------
3446 // Emit unlocking code.
3447 void GraphKit::shared_unlock(Node* box, Node* obj) {
3448   // bci is either a monitorenter bc or InvocationEntryBci
3449   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3450   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3451 
3452   if( !GenerateSynchronizationCode )
3453     return;
3454   if (stopped()) {               // Dead monitor?
3455     map()->pop_monitor();        // Kill monitor from debug info
3456     return;
3457   }

3458 
3459   // Memory barrier to avoid floating things down past the locked region
3460   insert_mem_bar(Op_MemBarReleaseLock);
3461 
3462   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3463   UnlockNode *unlock = new UnlockNode(C, tf);
3464 #ifdef ASSERT
3465   unlock->set_dbg_jvms(sync_jvms());
3466 #endif
3467   uint raw_idx = Compile::AliasIdxRaw;
3468   unlock->init_req( TypeFunc::Control, control() );
3469   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3470   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3471   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3472   unlock->init_req( TypeFunc::ReturnAdr, top() );
3473 
3474   unlock->init_req(TypeFunc::Parms + 0, obj);
3475   unlock->init_req(TypeFunc::Parms + 1, box);
3476   unlock = _gvn.transform(unlock)->as_Unlock();
3477 
3478   Node* mem = reset_memory();
3479 
3480   // unlock has no side-effects, sets few values
3481   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3482 
3483   // Kill monitor from debug info
3484   map()->pop_monitor( );
3485 }
3486 
3487 //-------------------------------get_layout_helper-----------------------------
3488 // If the given klass is a constant or known to be an array,
3489 // fetch the constant layout helper value into constant_value
3490 // and return (Node*)NULL.  Otherwise, load the non-constant
3491 // layout helper value, and return the node which represents it.
3492 // This two-faced routine is useful because allocation sites
3493 // almost always feature constant types.
3494 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3495   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3496   if (!StressReflectiveCode && inst_klass != NULL) {
3497     bool    xklass = inst_klass->klass_is_exact();
3498     if (xklass || inst_klass->isa_aryklassptr()) {







3499       jint lhelper;
3500       if (inst_klass->isa_aryklassptr()) {
3501         BasicType elem = inst_klass->as_instance_type()->isa_aryptr()->elem()->array_element_basic_type();


3502         if (is_reference_type(elem, true)) {
3503           elem = T_OBJECT;
3504         }
3505         lhelper = Klass::array_layout_helper(elem);
3506       } else {
3507         lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3508       }
3509       if (lhelper != Klass::_lh_neutral_value) {
3510         constant_value = lhelper;
3511         return (Node*) NULL;
3512       }
3513     }
3514   }
3515   constant_value = Klass::_lh_neutral_value;  // put in a known value
3516   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3517   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3518 }
3519 
3520 // We just put in an allocate/initialize with a big raw-memory effect.
3521 // Hook selected additional alias categories on the initialization.
3522 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3523                                 MergeMemNode* init_in_merge,
3524                                 Node* init_out_raw) {
3525   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3526   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3527 
3528   Node* prevmem = kit.memory(alias_idx);
3529   init_in_merge->set_memory_at(alias_idx, prevmem);
3530   kit.set_memory(init_out_raw, alias_idx);


3531 }
3532 
3533 //---------------------------set_output_for_allocation-------------------------
3534 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3535                                           const TypeOopPtr* oop_type,
3536                                           bool deoptimize_on_exception) {
3537   int rawidx = Compile::AliasIdxRaw;
3538   alloc->set_req( TypeFunc::FramePtr, frameptr() );
3539   add_safepoint_edges(alloc);
3540   Node* allocx = _gvn.transform(alloc);
3541   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3542   // create memory projection for i_o
3543   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3544   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3545 
3546   // create a memory projection as for the normal control path
3547   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3548   set_memory(malloc, rawidx);
3549 
3550   // a normal slow-call doesn't change i_o, but an allocation does
3551   // we create a separate i_o projection for the normal control path
3552   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3553   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3554 
3555   // put in an initialization barrier
3556   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3557                                                  rawoop)->as_Initialize();
3558   assert(alloc->initialization() == init,  "2-way macro link must work");
3559   assert(init ->allocation()     == alloc, "2-way macro link must work");
3560   {
3561     // Extract memory strands which may participate in the new object's
3562     // initialization, and source them from the new InitializeNode.
3563     // This will allow us to observe initializations when they occur,
3564     // and link them properly (as a group) to the InitializeNode.
3565     assert(init->in(InitializeNode::Memory) == malloc, "");
3566     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3567     init->set_req(InitializeNode::Memory, minit_in);
3568     record_for_igvn(minit_in); // fold it up later, if possible

3569     Node* minit_out = memory(rawidx);
3570     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3571     // Add an edge in the MergeMem for the header fields so an access
3572     // to one of those has correct memory state
3573     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3574     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3575     if (oop_type->isa_aryptr()) {
3576       const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3577       int            elemidx  = C->get_alias_index(telemref);
3578       hook_memory_on_init(*this, elemidx, minit_in, minit_out);

























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

3580       ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3581       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3582         ciField* field = ik->nonstatic_field_at(i);
3583         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3584           continue;  // do not bother to track really large numbers of fields
3585         // Find (or create) the alias category for this field:
3586         int fieldidx = C->alias_type(field)->index();
3587         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3588       }
3589     }
3590   }
3591 
3592   // Cast raw oop to the real thing...
3593   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3594   javaoop = _gvn.transform(javaoop);
3595   C->set_recent_alloc(control(), javaoop);
3596   assert(just_allocated_object(control()) == javaoop, "just allocated");
3597 
3598 #ifdef ASSERT
3599   { // Verify that the AllocateNode::Ideal_allocation recognizers work:

3610       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3611     }
3612   }
3613 #endif //ASSERT
3614 
3615   return javaoop;
3616 }
3617 
3618 //---------------------------new_instance--------------------------------------
3619 // This routine takes a klass_node which may be constant (for a static type)
3620 // or may be non-constant (for reflective code).  It will work equally well
3621 // for either, and the graph will fold nicely if the optimizer later reduces
3622 // the type to a constant.
3623 // The optional arguments are for specialized use by intrinsics:
3624 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3625 //  - If 'return_size_val', report the total object size to the caller.
3626 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
3627 Node* GraphKit::new_instance(Node* klass_node,
3628                              Node* extra_slow_test,
3629                              Node* *return_size_val,
3630                              bool deoptimize_on_exception) {

3631   // Compute size in doublewords
3632   // The size is always an integral number of doublewords, represented
3633   // as a positive bytewise size stored in the klass's layout_helper.
3634   // The layout_helper also encodes (in a low bit) the need for a slow path.
3635   jint  layout_con = Klass::_lh_neutral_value;
3636   Node* layout_val = get_layout_helper(klass_node, layout_con);
3637   int   layout_is_con = (layout_val == NULL);
3638 
3639   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
3640   // Generate the initial go-slow test.  It's either ALWAYS (return a
3641   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
3642   // case) a computed value derived from the layout_helper.
3643   Node* initial_slow_test = NULL;
3644   if (layout_is_con) {
3645     assert(!StressReflectiveCode, "stress mode does not use these paths");
3646     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
3647     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
3648   } else {   // reflective case
3649     // This reflective path is used by Unsafe.allocateInstance.
3650     // (It may be stress-tested by specifying StressReflectiveCode.)
3651     // Basically, we want to get into the VM is there's an illegal argument.
3652     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
3653     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
3654     if (extra_slow_test != intcon(0)) {
3655       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
3656     }
3657     // (Macro-expander will further convert this to a Bool, if necessary.)

3668 
3669     // Clear the low bits to extract layout_helper_size_in_bytes:
3670     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
3671     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
3672     size = _gvn.transform( new AndXNode(size, mask) );
3673   }
3674   if (return_size_val != NULL) {
3675     (*return_size_val) = size;
3676   }
3677 
3678   // This is a precise notnull oop of the klass.
3679   // (Actually, it need not be precise if this is a reflective allocation.)
3680   // It's what we cast the result to.
3681   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
3682   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
3683   const TypeOopPtr* oop_type = tklass->as_instance_type();
3684 
3685   // Now generate allocation code
3686 
3687   // The entire memory state is needed for slow path of the allocation
3688   // since GC and deoptimization can happened.
3689   Node *mem = reset_memory();
3690   set_all_memory(mem); // Create new memory state
3691 
3692   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
3693                                          control(), mem, i_o(),
3694                                          size, klass_node,
3695                                          initial_slow_test);
3696 
3697   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
3698 }
3699 
3700 //-------------------------------new_array-------------------------------------
3701 // helper for both newarray and anewarray
3702 // The 'length' parameter is (obviously) the length of the array.
3703 // See comments on new_instance for the meaning of the other arguments.
3704 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
3705                           Node* length,         // number of array elements
3706                           int   nargs,          // number of arguments to push back for uncommon trap
3707                           Node* *return_size_val,
3708                           bool deoptimize_on_exception) {
3709   jint  layout_con = Klass::_lh_neutral_value;
3710   Node* layout_val = get_layout_helper(klass_node, layout_con);
3711   int   layout_is_con = (layout_val == NULL);
3712 
3713   if (!layout_is_con && !StressReflectiveCode &&
3714       !too_many_traps(Deoptimization::Reason_class_check)) {
3715     // This is a reflective array creation site.
3716     // Optimistically assume that it is a subtype of Object[],
3717     // so that we can fold up all the address arithmetic.
3718     layout_con = Klass::array_layout_helper(T_OBJECT);
3719     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
3720     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
3721     { BuildCutout unless(this, bol_lh, PROB_MAX);
3722       inc_sp(nargs);
3723       uncommon_trap(Deoptimization::Reason_class_check,
3724                     Deoptimization::Action_maybe_recompile);
3725     }
3726     layout_val = NULL;
3727     layout_is_con = true;
3728   }
3729 
3730   // Generate the initial go-slow test.  Make sure we do not overflow
3731   // if length is huge (near 2Gig) or negative!  We do not need
3732   // exact double-words here, just a close approximation of needed
3733   // double-words.  We can't add any offset or rounding bits, lest we
3734   // take a size -1 of bytes and make it positive.  Use an unsigned
3735   // compare, so negative sizes look hugely positive.
3736   int fast_size_limit = FastAllocateSizeLimit;
3737   if (layout_is_con) {
3738     assert(!StressReflectiveCode, "stress mode does not use these paths");
3739     // Increase the size limit if we have exact knowledge of array type.
3740     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
3741     fast_size_limit <<= (LogBytesPerLong - log2_esize);
3742   }
3743 
3744   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
3745   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
3746 
3747   // --- Size Computation ---
3748   // array_size = round_to_heap(array_header + (length << elem_shift));
3749   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
3750   // and align_to(x, y) == ((x + y-1) & ~(y-1))
3751   // The rounding mask is strength-reduced, if possible.
3752   int round_mask = MinObjAlignmentInBytes - 1;
3753   Node* header_size = NULL;
3754   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
3755   // (T_BYTE has the weakest alignment and size restrictions...)
3756   if (layout_is_con) {
3757     int       hsize  = Klass::layout_helper_header_size(layout_con);
3758     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
3759     BasicType etype  = Klass::layout_helper_element_type(layout_con);
3760     if ((round_mask & ~right_n_bits(eshift)) == 0)
3761       round_mask = 0;  // strength-reduce it if it goes away completely
3762     assert((hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
3763     assert(header_size_min <= hsize, "generic minimum is smallest");
3764     header_size_min = hsize;
3765     header_size = intcon(hsize + round_mask);
3766   } else {
3767     Node* hss   = intcon(Klass::_lh_header_size_shift);
3768     Node* hsm   = intcon(Klass::_lh_header_size_mask);
3769     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
3770     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
3771     Node* mask  = intcon(round_mask);
3772     header_size = _gvn.transform( new AddINode(hsize, mask) );
3773   }
3774 
3775   Node* elem_shift = NULL;
3776   if (layout_is_con) {
3777     int eshift = Klass::layout_helper_log2_element_size(layout_con);
3778     if (eshift != 0)
3779       elem_shift = intcon(eshift);
3780   } else {
3781     // There is no need to mask or shift this value.
3782     // The semantics of LShiftINode include an implicit mask to 0x1F.

3826   // places, one where the length is sharply limited, and the other
3827   // after a successful allocation.
3828   Node* abody = lengthx;
3829   if (elem_shift != NULL)
3830     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
3831   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
3832   if (round_mask != 0) {
3833     Node* mask = MakeConX(~round_mask);
3834     size       = _gvn.transform( new AndXNode(size, mask) );
3835   }
3836   // else if round_mask == 0, the size computation is self-rounding
3837 
3838   if (return_size_val != NULL) {
3839     // This is the size
3840     (*return_size_val) = size;
3841   }
3842 
3843   // Now generate allocation code
3844 
3845   // The entire memory state is needed for slow path of the allocation
3846   // since GC and deoptimization can happened.
3847   Node *mem = reset_memory();
3848   set_all_memory(mem); // Create new memory state
3849 
3850   if (initial_slow_test->is_Bool()) {
3851     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
3852     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
3853   }
3854 




























































3855   // Create the AllocateArrayNode and its result projections
3856   AllocateArrayNode* alloc
3857     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
3858                             control(), mem, i_o(),
3859                             size, klass_node,
3860                             initial_slow_test,
3861                             length);
3862 
3863   // Cast to correct type.  Note that the klass_node may be constant or not,
3864   // and in the latter case the actual array type will be inexact also.
3865   // (This happens via a non-constant argument to inline_native_newArray.)
3866   // In any case, the value of klass_node provides the desired array type.
3867   const TypeInt* length_type = _gvn.find_int_type(length);
3868   const TypeOopPtr* ary_type = _gvn.type(klass_node)->is_klassptr()->as_instance_type();
3869   if (ary_type->isa_aryptr() && length_type != NULL) {
3870     // Try to get a better type than POS for the size
3871     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
3872   }
3873 
3874   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
3875 
3876   array_ideal_length(alloc, ary_type, true);
3877   return javaoop;
3878 }
3879 
3880 // The following "Ideal_foo" functions are placed here because they recognize
3881 // the graph shapes created by the functions immediately above.
3882 
3883 //---------------------------Ideal_allocation----------------------------------
3884 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
3885 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
3886   if (ptr == NULL) {     // reduce dumb test in callers
3887     return NULL;
3888   }

3997   set_all_memory(ideal.merged_memory());
3998   set_i_o(ideal.i_o());
3999   set_control(ideal.ctrl());
4000 }
4001 
4002 void GraphKit::final_sync(IdealKit& ideal) {
4003   // Final sync IdealKit and graphKit.
4004   sync_kit(ideal);
4005 }
4006 
4007 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4008   Node* len = load_array_length(load_String_value(str, set_ctrl));
4009   Node* coder = load_String_coder(str, set_ctrl);
4010   // Divide length by 2 if coder is UTF16
4011   return _gvn.transform(new RShiftINode(len, coder));
4012 }
4013 
4014 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4015   int value_offset = java_lang_String::value_offset();
4016   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4017                                                      false, NULL, 0);
4018   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4019   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4020                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS),
4021                                                   ciTypeArrayKlass::make(T_BYTE), true, 0);
4022   Node* p = basic_plus_adr(str, str, value_offset);
4023   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4024                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4025   return load;
4026 }
4027 
4028 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4029   if (!CompactStrings) {
4030     return intcon(java_lang_String::CODER_UTF16);
4031   }
4032   int coder_offset = java_lang_String::coder_offset();
4033   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4034                                                      false, NULL, 0);
4035   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4036 
4037   Node* p = basic_plus_adr(str, str, coder_offset);
4038   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4039                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4040   return load;
4041 }
4042 
4043 void GraphKit::store_String_value(Node* str, Node* value) {
4044   int value_offset = java_lang_String::value_offset();
4045   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4046                                                      false, NULL, 0);
4047   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4048 
4049   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4050                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4051 }
4052 
4053 void GraphKit::store_String_coder(Node* str, Node* value) {
4054   int coder_offset = java_lang_String::coder_offset();
4055   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4056                                                      false, NULL, 0);
4057   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4058 
4059   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4060                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4061 }
4062 
4063 // Capture src and dst memory state with a MergeMemNode
4064 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4065   if (src_type == dst_type) {
4066     // Types are equal, we don't need a MergeMemNode
4067     return memory(src_type);
4068   }
4069   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4070   record_for_igvn(merge); // fold it up later, if possible
4071   int src_idx = C->get_alias_index(src_type);
4072   int dst_idx = C->get_alias_index(dst_type);
4073   merge->set_memory_at(src_idx, memory(src_idx));
4074   merge->set_memory_at(dst_idx, memory(dst_idx));
4075   return merge;
4076 }

4149   i_char->init_req(2, AddI(i_char, intcon(2)));
4150 
4151   set_control(IfFalse(iff));
4152   set_memory(st, TypeAryPtr::BYTES);
4153 }
4154 
4155 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4156   if (!field->is_constant()) {
4157     return NULL; // Field not marked as constant.
4158   }
4159   ciInstance* holder = NULL;
4160   if (!field->is_static()) {
4161     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4162     if (const_oop != NULL && const_oop->is_instance()) {
4163       holder = const_oop->as_instance();
4164     }
4165   }
4166   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4167                                                         /*is_unsigned_load=*/false);
4168   if (con_type != NULL) {
4169     return makecon(con_type);






4170   }
4171   return NULL;
4172 }










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

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

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

1180   Node* conv = _gvn.transform( new ConvI2LNode(offset));
1181   Node* mask = _gvn.transform(ConLNode::make((julong) max_juint));
1182   return _gvn.transform( new AndLNode(conv, mask) );
1183 }
1184 
1185 Node* GraphKit::ConvL2I(Node* offset) {
1186   // short-circuit a common case
1187   jlong offset_con = find_long_con(offset, (jlong)Type::OffsetBot);
1188   if (offset_con != (jlong)Type::OffsetBot) {
1189     return intcon((int) offset_con);
1190   }
1191   return _gvn.transform( new ConvL2INode(offset));
1192 }
1193 
1194 //-------------------------load_object_klass-----------------------------------
1195 Node* GraphKit::load_object_klass(Node* obj) {
1196   // Special-case a fresh allocation to avoid building nodes:
1197   Node* akls = AllocateNode::Ideal_klass(obj, &_gvn);
1198   if (akls != NULL)  return akls;
1199   Node* k_adr = basic_plus_adr(obj, oopDesc::klass_offset_in_bytes());
1200   return _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), k_adr, TypeInstPtr::KLASS, TypeInstKlassPtr::OBJECT));
1201 }
1202 
1203 //-------------------------load_array_length-----------------------------------
1204 Node* GraphKit::load_array_length(Node* array) {
1205   // Special-case a fresh allocation to avoid building nodes:
1206   AllocateArrayNode* alloc = AllocateArrayNode::Ideal_array_allocation(array, &_gvn);
1207   Node *alen;
1208   if (alloc == NULL) {
1209     Node *r_adr = basic_plus_adr(array, arrayOopDesc::length_offset_in_bytes());
1210     alen = _gvn.transform( new LoadRangeNode(0, immutable_memory(), r_adr, TypeInt::POS));
1211   } else {
1212     alen = array_ideal_length(alloc, _gvn.type(array)->is_oopptr(), false);
1213   }
1214   return alen;
1215 }
1216 
1217 Node* GraphKit::array_ideal_length(AllocateArrayNode* alloc,
1218                                    const TypeOopPtr* oop_type,
1219                                    bool replace_length_in_map) {
1220   Node* length = alloc->Ideal_length();

1229         replace_in_map(length, ccast);
1230       }
1231       return ccast;
1232     }
1233   }
1234   return length;
1235 }
1236 
1237 //------------------------------do_null_check----------------------------------
1238 // Helper function to do a NULL pointer check.  Returned value is
1239 // the incoming address with NULL casted away.  You are allowed to use the
1240 // not-null value only if you are control dependent on the test.
1241 #ifndef PRODUCT
1242 extern int explicit_null_checks_inserted,
1243            explicit_null_checks_elided;
1244 #endif
1245 Node* GraphKit::null_check_common(Node* value, BasicType type,
1246                                   // optional arguments for variations:
1247                                   bool assert_null,
1248                                   Node* *null_control,
1249                                   bool speculative,
1250                                   bool is_init_check) {
1251   assert(!assert_null || null_control == NULL, "not both at once");
1252   if (stopped())  return top();
1253   NOT_PRODUCT(explicit_null_checks_inserted++);
1254 
1255   if (value->is_InlineType()) {
1256     InlineTypeNode* vt = value->as_InlineType();
1257     null_check_common(vt->get_is_init(), T_INT, assert_null, null_control, speculative, true);
1258     if (stopped()) {
1259       return top();
1260     }
1261     if (assert_null) {
1262       // TODO 8284443 Scalarize here (this currently leads to compilation bailouts)
1263       // vt = InlineTypeNode::make_null(_gvn, vt->type()->inline_klass());
1264       // replace_in_map(value, vt);
1265       // return vt;
1266       return null();
1267     }
1268     bool do_replace_in_map = (null_control == NULL || (*null_control) == top());
1269     return cast_not_null(value, do_replace_in_map);
1270   } else if (value->is_InlineTypePtr()) {
1271     // Null checking a scalarized but nullable inline type. Check the IsInit
1272     // input instead of the oop input to avoid keeping buffer allocations alive.
1273     InlineTypePtrNode* vtptr = value->as_InlineTypePtr();
1274     while (vtptr->get_oop()->is_InlineTypePtr()) {
1275       vtptr = vtptr->get_oop()->as_InlineTypePtr();
1276     }
1277     null_check_common(vtptr->get_is_init(), T_INT, assert_null, null_control, speculative, true);
1278     if (stopped()) {
1279       return top();
1280     }
1281     if (assert_null) {
1282       // TODO 8284443 Scalarize here (this currently leads to compilation bailouts)
1283       // vtptr = InlineTypePtrNode::make_null(_gvn, vtptr->type()->inline_klass());
1284       // replace_in_map(value, vtptr);
1285       // return vtptr;
1286       return null();
1287     }
1288     bool do_replace_in_map = (null_control == NULL || (*null_control) == top());
1289     return cast_not_null(value, do_replace_in_map);
1290   }
1291 
1292   // Construct NULL check
1293   Node *chk = NULL;
1294   switch(type) {
1295     case T_LONG   : chk = new CmpLNode(value, _gvn.zerocon(T_LONG)); break;
1296     case T_INT    : chk = new CmpINode(value, _gvn.intcon(0)); break;
1297     case T_PRIMITIVE_OBJECT : // fall through
1298     case T_ARRAY  : // fall through
1299       type = T_OBJECT;  // simplify further tests
1300     case T_OBJECT : {
1301       const Type *t = _gvn.type( value );
1302 
1303       const TypeOopPtr* tp = t->isa_oopptr();
1304       if (tp != NULL && !tp->is_loaded()
1305           // Only for do_null_check, not any of its siblings:
1306           && !assert_null && null_control == NULL) {
1307         // Usually, any field access or invocation on an unloaded oop type
1308         // will simply fail to link, since the statically linked class is
1309         // likely also to be unloaded.  However, in -Xcomp mode, sometimes
1310         // the static class is loaded but the sharper oop type is not.
1311         // Rather than checking for this obscure case in lots of places,
1312         // we simply observe that a null check on an unloaded class
1313         // will always be followed by a nonsense operation, so we
1314         // can just issue the uncommon trap here.
1315         // Our access to the unloaded class will only be correct
1316         // after it has been loaded and initialized, which requires
1317         // a trip through the interpreter.

1376         }
1377         Node *oldcontrol = control();
1378         set_control(cfg);
1379         Node *res = cast_not_null(value);
1380         set_control(oldcontrol);
1381         NOT_PRODUCT(explicit_null_checks_elided++);
1382         return res;
1383       }
1384       cfg = IfNode::up_one_dom(cfg, /*linear_only=*/ true);
1385       if (cfg == NULL)  break;  // Quit at region nodes
1386       depth++;
1387     }
1388   }
1389 
1390   //-----------
1391   // Branch to failure if null
1392   float ok_prob = PROB_MAX;  // a priori estimate:  nulls never happen
1393   Deoptimization::DeoptReason reason;
1394   if (assert_null) {
1395     reason = Deoptimization::reason_null_assert(speculative);
1396   } else if (type == T_OBJECT || is_init_check) {
1397     reason = Deoptimization::reason_null_check(speculative);
1398   } else {
1399     reason = Deoptimization::Reason_div0_check;
1400   }
1401   // %%% Since Reason_unhandled is not recorded on a per-bytecode basis,
1402   // ciMethodData::has_trap_at will return a conservative -1 if any
1403   // must-be-null assertion has failed.  This could cause performance
1404   // problems for a method after its first do_null_assert failure.
1405   // Consider using 'Reason_class_check' instead?
1406 
1407   // To cause an implicit null check, we set the not-null probability
1408   // to the maximum (PROB_MAX).  For an explicit check the probability
1409   // is set to a smaller value.
1410   if (null_control != NULL || too_many_traps(reason)) {
1411     // probability is less likely
1412     ok_prob =  PROB_LIKELY_MAG(3);
1413   } else if (!assert_null &&
1414              (ImplicitNullCheckThreshold > 0) &&
1415              method() != NULL &&
1416              (method()->method_data()->trap_count(reason)

1450   }
1451 
1452   if (assert_null) {
1453     // Cast obj to null on this path.
1454     replace_in_map(value, zerocon(type));
1455     return zerocon(type);
1456   }
1457 
1458   // Cast obj to not-null on this path, if there is no null_control.
1459   // (If there is a null_control, a non-null value may come back to haunt us.)
1460   if (type == T_OBJECT) {
1461     Node* cast = cast_not_null(value, false);
1462     if (null_control == NULL || (*null_control) == top())
1463       replace_in_map(value, cast);
1464     value = cast;
1465   }
1466 
1467   return value;
1468 }
1469 

1470 //------------------------------cast_not_null----------------------------------
1471 // Cast obj to not-null on this path
1472 Node* GraphKit::cast_not_null(Node* obj, bool do_replace_in_map) {
1473   if (obj->is_InlineType()) {
1474     InlineTypeNode* vt = obj->clone()->as_InlineType();
1475     vt->set_is_init(_gvn);
1476     vt = _gvn.transform(vt)->as_InlineType();
1477     if (do_replace_in_map) {
1478       replace_in_map(obj, vt);
1479     }
1480     return vt;
1481   } else if (obj->is_InlineTypePtr()) {
1482     // Cast oop input instead
1483     Node* cast = cast_not_null(obj->as_InlineTypePtr()->get_oop(), do_replace_in_map);
1484     if (cast->is_top()) {
1485       // Always null
1486       return top();
1487     }
1488     // Create a new node with the casted oop input and is_init set
1489     InlineTypeBaseNode* vt = obj->clone()->as_InlineTypePtr();
1490     vt->set_oop(cast);
1491     vt->set_is_init(_gvn);
1492     vt = _gvn.transform(vt)->as_InlineTypePtr();
1493     if (do_replace_in_map) {
1494       replace_in_map(obj, vt);
1495     }
1496     return vt;
1497   }
1498   const Type *t = _gvn.type(obj);
1499   const Type *t_not_null = t->join_speculative(TypePtr::NOTNULL);
1500   // Object is already not-null?
1501   if( t == t_not_null ) return obj;
1502 
1503   Node *cast = new CastPPNode(obj,t_not_null);
1504   cast->init_req(0, control());
1505   cast = _gvn.transform( cast );
1506 
1507   // Scan for instances of 'obj' in the current JVM mapping.
1508   // These instances are known to be not-null after the test.
1509   if (do_replace_in_map)
1510     replace_in_map(obj, cast);
1511 
1512   return cast;                  // Return casted value
1513 }
1514 
1515 // Sometimes in intrinsics, we implicitly know an object is not null
1516 // (there's no actual null check) so we can cast it to not null. In
1517 // the course of optimizations, the input to the cast can become null.

1604 // These are layered on top of the factory methods in LoadNode and StoreNode,
1605 // and integrate with the parser's memory state and _gvn engine.
1606 //
1607 
1608 // factory methods in "int adr_idx"
1609 Node* GraphKit::make_load(Node* ctl, Node* adr, const Type* t, BasicType bt,
1610                           int adr_idx,
1611                           MemNode::MemOrd mo,
1612                           LoadNode::ControlDependency control_dependency,
1613                           bool require_atomic_access,
1614                           bool unaligned,
1615                           bool mismatched,
1616                           bool unsafe,
1617                           uint8_t barrier_data) {
1618   assert(adr_idx != Compile::AliasIdxTop, "use other make_load factory" );
1619   const TypePtr* adr_type = NULL; // debug-mode-only argument
1620   debug_only(adr_type = C->get_adr_type(adr_idx));
1621   Node* mem = memory(adr_idx);
1622   Node* ld = LoadNode::make(_gvn, ctl, mem, adr, adr_type, t, bt, mo, control_dependency, require_atomic_access, unaligned, mismatched, unsafe, barrier_data);
1623   ld = _gvn.transform(ld);
1624 
1625   if (((bt == T_OBJECT || bt == T_PRIMITIVE_OBJECT) && C->do_escape_analysis()) || C->eliminate_boxing()) {
1626     // Improve graph before escape analysis and boxing elimination.
1627     record_for_igvn(ld);
1628   }
1629   return ld;
1630 }
1631 
1632 Node* GraphKit::store_to_memory(Node* ctl, Node* adr, Node *val, BasicType bt,
1633                                 int adr_idx,
1634                                 MemNode::MemOrd mo,
1635                                 bool require_atomic_access,
1636                                 bool unaligned,
1637                                 bool mismatched,
1638                                 bool unsafe) {
1639   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1640   const TypePtr* adr_type = NULL;
1641   debug_only(adr_type = C->get_adr_type(adr_idx));
1642   Node *mem = memory(adr_idx);
1643   Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1644   if (unaligned) {
1645     st->as_Store()->set_unaligned_access();

1649   }
1650   if (unsafe) {
1651     st->as_Store()->set_unsafe_access();
1652   }
1653   st = _gvn.transform(st);
1654   set_memory(st, adr_idx);
1655   // Back-to-back stores can only remove intermediate store with DU info
1656   // so push on worklist for optimizer.
1657   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1658     record_for_igvn(st);
1659 
1660   return st;
1661 }
1662 
1663 Node* GraphKit::access_store_at(Node* obj,
1664                                 Node* adr,
1665                                 const TypePtr* adr_type,
1666                                 Node* val,
1667                                 const Type* val_type,
1668                                 BasicType bt,
1669                                 DecoratorSet decorators,
1670                                 bool safe_for_replace) {
1671   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1672   // could be delayed during Parse (for example, in adjust_map_after_if()).
1673   // Execute transformation here to avoid barrier generation in such case.
1674   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1675     val = _gvn.makecon(TypePtr::NULL_PTR);
1676   }
1677 
1678   if (stopped()) {
1679     return top(); // Dead path ?
1680   }
1681 
1682   assert(val != NULL, "not dead path");
1683   if (val->is_InlineType()) {
1684     // Store to non-flattened field. Buffer the inline type and make sure
1685     // the store is re-executed if the allocation triggers deoptimization.
1686     PreserveReexecuteState preexecs(this);
1687     jvms()->set_should_reexecute(true);
1688     val = val->as_InlineType()->buffer(this, safe_for_replace);
1689   }
1690 
1691   C2AccessValuePtr addr(adr, adr_type);
1692   C2AccessValue value(val, val_type);
1693   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1694   if (access.is_raw()) {
1695     return _barrier_set->BarrierSetC2::store_at(access, value);
1696   } else {
1697     return _barrier_set->store_at(access, value);
1698   }
1699 }
1700 
1701 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1702                                Node* adr,   // actual address to store val at
1703                                const TypePtr* adr_type,
1704                                const Type* val_type,
1705                                BasicType bt,
1706                                DecoratorSet decorators,
1707                                Node* ctl) {
1708   if (stopped()) {
1709     return top(); // Dead path ?
1710   }
1711 
1712   C2AccessValuePtr addr(adr, adr_type);
1713   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1714   if (access.is_raw()) {
1715     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1716   } else {
1717     return _barrier_set->load_at(access, val_type);
1718   }
1719 }
1720 
1721 Node* GraphKit::access_load(Node* adr,   // actual address to load val at
1722                             const Type* val_type,
1723                             BasicType bt,
1724                             DecoratorSet decorators) {
1725   if (stopped()) {
1726     return top(); // Dead path ?
1727   }
1728 
1729   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1730   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1731   if (access.is_raw()) {
1732     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1733   } else {

1798                                      Node* new_val,
1799                                      const Type* value_type,
1800                                      BasicType bt,
1801                                      DecoratorSet decorators) {
1802   C2AccessValuePtr addr(adr, adr_type);
1803   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1804   if (access.is_raw()) {
1805     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1806   } else {
1807     return _barrier_set->atomic_add_at(access, new_val, value_type);
1808   }
1809 }
1810 
1811 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1812   return _barrier_set->clone(this, src, dst, size, is_array);
1813 }
1814 
1815 //-------------------------array_element_address-------------------------
1816 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1817                                       const TypeInt* sizetype, Node* ctrl) {
1818   const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
1819   uint shift = arytype->is_flat() ? arytype->flat_log_elem_size() : exact_log2(type2aelembytes(elembt));
1820   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1821 
1822   // short-circuit a common case (saves lots of confusing waste motion)
1823   jint idx_con = find_int_con(idx, -1);
1824   if (idx_con >= 0) {
1825     intptr_t offset = header + ((intptr_t)idx_con << shift);
1826     return basic_plus_adr(ary, offset);
1827   }
1828 
1829   // must be correct type for alignment purposes
1830   Node* base  = basic_plus_adr(ary, header);
1831   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1832   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1833   return basic_plus_adr(ary, base, scale);
1834 }
1835 
1836 //-------------------------load_array_element-------------------------
1837 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1838   const Type* elemtype = arytype->elem();
1839   BasicType elembt = elemtype->array_element_basic_type();
1840   assert(elembt != T_PRIMITIVE_OBJECT, "inline types are not supported by this method");
1841   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1842   if (elembt == T_NARROWOOP) {
1843     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1844   }
1845   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1846                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1847   return ld;
1848 }
1849 
1850 //-------------------------set_arguments_for_java_call-------------------------
1851 // Arguments (pre-popped from the stack) are taken from the JVMS.
1852 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1853   PreserveReexecuteState preexecs(this);
1854   if (EnableValhalla) {
1855     // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization.
1856     // At this point, the call hasn't been executed yet, so we will only ever execute the call once.
1857     jvms()->set_should_reexecute(true);
1858     int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1859     inc_sp(arg_size);
1860   }
1861   // Add the call arguments
1862   const TypeTuple* domain = call->tf()->domain_sig();
1863   uint nargs = domain->cnt();
1864   int arg_num = 0;
1865   for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1866     Node* arg = argument(i-TypeFunc::Parms);
1867     const Type* t = domain->field_at(i);
1868     if (t->is_inlinetypeptr() && call->method()->is_scalarized_arg(arg_num)) {
1869       // We don't pass inline type arguments by reference but instead pass each field of the inline type
1870       if (!arg->is_InlineTypeBase()) {
1871         assert(_gvn.type(arg)->is_zero_type() && !t->inline_klass()->is_null_free(), "Unexpected argument type");
1872         arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass(), t->inline_klass()->is_null_free());
1873       }
1874       InlineTypeBaseNode* vt = arg->as_InlineTypeBase();
1875       vt->pass_fields(this, call, idx, true, !t->maybe_null());
1876       // If an inline type argument is passed as fields, attach the Method* to the call site
1877       // to be able to access the extended signature later via attached_method_before_pc().
1878       // For example, see CompiledMethod::preserve_callee_argument_oops().
1879       call->set_override_symbolic_info(true);
1880       arg_num++;
1881       continue;
1882     } else if (arg->is_InlineType()) {
1883       // Pass inline type argument via oop to callee
1884       arg = arg->as_InlineType()->buffer(this);
1885       if (!is_late_inline) {
1886         arg = arg->as_InlineTypePtr()->get_oop();
1887       }
1888     }
1889     if (t != Type::HALF) {
1890       arg_num++;
1891     }
1892     call->init_req(idx++, arg);
1893   }
1894 }
1895 
1896 //---------------------------set_edges_for_java_call---------------------------
1897 // Connect a newly created call into the current JVMS.
1898 // A return value node (if any) is returned from set_edges_for_java_call.
1899 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1900 
1901   // Add the predefined inputs:
1902   call->init_req( TypeFunc::Control, control() );
1903   call->init_req( TypeFunc::I_O    , i_o() );
1904   call->init_req( TypeFunc::Memory , reset_memory() );
1905   call->init_req( TypeFunc::FramePtr, frameptr() );
1906   call->init_req( TypeFunc::ReturnAdr, top() );
1907 
1908   add_safepoint_edges(call, must_throw);
1909 
1910   Node* xcall = _gvn.transform(call);
1911 
1912   if (xcall == top()) {
1913     set_control(top());
1914     return;
1915   }
1916   assert(xcall == call, "call identity is stable");
1917 
1918   // Re-use the current map to produce the result.
1919 
1920   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1921   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1922   set_all_memory_call(xcall, separate_io_proj);
1923 
1924   //return xcall;   // no need, caller already has it
1925 }
1926 
1927 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1928   if (stopped())  return top();  // maybe the call folded up?
1929 







1930   // Note:  Since any out-of-line call can produce an exception,
1931   // we always insert an I_O projection from the call into the result.
1932 
1933   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1934 
1935   if (separate_io_proj) {
1936     // The caller requested separate projections be used by the fall
1937     // through and exceptional paths, so replace the projections for
1938     // the fall through path.
1939     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1940     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1941   }
1942 
1943   // Capture the return value, if any.
1944   Node* ret;
1945   if (call->method() == NULL || call->method()->return_type()->basic_type() == T_VOID) {
1946     ret = top();
1947   } else if (call->tf()->returns_inline_type_as_fields()) {
1948     // Return of multiple values (inline type fields): we create a
1949     // InlineType node, each field is a projection from the call.
1950     ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
1951     uint base_input = TypeFunc::Parms;
1952     ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, call->method()->signature()->returns_null_free_inline_type());
1953   } else {
1954     ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1955   }
1956 
1957   return ret;
1958 }
1959 
1960 //--------------------set_predefined_input_for_runtime_call--------------------
1961 // Reading and setting the memory state is way conservative here.
1962 // The real problem is that I am not doing real Type analysis on memory,
1963 // so I cannot distinguish card mark stores from other stores.  Across a GC
1964 // point the Store Barrier and the card mark memory has to agree.  I cannot
1965 // have a card mark store and its barrier split across the GC point from
1966 // either above or below.  Here I get that to happen by reading ALL of memory.
1967 // A better answer would be to separate out card marks from other memory.
1968 // For now, return the input memory state, so that it can be reused
1969 // after the call, if this call has restricted memory effects.
1970 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1971   // Set fixed predefined input arguments
1972   Node* memory = reset_memory();
1973   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1974   call->init_req( TypeFunc::Control,   control()  );
1975   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1976   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs

2027     if (use->is_MergeMem()) {
2028       wl.push(use);
2029     }
2030   }
2031 }
2032 
2033 // Replace the call with the current state of the kit.
2034 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
2035   JVMState* ejvms = NULL;
2036   if (has_exceptions()) {
2037     ejvms = transfer_exceptions_into_jvms();
2038   }
2039 
2040   ReplacedNodes replaced_nodes = map()->replaced_nodes();
2041   ReplacedNodes replaced_nodes_exception;
2042   Node* ex_ctl = top();
2043 
2044   SafePointNode* final_state = stop();
2045 
2046   // Find all the needed outputs of this call
2047   CallProjections* callprojs = call->extract_projections(true);

2048 
2049   Unique_Node_List wl;
2050   Node* init_mem = call->in(TypeFunc::Memory);
2051   Node* final_mem = final_state->in(TypeFunc::Memory);
2052   Node* final_ctl = final_state->in(TypeFunc::Control);
2053   Node* final_io = final_state->in(TypeFunc::I_O);
2054 
2055   // Replace all the old call edges with the edges from the inlining result
2056   if (callprojs->fallthrough_catchproj != NULL) {
2057     C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2058   }
2059   if (callprojs->fallthrough_memproj != NULL) {
2060     if (final_mem->is_MergeMem()) {
2061       // Parser's exits MergeMem was not transformed but may be optimized
2062       final_mem = _gvn.transform(final_mem);
2063     }
2064     C->gvn_replace_by(callprojs->fallthrough_memproj,   final_mem);
2065     add_mergemem_users_to_worklist(wl, final_mem);
2066   }
2067   if (callprojs->fallthrough_ioproj != NULL) {
2068     C->gvn_replace_by(callprojs->fallthrough_ioproj,    final_io);
2069   }
2070 
2071   // Replace the result with the new result if it exists and is used
2072   if (callprojs->resproj[0] != NULL && result != NULL) {
2073     // If the inlined code is dead, the result projections for an inline type returned as
2074     // fields have not been replaced. They will go away once the call is replaced by TOP below.
2075     assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()),
2076            "unexpected number of results");
2077     C->gvn_replace_by(callprojs->resproj[0], result);
2078   }
2079 
2080   if (ejvms == NULL) {
2081     // No exception edges to simply kill off those paths
2082     if (callprojs->catchall_catchproj != NULL) {
2083       C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2084     }
2085     if (callprojs->catchall_memproj != NULL) {
2086       C->gvn_replace_by(callprojs->catchall_memproj,   C->top());
2087     }
2088     if (callprojs->catchall_ioproj != NULL) {
2089       C->gvn_replace_by(callprojs->catchall_ioproj,    C->top());
2090     }
2091     // Replace the old exception object with top
2092     if (callprojs->exobj != NULL) {
2093       C->gvn_replace_by(callprojs->exobj, C->top());
2094     }
2095   } else {
2096     GraphKit ekit(ejvms);
2097 
2098     // Load my combined exception state into the kit, with all phis transformed:
2099     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2100     replaced_nodes_exception = ex_map->replaced_nodes();
2101 
2102     Node* ex_oop = ekit.use_exception_state(ex_map);
2103 
2104     if (callprojs->catchall_catchproj != NULL) {
2105       C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2106       ex_ctl = ekit.control();
2107     }
2108     if (callprojs->catchall_memproj != NULL) {
2109       Node* ex_mem = ekit.reset_memory();
2110       C->gvn_replace_by(callprojs->catchall_memproj,   ex_mem);
2111       add_mergemem_users_to_worklist(wl, ex_mem);
2112     }
2113     if (callprojs->catchall_ioproj != NULL) {
2114       C->gvn_replace_by(callprojs->catchall_ioproj,    ekit.i_o());
2115     }
2116 
2117     // Replace the old exception object with the newly created one
2118     if (callprojs->exobj != NULL) {
2119       C->gvn_replace_by(callprojs->exobj, ex_oop);
2120     }
2121   }
2122 
2123   // Disconnect the call from the graph
2124   call->disconnect_inputs(C);
2125   C->gvn_replace_by(call, C->top());
2126 
2127   // Clean up any MergeMems that feed other MergeMems since the
2128   // optimizer doesn't like that.
2129   while (wl.size() > 0) {
2130     _gvn.transform(wl.pop());
2131   }
2132 
2133   if (callprojs->fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
2134     replaced_nodes.apply(C, final_ctl);
2135   }
2136   if (!ex_ctl->is_top() && do_replaced_nodes) {
2137     replaced_nodes_exception.apply(C, ex_ctl);
2138   }
2139 }
2140 
2141 
2142 //------------------------------increment_counter------------------------------
2143 // for statistics: increment a VM counter by 1
2144 
2145 void GraphKit::increment_counter(address counter_addr) {
2146   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2147   increment_counter(adr1);
2148 }
2149 
2150 void GraphKit::increment_counter(Node* counter_addr) {
2151   int adr_type = Compile::AliasIdxRaw;
2152   Node* ctrl = control();
2153   Node* cnt  = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);

2312  *
2313  * @param n          node that the type applies to
2314  * @param exact_kls  type from profiling
2315  * @param maybe_null did profiling see null?
2316  *
2317  * @return           node with improved type
2318  */
2319 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2320   const Type* current_type = _gvn.type(n);
2321   assert(UseTypeSpeculation, "type speculation must be on");
2322 
2323   const TypePtr* speculative = current_type->speculative();
2324 
2325   // Should the klass from the profile be recorded in the speculative type?
2326   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2327     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls);
2328     const TypeOopPtr* xtype = tklass->as_instance_type();
2329     assert(xtype->klass_is_exact(), "Should be exact");
2330     // Any reason to believe n is not null (from this profiling or a previous one)?
2331     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2332     const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2333     // record the new speculative type's depth
2334     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2335     speculative = speculative->with_inline_depth(jvms()->depth());
2336   } else if (current_type->would_improve_ptr(ptr_kind)) {
2337     // Profiling report that null was never seen so we can change the
2338     // speculative type to non null ptr.
2339     if (ptr_kind == ProfileAlwaysNull) {
2340       speculative = TypePtr::NULL_PTR;
2341     } else {
2342       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2343       const TypePtr* ptr = TypePtr::NOTNULL;
2344       if (speculative != NULL) {
2345         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2346       } else {
2347         speculative = ptr;
2348       }
2349     }
2350   }
2351 
2352   if (speculative != current_type->speculative()) {
2353     // Build a type with a speculative type (what we think we know
2354     // about the type but will need a guard when we use it)
2355     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2356     // We're changing the type, we need a new CheckCast node to carry
2357     // the new type. The new type depends on the control: what
2358     // profiling tells us is only valid from here as far as we can
2359     // tell.
2360     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2361     cast = _gvn.transform(cast);
2362     replace_in_map(n, cast);
2363     n = cast;
2364   }
2365 
2366   return n;
2367 }
2368 
2369 /**
2370  * Record profiling data from receiver profiling at an invoke with the
2371  * type system so that it can propagate it (speculation)
2372  *
2373  * @param n  receiver node
2374  *
2375  * @return   node with improved type
2376  */
2377 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2378   if (!UseTypeSpeculation) {
2379     return n;
2380   }
2381   ciKlass* exact_kls = profile_has_unique_klass();
2382   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2383   if ((java_bc() == Bytecodes::_checkcast ||
2384        java_bc() == Bytecodes::_instanceof ||
2385        java_bc() == Bytecodes::_aastore) &&
2386       method()->method_data()->is_mature()) {
2387     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2388     if (data != NULL) {
2389       if (java_bc() == Bytecodes::_aastore) {
2390         ciKlass* array_type = NULL;
2391         ciKlass* element_type = NULL;
2392         ProfilePtrKind element_ptr = ProfileMaybeNull;
2393         bool flat_array = true;
2394         bool null_free_array = true;
2395         method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2396         exact_kls = element_type;
2397         ptr_kind = element_ptr;
2398       } else {
2399         if (!data->as_BitData()->null_seen()) {
2400           ptr_kind = ProfileNeverNull;
2401         } else {
2402           assert(data->is_ReceiverTypeData(), "bad profile data type");
2403           ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2404           uint i = 0;
2405           for (; i < call->row_limit(); i++) {
2406             ciKlass* receiver = call->receiver(i);
2407             if (receiver != NULL) {
2408               break;
2409             }
2410           }
2411           ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2412         }

2413       }
2414     }
2415   }
2416   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2417 }
2418 
2419 /**
2420  * Record profiling data from argument profiling at an invoke with the
2421  * type system so that it can propagate it (speculation)
2422  *
2423  * @param dest_method  target method for the call
2424  * @param bc           what invoke bytecode is this?
2425  */
2426 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2427   if (!UseTypeSpeculation) {
2428     return;
2429   }
2430   const TypeFunc* tf    = TypeFunc::make(dest_method);
2431   int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2432   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2433   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2434     const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2435     if (is_reference_type(targ->basic_type())) {
2436       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2437       ciKlass* better_type = NULL;
2438       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2439         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2440       }
2441       i++;
2442     }
2443   }
2444 }
2445 
2446 /**
2447  * Record profiling data from parameter profiling at an invoke with
2448  * the type system so that it can propagate it (speculation)
2449  */
2450 void GraphKit::record_profiled_parameters_for_speculation() {
2451   if (!UseTypeSpeculation) {
2452     return;
2453   }
2454   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {

2468  * the type system so that it can propagate it (speculation)
2469  */
2470 void GraphKit::record_profiled_return_for_speculation() {
2471   if (!UseTypeSpeculation) {
2472     return;
2473   }
2474   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2475   ciKlass* better_type = NULL;
2476   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2477     // If profiling reports a single type for the return value,
2478     // feed it to the type system so it can propagate it as a
2479     // speculative type
2480     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2481   }
2482 }
2483 
2484 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2485   if (Matcher::strict_fp_requires_explicit_rounding) {
2486     // (Note:  TypeFunc::make has a cache that makes this fast.)
2487     const TypeFunc* tf    = TypeFunc::make(dest_method);
2488     int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2489     for (int j = 0; j < nargs; j++) {
2490       const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2491       if (targ->basic_type() == T_DOUBLE) {
2492         // If any parameters are doubles, they must be rounded before
2493         // the call, dprecision_rounding does gvn.transform
2494         Node *arg = argument(j);
2495         arg = dprecision_rounding(arg);
2496         set_argument(j, arg);
2497       }
2498     }
2499   }
2500 }
2501 
2502 // rounding for strict float precision conformance
2503 Node* GraphKit::precision_rounding(Node* n) {
2504   if (Matcher::strict_fp_requires_explicit_rounding) {
2505 #ifdef IA32
2506     if (UseSSE == 0) {
2507       return _gvn.transform(new RoundFloatNode(0, n));
2508     }
2509 #else
2510     Unimplemented();

2619                                   // The first NULL ends the list.
2620                                   Node* parm0, Node* parm1,
2621                                   Node* parm2, Node* parm3,
2622                                   Node* parm4, Node* parm5,
2623                                   Node* parm6, Node* parm7) {
2624   assert(call_addr != NULL, "must not call NULL targets");
2625 
2626   // Slow-path call
2627   bool is_leaf = !(flags & RC_NO_LEAF);
2628   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2629   if (call_name == NULL) {
2630     assert(!is_leaf, "must supply name for leaf");
2631     call_name = OptoRuntime::stub_name(call_addr);
2632   }
2633   CallNode* call;
2634   if (!is_leaf) {
2635     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2636   } else if (flags & RC_NO_FP) {
2637     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2638   } else  if (flags & RC_VECTOR){
2639     uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2640     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2641   } else {
2642     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2643   }
2644 
2645   // The following is similar to set_edges_for_java_call,
2646   // except that the memory effects of the call are restricted to AliasIdxRaw.
2647 
2648   // Slow path call has no side-effects, uses few values
2649   bool wide_in  = !(flags & RC_NARROW_MEM);
2650   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2651 
2652   Node* prev_mem = NULL;
2653   if (wide_in) {
2654     prev_mem = set_predefined_input_for_runtime_call(call);
2655   } else {
2656     assert(!wide_out, "narrow in => narrow out");
2657     Node* narrow_mem = memory(adr_type);
2658     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2659   }

2699 
2700   if (has_io) {
2701     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2702   }
2703   return call;
2704 
2705 }
2706 
2707 // i2b
2708 Node* GraphKit::sign_extend_byte(Node* in) {
2709   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2710   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2711 }
2712 
2713 // i2s
2714 Node* GraphKit::sign_extend_short(Node* in) {
2715   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2716   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2717 }
2718 
2719 
2720 //------------------------------merge_memory-----------------------------------
2721 // Merge memory from one path into the current memory state.
2722 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2723   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2724     Node* old_slice = mms.force_memory();
2725     Node* new_slice = mms.memory2();
2726     if (old_slice != new_slice) {
2727       PhiNode* phi;
2728       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2729         if (mms.is_empty()) {
2730           // clone base memory Phi's inputs for this memory slice
2731           assert(old_slice == mms.base_memory(), "sanity");
2732           phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2733           _gvn.set_type(phi, Type::MEMORY);
2734           for (uint i = 1; i < phi->req(); i++) {
2735             phi->init_req(i, old_slice->in(i));
2736           }
2737         } else {
2738           phi = old_slice->as_Phi(); // Phi was generated already
2739         }

2951 
2952   // Now do a linear scan of the secondary super-klass array.  Again, no real
2953   // performance impact (too rare) but it's gotta be done.
2954   // Since the code is rarely used, there is no penalty for moving it
2955   // out of line, and it can only improve I-cache density.
2956   // The decision to inline or out-of-line this final check is platform
2957   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2958   Node* psc = gvn.transform(
2959     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2960 
2961   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2962   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2963   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2964 
2965   // Return false path; set default control to true path.
2966   *ctrl = gvn.transform(r_ok_subtype);
2967   return gvn.transform(r_not_subtype);
2968 }
2969 
2970 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2971   const Type* sub_t = _gvn.type(obj_or_subklass);
2972   if (sub_t->isa_inlinetype()) {
2973     obj_or_subklass = makecon(TypeKlassPtr::make(sub_t->inline_klass()));
2974   }
2975   bool expand_subtype_check = C->post_loop_opts_phase() ||   // macro node expansion is over
2976                               ExpandSubTypeCheckAtParseTime; // forced expansion
2977   if (expand_subtype_check) {
2978     MergeMemNode* mem = merged_memory();
2979     Node* ctrl = control();
2980     Node* subklass = obj_or_subklass;
2981     if (!sub_t->isa_klassptr() && !sub_t->isa_inlinetype()) {
2982       subklass = load_object_klass(obj_or_subklass);
2983     }

2984     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2985     set_control(ctrl);
2986     return n;
2987   }
2988 
2989   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2990   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2991   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2992   set_control(_gvn.transform(new IfTrueNode(iff)));
2993   return _gvn.transform(new IfFalseNode(iff));
2994 }
2995 
2996 // Profile-driven exact type check:
2997 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2998                                     float prob, Node* *casted_receiver) {

2999   assert(!klass->is_interface(), "no exact type check on interfaces");
3000   Node* fail = top();
3001   const Type* rec_t = _gvn.type(receiver);
3002   if (rec_t->isa_inlinetype()) {
3003     if (klass->equals(rec_t->inline_klass())) {
3004       (*casted_receiver) = receiver; // Always passes
3005     } else {
3006       (*casted_receiver) = top();    // Always fails
3007       fail = control();
3008       set_control(top());
3009     }
3010     return fail;
3011   }
3012   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
3013   Node* recv_klass = load_object_klass(receiver);
3014   fail = type_check(recv_klass, tklass, prob);





3015 
3016   if (!stopped()) {
3017     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3018     const TypeOopPtr* recv_xtype = tklass->as_instance_type();
3019     assert(recv_xtype->klass_is_exact(), "");
3020 
3021     if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts
3022       // Subsume downstream occurrences of receiver with a cast to
3023       // recv_xtype, since now we know what the type will be.
3024       Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
3025       Node* res = _gvn.transform(cast);
3026       if (recv_xtype->is_inlinetypeptr()) {
3027         assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
3028         res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass())->as_InlineTypeBase()->as_ptr(&gvn());
3029       }
3030       (*casted_receiver) = res;
3031       // (User must make the replace_in_map call.)
3032     }
3033   }
3034 
3035   return fail;
3036 }
3037 
3038 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
3039                            float prob) {
3040   Node* want_klass = makecon(tklass);
3041   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
3042   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3043   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
3044   set_control(_gvn.transform(new IfTrueNode (iff)));
3045   Node* fail = _gvn.transform(new IfFalseNode(iff));
3046   return fail;
3047 }
3048 
3049 //------------------------------subtype_check_receiver-------------------------
3050 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3051                                        Node** casted_receiver) {
3052   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass);
3053   Node* want_klass = makecon(tklass);
3054 
3055   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3056 
3057   // Ignore interface type information until interface types are properly tracked.
3058   if (!stopped() && !klass->is_interface()) {
3059     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3060     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3061     if (receiver_type != NULL && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3062       Node* cast = new CheckCastPPNode(control(), receiver, recv_type);
3063       (*casted_receiver) = _gvn.transform(cast);
3064     }
3065   }
3066 
3067   return slow_ctl;
3068 }
3069 
3070 //------------------------------seems_never_null-------------------------------
3071 // Use null_seen information if it is available from the profile.
3072 // If we see an unexpected null at a type check we record it and force a
3073 // recompile; the offending check will be recompiled to handle NULLs.
3074 // If we see several offending BCIs, then all checks in the
3075 // method will be recompiled.
3076 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3077   speculating = !_gvn.type(obj)->speculative_maybe_null();
3078   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3079   if (UncommonNullCast               // Cutout for this technique
3080       && obj != null()               // And not the -Xcomp stupid case?
3081       && !too_many_traps(reason)
3082       ) {
3083     if (speculating) {
3084       return true;
3085     }
3086     if (data == NULL)
3087       // Edge case:  no mature data.  Be optimistic here.
3088       return true;
3089     // If the profile has not seen a null, assume it won't happen.
3090     assert(java_bc() == Bytecodes::_checkcast ||
3091            java_bc() == Bytecodes::_instanceof ||
3092            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3093     if (java_bc() == Bytecodes::_aastore) {
3094       return ((ciArrayLoadStoreData*)data->as_ArrayLoadStoreData())->element()->ptr_kind() == ProfileNeverNull;
3095     }
3096     return !data->as_BitData()->null_seen();
3097   }
3098   speculating = false;
3099   return false;
3100 }
3101 
3102 void GraphKit::guard_klass_being_initialized(Node* klass) {
3103   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3104   Node* adr = basic_plus_adr(top(), klass, init_state_off);
3105   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3106                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3107                                     T_BYTE, MemNode::unordered);
3108   init_state = _gvn.transform(init_state);
3109 
3110   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3111 
3112   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3113   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3114 
3115   { BuildCutout unless(this, tst, PROB_MAX);

3155 
3156 //------------------------maybe_cast_profiled_receiver-------------------------
3157 // If the profile has seen exactly one type, narrow to exactly that type.
3158 // Subsequent type checks will always fold up.
3159 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3160                                              const TypeKlassPtr* require_klass,
3161                                              ciKlass* spec_klass,
3162                                              bool safe_for_replace) {
3163   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
3164 
3165   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
3166 
3167   // Make sure we haven't already deoptimized from this tactic.
3168   if (too_many_traps_or_recompiles(reason))
3169     return NULL;
3170 
3171   // (No, this isn't a call, but it's enough like a virtual call
3172   // to use the same ciMethod accessor to get the profile info...)
3173   // If we have a speculative type use it instead of profiling (which
3174   // may not help us)
3175   ciKlass* exact_kls = spec_klass;
3176   if (exact_kls == NULL) {
3177     if (java_bc() == Bytecodes::_aastore) {
3178       ciKlass* array_type = NULL;
3179       ciKlass* element_type = NULL;
3180       ProfilePtrKind element_ptr = ProfileMaybeNull;
3181       bool flat_array = true;
3182       bool null_free_array = true;
3183       method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3184       exact_kls = element_type;
3185     } else {
3186       exact_kls = profile_has_unique_klass();
3187     }
3188   }
3189   if (exact_kls != NULL) {// no cast failures here
3190     if (require_klass == NULL ||
3191         C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls)) == Compile::SSC_always_true) {
3192       // If we narrow the type to match what the type profile sees or
3193       // the speculative type, we can then remove the rest of the
3194       // cast.
3195       // This is a win, even if the exact_kls is very specific,
3196       // because downstream operations, such as method calls,
3197       // will often benefit from the sharper type.
3198       Node* exact_obj = not_null_obj; // will get updated in place...
3199       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3200                                             &exact_obj);
3201       { PreserveJVMState pjvms(this);
3202         set_control(slow_ctl);
3203         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3204       }
3205       if (safe_for_replace) {
3206         replace_in_map(not_null_obj, exact_obj);
3207       }
3208       return exact_obj;

3273 // and the reflective instance-of call.
3274 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3275   kill_dead_locals();           // Benefit all the uncommon traps
3276   assert( !stopped(), "dead parse path should be checked in callers" );
3277   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3278          "must check for not-null not-dead klass in callers");
3279 
3280   // Make the merge point
3281   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3282   RegionNode* region = new RegionNode(PATH_LIMIT);
3283   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3284   C->set_has_split_ifs(true); // Has chance for split-if optimization
3285 
3286   ciProfileData* data = NULL;
3287   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3288     data = method()->method_data()->bci_to_data(bci());
3289   }
3290   bool speculative_not_null = false;
3291   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3292                          && seems_never_null(obj, data, speculative_not_null));
3293   bool is_value = obj->is_InlineType();
3294 
3295   // Null check; get casted pointer; set region slot 3
3296   Node* null_ctl = top();
3297   if (is_value) {
3298     // TODO 8284443 Enable this
3299     safe_for_replace = false;
3300     never_see_null = false;
3301   }
3302   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3303 
3304   // If not_null_obj is dead, only null-path is taken
3305   if (stopped()) {              // Doing instance-of on a NULL?
3306     set_control(null_ctl);
3307     return intcon(0);
3308   }
3309   region->init_req(_null_path, null_ctl);
3310   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3311   if (null_ctl == top()) {
3312     // Do this eagerly, so that pattern matches like is_diamond_phi
3313     // will work even during parsing.
3314     assert(_null_path == PATH_LIMIT-1, "delete last");
3315     region->del_req(_null_path);
3316     phi   ->del_req(_null_path);
3317   }
3318 
3319   // Do we know the type check always succeed?
3320   if (!is_value) {
3321     bool known_statically = false;
3322     if (_gvn.type(superklass)->singleton()) {
3323       const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3324       const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3325       if (subk != NULL && subk->is_loaded()) {
3326         int static_res = C->static_subtype_check(superk, subk);
3327         known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3328       }
3329     }

3330 
3331     if (!known_statically) {
3332       const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3333       // We may not have profiling here or it may not help us. If we
3334       // have a speculative type use it to perform an exact cast.
3335       ciKlass* spec_obj_type = obj_type->speculative_type();
3336       if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3337         Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3338         if (stopped()) {            // Profile disagrees with this path.
3339           set_control(null_ctl);    // Null is the only remaining possibility.
3340           return intcon(0);
3341         }
3342         if (cast_obj != NULL) {
3343           not_null_obj = cast_obj;
3344           is_value = not_null_obj->is_InlineType();
3345         }
3346       }
3347     }
3348   }
3349 
3350   // Generate the subtype check
3351   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3352 
3353   // Plug in the success path to the general merge in slot 1.
3354   region->init_req(_obj_path, control());
3355   phi   ->init_req(_obj_path, intcon(1));
3356 
3357   // Plug in the failing path to the general merge in slot 2.
3358   region->init_req(_fail_path, not_subtype_ctrl);
3359   phi   ->init_req(_fail_path, intcon(0));
3360 
3361   // Return final merged results
3362   set_control( _gvn.transform(region) );
3363   record_for_igvn(region);
3364 
3365   // If we know the type check always succeeds then we don't use the
3366   // profiling data at this bytecode. Don't lose it, feed it to the
3367   // type system as a speculative type.
3368   if (safe_for_replace && !is_value) {
3369     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3370     replace_in_map(obj, casted_obj);
3371   }
3372 
3373   return _gvn.transform(phi);
3374 }
3375 
3376 //-------------------------------gen_checkcast---------------------------------
3377 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3378 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3379 // uncommon-trap paths work.  Adjust stack after this call.
3380 // If failure_control is supplied and not null, it is filled in with
3381 // the control edge for the cast failure.  Otherwise, an appropriate
3382 // uncommon trap or exception is thrown.
3383 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass, Node* *failure_control, bool null_free) {

3384   kill_dead_locals();           // Benefit all the uncommon traps
3385   const TypeKlassPtr* tk = _gvn.type(superklass)->is_klassptr();
3386   const TypeOopPtr* toop = tk->cast_to_exactness(false)->as_instance_type();
3387   bool safe_for_replace = (failure_control == NULL);
3388   bool from_inline = obj->is_InlineType();
3389   assert(!null_free || toop->is_inlinetypeptr(), "must be an inline type pointer");
3390 
3391   // Fast cutout:  Check the case that the cast is vacuously true.
3392   // This detects the common cases where the test will short-circuit
3393   // away completely.  We do this before we perform the null check,
3394   // because if the test is going to turn into zero code, we don't
3395   // want a residual null check left around.  (Causes a slowdown,
3396   // for example, in some objArray manipulations, such as a[i]=a[j].)
3397   if (tk->singleton()) {
3398     const TypeKlassPtr* kptr = NULL;
3399     const Type* t = _gvn.type(obj);
3400     if (t->isa_oop_ptr()) {
3401       kptr = t->is_oopptr()->as_klass_type();
3402     } else if (obj->is_InlineTypeBase()) {
3403       ciInlineKlass* vk = t->inline_klass();
3404       kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0), vk->flatten_array());
3405     }
3406     if (kptr != NULL) {
3407       switch (C->static_subtype_check(tk, kptr)) {
3408       case Compile::SSC_always_true:
3409         // If we know the type check always succeed then we don't use
3410         // the profiling data at this bytecode. Don't lose it, feed it
3411         // to the type system as a speculative type.
3412         if (!from_inline) {
3413           obj = record_profiled_receiver_for_speculation(obj);
3414         }
3415         if (null_free) {
3416           assert(safe_for_replace, "must be");
3417           obj = null_check(obj);
3418         }
3419         assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineTypeBase(), "should have been scalarized");
3420         return obj;
3421       case Compile::SSC_always_false:
3422         if (null_free) {
3423           assert(safe_for_replace, "must be");
3424           obj = null_check(obj);
3425         }
3426         // It needs a null check because a null will *pass* the cast check.
3427         if (t->isa_oopptr() != NULL && !t->is_oopptr()->maybe_null()) {

3428           bool is_aastore = (java_bc() == Bytecodes::_aastore);
3429           Deoptimization::DeoptReason reason = is_aastore ?
3430             Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3431           builtin_throw(reason);
3432           return top();
3433         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3434           return null_assert(obj);
3435         }
3436         break; // Fall through to full check
3437       default:
3438         break;
3439       }
3440     }
3441   }
3442 
3443   ciProfileData* data = NULL;

3444   if (failure_control == NULL) {        // use MDO in regular case only
3445     assert(java_bc() == Bytecodes::_aastore ||
3446            java_bc() == Bytecodes::_checkcast,
3447            "interpreter profiles type checks only for these BCs");
3448     if (method()->method_data()->is_mature()) {
3449       data = method()->method_data()->bci_to_data(bci());
3450     }
3451   }
3452 
3453   // Make the merge point
3454   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3455   RegionNode* region = new RegionNode(PATH_LIMIT);
3456   Node*       phi    = new PhiNode(region, toop);
3457   _gvn.set_type(region, Type::CONTROL);
3458   _gvn.set_type(phi, toop);
3459 
3460   C->set_has_split_ifs(true); // Has chance for split-if optimization
3461 
3462   // Use null-cast information if it is available
3463   bool speculative_not_null = false;
3464   bool never_see_null = ((failure_control == NULL)  // regular case only
3465                          && seems_never_null(obj, data, speculative_not_null));
3466 
3467   // Null check; get casted pointer; set region slot 3
3468   Node* null_ctl = top();
3469   Node* not_null_obj = NULL;
3470   if (null_free) {
3471     assert(safe_for_replace, "must be");
3472     not_null_obj = null_check(obj);
3473   } else if (from_inline) {
3474     // TODO 8284443 obj can be null and null should pass
3475     not_null_obj = obj;
3476   } else {
3477     not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3478   }
3479 
3480   // If not_null_obj is dead, only null-path is taken
3481   if (stopped()) {              // Doing instance-of on a NULL?
3482     set_control(null_ctl);
3483     if (toop->is_inlinetypeptr()) {
3484       return InlineTypePtrNode::make_null(_gvn, toop->inline_klass());
3485     }
3486     return null();
3487   }
3488   region->init_req(_null_path, null_ctl);
3489   phi   ->init_req(_null_path, null());  // Set null path value
3490   if (null_ctl == top()) {
3491     // Do this eagerly, so that pattern matches like is_diamond_phi
3492     // will work even during parsing.
3493     assert(_null_path == PATH_LIMIT-1, "delete last");
3494     region->del_req(_null_path);
3495     phi   ->del_req(_null_path);
3496   }
3497 
3498   Node* cast_obj = NULL;
3499   if (!from_inline && tk->klass_is_exact()) {
3500     // The following optimization tries to statically cast the speculative type of the object
3501     // (for example obtained during profiling) to the type of the superklass and then do a
3502     // dynamic check that the type of the object is what we expect. To work correctly
3503     // for checkcast and aastore the type of superklass should be exact.
3504     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3505     // We may not have profiling here or it may not help us. If we have
3506     // a speculative type use it to perform an exact cast.
3507     ciKlass* spec_obj_type = obj_type->speculative_type();
3508     if (spec_obj_type != NULL || data != NULL) {
3509       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3510       if (cast_obj != NULL) {
3511         if (failure_control != NULL) // failure is now impossible
3512           (*failure_control) = top();
3513         // adjust the type of the phi to the exact klass:
3514         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3515       }
3516     }
3517   }
3518 
3519   if (cast_obj == NULL) {
3520     // Generate the subtype check
3521     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3522 
3523     // Plug in success path into the merge
3524     cast_obj = from_inline ? not_null_obj : _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3525     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3526     if (failure_control == NULL) {
3527       if (not_subtype_ctrl != top()) { // If failure is possible
3528         PreserveJVMState pjvms(this);
3529         set_control(not_subtype_ctrl);
3530         Node* obj_klass = NULL;
3531         if (not_null_obj->is_InlineTypeBase()) {
3532           obj_klass = makecon(TypeKlassPtr::make(_gvn.type(not_null_obj)->inline_klass()));
3533         } else {
3534           obj_klass = load_object_klass(not_null_obj);
3535         }
3536         bool is_aastore = (java_bc() == Bytecodes::_aastore);
3537         Deoptimization::DeoptReason reason = is_aastore ?
3538           Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3539         builtin_throw(reason);
3540       }
3541     } else {
3542       (*failure_control) = not_subtype_ctrl;
3543     }
3544   }
3545 
3546   region->init_req(_obj_path, control());
3547   phi   ->init_req(_obj_path, cast_obj);
3548 
3549   // A merge of NULL or Casted-NotNull obj
3550   Node* res = _gvn.transform(phi);
3551 
3552   // Note I do NOT always 'replace_in_map(obj,result)' here.
3553   //  if( tk->klass()->can_be_primary_super()  )
3554     // This means that if I successfully store an Object into an array-of-String
3555     // I 'forget' that the Object is really now known to be a String.  I have to
3556     // do this because we don't have true union types for interfaces - if I store
3557     // a Baz into an array-of-Interface and then tell the optimizer it's an
3558     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3559     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3560   //  replace_in_map( obj, res );
3561 
3562   // Return final merged results
3563   set_control( _gvn.transform(region) );
3564   record_for_igvn(region);
3565 
3566   bool not_inline = !toop->can_be_inline_type();
3567   bool not_flattened = !UseFlatArray || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->flatten_array());
3568   if (EnableValhalla && not_flattened) {
3569     // Check if obj has been loaded from an array
3570     obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3571     Node* array = NULL;
3572     if (obj->isa_Load()) {
3573       Node* address = obj->in(MemNode::Address);
3574       if (address->isa_AddP()) {
3575         array = address->as_AddP()->in(AddPNode::Base);
3576       }
3577     } else if (obj->is_Phi()) {
3578       Node* region = obj->in(0);
3579       // TODO make this more robust (see JDK-8231346)
3580       if (region->req() == 3 && region->in(2) != NULL && region->in(2)->in(0) != NULL) {
3581         IfNode* iff = region->in(2)->in(0)->isa_If();
3582         if (iff != NULL) {
3583           iff->is_flat_array_check(&_gvn, &array);
3584         }
3585       }
3586     }
3587     if (array != NULL) {
3588       const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3589       if (ary_t != NULL) {
3590         if (!ary_t->is_not_null_free() && not_inline) {
3591           // Casting array element to a non-inline-type, mark array as not null-free.
3592           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3593           replace_in_map(array, cast);
3594         } else if (!ary_t->is_not_flat()) {
3595           // Casting array element to a non-flattened type, mark array as not flat.
3596           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3597           replace_in_map(array, cast);
3598         }
3599       }
3600     }
3601   }
3602 
3603   if (!stopped() && !res->is_InlineTypeBase()) {
3604     res = record_profiled_receiver_for_speculation(res);
3605     if (toop->is_inlinetypeptr()) {
3606       Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass(), !gvn().type(res)->maybe_null());
3607       res = vt;
3608       if (safe_for_replace) {
3609         if (vt->is_InlineType() && C->inlining_incrementally()) {
3610           vt = vt->as_InlineType()->as_ptr(&_gvn);
3611         }
3612         replace_in_map(obj, vt);
3613         replace_in_map(not_null_obj, vt);
3614         replace_in_map(res, vt);
3615       }
3616     }
3617   }
3618   return res;
3619 }
3620 
3621 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) {
3622   Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3623   Node* mark = make_load(NULL, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3624   Node* mask = MakeConX(markWord::inline_type_pattern);
3625   Node* masked = _gvn.transform(new AndXNode(mark, mask));
3626   Node* cmp = _gvn.transform(new CmpXNode(masked, mask));
3627   return _gvn.transform(new BoolNode(cmp, is_inline ? BoolTest::eq : BoolTest::ne));
3628 }
3629 
3630 Node* GraphKit::is_val_mirror(Node* mirror) {
3631   Node* p = basic_plus_adr(mirror, java_lang_Class::secondary_mirror_offset());
3632   Node* secondary_mirror = access_load_at(mirror, p, _gvn.type(p)->is_ptr(), TypeInstPtr::MIRROR->cast_to_ptr_type(TypePtr::BotPTR), T_OBJECT, IN_HEAP);
3633   Node* cmp = _gvn.transform(new CmpPNode(mirror, secondary_mirror));
3634   return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3635 }
3636 
3637 Node* GraphKit::array_lh_test(Node* klass, jint mask, jint val, bool eq) {
3638   Node* lh_adr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
3639   // Make sure to use immutable memory here to enable hoisting the check out of loops
3640   Node* lh_val = _gvn.transform(LoadNode::make(_gvn, NULL, immutable_memory(), lh_adr, lh_adr->bottom_type()->is_ptr(), TypeInt::INT, T_INT, MemNode::unordered));
3641   Node* masked = _gvn.transform(new AndINode(lh_val, intcon(mask)));
3642   Node* cmp = _gvn.transform(new CmpINode(masked, intcon(val)));
3643   return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne));
3644 }
3645 
3646 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) {
3647   // We can't use immutable memory here because the mark word is mutable.
3648   // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the
3649   // check is moved out of loops (mainly to enable loop unswitching).
3650   Node* mem = UseArrayMarkWordCheck ? memory(Compile::AliasIdxRaw) : immutable_memory();
3651   Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, mem, array_or_klass));
3652   record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN
3653   return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne));
3654 }
3655 
3656 Node* GraphKit::null_free_array_test(Node* klass, bool null_free) {
3657   return array_lh_test(klass, Klass::_lh_null_free_array_bit_inplace, 0, !null_free);
3658 }
3659 
3660 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3661 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3662   RegionNode* region = new RegionNode(3);
3663   Node* null_ctl = top();
3664   null_check_oop(val, &null_ctl);
3665   if (null_ctl != top()) {
3666     PreserveJVMState pjvms(this);
3667     set_control(null_ctl);
3668     {
3669       // Deoptimize if null-free array
3670       BuildCutout unless(this, null_free_array_test(load_object_klass(ary), /* null_free = */ false), PROB_MAX);
3671       inc_sp(nargs);
3672       uncommon_trap(Deoptimization::Reason_null_check,
3673                     Deoptimization::Action_none);
3674     }
3675     region->init_req(1, control());
3676   }
3677   region->init_req(2, control());
3678   set_control(_gvn.transform(region));
3679   record_for_igvn(region);
3680   if (_gvn.type(val) == TypePtr::NULL_PTR) {
3681     // Since we were just successfully storing null, the array can't be null free.
3682     const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3683     ary_t = ary_t->cast_to_not_null_free();
3684     Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3685     if (safe_for_replace) {
3686       replace_in_map(ary, cast);
3687     }
3688     ary = cast;
3689   }
3690   return ary;
3691 }
3692 
3693 //------------------------------next_monitor-----------------------------------
3694 // What number should be given to the next monitor?
3695 int GraphKit::next_monitor() {
3696   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3697   int next = current + C->sync_stack_slots();
3698   // Keep the toplevel high water mark current:
3699   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3700   return current;
3701 }
3702 
3703 //------------------------------insert_mem_bar---------------------------------
3704 // Memory barrier to avoid floating things around
3705 // The membar serves as a pinch point between both control and all memory slices.
3706 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3707   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3708   mb->init_req(TypeFunc::Control, control());
3709   mb->init_req(TypeFunc::Memory,  reset_memory());
3710   Node* membar = _gvn.transform(mb);

3738   }
3739   Node* membar = _gvn.transform(mb);
3740   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3741   if (alias_idx == Compile::AliasIdxBot) {
3742     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3743   } else {
3744     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3745   }
3746   return membar;
3747 }
3748 
3749 //------------------------------shared_lock------------------------------------
3750 // Emit locking code.
3751 FastLockNode* GraphKit::shared_lock(Node* obj) {
3752   // bci is either a monitorenter bc or InvocationEntryBci
3753   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3754   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3755 
3756   if( !GenerateSynchronizationCode )
3757     return NULL;                // Not locking things?
3758 
3759   if (stopped())                // Dead monitor?
3760     return NULL;
3761 
3762   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3763 
3764   // Box the stack location
3765   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3766   Node* mem = reset_memory();
3767 
3768   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3769 
3770   // Create the rtm counters for this fast lock if needed.
3771   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3772 
3773   // Add monitor to debug info for the slow path.  If we block inside the
3774   // slow path and de-opt, we need the monitor hanging around
3775   map()->push_monitor( flock );
3776 
3777   const TypeFunc *tf = LockNode::lock_type();
3778   LockNode *lock = new LockNode(C, tf);

3807   }
3808 #endif
3809 
3810   return flock;
3811 }
3812 
3813 
3814 //------------------------------shared_unlock----------------------------------
3815 // Emit unlocking code.
3816 void GraphKit::shared_unlock(Node* box, Node* obj) {
3817   // bci is either a monitorenter bc or InvocationEntryBci
3818   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3819   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3820 
3821   if( !GenerateSynchronizationCode )
3822     return;
3823   if (stopped()) {               // Dead monitor?
3824     map()->pop_monitor();        // Kill monitor from debug info
3825     return;
3826   }
3827   assert(!obj->is_InlineTypeBase(), "should not unlock on inline type");
3828 
3829   // Memory barrier to avoid floating things down past the locked region
3830   insert_mem_bar(Op_MemBarReleaseLock);
3831 
3832   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3833   UnlockNode *unlock = new UnlockNode(C, tf);
3834 #ifdef ASSERT
3835   unlock->set_dbg_jvms(sync_jvms());
3836 #endif
3837   uint raw_idx = Compile::AliasIdxRaw;
3838   unlock->init_req( TypeFunc::Control, control() );
3839   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3840   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3841   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3842   unlock->init_req( TypeFunc::ReturnAdr, top() );
3843 
3844   unlock->init_req(TypeFunc::Parms + 0, obj);
3845   unlock->init_req(TypeFunc::Parms + 1, box);
3846   unlock = _gvn.transform(unlock)->as_Unlock();
3847 
3848   Node* mem = reset_memory();
3849 
3850   // unlock has no side-effects, sets few values
3851   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3852 
3853   // Kill monitor from debug info
3854   map()->pop_monitor( );
3855 }
3856 
3857 //-------------------------------get_layout_helper-----------------------------
3858 // If the given klass is a constant or known to be an array,
3859 // fetch the constant layout helper value into constant_value
3860 // and return (Node*)NULL.  Otherwise, load the non-constant
3861 // layout helper value, and return the node which represents it.
3862 // This two-faced routine is useful because allocation sites
3863 // almost always feature constant types.
3864 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3865   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3866   if (!StressReflectiveCode && inst_klass != NULL) {
3867     bool xklass = inst_klass->klass_is_exact();
3868     bool can_be_flattened = false;
3869     const TypeAryPtr* ary_type = inst_klass->as_instance_type()->isa_aryptr();
3870     if (UseFlatArray && !xklass && ary_type != NULL && !ary_type->is_null_free()) {
3871       // The runtime type of [LMyValue might be [QMyValue due to [QMyValue <: [LMyValue. Don't constant fold.
3872       const TypeOopPtr* elem = ary_type->elem()->make_oopptr();
3873       can_be_flattened = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->flatten_array());
3874     }
3875     if (!can_be_flattened && (xklass || inst_klass->isa_aryklassptr())) {
3876       jint lhelper;
3877       if (inst_klass->is_flat()) {
3878         lhelper = ary_type->flat_layout_helper();
3879       } else if (inst_klass->isa_aryklassptr()) {
3880         BasicType elem = ary_type->elem()->array_element_basic_type();
3881         if (is_reference_type(elem, true)) {
3882           elem = T_OBJECT;
3883         }
3884         lhelper = Klass::array_layout_helper(elem);
3885       } else {
3886         lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3887       }
3888       if (lhelper != Klass::_lh_neutral_value) {
3889         constant_value = lhelper;
3890         return (Node*) NULL;
3891       }
3892     }
3893   }
3894   constant_value = Klass::_lh_neutral_value;  // put in a known value
3895   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3896   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3897 }
3898 
3899 // We just put in an allocate/initialize with a big raw-memory effect.
3900 // Hook selected additional alias categories on the initialization.
3901 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3902                                 MergeMemNode* init_in_merge,
3903                                 Node* init_out_raw) {
3904   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3905   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3906 
3907   Node* prevmem = kit.memory(alias_idx);
3908   init_in_merge->set_memory_at(alias_idx, prevmem);
3909   if (init_out_raw != NULL) {
3910     kit.set_memory(init_out_raw, alias_idx);
3911   }
3912 }
3913 
3914 //---------------------------set_output_for_allocation-------------------------
3915 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3916                                           const TypeOopPtr* oop_type,
3917                                           bool deoptimize_on_exception) {
3918   int rawidx = Compile::AliasIdxRaw;
3919   alloc->set_req( TypeFunc::FramePtr, frameptr() );
3920   add_safepoint_edges(alloc);
3921   Node* allocx = _gvn.transform(alloc);
3922   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3923   // create memory projection for i_o
3924   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3925   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3926 
3927   // create a memory projection as for the normal control path
3928   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3929   set_memory(malloc, rawidx);
3930 
3931   // a normal slow-call doesn't change i_o, but an allocation does
3932   // we create a separate i_o projection for the normal control path
3933   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3934   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3935 
3936   // put in an initialization barrier
3937   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3938                                                  rawoop)->as_Initialize();
3939   assert(alloc->initialization() == init,  "2-way macro link must work");
3940   assert(init ->allocation()     == alloc, "2-way macro link must work");
3941   {
3942     // Extract memory strands which may participate in the new object's
3943     // initialization, and source them from the new InitializeNode.
3944     // This will allow us to observe initializations when they occur,
3945     // and link them properly (as a group) to the InitializeNode.
3946     assert(init->in(InitializeNode::Memory) == malloc, "");
3947     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3948     init->set_req(InitializeNode::Memory, minit_in);
3949     record_for_igvn(minit_in); // fold it up later, if possible
3950     _gvn.set_type(minit_in, Type::MEMORY);
3951     Node* minit_out = memory(rawidx);
3952     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3953     // Add an edge in the MergeMem for the header fields so an access
3954     // to one of those has correct memory state
3955     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3956     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3957     if (oop_type->isa_aryptr()) {
3958       const TypeAryPtr* arytype = oop_type->is_aryptr();
3959       if (arytype->is_flat()) {
3960         // Initially all flattened array accesses share a single slice
3961         // but that changes after parsing. Prepare the memory graph so
3962         // it can optimize flattened array accesses properly once they
3963         // don't share a single slice.
3964         assert(C->flattened_accesses_share_alias(), "should be set at parse time");
3965         C->set_flattened_accesses_share_alias(false);
3966         ciInlineKlass* vk = arytype->elem()->inline_klass();
3967         for (int i = 0, len = vk->nof_nonstatic_fields(); i < len; i++) {
3968           ciField* field = vk->nonstatic_field_at(i);
3969           if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3970             continue;  // do not bother to track really large numbers of fields
3971           int off_in_vt = field->offset() - vk->first_field_offset();
3972           const TypePtr* adr_type = arytype->with_field_offset(off_in_vt)->add_offset(Type::OffsetBot);
3973           int fieldidx = C->get_alias_index(adr_type, true);
3974           // Pass NULL for init_out. Having per flat array element field memory edges as uses of the Initialize node
3975           // can result in per flat array field Phis to be created which confuses the logic of
3976           // Compile::adjust_flattened_array_access_aliases().
3977           hook_memory_on_init(*this, fieldidx, minit_in, NULL);
3978         }
3979         C->set_flattened_accesses_share_alias(true);
3980         hook_memory_on_init(*this, C->get_alias_index(TypeAryPtr::INLINES), minit_in, minit_out);
3981       } else {
3982         const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3983         int            elemidx  = C->get_alias_index(telemref);
3984         hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3985       }
3986     } else if (oop_type->isa_instptr()) {
3987       set_memory(minit_out, C->get_alias_index(oop_type)); // mark word
3988       ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3989       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3990         ciField* field = ik->nonstatic_field_at(i);
3991         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3992           continue;  // do not bother to track really large numbers of fields
3993         // Find (or create) the alias category for this field:
3994         int fieldidx = C->alias_type(field)->index();
3995         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3996       }
3997     }
3998   }
3999 
4000   // Cast raw oop to the real thing...
4001   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
4002   javaoop = _gvn.transform(javaoop);
4003   C->set_recent_alloc(control(), javaoop);
4004   assert(just_allocated_object(control()) == javaoop, "just allocated");
4005 
4006 #ifdef ASSERT
4007   { // Verify that the AllocateNode::Ideal_allocation recognizers work:

4018       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
4019     }
4020   }
4021 #endif //ASSERT
4022 
4023   return javaoop;
4024 }
4025 
4026 //---------------------------new_instance--------------------------------------
4027 // This routine takes a klass_node which may be constant (for a static type)
4028 // or may be non-constant (for reflective code).  It will work equally well
4029 // for either, and the graph will fold nicely if the optimizer later reduces
4030 // the type to a constant.
4031 // The optional arguments are for specialized use by intrinsics:
4032 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
4033 //  - If 'return_size_val', report the total object size to the caller.
4034 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4035 Node* GraphKit::new_instance(Node* klass_node,
4036                              Node* extra_slow_test,
4037                              Node* *return_size_val,
4038                              bool deoptimize_on_exception,
4039                              InlineTypeBaseNode* inline_type_node) {
4040   // Compute size in doublewords
4041   // The size is always an integral number of doublewords, represented
4042   // as a positive bytewise size stored in the klass's layout_helper.
4043   // The layout_helper also encodes (in a low bit) the need for a slow path.
4044   jint  layout_con = Klass::_lh_neutral_value;
4045   Node* layout_val = get_layout_helper(klass_node, layout_con);
4046   bool  layout_is_con = (layout_val == NULL);
4047 
4048   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
4049   // Generate the initial go-slow test.  It's either ALWAYS (return a
4050   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
4051   // case) a computed value derived from the layout_helper.
4052   Node* initial_slow_test = NULL;
4053   if (layout_is_con) {
4054     assert(!StressReflectiveCode, "stress mode does not use these paths");
4055     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
4056     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
4057   } else {   // reflective case
4058     // This reflective path is used by Unsafe.allocateInstance.
4059     // (It may be stress-tested by specifying StressReflectiveCode.)
4060     // Basically, we want to get into the VM is there's an illegal argument.
4061     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
4062     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
4063     if (extra_slow_test != intcon(0)) {
4064       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
4065     }
4066     // (Macro-expander will further convert this to a Bool, if necessary.)

4077 
4078     // Clear the low bits to extract layout_helper_size_in_bytes:
4079     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4080     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4081     size = _gvn.transform( new AndXNode(size, mask) );
4082   }
4083   if (return_size_val != NULL) {
4084     (*return_size_val) = size;
4085   }
4086 
4087   // This is a precise notnull oop of the klass.
4088   // (Actually, it need not be precise if this is a reflective allocation.)
4089   // It's what we cast the result to.
4090   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4091   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
4092   const TypeOopPtr* oop_type = tklass->as_instance_type();
4093 
4094   // Now generate allocation code
4095 
4096   // The entire memory state is needed for slow path of the allocation
4097   // since GC and deoptimization can happen.
4098   Node *mem = reset_memory();
4099   set_all_memory(mem); // Create new memory state
4100 
4101   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4102                                          control(), mem, i_o(),
4103                                          size, klass_node,
4104                                          initial_slow_test, inline_type_node);
4105 
4106   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4107 }
4108 
4109 //-------------------------------new_array-------------------------------------
4110 // helper for newarray and anewarray
4111 // The 'length' parameter is (obviously) the length of the array.
4112 // See comments on new_instance for the meaning of the other arguments.
4113 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
4114                           Node* length,         // number of array elements
4115                           int   nargs,          // number of arguments to push back for uncommon trap
4116                           Node* *return_size_val,
4117                           bool deoptimize_on_exception) {
4118   jint  layout_con = Klass::_lh_neutral_value;
4119   Node* layout_val = get_layout_helper(klass_node, layout_con);
4120   bool  layout_is_con = (layout_val == NULL);
4121 
4122   if (!layout_is_con && !StressReflectiveCode &&
4123       !too_many_traps(Deoptimization::Reason_class_check)) {
4124     // This is a reflective array creation site.
4125     // Optimistically assume that it is a subtype of Object[],
4126     // so that we can fold up all the address arithmetic.
4127     layout_con = Klass::array_layout_helper(T_OBJECT);
4128     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4129     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4130     { BuildCutout unless(this, bol_lh, PROB_MAX);
4131       inc_sp(nargs);
4132       uncommon_trap(Deoptimization::Reason_class_check,
4133                     Deoptimization::Action_maybe_recompile);
4134     }
4135     layout_val = NULL;
4136     layout_is_con = true;
4137   }
4138 
4139   // Generate the initial go-slow test.  Make sure we do not overflow
4140   // if length is huge (near 2Gig) or negative!  We do not need
4141   // exact double-words here, just a close approximation of needed
4142   // double-words.  We can't add any offset or rounding bits, lest we
4143   // take a size -1 of bytes and make it positive.  Use an unsigned
4144   // compare, so negative sizes look hugely positive.
4145   int fast_size_limit = FastAllocateSizeLimit;
4146   if (layout_is_con) {
4147     assert(!StressReflectiveCode, "stress mode does not use these paths");
4148     // Increase the size limit if we have exact knowledge of array type.
4149     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4150     fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4151   }
4152 
4153   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4154   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4155 
4156   // --- Size Computation ---
4157   // array_size = round_to_heap(array_header + (length << elem_shift));
4158   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4159   // and align_to(x, y) == ((x + y-1) & ~(y-1))
4160   // The rounding mask is strength-reduced, if possible.
4161   int round_mask = MinObjAlignmentInBytes - 1;
4162   Node* header_size = NULL;
4163   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4164   // (T_BYTE has the weakest alignment and size restrictions...)
4165   if (layout_is_con) {
4166     int       hsize  = Klass::layout_helper_header_size(layout_con);
4167     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
4168     bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4169     if ((round_mask & ~right_n_bits(eshift)) == 0)
4170       round_mask = 0;  // strength-reduce it if it goes away completely
4171     assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4172     assert(header_size_min <= hsize, "generic minimum is smallest");
4173     header_size_min = hsize;
4174     header_size = intcon(hsize + round_mask);
4175   } else {
4176     Node* hss   = intcon(Klass::_lh_header_size_shift);
4177     Node* hsm   = intcon(Klass::_lh_header_size_mask);
4178     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
4179     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
4180     Node* mask  = intcon(round_mask);
4181     header_size = _gvn.transform( new AddINode(hsize, mask) );
4182   }
4183 
4184   Node* elem_shift = NULL;
4185   if (layout_is_con) {
4186     int eshift = Klass::layout_helper_log2_element_size(layout_con);
4187     if (eshift != 0)
4188       elem_shift = intcon(eshift);
4189   } else {
4190     // There is no need to mask or shift this value.
4191     // The semantics of LShiftINode include an implicit mask to 0x1F.

4235   // places, one where the length is sharply limited, and the other
4236   // after a successful allocation.
4237   Node* abody = lengthx;
4238   if (elem_shift != NULL)
4239     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
4240   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
4241   if (round_mask != 0) {
4242     Node* mask = MakeConX(~round_mask);
4243     size       = _gvn.transform( new AndXNode(size, mask) );
4244   }
4245   // else if round_mask == 0, the size computation is self-rounding
4246 
4247   if (return_size_val != NULL) {
4248     // This is the size
4249     (*return_size_val) = size;
4250   }
4251 
4252   // Now generate allocation code
4253 
4254   // The entire memory state is needed for slow path of the allocation
4255   // since GC and deoptimization can happen.
4256   Node *mem = reset_memory();
4257   set_all_memory(mem); // Create new memory state
4258 
4259   if (initial_slow_test->is_Bool()) {
4260     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4261     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4262   }
4263 
4264   const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4265   const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4266   const TypeAryPtr* ary_ptr = ary_type->isa_aryptr();
4267 
4268   // Inline type array variants:
4269   // - null-ok:              MyValue.ref[] (ciObjArrayKlass "[LMyValue")
4270   // - null-free:            MyValue.val[] (ciObjArrayKlass "[QMyValue")
4271   // - null-free, flattened: MyValue.val[] (ciFlatArrayKlass "[QMyValue")
4272   // Check if array is a null-free, non-flattened inline type array
4273   // that needs to be initialized with the default inline type.
4274   Node* default_value = NULL;
4275   Node* raw_default_value = NULL;
4276   if (ary_ptr != NULL && ary_ptr->klass_is_exact()) {
4277     // Array type is known
4278     if (ary_ptr->is_null_free() && !ary_ptr->is_flat()) {
4279       ciInlineKlass* vk = ary_ptr->elem()->make_oopptr()->inline_klass();
4280       default_value = InlineTypeNode::default_oop(gvn(), vk);
4281     }
4282   } else if (ary_type->can_be_inline_array()) {
4283     // Array type is not known, add runtime checks
4284     assert(!ary_klass->klass_is_exact(), "unexpected exact type");
4285     Node* r = new RegionNode(3);
4286     default_value = new PhiNode(r, TypeInstPtr::BOTTOM);
4287 
4288     Node* bol = array_lh_test(klass_node, Klass::_lh_array_tag_flat_value_bit_inplace | Klass::_lh_null_free_array_bit_inplace, Klass::_lh_null_free_array_bit_inplace);
4289     IfNode* iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4290 
4291     // Null-free, non-flattened inline type array, initialize with the default value
4292     set_control(_gvn.transform(new IfTrueNode(iff)));
4293     Node* p = basic_plus_adr(klass_node, in_bytes(ArrayKlass::element_klass_offset()));
4294     Node* eklass = _gvn.transform(LoadKlassNode::make(_gvn, control(), immutable_memory(), p, TypeInstPtr::KLASS));
4295     Node* adr_fixed_block_addr = basic_plus_adr(eklass, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()));
4296     Node* adr_fixed_block = make_load(control(), adr_fixed_block_addr, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4297     Node* default_value_offset_addr = basic_plus_adr(adr_fixed_block, in_bytes(InlineKlass::default_value_offset_offset()));
4298     Node* default_value_offset = make_load(control(), default_value_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
4299     Node* elem_mirror = load_mirror_from_klass(eklass);
4300     Node* default_value_addr = basic_plus_adr(elem_mirror, ConvI2X(default_value_offset));
4301     Node* val = access_load_at(elem_mirror, default_value_addr, TypeInstPtr::MIRROR, TypeInstPtr::NOTNULL, T_OBJECT, IN_HEAP);
4302     r->init_req(1, control());
4303     default_value->init_req(1, val);
4304 
4305     // Otherwise initialize with all zero
4306     r->init_req(2, _gvn.transform(new IfFalseNode(iff)));
4307     default_value->init_req(2, null());
4308 
4309     set_control(_gvn.transform(r));
4310     default_value = _gvn.transform(default_value);
4311   }
4312   if (default_value != NULL) {
4313     if (UseCompressedOops) {
4314       // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops
4315       default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop()));
4316       Node* lower = _gvn.transform(new CastP2XNode(control(), default_value));
4317       Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32)));
4318       raw_default_value = _gvn.transform(new OrLNode(lower, upper));
4319     } else {
4320       raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value));
4321     }
4322   }
4323 
4324   // Create the AllocateArrayNode and its result projections
4325   AllocateArrayNode* alloc
4326     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4327                             control(), mem, i_o(),
4328                             size, klass_node,
4329                             initial_slow_test,
4330                             length,
4331                             default_value, raw_default_value);
4332   // Cast to correct type.  Note that the klass_node may be constant or not,
4333   // and in the latter case the actual array type will be inexact also.
4334   // (This happens via a non-constant argument to inline_native_newArray.)
4335   // In any case, the value of klass_node provides the desired array type.
4336   const TypeInt* length_type = _gvn.find_int_type(length);

4337   if (ary_type->isa_aryptr() && length_type != NULL) {
4338     // Try to get a better type than POS for the size
4339     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4340   }
4341 
4342   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4343 
4344   array_ideal_length(alloc, ary_type, true);
4345   return javaoop;
4346 }
4347 
4348 // The following "Ideal_foo" functions are placed here because they recognize
4349 // the graph shapes created by the functions immediately above.
4350 
4351 //---------------------------Ideal_allocation----------------------------------
4352 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
4353 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
4354   if (ptr == NULL) {     // reduce dumb test in callers
4355     return NULL;
4356   }

4465   set_all_memory(ideal.merged_memory());
4466   set_i_o(ideal.i_o());
4467   set_control(ideal.ctrl());
4468 }
4469 
4470 void GraphKit::final_sync(IdealKit& ideal) {
4471   // Final sync IdealKit and graphKit.
4472   sync_kit(ideal);
4473 }
4474 
4475 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4476   Node* len = load_array_length(load_String_value(str, set_ctrl));
4477   Node* coder = load_String_coder(str, set_ctrl);
4478   // Divide length by 2 if coder is UTF16
4479   return _gvn.transform(new RShiftINode(len, coder));
4480 }
4481 
4482 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4483   int value_offset = java_lang_String::value_offset();
4484   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4485                                                      false, NULL, Type::Offset(0));
4486   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4487   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4488                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, true, true),
4489                                                   ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4490   Node* p = basic_plus_adr(str, str, value_offset);
4491   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4492                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4493   return load;
4494 }
4495 
4496 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4497   if (!CompactStrings) {
4498     return intcon(java_lang_String::CODER_UTF16);
4499   }
4500   int coder_offset = java_lang_String::coder_offset();
4501   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4502                                                      false, NULL, Type::Offset(0));
4503   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4504 
4505   Node* p = basic_plus_adr(str, str, coder_offset);
4506   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4507                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4508   return load;
4509 }
4510 
4511 void GraphKit::store_String_value(Node* str, Node* value) {
4512   int value_offset = java_lang_String::value_offset();
4513   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4514                                                      false, NULL, Type::Offset(0));
4515   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4516 
4517   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4518                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4519 }
4520 
4521 void GraphKit::store_String_coder(Node* str, Node* value) {
4522   int coder_offset = java_lang_String::coder_offset();
4523   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4524                                                      false, NULL, Type::Offset(0));
4525   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4526 
4527   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4528                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4529 }
4530 
4531 // Capture src and dst memory state with a MergeMemNode
4532 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4533   if (src_type == dst_type) {
4534     // Types are equal, we don't need a MergeMemNode
4535     return memory(src_type);
4536   }
4537   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4538   record_for_igvn(merge); // fold it up later, if possible
4539   int src_idx = C->get_alias_index(src_type);
4540   int dst_idx = C->get_alias_index(dst_type);
4541   merge->set_memory_at(src_idx, memory(src_idx));
4542   merge->set_memory_at(dst_idx, memory(dst_idx));
4543   return merge;
4544 }

4617   i_char->init_req(2, AddI(i_char, intcon(2)));
4618 
4619   set_control(IfFalse(iff));
4620   set_memory(st, TypeAryPtr::BYTES);
4621 }
4622 
4623 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4624   if (!field->is_constant()) {
4625     return NULL; // Field not marked as constant.
4626   }
4627   ciInstance* holder = NULL;
4628   if (!field->is_static()) {
4629     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4630     if (const_oop != NULL && const_oop->is_instance()) {
4631       holder = const_oop->as_instance();
4632     }
4633   }
4634   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4635                                                         /*is_unsigned_load=*/false);
4636   if (con_type != NULL) {
4637     Node* con = makecon(con_type);
4638     if (field->type()->is_inlinetype()) {
4639       con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass(), field->is_null_free());
4640     } else if (con_type->is_inlinetypeptr()) {
4641       con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass(), field->is_null_free());
4642     }
4643     return con;
4644   }
4645   return NULL;
4646 }
4647 
4648 //---------------------------load_mirror_from_klass----------------------------
4649 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4650 Node* GraphKit::load_mirror_from_klass(Node* klass) {
4651   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4652   Node* load = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4653   // mirror = ((OopHandle)mirror)->resolve();
4654   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4655 }
< prev index next >