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