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