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