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