1 /*
   2  * Copyright (c) 2001, 2023, 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   if (code != Bytecodes::_illegal) {
1035     depth = Bytecodes::depth(code); // checkcast=0, athrow=-1
1036   }
1037 
1038   auto rsize = [&]() {
1039     assert(code != Bytecodes::_illegal, "code is illegal!");
1040     BasicType rtype = Bytecodes::result_type(code); // checkcast=P, athrow=V
1041     return (rtype < T_CONFLICT) ? type2size[rtype] : 0;
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 = 1 - 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 = -depth;
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                                 int barrier_data) {
1609   assert(adr_idx != Compile::AliasIdxTop, "use other store_to_memory factory" );
1610   const TypePtr* adr_type = NULL;
1611   debug_only(adr_type = C->get_adr_type(adr_idx));
1612   Node *mem = memory(adr_idx);
1613   Node* st = StoreNode::make(_gvn, ctl, mem, adr, adr_type, val, bt, mo, require_atomic_access);
1614   if (unaligned) {
1615     st->as_Store()->set_unaligned_access();
1616   }
1617   if (mismatched) {
1618     st->as_Store()->set_mismatched_access();
1619   }
1620   if (unsafe) {
1621     st->as_Store()->set_unsafe_access();
1622   }
1623   st->as_Store()->set_barrier_data(barrier_data);
1624   st = _gvn.transform(st);
1625   set_memory(st, adr_idx);
1626   // Back-to-back stores can only remove intermediate store with DU info
1627   // so push on worklist for optimizer.
1628   if (mem->req() > MemNode::Address && adr == mem->in(MemNode::Address))
1629     record_for_igvn(st);
1630 
1631   return st;
1632 }
1633 
1634 Node* GraphKit::access_store_at(Node* obj,
1635                                 Node* adr,
1636                                 const TypePtr* adr_type,
1637                                 Node* val,
1638                                 const Type* val_type,
1639                                 BasicType bt,
1640                                 DecoratorSet decorators,
1641                                 bool safe_for_replace) {
1642   // Transformation of a value which could be NULL pointer (CastPP #NULL)
1643   // could be delayed during Parse (for example, in adjust_map_after_if()).
1644   // Execute transformation here to avoid barrier generation in such case.
1645   if (_gvn.type(val) == TypePtr::NULL_PTR) {
1646     val = _gvn.makecon(TypePtr::NULL_PTR);
1647   }
1648 
1649   if (stopped()) {
1650     return top(); // Dead path ?
1651   }
1652 
1653   assert(val != NULL, "not dead path");
1654   if (val->is_InlineType()) {
1655     // Store to non-flattened field. Buffer the inline type and make sure
1656     // the store is re-executed if the allocation triggers deoptimization.
1657     PreserveReexecuteState preexecs(this);
1658     jvms()->set_should_reexecute(true);
1659     val = val->as_InlineType()->buffer(this, safe_for_replace);
1660   }
1661 
1662   C2AccessValuePtr addr(adr, adr_type);
1663   C2AccessValue value(val, val_type);
1664   C2ParseAccess access(this, decorators | C2_WRITE_ACCESS, bt, obj, addr);
1665   if (access.is_raw()) {
1666     return _barrier_set->BarrierSetC2::store_at(access, value);
1667   } else {
1668     return _barrier_set->store_at(access, value);
1669   }
1670 }
1671 
1672 Node* GraphKit::access_load_at(Node* obj,   // containing obj
1673                                Node* adr,   // actual address to store val at
1674                                const TypePtr* adr_type,
1675                                const Type* val_type,
1676                                BasicType bt,
1677                                DecoratorSet decorators,
1678                                Node* ctl) {
1679   if (stopped()) {
1680     return top(); // Dead path ?
1681   }
1682 
1683   C2AccessValuePtr addr(adr, adr_type);
1684   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, obj, addr, ctl);
1685   if (access.is_raw()) {
1686     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1687   } else {
1688     return _barrier_set->load_at(access, val_type);
1689   }
1690 }
1691 
1692 Node* GraphKit::access_load(Node* adr,   // actual address to load val at
1693                             const Type* val_type,
1694                             BasicType bt,
1695                             DecoratorSet decorators) {
1696   if (stopped()) {
1697     return top(); // Dead path ?
1698   }
1699 
1700   C2AccessValuePtr addr(adr, adr->bottom_type()->is_ptr());
1701   C2ParseAccess access(this, decorators | C2_READ_ACCESS, bt, NULL, addr);
1702   if (access.is_raw()) {
1703     return _barrier_set->BarrierSetC2::load_at(access, val_type);
1704   } else {
1705     return _barrier_set->load_at(access, val_type);
1706   }
1707 }
1708 
1709 Node* GraphKit::access_atomic_cmpxchg_val_at(Node* obj,
1710                                              Node* adr,
1711                                              const TypePtr* adr_type,
1712                                              int alias_idx,
1713                                              Node* expected_val,
1714                                              Node* new_val,
1715                                              const Type* value_type,
1716                                              BasicType bt,
1717                                              DecoratorSet decorators) {
1718   C2AccessValuePtr addr(adr, adr_type);
1719   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1720                         bt, obj, addr, alias_idx);
1721   if (access.is_raw()) {
1722     return _barrier_set->BarrierSetC2::atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1723   } else {
1724     return _barrier_set->atomic_cmpxchg_val_at(access, expected_val, new_val, value_type);
1725   }
1726 }
1727 
1728 Node* GraphKit::access_atomic_cmpxchg_bool_at(Node* obj,
1729                                               Node* adr,
1730                                               const TypePtr* adr_type,
1731                                               int alias_idx,
1732                                               Node* expected_val,
1733                                               Node* new_val,
1734                                               const Type* value_type,
1735                                               BasicType bt,
1736                                               DecoratorSet decorators) {
1737   C2AccessValuePtr addr(adr, adr_type);
1738   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1739                         bt, obj, addr, alias_idx);
1740   if (access.is_raw()) {
1741     return _barrier_set->BarrierSetC2::atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1742   } else {
1743     return _barrier_set->atomic_cmpxchg_bool_at(access, expected_val, new_val, value_type);
1744   }
1745 }
1746 
1747 Node* GraphKit::access_atomic_xchg_at(Node* obj,
1748                                       Node* adr,
1749                                       const TypePtr* adr_type,
1750                                       int alias_idx,
1751                                       Node* new_val,
1752                                       const Type* value_type,
1753                                       BasicType bt,
1754                                       DecoratorSet decorators) {
1755   C2AccessValuePtr addr(adr, adr_type);
1756   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS,
1757                         bt, obj, addr, alias_idx);
1758   if (access.is_raw()) {
1759     return _barrier_set->BarrierSetC2::atomic_xchg_at(access, new_val, value_type);
1760   } else {
1761     return _barrier_set->atomic_xchg_at(access, new_val, value_type);
1762   }
1763 }
1764 
1765 Node* GraphKit::access_atomic_add_at(Node* obj,
1766                                      Node* adr,
1767                                      const TypePtr* adr_type,
1768                                      int alias_idx,
1769                                      Node* new_val,
1770                                      const Type* value_type,
1771                                      BasicType bt,
1772                                      DecoratorSet decorators) {
1773   C2AccessValuePtr addr(adr, adr_type);
1774   C2AtomicParseAccess access(this, decorators | C2_READ_ACCESS | C2_WRITE_ACCESS, bt, obj, addr, alias_idx);
1775   if (access.is_raw()) {
1776     return _barrier_set->BarrierSetC2::atomic_add_at(access, new_val, value_type);
1777   } else {
1778     return _barrier_set->atomic_add_at(access, new_val, value_type);
1779   }
1780 }
1781 
1782 void GraphKit::access_clone(Node* src, Node* dst, Node* size, bool is_array) {
1783   return _barrier_set->clone(this, src, dst, size, is_array);
1784 }
1785 
1786 //-------------------------array_element_address-------------------------
1787 Node* GraphKit::array_element_address(Node* ary, Node* idx, BasicType elembt,
1788                                       const TypeInt* sizetype, Node* ctrl) {
1789   const TypeAryPtr* arytype = _gvn.type(ary)->is_aryptr();
1790   uint shift = arytype->is_flat() ? arytype->flat_log_elem_size() : exact_log2(type2aelembytes(elembt));
1791   uint header = arrayOopDesc::base_offset_in_bytes(elembt);
1792 
1793   // short-circuit a common case (saves lots of confusing waste motion)
1794   jint idx_con = find_int_con(idx, -1);
1795   if (idx_con >= 0) {
1796     intptr_t offset = header + ((intptr_t)idx_con << shift);
1797     return basic_plus_adr(ary, offset);
1798   }
1799 
1800   // must be correct type for alignment purposes
1801   Node* base  = basic_plus_adr(ary, header);
1802   idx = Compile::conv_I2X_index(&_gvn, idx, sizetype, ctrl);
1803   Node* scale = _gvn.transform( new LShiftXNode(idx, intcon(shift)) );
1804   return basic_plus_adr(ary, base, scale);
1805 }
1806 
1807 //-------------------------load_array_element-------------------------
1808 Node* GraphKit::load_array_element(Node* ary, Node* idx, const TypeAryPtr* arytype, bool set_ctrl) {
1809   const Type* elemtype = arytype->elem();
1810   BasicType elembt = elemtype->array_element_basic_type();
1811   assert(elembt != T_PRIMITIVE_OBJECT, "inline types are not supported by this method");
1812   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
1813   if (elembt == T_NARROWOOP) {
1814     elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
1815   }
1816   Node* ld = access_load_at(ary, adr, arytype, elemtype, elembt,
1817                             IN_HEAP | IS_ARRAY | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0));
1818   return ld;
1819 }
1820 
1821 //-------------------------set_arguments_for_java_call-------------------------
1822 // Arguments (pre-popped from the stack) are taken from the JVMS.
1823 void GraphKit::set_arguments_for_java_call(CallJavaNode* call, bool is_late_inline) {
1824   PreserveReexecuteState preexecs(this);
1825   if (EnableValhalla) {
1826     // Make sure the call is "re-executed", if buffering of inline type arguments triggers deoptimization.
1827     // At this point, the call hasn't been executed yet, so we will only ever execute the call once.
1828     jvms()->set_should_reexecute(true);
1829     int arg_size = method()->get_declared_signature_at_bci(bci())->arg_size_for_bc(java_bc());
1830     inc_sp(arg_size);
1831   }
1832   // Add the call arguments
1833   const TypeTuple* domain = call->tf()->domain_sig();
1834   uint nargs = domain->cnt();
1835   int arg_num = 0;
1836   for (uint i = TypeFunc::Parms, idx = TypeFunc::Parms; i < nargs; i++) {
1837     Node* arg = argument(i-TypeFunc::Parms);
1838     const Type* t = domain->field_at(i);
1839     if (t->is_inlinetypeptr() && call->method()->is_scalarized_arg(arg_num)) {
1840       // We don't pass inline type arguments by reference but instead pass each field of the inline type
1841       if (!arg->is_InlineType()) {
1842         assert(_gvn.type(arg)->is_zero_type() && !t->inline_klass()->is_null_free(), "Unexpected argument type");
1843         arg = InlineTypeNode::make_from_oop(this, arg, t->inline_klass(), t->inline_klass()->is_null_free());
1844       }
1845       InlineTypeNode* vt = arg->as_InlineType();
1846       vt->pass_fields(this, call, idx, true, !t->maybe_null());
1847       // If an inline type argument is passed as fields, attach the Method* to the call site
1848       // to be able to access the extended signature later via attached_method_before_pc().
1849       // For example, see CompiledMethod::preserve_callee_argument_oops().
1850       call->set_override_symbolic_info(true);
1851       arg_num++;
1852       continue;
1853     } else if (arg->is_InlineType()) {
1854       // Pass inline type argument via oop to callee
1855       arg = arg->as_InlineType()->buffer(this);
1856       if (!is_late_inline) {
1857         arg = arg->as_InlineType()->get_oop();
1858       }
1859     }
1860     if (t != Type::HALF) {
1861       arg_num++;
1862     }
1863     call->init_req(idx++, arg);
1864   }
1865 }
1866 
1867 //---------------------------set_edges_for_java_call---------------------------
1868 // Connect a newly created call into the current JVMS.
1869 // A return value node (if any) is returned from set_edges_for_java_call.
1870 void GraphKit::set_edges_for_java_call(CallJavaNode* call, bool must_throw, bool separate_io_proj) {
1871 
1872   // Add the predefined inputs:
1873   call->init_req( TypeFunc::Control, control() );
1874   call->init_req( TypeFunc::I_O    , i_o() );
1875   call->init_req( TypeFunc::Memory , reset_memory() );
1876   call->init_req( TypeFunc::FramePtr, frameptr() );
1877   call->init_req( TypeFunc::ReturnAdr, top() );
1878 
1879   add_safepoint_edges(call, must_throw);
1880 
1881   Node* xcall = _gvn.transform(call);
1882 
1883   if (xcall == top()) {
1884     set_control(top());
1885     return;
1886   }
1887   assert(xcall == call, "call identity is stable");
1888 
1889   // Re-use the current map to produce the result.
1890 
1891   set_control(_gvn.transform(new ProjNode(call, TypeFunc::Control)));
1892   set_i_o(    _gvn.transform(new ProjNode(call, TypeFunc::I_O    , separate_io_proj)));
1893   set_all_memory_call(xcall, separate_io_proj);
1894 
1895   //return xcall;   // no need, caller already has it
1896 }
1897 
1898 Node* GraphKit::set_results_for_java_call(CallJavaNode* call, bool separate_io_proj, bool deoptimize) {
1899   if (stopped())  return top();  // maybe the call folded up?
1900 
1901   // Note:  Since any out-of-line call can produce an exception,
1902   // we always insert an I_O projection from the call into the result.
1903 
1904   make_slow_call_ex(call, env()->Throwable_klass(), separate_io_proj, deoptimize);
1905 
1906   if (separate_io_proj) {
1907     // The caller requested separate projections be used by the fall
1908     // through and exceptional paths, so replace the projections for
1909     // the fall through path.
1910     set_i_o(_gvn.transform( new ProjNode(call, TypeFunc::I_O) ));
1911     set_all_memory(_gvn.transform( new ProjNode(call, TypeFunc::Memory) ));
1912   }
1913 
1914   // Capture the return value, if any.
1915   Node* ret;
1916   if (call->method() == NULL || call->method()->return_type()->basic_type() == T_VOID) {
1917     ret = top();
1918   } else if (call->tf()->returns_inline_type_as_fields()) {
1919     // Return of multiple values (inline type fields): we create a
1920     // InlineType node, each field is a projection from the call.
1921     ciInlineKlass* vk = call->method()->return_type()->as_inline_klass();
1922     uint base_input = TypeFunc::Parms;
1923     ret = InlineTypeNode::make_from_multi(this, call, vk, base_input, false, call->method()->signature()->returns_null_free_inline_type());
1924   } else {
1925     ret = _gvn.transform(new ProjNode(call, TypeFunc::Parms));
1926   }
1927 
1928   return ret;
1929 }
1930 
1931 //--------------------set_predefined_input_for_runtime_call--------------------
1932 // Reading and setting the memory state is way conservative here.
1933 // The real problem is that I am not doing real Type analysis on memory,
1934 // so I cannot distinguish card mark stores from other stores.  Across a GC
1935 // point the Store Barrier and the card mark memory has to agree.  I cannot
1936 // have a card mark store and its barrier split across the GC point from
1937 // either above or below.  Here I get that to happen by reading ALL of memory.
1938 // A better answer would be to separate out card marks from other memory.
1939 // For now, return the input memory state, so that it can be reused
1940 // after the call, if this call has restricted memory effects.
1941 Node* GraphKit::set_predefined_input_for_runtime_call(SafePointNode* call, Node* narrow_mem) {
1942   // Set fixed predefined input arguments
1943   Node* memory = reset_memory();
1944   Node* m = narrow_mem == NULL ? memory : narrow_mem;
1945   call->init_req( TypeFunc::Control,   control()  );
1946   call->init_req( TypeFunc::I_O,       top()      ); // does no i/o
1947   call->init_req( TypeFunc::Memory,    m          ); // may gc ptrs
1948   call->init_req( TypeFunc::FramePtr,  frameptr() );
1949   call->init_req( TypeFunc::ReturnAdr, top()      );
1950   return memory;
1951 }
1952 
1953 //-------------------set_predefined_output_for_runtime_call--------------------
1954 // Set control and memory (not i_o) from the call.
1955 // If keep_mem is not NULL, use it for the output state,
1956 // except for the RawPtr output of the call, if hook_mem is TypeRawPtr::BOTTOM.
1957 // If hook_mem is NULL, this call produces no memory effects at all.
1958 // If hook_mem is a Java-visible memory slice (such as arraycopy operands),
1959 // then only that memory slice is taken from the call.
1960 // In the last case, we must put an appropriate memory barrier before
1961 // the call, so as to create the correct anti-dependencies on loads
1962 // preceding the call.
1963 void GraphKit::set_predefined_output_for_runtime_call(Node* call,
1964                                                       Node* keep_mem,
1965                                                       const TypePtr* hook_mem) {
1966   // no i/o
1967   set_control(_gvn.transform( new ProjNode(call,TypeFunc::Control) ));
1968   if (keep_mem) {
1969     // First clone the existing memory state
1970     set_all_memory(keep_mem);
1971     if (hook_mem != NULL) {
1972       // Make memory for the call
1973       Node* mem = _gvn.transform( new ProjNode(call, TypeFunc::Memory) );
1974       // Set the RawPtr memory state only.  This covers all the heap top/GC stuff
1975       // We also use hook_mem to extract specific effects from arraycopy stubs.
1976       set_memory(mem, hook_mem);
1977     }
1978     // ...else the call has NO memory effects.
1979 
1980     // Make sure the call advertises its memory effects precisely.
1981     // This lets us build accurate anti-dependences in gcm.cpp.
1982     assert(C->alias_type(call->adr_type()) == C->alias_type(hook_mem),
1983            "call node must be constructed correctly");
1984   } else {
1985     assert(hook_mem == NULL, "");
1986     // This is not a "slow path" call; all memory comes from the call.
1987     set_all_memory_call(call);
1988   }
1989 }
1990 
1991 // Keep track of MergeMems feeding into other MergeMems
1992 static void add_mergemem_users_to_worklist(Unique_Node_List& wl, Node* mem) {
1993   if (!mem->is_MergeMem()) {
1994     return;
1995   }
1996   for (SimpleDUIterator i(mem); i.has_next(); i.next()) {
1997     Node* use = i.get();
1998     if (use->is_MergeMem()) {
1999       wl.push(use);
2000     }
2001   }
2002 }
2003 
2004 // Replace the call with the current state of the kit.
2005 void GraphKit::replace_call(CallNode* call, Node* result, bool do_replaced_nodes) {
2006   JVMState* ejvms = NULL;
2007   if (has_exceptions()) {
2008     ejvms = transfer_exceptions_into_jvms();
2009   }
2010 
2011   ReplacedNodes replaced_nodes = map()->replaced_nodes();
2012   ReplacedNodes replaced_nodes_exception;
2013   Node* ex_ctl = top();
2014 
2015   SafePointNode* final_state = stop();
2016 
2017   // Find all the needed outputs of this call
2018   CallProjections* callprojs = call->extract_projections(true);
2019 
2020   Unique_Node_List wl;
2021   Node* init_mem = call->in(TypeFunc::Memory);
2022   Node* final_mem = final_state->in(TypeFunc::Memory);
2023   Node* final_ctl = final_state->in(TypeFunc::Control);
2024   Node* final_io = final_state->in(TypeFunc::I_O);
2025 
2026   // Replace all the old call edges with the edges from the inlining result
2027   if (callprojs->fallthrough_catchproj != NULL) {
2028     C->gvn_replace_by(callprojs->fallthrough_catchproj, final_ctl);
2029   }
2030   if (callprojs->fallthrough_memproj != NULL) {
2031     if (final_mem->is_MergeMem()) {
2032       // Parser's exits MergeMem was not transformed but may be optimized
2033       final_mem = _gvn.transform(final_mem);
2034     }
2035     C->gvn_replace_by(callprojs->fallthrough_memproj,   final_mem);
2036     add_mergemem_users_to_worklist(wl, final_mem);
2037   }
2038   if (callprojs->fallthrough_ioproj != NULL) {
2039     C->gvn_replace_by(callprojs->fallthrough_ioproj,    final_io);
2040   }
2041 
2042   // Replace the result with the new result if it exists and is used
2043   if (callprojs->resproj[0] != NULL && result != NULL) {
2044     // If the inlined code is dead, the result projections for an inline type returned as
2045     // fields have not been replaced. They will go away once the call is replaced by TOP below.
2046     assert(callprojs->nb_resproj == 1 || (call->tf()->returns_inline_type_as_fields() && stopped()),
2047            "unexpected number of results");
2048     C->gvn_replace_by(callprojs->resproj[0], result);
2049   }
2050 
2051   if (ejvms == NULL) {
2052     // No exception edges to simply kill off those paths
2053     if (callprojs->catchall_catchproj != NULL) {
2054       C->gvn_replace_by(callprojs->catchall_catchproj, C->top());
2055     }
2056     if (callprojs->catchall_memproj != NULL) {
2057       C->gvn_replace_by(callprojs->catchall_memproj,   C->top());
2058     }
2059     if (callprojs->catchall_ioproj != NULL) {
2060       C->gvn_replace_by(callprojs->catchall_ioproj,    C->top());
2061     }
2062     // Replace the old exception object with top
2063     if (callprojs->exobj != NULL) {
2064       C->gvn_replace_by(callprojs->exobj, C->top());
2065     }
2066   } else {
2067     GraphKit ekit(ejvms);
2068 
2069     // Load my combined exception state into the kit, with all phis transformed:
2070     SafePointNode* ex_map = ekit.combine_and_pop_all_exception_states();
2071     replaced_nodes_exception = ex_map->replaced_nodes();
2072 
2073     Node* ex_oop = ekit.use_exception_state(ex_map);
2074 
2075     if (callprojs->catchall_catchproj != NULL) {
2076       C->gvn_replace_by(callprojs->catchall_catchproj, ekit.control());
2077       ex_ctl = ekit.control();
2078     }
2079     if (callprojs->catchall_memproj != NULL) {
2080       Node* ex_mem = ekit.reset_memory();
2081       C->gvn_replace_by(callprojs->catchall_memproj,   ex_mem);
2082       add_mergemem_users_to_worklist(wl, ex_mem);
2083     }
2084     if (callprojs->catchall_ioproj != NULL) {
2085       C->gvn_replace_by(callprojs->catchall_ioproj,    ekit.i_o());
2086     }
2087 
2088     // Replace the old exception object with the newly created one
2089     if (callprojs->exobj != NULL) {
2090       C->gvn_replace_by(callprojs->exobj, ex_oop);
2091     }
2092   }
2093 
2094   // Disconnect the call from the graph
2095   call->disconnect_inputs(C);
2096   C->gvn_replace_by(call, C->top());
2097 
2098   // Clean up any MergeMems that feed other MergeMems since the
2099   // optimizer doesn't like that.
2100   while (wl.size() > 0) {
2101     _gvn.transform(wl.pop());
2102   }
2103 
2104   if (callprojs->fallthrough_catchproj != NULL && !final_ctl->is_top() && do_replaced_nodes) {
2105     replaced_nodes.apply(C, final_ctl);
2106   }
2107   if (!ex_ctl->is_top() && do_replaced_nodes) {
2108     replaced_nodes_exception.apply(C, ex_ctl);
2109   }
2110 }
2111 
2112 
2113 //------------------------------increment_counter------------------------------
2114 // for statistics: increment a VM counter by 1
2115 
2116 void GraphKit::increment_counter(address counter_addr) {
2117   Node* adr1 = makecon(TypeRawPtr::make(counter_addr));
2118   increment_counter(adr1);
2119 }
2120 
2121 void GraphKit::increment_counter(Node* counter_addr) {
2122   int adr_type = Compile::AliasIdxRaw;
2123   Node* ctrl = control();
2124   Node* cnt  = make_load(ctrl, counter_addr, TypeLong::LONG, T_LONG, adr_type, MemNode::unordered);
2125   Node* incr = _gvn.transform(new AddLNode(cnt, _gvn.longcon(1)));
2126   store_to_memory(ctrl, counter_addr, incr, T_LONG, adr_type, MemNode::unordered);
2127 }
2128 
2129 
2130 //------------------------------uncommon_trap----------------------------------
2131 // Bail out to the interpreter in mid-method.  Implemented by calling the
2132 // uncommon_trap blob.  This helper function inserts a runtime call with the
2133 // right debug info.
2134 Node* GraphKit::uncommon_trap(int trap_request,
2135                              ciKlass* klass, const char* comment,
2136                              bool must_throw,
2137                              bool keep_exact_action) {
2138   if (failing())  stop();
2139   if (stopped())  return NULL; // trap reachable?
2140 
2141   // Note:  If ProfileTraps is true, and if a deopt. actually
2142   // occurs here, the runtime will make sure an MDO exists.  There is
2143   // no need to call method()->ensure_method_data() at this point.
2144 
2145   // Set the stack pointer to the right value for reexecution:
2146   set_sp(reexecute_sp());
2147 
2148 #ifdef ASSERT
2149   if (!must_throw) {
2150     // Make sure the stack has at least enough depth to execute
2151     // the current bytecode.
2152     int inputs, ignored_depth;
2153     if (compute_stack_effects(inputs, ignored_depth)) {
2154       assert(sp() >= inputs, "must have enough JVMS stack to execute %s: sp=%d, inputs=%d",
2155              Bytecodes::name(java_bc()), sp(), inputs);
2156     }
2157   }
2158 #endif
2159 
2160   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
2161   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
2162 
2163   switch (action) {
2164   case Deoptimization::Action_maybe_recompile:
2165   case Deoptimization::Action_reinterpret:
2166     // Temporary fix for 6529811 to allow virtual calls to be sure they
2167     // get the chance to go from mono->bi->mega
2168     if (!keep_exact_action &&
2169         Deoptimization::trap_request_index(trap_request) < 0 &&
2170         too_many_recompiles(reason)) {
2171       // This BCI is causing too many recompilations.
2172       if (C->log() != NULL) {
2173         C->log()->elem("observe that='trap_action_change' reason='%s' from='%s' to='none'",
2174                 Deoptimization::trap_reason_name(reason),
2175                 Deoptimization::trap_action_name(action));
2176       }
2177       action = Deoptimization::Action_none;
2178       trap_request = Deoptimization::make_trap_request(reason, action);
2179     } else {
2180       C->set_trap_can_recompile(true);
2181     }
2182     break;
2183   case Deoptimization::Action_make_not_entrant:
2184     C->set_trap_can_recompile(true);
2185     break;
2186   case Deoptimization::Action_none:
2187   case Deoptimization::Action_make_not_compilable:
2188     break;
2189   default:
2190 #ifdef ASSERT
2191     fatal("unknown action %d: %s", action, Deoptimization::trap_action_name(action));
2192 #endif
2193     break;
2194   }
2195 
2196   if (TraceOptoParse) {
2197     char buf[100];
2198     tty->print_cr("Uncommon trap %s at bci:%d",
2199                   Deoptimization::format_trap_request(buf, sizeof(buf),
2200                                                       trap_request), bci());
2201   }
2202 
2203   CompileLog* log = C->log();
2204   if (log != NULL) {
2205     int kid = (klass == NULL)? -1: log->identify(klass);
2206     log->begin_elem("uncommon_trap bci='%d'", bci());
2207     char buf[100];
2208     log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
2209                                                           trap_request));
2210     if (kid >= 0)         log->print(" klass='%d'", kid);
2211     if (comment != NULL)  log->print(" comment='%s'", comment);
2212     log->end_elem();
2213   }
2214 
2215   // Make sure any guarding test views this path as very unlikely
2216   Node *i0 = control()->in(0);
2217   if (i0 != NULL && i0->is_If()) {        // Found a guarding if test?
2218     IfNode *iff = i0->as_If();
2219     float f = iff->_prob;   // Get prob
2220     if (control()->Opcode() == Op_IfTrue) {
2221       if (f > PROB_UNLIKELY_MAG(4))
2222         iff->_prob = PROB_MIN;
2223     } else {
2224       if (f < PROB_LIKELY_MAG(4))
2225         iff->_prob = PROB_MAX;
2226     }
2227   }
2228 
2229   // Clear out dead values from the debug info.
2230   kill_dead_locals();
2231 
2232   // Now insert the uncommon trap subroutine call
2233   address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
2234   const TypePtr* no_memory_effects = NULL;
2235   // Pass the index of the class to be loaded
2236   Node* call = make_runtime_call(RC_NO_LEAF | RC_UNCOMMON |
2237                                  (must_throw ? RC_MUST_THROW : 0),
2238                                  OptoRuntime::uncommon_trap_Type(),
2239                                  call_addr, "uncommon_trap", no_memory_effects,
2240                                  intcon(trap_request));
2241   assert(call->as_CallStaticJava()->uncommon_trap_request() == trap_request,
2242          "must extract request correctly from the graph");
2243   assert(trap_request != 0, "zero value reserved by uncommon_trap_request");
2244 
2245   call->set_req(TypeFunc::ReturnAdr, returnadr());
2246   // The debug info is the only real input to this call.
2247 
2248   // Halt-and-catch fire here.  The above call should never return!
2249   HaltNode* halt = new HaltNode(control(), frameptr(), "uncommon trap returned which should never happen"
2250                                                        PRODUCT_ONLY(COMMA /*reachable*/false));
2251   _gvn.set_type_bottom(halt);
2252   root()->add_req(halt);
2253 
2254   stop_and_kill_map();
2255   return call;
2256 }
2257 
2258 
2259 //--------------------------just_allocated_object------------------------------
2260 // Report the object that was just allocated.
2261 // It must be the case that there are no intervening safepoints.
2262 // We use this to determine if an object is so "fresh" that
2263 // it does not require card marks.
2264 Node* GraphKit::just_allocated_object(Node* current_control) {
2265   Node* ctrl = current_control;
2266   // Object::<init> is invoked after allocation, most of invoke nodes
2267   // will be reduced, but a region node is kept in parse time, we check
2268   // the pattern and skip the region node if it degraded to a copy.
2269   if (ctrl != NULL && ctrl->is_Region() && ctrl->req() == 2 &&
2270       ctrl->as_Region()->is_copy()) {
2271     ctrl = ctrl->as_Region()->is_copy();
2272   }
2273   if (C->recent_alloc_ctl() == ctrl) {
2274    return C->recent_alloc_obj();
2275   }
2276   return NULL;
2277 }
2278 
2279 
2280 /**
2281  * Record profiling data exact_kls for Node n with the type system so
2282  * that it can propagate it (speculation)
2283  *
2284  * @param n          node that the type applies to
2285  * @param exact_kls  type from profiling
2286  * @param maybe_null did profiling see null?
2287  *
2288  * @return           node with improved type
2289  */
2290 Node* GraphKit::record_profile_for_speculation(Node* n, ciKlass* exact_kls, ProfilePtrKind ptr_kind) {
2291   const Type* current_type = _gvn.type(n);
2292   assert(UseTypeSpeculation, "type speculation must be on");
2293 
2294   const TypePtr* speculative = current_type->speculative();
2295 
2296   // Should the klass from the profile be recorded in the speculative type?
2297   if (current_type->would_improve_type(exact_kls, jvms()->depth())) {
2298     const TypeKlassPtr* tklass = TypeKlassPtr::make(exact_kls, Type::trust_interfaces);
2299     const TypeOopPtr* xtype = tklass->as_instance_type();
2300     assert(xtype->klass_is_exact(), "Should be exact");
2301     // Any reason to believe n is not null (from this profiling or a previous one)?
2302     assert(ptr_kind != ProfileAlwaysNull, "impossible here");
2303     const TypePtr* ptr = (ptr_kind != ProfileNeverNull && current_type->speculative_maybe_null()) ? TypePtr::BOTTOM : TypePtr::NOTNULL;
2304     // record the new speculative type's depth
2305     speculative = xtype->cast_to_ptr_type(ptr->ptr())->is_ptr();
2306     speculative = speculative->with_inline_depth(jvms()->depth());
2307   } else if (current_type->would_improve_ptr(ptr_kind)) {
2308     // Profiling report that null was never seen so we can change the
2309     // speculative type to non null ptr.
2310     if (ptr_kind == ProfileAlwaysNull) {
2311       speculative = TypePtr::NULL_PTR;
2312     } else {
2313       assert(ptr_kind == ProfileNeverNull, "nothing else is an improvement");
2314       const TypePtr* ptr = TypePtr::NOTNULL;
2315       if (speculative != NULL) {
2316         speculative = speculative->cast_to_ptr_type(ptr->ptr())->is_ptr();
2317       } else {
2318         speculative = ptr;
2319       }
2320     }
2321   }
2322 
2323   if (speculative != current_type->speculative()) {
2324     // Build a type with a speculative type (what we think we know
2325     // about the type but will need a guard when we use it)
2326     const TypeOopPtr* spec_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, speculative);
2327     // We're changing the type, we need a new CheckCast node to carry
2328     // the new type. The new type depends on the control: what
2329     // profiling tells us is only valid from here as far as we can
2330     // tell.
2331     Node* cast = new CheckCastPPNode(control(), n, current_type->remove_speculative()->join_speculative(spec_type));
2332     cast = _gvn.transform(cast);
2333     replace_in_map(n, cast);
2334     n = cast;
2335   }
2336 
2337   return n;
2338 }
2339 
2340 /**
2341  * Record profiling data from receiver profiling at an invoke with the
2342  * type system so that it can propagate it (speculation)
2343  *
2344  * @param n  receiver node
2345  *
2346  * @return   node with improved type
2347  */
2348 Node* GraphKit::record_profiled_receiver_for_speculation(Node* n) {
2349   if (!UseTypeSpeculation) {
2350     return n;
2351   }
2352   ciKlass* exact_kls = profile_has_unique_klass();
2353   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2354   if ((java_bc() == Bytecodes::_checkcast ||
2355        java_bc() == Bytecodes::_instanceof ||
2356        java_bc() == Bytecodes::_aastore) &&
2357       method()->method_data()->is_mature()) {
2358     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2359     if (data != NULL) {
2360       if (java_bc() == Bytecodes::_aastore) {
2361         ciKlass* array_type = NULL;
2362         ciKlass* element_type = NULL;
2363         ProfilePtrKind element_ptr = ProfileMaybeNull;
2364         bool flat_array = true;
2365         bool null_free_array = true;
2366         method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
2367         exact_kls = element_type;
2368         ptr_kind = element_ptr;
2369       } else {
2370         if (!data->as_BitData()->null_seen()) {
2371           ptr_kind = ProfileNeverNull;
2372         } else {
2373           assert(data->is_ReceiverTypeData(), "bad profile data type");
2374           ciReceiverTypeData* call = (ciReceiverTypeData*)data->as_ReceiverTypeData();
2375           uint i = 0;
2376           for (; i < call->row_limit(); i++) {
2377             ciKlass* receiver = call->receiver(i);
2378             if (receiver != NULL) {
2379               break;
2380             }
2381           }
2382           ptr_kind = (i == call->row_limit()) ? ProfileAlwaysNull : ProfileMaybeNull;
2383         }
2384       }
2385     }
2386   }
2387   return record_profile_for_speculation(n, exact_kls, ptr_kind);
2388 }
2389 
2390 /**
2391  * Record profiling data from argument profiling at an invoke with the
2392  * type system so that it can propagate it (speculation)
2393  *
2394  * @param dest_method  target method for the call
2395  * @param bc           what invoke bytecode is this?
2396  */
2397 void GraphKit::record_profiled_arguments_for_speculation(ciMethod* dest_method, Bytecodes::Code bc) {
2398   if (!UseTypeSpeculation) {
2399     return;
2400   }
2401   const TypeFunc* tf    = TypeFunc::make(dest_method);
2402   int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2403   int skip = Bytecodes::has_receiver(bc) ? 1 : 0;
2404   for (int j = skip, i = 0; j < nargs && i < TypeProfileArgsLimit; j++) {
2405     const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2406     if (is_reference_type(targ->basic_type())) {
2407       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2408       ciKlass* better_type = NULL;
2409       if (method()->argument_profiled_type(bci(), i, better_type, ptr_kind)) {
2410         record_profile_for_speculation(argument(j), better_type, ptr_kind);
2411       }
2412       i++;
2413     }
2414   }
2415 }
2416 
2417 /**
2418  * Record profiling data from parameter profiling at an invoke with
2419  * the type system so that it can propagate it (speculation)
2420  */
2421 void GraphKit::record_profiled_parameters_for_speculation() {
2422   if (!UseTypeSpeculation) {
2423     return;
2424   }
2425   for (int i = 0, j = 0; i < method()->arg_size() ; i++) {
2426     if (_gvn.type(local(i))->isa_oopptr()) {
2427       ProfilePtrKind ptr_kind = ProfileMaybeNull;
2428       ciKlass* better_type = NULL;
2429       if (method()->parameter_profiled_type(j, better_type, ptr_kind)) {
2430         record_profile_for_speculation(local(i), better_type, ptr_kind);
2431       }
2432       j++;
2433     }
2434   }
2435 }
2436 
2437 /**
2438  * Record profiling data from return value profiling at an invoke with
2439  * the type system so that it can propagate it (speculation)
2440  */
2441 void GraphKit::record_profiled_return_for_speculation() {
2442   if (!UseTypeSpeculation) {
2443     return;
2444   }
2445   ProfilePtrKind ptr_kind = ProfileMaybeNull;
2446   ciKlass* better_type = NULL;
2447   if (method()->return_profiled_type(bci(), better_type, ptr_kind)) {
2448     // If profiling reports a single type for the return value,
2449     // feed it to the type system so it can propagate it as a
2450     // speculative type
2451     record_profile_for_speculation(stack(sp()-1), better_type, ptr_kind);
2452   }
2453 }
2454 
2455 void GraphKit::round_double_arguments(ciMethod* dest_method) {
2456   if (Matcher::strict_fp_requires_explicit_rounding) {
2457     // (Note:  TypeFunc::make has a cache that makes this fast.)
2458     const TypeFunc* tf    = TypeFunc::make(dest_method);
2459     int             nargs = tf->domain_sig()->cnt() - TypeFunc::Parms;
2460     for (int j = 0; j < nargs; j++) {
2461       const Type *targ = tf->domain_sig()->field_at(j + TypeFunc::Parms);
2462       if (targ->basic_type() == T_DOUBLE) {
2463         // If any parameters are doubles, they must be rounded before
2464         // the call, dprecision_rounding does gvn.transform
2465         Node *arg = argument(j);
2466         arg = dprecision_rounding(arg);
2467         set_argument(j, arg);
2468       }
2469     }
2470   }
2471 }
2472 
2473 // rounding for strict float precision conformance
2474 Node* GraphKit::precision_rounding(Node* n) {
2475   if (Matcher::strict_fp_requires_explicit_rounding) {
2476 #ifdef IA32
2477     if (UseSSE == 0) {
2478       return _gvn.transform(new RoundFloatNode(0, n));
2479     }
2480 #else
2481     Unimplemented();
2482 #endif // IA32
2483   }
2484   return n;
2485 }
2486 
2487 // rounding for strict double precision conformance
2488 Node* GraphKit::dprecision_rounding(Node *n) {
2489   if (Matcher::strict_fp_requires_explicit_rounding) {
2490 #ifdef IA32
2491     if (UseSSE < 2) {
2492       return _gvn.transform(new RoundDoubleNode(0, n));
2493     }
2494 #else
2495     Unimplemented();
2496 #endif // IA32
2497   }
2498   return n;
2499 }
2500 
2501 //=============================================================================
2502 // Generate a fast path/slow path idiom.  Graph looks like:
2503 // [foo] indicates that 'foo' is a parameter
2504 //
2505 //              [in]     NULL
2506 //                 \    /
2507 //                  CmpP
2508 //                  Bool ne
2509 //                   If
2510 //                  /  \
2511 //              True    False-<2>
2512 //              / |
2513 //             /  cast_not_null
2514 //           Load  |    |   ^
2515 //        [fast_test]   |   |
2516 // gvn to   opt_test    |   |
2517 //          /    \      |  <1>
2518 //      True     False  |
2519 //        |         \\  |
2520 //   [slow_call]     \[fast_result]
2521 //    Ctl   Val       \      \
2522 //     |               \      \
2523 //    Catch       <1>   \      \
2524 //   /    \        ^     \      \
2525 //  Ex    No_Ex    |      \      \
2526 //  |       \   \  |       \ <2>  \
2527 //  ...      \  [slow_res] |  |    \   [null_result]
2528 //            \         \--+--+---  |  |
2529 //             \           | /    \ | /
2530 //              --------Region     Phi
2531 //
2532 //=============================================================================
2533 // Code is structured as a series of driver functions all called 'do_XXX' that
2534 // call a set of helper functions.  Helper functions first, then drivers.
2535 
2536 //------------------------------null_check_oop---------------------------------
2537 // Null check oop.  Set null-path control into Region in slot 3.
2538 // Make a cast-not-nullness use the other not-null control.  Return cast.
2539 Node* GraphKit::null_check_oop(Node* value, Node* *null_control,
2540                                bool never_see_null,
2541                                bool safe_for_replace,
2542                                bool speculative) {
2543   // Initial NULL check taken path
2544   (*null_control) = top();
2545   Node* cast = null_check_common(value, T_OBJECT, false, null_control, speculative);
2546 
2547   // Generate uncommon_trap:
2548   if (never_see_null && (*null_control) != top()) {
2549     // If we see an unexpected null at a check-cast we record it and force a
2550     // recompile; the offending check-cast will be compiled to handle NULLs.
2551     // If we see more than one offending BCI, then all checkcasts in the
2552     // method will be compiled to handle NULLs.
2553     PreserveJVMState pjvms(this);
2554     set_control(*null_control);
2555     replace_in_map(value, null());
2556     Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculative);
2557     uncommon_trap(reason,
2558                   Deoptimization::Action_make_not_entrant);
2559     (*null_control) = top();    // NULL path is dead
2560   }
2561   if ((*null_control) == top() && safe_for_replace) {
2562     replace_in_map(value, cast);
2563   }
2564 
2565   // Cast away null-ness on the result
2566   return cast;
2567 }
2568 
2569 //------------------------------opt_iff----------------------------------------
2570 // Optimize the fast-check IfNode.  Set the fast-path region slot 2.
2571 // Return slow-path control.
2572 Node* GraphKit::opt_iff(Node* region, Node* iff) {
2573   IfNode *opt_iff = _gvn.transform(iff)->as_If();
2574 
2575   // Fast path taken; set region slot 2
2576   Node *fast_taken = _gvn.transform( new IfFalseNode(opt_iff) );
2577   region->init_req(2,fast_taken); // Capture fast-control
2578 
2579   // Fast path not-taken, i.e. slow path
2580   Node *slow_taken = _gvn.transform( new IfTrueNode(opt_iff) );
2581   return slow_taken;
2582 }
2583 
2584 //-----------------------------make_runtime_call-------------------------------
2585 Node* GraphKit::make_runtime_call(int flags,
2586                                   const TypeFunc* call_type, address call_addr,
2587                                   const char* call_name,
2588                                   const TypePtr* adr_type,
2589                                   // The following parms are all optional.
2590                                   // The first NULL ends the list.
2591                                   Node* parm0, Node* parm1,
2592                                   Node* parm2, Node* parm3,
2593                                   Node* parm4, Node* parm5,
2594                                   Node* parm6, Node* parm7) {
2595   assert(call_addr != NULL, "must not call NULL targets");
2596 
2597   // Slow-path call
2598   bool is_leaf = !(flags & RC_NO_LEAF);
2599   bool has_io  = (!is_leaf && !(flags & RC_NO_IO));
2600   if (call_name == NULL) {
2601     assert(!is_leaf, "must supply name for leaf");
2602     call_name = OptoRuntime::stub_name(call_addr);
2603   }
2604   CallNode* call;
2605   if (!is_leaf) {
2606     call = new CallStaticJavaNode(call_type, call_addr, call_name, adr_type);
2607   } else if (flags & RC_NO_FP) {
2608     call = new CallLeafNoFPNode(call_type, call_addr, call_name, adr_type);
2609   } else  if (flags & RC_VECTOR){
2610     uint num_bits = call_type->range_sig()->field_at(TypeFunc::Parms)->is_vect()->length_in_bytes() * BitsPerByte;
2611     call = new CallLeafVectorNode(call_type, call_addr, call_name, adr_type, num_bits);
2612   } else {
2613     call = new CallLeafNode(call_type, call_addr, call_name, adr_type);
2614   }
2615 
2616   // The following is similar to set_edges_for_java_call,
2617   // except that the memory effects of the call are restricted to AliasIdxRaw.
2618 
2619   // Slow path call has no side-effects, uses few values
2620   bool wide_in  = !(flags & RC_NARROW_MEM);
2621   bool wide_out = (C->get_alias_index(adr_type) == Compile::AliasIdxBot);
2622 
2623   Node* prev_mem = NULL;
2624   if (wide_in) {
2625     prev_mem = set_predefined_input_for_runtime_call(call);
2626   } else {
2627     assert(!wide_out, "narrow in => narrow out");
2628     Node* narrow_mem = memory(adr_type);
2629     prev_mem = set_predefined_input_for_runtime_call(call, narrow_mem);
2630   }
2631 
2632   // Hook each parm in order.  Stop looking at the first NULL.
2633   if (parm0 != NULL) { call->init_req(TypeFunc::Parms+0, parm0);
2634   if (parm1 != NULL) { call->init_req(TypeFunc::Parms+1, parm1);
2635   if (parm2 != NULL) { call->init_req(TypeFunc::Parms+2, parm2);
2636   if (parm3 != NULL) { call->init_req(TypeFunc::Parms+3, parm3);
2637   if (parm4 != NULL) { call->init_req(TypeFunc::Parms+4, parm4);
2638   if (parm5 != NULL) { call->init_req(TypeFunc::Parms+5, parm5);
2639   if (parm6 != NULL) { call->init_req(TypeFunc::Parms+6, parm6);
2640   if (parm7 != NULL) { call->init_req(TypeFunc::Parms+7, parm7);
2641   /* close each nested if ===> */  } } } } } } } }
2642   assert(call->in(call->req()-1) != NULL, "must initialize all parms");
2643 
2644   if (!is_leaf) {
2645     // Non-leaves can block and take safepoints:
2646     add_safepoint_edges(call, ((flags & RC_MUST_THROW) != 0));
2647   }
2648   // Non-leaves can throw exceptions:
2649   if (has_io) {
2650     call->set_req(TypeFunc::I_O, i_o());
2651   }
2652 
2653   if (flags & RC_UNCOMMON) {
2654     // Set the count to a tiny probability.  Cf. Estimate_Block_Frequency.
2655     // (An "if" probability corresponds roughly to an unconditional count.
2656     // Sort of.)
2657     call->set_cnt(PROB_UNLIKELY_MAG(4));
2658   }
2659 
2660   Node* c = _gvn.transform(call);
2661   assert(c == call, "cannot disappear");
2662 
2663   if (wide_out) {
2664     // Slow path call has full side-effects.
2665     set_predefined_output_for_runtime_call(call);
2666   } else {
2667     // Slow path call has few side-effects, and/or sets few values.
2668     set_predefined_output_for_runtime_call(call, prev_mem, adr_type);
2669   }
2670 
2671   if (has_io) {
2672     set_i_o(_gvn.transform(new ProjNode(call, TypeFunc::I_O)));
2673   }
2674   return call;
2675 
2676 }
2677 
2678 // i2b
2679 Node* GraphKit::sign_extend_byte(Node* in) {
2680   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(24)));
2681   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(24)));
2682 }
2683 
2684 // i2s
2685 Node* GraphKit::sign_extend_short(Node* in) {
2686   Node* tmp = _gvn.transform(new LShiftINode(in, _gvn.intcon(16)));
2687   return _gvn.transform(new RShiftINode(tmp, _gvn.intcon(16)));
2688 }
2689 
2690 
2691 //------------------------------merge_memory-----------------------------------
2692 // Merge memory from one path into the current memory state.
2693 void GraphKit::merge_memory(Node* new_mem, Node* region, int new_path) {
2694   for (MergeMemStream mms(merged_memory(), new_mem->as_MergeMem()); mms.next_non_empty2(); ) {
2695     Node* old_slice = mms.force_memory();
2696     Node* new_slice = mms.memory2();
2697     if (old_slice != new_slice) {
2698       PhiNode* phi;
2699       if (old_slice->is_Phi() && old_slice->as_Phi()->region() == region) {
2700         if (mms.is_empty()) {
2701           // clone base memory Phi's inputs for this memory slice
2702           assert(old_slice == mms.base_memory(), "sanity");
2703           phi = PhiNode::make(region, NULL, Type::MEMORY, mms.adr_type(C));
2704           _gvn.set_type(phi, Type::MEMORY);
2705           for (uint i = 1; i < phi->req(); i++) {
2706             phi->init_req(i, old_slice->in(i));
2707           }
2708         } else {
2709           phi = old_slice->as_Phi(); // Phi was generated already
2710         }
2711       } else {
2712         phi = PhiNode::make(region, old_slice, Type::MEMORY, mms.adr_type(C));
2713         _gvn.set_type(phi, Type::MEMORY);
2714       }
2715       phi->set_req(new_path, new_slice);
2716       mms.set_memory(phi);
2717     }
2718   }
2719 }
2720 
2721 //------------------------------make_slow_call_ex------------------------------
2722 // Make the exception handler hookups for the slow call
2723 void GraphKit::make_slow_call_ex(Node* call, ciInstanceKlass* ex_klass, bool separate_io_proj, bool deoptimize) {
2724   if (stopped())  return;
2725 
2726   // Make a catch node with just two handlers:  fall-through and catch-all
2727   Node* i_o  = _gvn.transform( new ProjNode(call, TypeFunc::I_O, separate_io_proj) );
2728   Node* catc = _gvn.transform( new CatchNode(control(), i_o, 2) );
2729   Node* norm = new CatchProjNode(catc, CatchProjNode::fall_through_index, CatchProjNode::no_handler_bci);
2730   _gvn.set_type_bottom(norm);
2731   C->record_for_igvn(norm);
2732   Node* excp = _gvn.transform( new CatchProjNode(catc, CatchProjNode::catch_all_index,    CatchProjNode::no_handler_bci) );
2733 
2734   { PreserveJVMState pjvms(this);
2735     set_control(excp);
2736     set_i_o(i_o);
2737 
2738     if (excp != top()) {
2739       if (deoptimize) {
2740         // Deoptimize if an exception is caught. Don't construct exception state in this case.
2741         uncommon_trap(Deoptimization::Reason_unhandled,
2742                       Deoptimization::Action_none);
2743       } else {
2744         // Create an exception state also.
2745         // Use an exact type if the caller has a specific exception.
2746         const Type* ex_type = TypeOopPtr::make_from_klass_unique(ex_klass)->cast_to_ptr_type(TypePtr::NotNull);
2747         Node*       ex_oop  = new CreateExNode(ex_type, control(), i_o);
2748         add_exception_state(make_exception_state(_gvn.transform(ex_oop)));
2749       }
2750     }
2751   }
2752 
2753   // Get the no-exception control from the CatchNode.
2754   set_control(norm);
2755 }
2756 
2757 static IfNode* gen_subtype_check_compare(Node* ctrl, Node* in1, Node* in2, BoolTest::mask test, float p, PhaseGVN& gvn, BasicType bt) {
2758   Node* cmp = NULL;
2759   switch(bt) {
2760   case T_INT: cmp = new CmpINode(in1, in2); break;
2761   case T_ADDRESS: cmp = new CmpPNode(in1, in2); break;
2762   default: fatal("unexpected comparison type %s", type2name(bt));
2763   }
2764   cmp = gvn.transform(cmp);
2765   Node* bol = gvn.transform(new BoolNode(cmp, test));
2766   IfNode* iff = new IfNode(ctrl, bol, p, COUNT_UNKNOWN);
2767   gvn.transform(iff);
2768   if (!bol->is_Con()) gvn.record_for_igvn(iff);
2769   return iff;
2770 }
2771 
2772 //-------------------------------gen_subtype_check-----------------------------
2773 // Generate a subtyping check.  Takes as input the subtype and supertype.
2774 // Returns 2 values: sets the default control() to the true path and returns
2775 // the false path.  Only reads invariant memory; sets no (visible) memory.
2776 // The PartialSubtypeCheckNode sets the hidden 1-word cache in the encoding
2777 // but that's not exposed to the optimizer.  This call also doesn't take in an
2778 // Object; if you wish to check an Object you need to load the Object's class
2779 // prior to coming here.
2780 Node* Phase::gen_subtype_check(Node* subklass, Node* superklass, Node** ctrl, Node* mem, PhaseGVN& gvn) {
2781   Compile* C = gvn.C;
2782   if ((*ctrl)->is_top()) {
2783     return C->top();
2784   }
2785 
2786   // Fast check for identical types, perhaps identical constants.
2787   // The types can even be identical non-constants, in cases
2788   // involving Array.newInstance, Object.clone, etc.
2789   if (subklass == superklass)
2790     return C->top();             // false path is dead; no test needed.
2791 
2792   if (gvn.type(superklass)->singleton()) {
2793     const TypeKlassPtr* superk = gvn.type(superklass)->is_klassptr();
2794     const TypeKlassPtr* subk   = gvn.type(subklass)->is_klassptr();
2795 
2796     // In the common case of an exact superklass, try to fold up the
2797     // test before generating code.  You may ask, why not just generate
2798     // the code and then let it fold up?  The answer is that the generated
2799     // code will necessarily include null checks, which do not always
2800     // completely fold away.  If they are also needless, then they turn
2801     // into a performance loss.  Example:
2802     //    Foo[] fa = blah(); Foo x = fa[0]; fa[1] = x;
2803     // Here, the type of 'fa' is often exact, so the store check
2804     // of fa[1]=x will fold up, without testing the nullness of x.
2805     switch (C->static_subtype_check(superk, subk)) {
2806     case Compile::SSC_always_false:
2807       {
2808         Node* always_fail = *ctrl;
2809         *ctrl = gvn.C->top();
2810         return always_fail;
2811       }
2812     case Compile::SSC_always_true:
2813       return C->top();
2814     case Compile::SSC_easy_test:
2815       {
2816         // Just do a direct pointer compare and be done.
2817         IfNode* iff = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_STATIC_FREQUENT, gvn, T_ADDRESS);
2818         *ctrl = gvn.transform(new IfTrueNode(iff));
2819         return gvn.transform(new IfFalseNode(iff));
2820       }
2821     case Compile::SSC_full_test:
2822       break;
2823     default:
2824       ShouldNotReachHere();
2825     }
2826   }
2827 
2828   // %%% Possible further optimization:  Even if the superklass is not exact,
2829   // if the subklass is the unique subtype of the superklass, the check
2830   // will always succeed.  We could leave a dependency behind to ensure this.
2831 
2832   // First load the super-klass's check-offset
2833   Node *p1 = gvn.transform(new AddPNode(superklass, superklass, gvn.MakeConX(in_bytes(Klass::super_check_offset_offset()))));
2834   Node* m = C->immutable_memory();
2835   Node *chk_off = gvn.transform(new LoadINode(NULL, m, p1, gvn.type(p1)->is_ptr(), TypeInt::INT, MemNode::unordered));
2836   int cacheoff_con = in_bytes(Klass::secondary_super_cache_offset());
2837   bool might_be_cache = (gvn.find_int_con(chk_off, cacheoff_con) == cacheoff_con);
2838 
2839   // Load from the sub-klass's super-class display list, or a 1-word cache of
2840   // the secondary superclass list, or a failing value with a sentinel offset
2841   // if the super-klass is an interface or exceptionally deep in the Java
2842   // hierarchy and we have to scan the secondary superclass list the hard way.
2843   // Worst-case type is a little odd: NULL is allowed as a result (usually
2844   // klass loads can never produce a NULL).
2845   Node *chk_off_X = chk_off;
2846 #ifdef _LP64
2847   chk_off_X = gvn.transform(new ConvI2LNode(chk_off_X));
2848 #endif
2849   Node *p2 = gvn.transform(new AddPNode(subklass,subklass,chk_off_X));
2850   // For some types like interfaces the following loadKlass is from a 1-word
2851   // cache which is mutable so can't use immutable memory.  Other
2852   // types load from the super-class display table which is immutable.
2853   Node *kmem = C->immutable_memory();
2854   // secondary_super_cache is not immutable but can be treated as such because:
2855   // - no ideal node writes to it in a way that could cause an
2856   //   incorrect/missed optimization of the following Load.
2857   // - it's a cache so, worse case, not reading the latest value
2858   //   wouldn't cause incorrect execution
2859   if (might_be_cache && mem != NULL) {
2860     kmem = mem->is_MergeMem() ? mem->as_MergeMem()->memory_at(C->get_alias_index(gvn.type(p2)->is_ptr())) : mem;
2861   }
2862   Node *nkls = gvn.transform(LoadKlassNode::make(gvn, NULL, kmem, p2, gvn.type(p2)->is_ptr(), TypeInstKlassPtr::OBJECT_OR_NULL));
2863 
2864   // Compile speed common case: ARE a subtype and we canNOT fail
2865   if( superklass == nkls )
2866     return C->top();             // false path is dead; no test needed.
2867 
2868   // See if we get an immediate positive hit.  Happens roughly 83% of the
2869   // time.  Test to see if the value loaded just previously from the subklass
2870   // is exactly the superklass.
2871   IfNode *iff1 = gen_subtype_check_compare(*ctrl, superklass, nkls, BoolTest::eq, PROB_LIKELY(0.83f), gvn, T_ADDRESS);
2872   Node *iftrue1 = gvn.transform( new IfTrueNode (iff1));
2873   *ctrl = gvn.transform(new IfFalseNode(iff1));
2874 
2875   // Compile speed common case: Check for being deterministic right now.  If
2876   // chk_off is a constant and not equal to cacheoff then we are NOT a
2877   // subklass.  In this case we need exactly the 1 test above and we can
2878   // return those results immediately.
2879   if (!might_be_cache) {
2880     Node* not_subtype_ctrl = *ctrl;
2881     *ctrl = iftrue1; // We need exactly the 1 test above
2882     return not_subtype_ctrl;
2883   }
2884 
2885   // Gather the various success & failures here
2886   RegionNode *r_ok_subtype = new RegionNode(4);
2887   gvn.record_for_igvn(r_ok_subtype);
2888   RegionNode *r_not_subtype = new RegionNode(3);
2889   gvn.record_for_igvn(r_not_subtype);
2890 
2891   r_ok_subtype->init_req(1, iftrue1);
2892 
2893   // Check for immediate negative hit.  Happens roughly 11% of the time (which
2894   // is roughly 63% of the remaining cases).  Test to see if the loaded
2895   // check-offset points into the subklass display list or the 1-element
2896   // cache.  If it points to the display (and NOT the cache) and the display
2897   // missed then it's not a subtype.
2898   Node *cacheoff = gvn.intcon(cacheoff_con);
2899   IfNode *iff2 = gen_subtype_check_compare(*ctrl, chk_off, cacheoff, BoolTest::ne, PROB_LIKELY(0.63f), gvn, T_INT);
2900   r_not_subtype->init_req(1, gvn.transform(new IfTrueNode (iff2)));
2901   *ctrl = gvn.transform(new IfFalseNode(iff2));
2902 
2903   // Check for self.  Very rare to get here, but it is taken 1/3 the time.
2904   // No performance impact (too rare) but allows sharing of secondary arrays
2905   // which has some footprint reduction.
2906   IfNode *iff3 = gen_subtype_check_compare(*ctrl, subklass, superklass, BoolTest::eq, PROB_LIKELY(0.36f), gvn, T_ADDRESS);
2907   r_ok_subtype->init_req(2, gvn.transform(new IfTrueNode(iff3)));
2908   *ctrl = gvn.transform(new IfFalseNode(iff3));
2909 
2910   // -- Roads not taken here: --
2911   // We could also have chosen to perform the self-check at the beginning
2912   // of this code sequence, as the assembler does.  This would not pay off
2913   // the same way, since the optimizer, unlike the assembler, can perform
2914   // static type analysis to fold away many successful self-checks.
2915   // Non-foldable self checks work better here in second position, because
2916   // the initial primary superclass check subsumes a self-check for most
2917   // types.  An exception would be a secondary type like array-of-interface,
2918   // which does not appear in its own primary supertype display.
2919   // Finally, we could have chosen to move the self-check into the
2920   // PartialSubtypeCheckNode, and from there out-of-line in a platform
2921   // dependent manner.  But it is worthwhile to have the check here,
2922   // where it can be perhaps be optimized.  The cost in code space is
2923   // small (register compare, branch).
2924 
2925   // Now do a linear scan of the secondary super-klass array.  Again, no real
2926   // performance impact (too rare) but it's gotta be done.
2927   // Since the code is rarely used, there is no penalty for moving it
2928   // out of line, and it can only improve I-cache density.
2929   // The decision to inline or out-of-line this final check is platform
2930   // dependent, and is found in the AD file definition of PartialSubtypeCheck.
2931   Node* psc = gvn.transform(
2932     new PartialSubtypeCheckNode(*ctrl, subklass, superklass));
2933 
2934   IfNode *iff4 = gen_subtype_check_compare(*ctrl, psc, gvn.zerocon(T_OBJECT), BoolTest::ne, PROB_FAIR, gvn, T_ADDRESS);
2935   r_not_subtype->init_req(2, gvn.transform(new IfTrueNode (iff4)));
2936   r_ok_subtype ->init_req(3, gvn.transform(new IfFalseNode(iff4)));
2937 
2938   // Return false path; set default control to true path.
2939   *ctrl = gvn.transform(r_ok_subtype);
2940   return gvn.transform(r_not_subtype);
2941 }
2942 
2943 Node* GraphKit::gen_subtype_check(Node* obj_or_subklass, Node* superklass) {
2944   const Type* sub_t = _gvn.type(obj_or_subklass);
2945   if (sub_t->make_oopptr() != NULL && sub_t->make_oopptr()->is_inlinetypeptr()) {
2946     sub_t = TypeKlassPtr::make(sub_t->inline_klass());
2947     obj_or_subklass = makecon(sub_t);
2948   }
2949   bool expand_subtype_check = C->post_loop_opts_phase() ||   // macro node expansion is over
2950                               ExpandSubTypeCheckAtParseTime; // forced expansion
2951   if (expand_subtype_check) {
2952     MergeMemNode* mem = merged_memory();
2953     Node* ctrl = control();
2954     Node* subklass = obj_or_subklass;
2955     if (!sub_t->isa_klassptr()) {
2956       subklass = load_object_klass(obj_or_subklass);
2957     }
2958     Node* n = Phase::gen_subtype_check(subklass, superklass, &ctrl, mem, _gvn);
2959     set_control(ctrl);
2960     return n;
2961   }
2962 
2963   Node* check = _gvn.transform(new SubTypeCheckNode(C, obj_or_subklass, superklass));
2964   Node* bol = _gvn.transform(new BoolNode(check, BoolTest::eq));
2965   IfNode* iff = create_and_xform_if(control(), bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN);
2966   set_control(_gvn.transform(new IfTrueNode(iff)));
2967   return _gvn.transform(new IfFalseNode(iff));
2968 }
2969 
2970 // Profile-driven exact type check:
2971 Node* GraphKit::type_check_receiver(Node* receiver, ciKlass* klass,
2972                                     float prob, Node* *casted_receiver) {
2973   assert(!klass->is_interface(), "no exact type check on interfaces");
2974   Node* fail = top();
2975   const Type* rec_t = _gvn.type(receiver);
2976   if (rec_t->is_inlinetypeptr()) {
2977     if (klass->equals(rec_t->inline_klass())) {
2978       (*casted_receiver) = receiver; // Always passes
2979     } else {
2980       (*casted_receiver) = top();    // Always fails
2981       fail = control();
2982       set_control(top());
2983     }
2984     return fail;
2985   }
2986   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces);
2987   Node* recv_klass = load_object_klass(receiver);
2988   fail = type_check(recv_klass, tklass, prob);
2989 
2990   if (!stopped()) {
2991     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
2992     const TypeOopPtr* recv_xtype = tklass->as_instance_type();
2993     assert(recv_xtype->klass_is_exact(), "");
2994 
2995     if (!receiver_type->higher_equal(recv_xtype)) { // ignore redundant casts
2996       // Subsume downstream occurrences of receiver with a cast to
2997       // recv_xtype, since now we know what the type will be.
2998       Node* cast = new CheckCastPPNode(control(), receiver, recv_xtype);
2999       Node* res = _gvn.transform(cast);
3000       if (recv_xtype->is_inlinetypeptr()) {
3001         assert(!gvn().type(res)->maybe_null(), "receiver should never be null");
3002         res = InlineTypeNode::make_from_oop(this, res, recv_xtype->inline_klass());
3003       }
3004       (*casted_receiver) = res;
3005       // (User must make the replace_in_map call.)
3006     }
3007   }
3008 
3009   return fail;
3010 }
3011 
3012 Node* GraphKit::type_check(Node* recv_klass, const TypeKlassPtr* tklass,
3013                            float prob) {
3014   Node* want_klass = makecon(tklass);
3015   Node* cmp = _gvn.transform(new CmpPNode(recv_klass, want_klass));
3016   Node* bol = _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3017   IfNode* iff = create_and_xform_if(control(), bol, prob, COUNT_UNKNOWN);
3018   set_control(_gvn.transform(new IfTrueNode (iff)));
3019   Node* fail = _gvn.transform(new IfFalseNode(iff));
3020   return fail;
3021 }
3022 
3023 //------------------------------subtype_check_receiver-------------------------
3024 Node* GraphKit::subtype_check_receiver(Node* receiver, ciKlass* klass,
3025                                        Node** casted_receiver) {
3026   const TypeKlassPtr* tklass = TypeKlassPtr::make(klass, Type::trust_interfaces)->try_improve();
3027   Node* want_klass = makecon(tklass);
3028 
3029   Node* slow_ctl = gen_subtype_check(receiver, want_klass);
3030 
3031   // Ignore interface type information until interface types are properly tracked.
3032   if (!stopped() && !klass->is_interface()) {
3033     const TypeOopPtr* receiver_type = _gvn.type(receiver)->isa_oopptr();
3034     const TypeOopPtr* recv_type = tklass->cast_to_exactness(false)->is_klassptr()->as_instance_type();
3035     if (receiver_type != NULL && !receiver_type->higher_equal(recv_type)) { // ignore redundant casts
3036       Node* cast = _gvn.transform(new CheckCastPPNode(control(), receiver, recv_type));
3037       if (recv_type->is_inlinetypeptr()) {
3038         cast = InlineTypeNode::make_from_oop(this, cast, recv_type->inline_klass());
3039       }
3040       (*casted_receiver) = cast;
3041     }
3042   }
3043 
3044   return slow_ctl;
3045 }
3046 
3047 //------------------------------seems_never_null-------------------------------
3048 // Use null_seen information if it is available from the profile.
3049 // If we see an unexpected null at a type check we record it and force a
3050 // recompile; the offending check will be recompiled to handle NULLs.
3051 // If we see several offending BCIs, then all checks in the
3052 // method will be recompiled.
3053 bool GraphKit::seems_never_null(Node* obj, ciProfileData* data, bool& speculating) {
3054   speculating = !_gvn.type(obj)->speculative_maybe_null();
3055   Deoptimization::DeoptReason reason = Deoptimization::reason_null_check(speculating);
3056   if (UncommonNullCast               // Cutout for this technique
3057       && obj != null()               // And not the -Xcomp stupid case?
3058       && !too_many_traps(reason)
3059       ) {
3060     if (speculating) {
3061       return true;
3062     }
3063     if (data == NULL)
3064       // Edge case:  no mature data.  Be optimistic here.
3065       return true;
3066     // If the profile has not seen a null, assume it won't happen.
3067     assert(java_bc() == Bytecodes::_checkcast ||
3068            java_bc() == Bytecodes::_instanceof ||
3069            java_bc() == Bytecodes::_aastore, "MDO must collect null_seen bit here");
3070     if (java_bc() == Bytecodes::_aastore) {
3071       return ((ciArrayLoadStoreData*)data->as_ArrayLoadStoreData())->element()->ptr_kind() == ProfileNeverNull;
3072     }
3073     return !data->as_BitData()->null_seen();
3074   }
3075   speculating = false;
3076   return false;
3077 }
3078 
3079 void GraphKit::guard_klass_being_initialized(Node* klass) {
3080   int init_state_off = in_bytes(InstanceKlass::init_state_offset());
3081   Node* adr = basic_plus_adr(top(), klass, init_state_off);
3082   Node* init_state = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3083                                     adr->bottom_type()->is_ptr(), TypeInt::BYTE,
3084                                     T_BYTE, MemNode::unordered);
3085   init_state = _gvn.transform(init_state);
3086 
3087   Node* being_initialized_state = makecon(TypeInt::make(InstanceKlass::being_initialized));
3088 
3089   Node* chk = _gvn.transform(new CmpINode(being_initialized_state, init_state));
3090   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3091 
3092   { BuildCutout unless(this, tst, PROB_MAX);
3093     uncommon_trap(Deoptimization::Reason_initialized, Deoptimization::Action_reinterpret);
3094   }
3095 }
3096 
3097 void GraphKit::guard_init_thread(Node* klass) {
3098   int init_thread_off = in_bytes(InstanceKlass::init_thread_offset());
3099   Node* adr = basic_plus_adr(top(), klass, init_thread_off);
3100 
3101   Node* init_thread = LoadNode::make(_gvn, NULL, immutable_memory(), adr,
3102                                      adr->bottom_type()->is_ptr(), TypePtr::NOTNULL,
3103                                      T_ADDRESS, MemNode::unordered);
3104   init_thread = _gvn.transform(init_thread);
3105 
3106   Node* cur_thread = _gvn.transform(new ThreadLocalNode());
3107 
3108   Node* chk = _gvn.transform(new CmpPNode(cur_thread, init_thread));
3109   Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
3110 
3111   { BuildCutout unless(this, tst, PROB_MAX);
3112     uncommon_trap(Deoptimization::Reason_uninitialized, Deoptimization::Action_none);
3113   }
3114 }
3115 
3116 void GraphKit::clinit_barrier(ciInstanceKlass* ik, ciMethod* context) {
3117   if (ik->is_being_initialized()) {
3118     if (C->needs_clinit_barrier(ik, context)) {
3119       Node* klass = makecon(TypeKlassPtr::make(ik));
3120       guard_klass_being_initialized(klass);
3121       guard_init_thread(klass);
3122       insert_mem_bar(Op_MemBarCPUOrder);
3123     }
3124   } else if (ik->is_initialized()) {
3125     return; // no barrier needed
3126   } else {
3127     uncommon_trap(Deoptimization::Reason_uninitialized,
3128                   Deoptimization::Action_reinterpret,
3129                   NULL);
3130   }
3131 }
3132 
3133 //------------------------maybe_cast_profiled_receiver-------------------------
3134 // If the profile has seen exactly one type, narrow to exactly that type.
3135 // Subsequent type checks will always fold up.
3136 Node* GraphKit::maybe_cast_profiled_receiver(Node* not_null_obj,
3137                                              const TypeKlassPtr* require_klass,
3138                                              ciKlass* spec_klass,
3139                                              bool safe_for_replace) {
3140   if (!UseTypeProfile || !TypeProfileCasts) return NULL;
3141 
3142   Deoptimization::DeoptReason reason = Deoptimization::reason_class_check(spec_klass != NULL);
3143 
3144   // Make sure we haven't already deoptimized from this tactic.
3145   if (too_many_traps_or_recompiles(reason))
3146     return NULL;
3147 
3148   // (No, this isn't a call, but it's enough like a virtual call
3149   // to use the same ciMethod accessor to get the profile info...)
3150   // If we have a speculative type use it instead of profiling (which
3151   // may not help us)
3152   ciKlass* exact_kls = spec_klass;
3153   if (exact_kls == NULL) {
3154     if (java_bc() == Bytecodes::_aastore) {
3155       ciKlass* array_type = NULL;
3156       ciKlass* element_type = NULL;
3157       ProfilePtrKind element_ptr = ProfileMaybeNull;
3158       bool flat_array = true;
3159       bool null_free_array = true;
3160       method()->array_access_profiled_type(bci(), array_type, element_type, element_ptr, flat_array, null_free_array);
3161       exact_kls = element_type;
3162     } else {
3163       exact_kls = profile_has_unique_klass();
3164     }
3165   }
3166   if (exact_kls != NULL) {// no cast failures here
3167     if (require_klass == NULL ||
3168         C->static_subtype_check(require_klass, TypeKlassPtr::make(exact_kls, Type::trust_interfaces)) == Compile::SSC_always_true) {
3169       // If we narrow the type to match what the type profile sees or
3170       // the speculative type, we can then remove the rest of the
3171       // cast.
3172       // This is a win, even if the exact_kls is very specific,
3173       // because downstream operations, such as method calls,
3174       // will often benefit from the sharper type.
3175       Node* exact_obj = not_null_obj; // will get updated in place...
3176       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3177                                             &exact_obj);
3178       { PreserveJVMState pjvms(this);
3179         set_control(slow_ctl);
3180         uncommon_trap_exact(reason, Deoptimization::Action_maybe_recompile);
3181       }
3182       if (safe_for_replace) {
3183         replace_in_map(not_null_obj, exact_obj);
3184       }
3185       return exact_obj;
3186     }
3187     // assert(ssc == Compile::SSC_always_true)... except maybe the profile lied to us.
3188   }
3189 
3190   return NULL;
3191 }
3192 
3193 /**
3194  * Cast obj to type and emit guard unless we had too many traps here
3195  * already
3196  *
3197  * @param obj       node being casted
3198  * @param type      type to cast the node to
3199  * @param not_null  true if we know node cannot be null
3200  */
3201 Node* GraphKit::maybe_cast_profiled_obj(Node* obj,
3202                                         ciKlass* type,
3203                                         bool not_null) {
3204   if (stopped()) {
3205     return obj;
3206   }
3207 
3208   // type == NULL if profiling tells us this object is always null
3209   if (type != NULL) {
3210     Deoptimization::DeoptReason class_reason = Deoptimization::Reason_speculate_class_check;
3211     Deoptimization::DeoptReason null_reason = Deoptimization::Reason_speculate_null_check;
3212 
3213     if (!too_many_traps_or_recompiles(null_reason) &&
3214         !too_many_traps_or_recompiles(class_reason)) {
3215       Node* not_null_obj = NULL;
3216       // not_null is true if we know the object is not null and
3217       // there's no need for a null check
3218       if (!not_null) {
3219         Node* null_ctl = top();
3220         not_null_obj = null_check_oop(obj, &null_ctl, true, true, true);
3221         assert(null_ctl->is_top(), "no null control here");
3222       } else {
3223         not_null_obj = obj;
3224       }
3225 
3226       Node* exact_obj = not_null_obj;
3227       ciKlass* exact_kls = type;
3228       Node* slow_ctl  = type_check_receiver(exact_obj, exact_kls, 1.0,
3229                                             &exact_obj);
3230       {
3231         PreserveJVMState pjvms(this);
3232         set_control(slow_ctl);
3233         uncommon_trap_exact(class_reason, Deoptimization::Action_maybe_recompile);
3234       }
3235       replace_in_map(not_null_obj, exact_obj);
3236       obj = exact_obj;
3237     }
3238   } else {
3239     if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3240       Node* exact_obj = null_assert(obj);
3241       replace_in_map(obj, exact_obj);
3242       obj = exact_obj;
3243     }
3244   }
3245   return obj;
3246 }
3247 
3248 //-------------------------------gen_instanceof--------------------------------
3249 // Generate an instance-of idiom.  Used by both the instance-of bytecode
3250 // and the reflective instance-of call.
3251 Node* GraphKit::gen_instanceof(Node* obj, Node* superklass, bool safe_for_replace) {
3252   kill_dead_locals();           // Benefit all the uncommon traps
3253   assert( !stopped(), "dead parse path should be checked in callers" );
3254   assert(!TypePtr::NULL_PTR->higher_equal(_gvn.type(superklass)->is_klassptr()),
3255          "must check for not-null not-dead klass in callers");
3256 
3257   // Make the merge point
3258   enum { _obj_path = 1, _fail_path, _null_path, PATH_LIMIT };
3259   RegionNode* region = new RegionNode(PATH_LIMIT);
3260   Node*       phi    = new PhiNode(region, TypeInt::BOOL);
3261   C->set_has_split_ifs(true); // Has chance for split-if optimization
3262 
3263   ciProfileData* data = NULL;
3264   if (java_bc() == Bytecodes::_instanceof) {  // Only for the bytecode
3265     data = method()->method_data()->bci_to_data(bci());
3266   }
3267   bool speculative_not_null = false;
3268   bool never_see_null = (ProfileDynamicTypes  // aggressive use of profile
3269                          && seems_never_null(obj, data, speculative_not_null));
3270 
3271   // Null check; get casted pointer; set region slot 3
3272   Node* null_ctl = top();
3273   Node* not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3274 
3275   // If not_null_obj is dead, only null-path is taken
3276   if (stopped()) {              // Doing instance-of on a NULL?
3277     set_control(null_ctl);
3278     return intcon(0);
3279   }
3280   region->init_req(_null_path, null_ctl);
3281   phi   ->init_req(_null_path, intcon(0)); // Set null path value
3282   if (null_ctl == top()) {
3283     // Do this eagerly, so that pattern matches like is_diamond_phi
3284     // will work even during parsing.
3285     assert(_null_path == PATH_LIMIT-1, "delete last");
3286     region->del_req(_null_path);
3287     phi   ->del_req(_null_path);
3288   }
3289 
3290   // Do we know the type check always succeed?
3291   bool known_statically = false;
3292   if (_gvn.type(superklass)->singleton()) {
3293     const TypeKlassPtr* superk = _gvn.type(superklass)->is_klassptr();
3294     const TypeKlassPtr* subk = _gvn.type(obj)->is_oopptr()->as_klass_type();
3295     if (subk != NULL && subk->is_loaded()) {
3296       int static_res = C->static_subtype_check(superk, subk);
3297       known_statically = (static_res == Compile::SSC_always_true || static_res == Compile::SSC_always_false);
3298     }
3299   }
3300 
3301   if (!known_statically) {
3302     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3303     // We may not have profiling here or it may not help us. If we
3304     // have a speculative type use it to perform an exact cast.
3305     ciKlass* spec_obj_type = obj_type->speculative_type();
3306     if (spec_obj_type != NULL || (ProfileDynamicTypes && data != NULL)) {
3307       Node* cast_obj = maybe_cast_profiled_receiver(not_null_obj, NULL, spec_obj_type, safe_for_replace);
3308       if (stopped()) {            // Profile disagrees with this path.
3309         set_control(null_ctl);    // Null is the only remaining possibility.
3310         return intcon(0);
3311       }
3312       if (cast_obj != NULL) {
3313         not_null_obj = cast_obj;
3314       }
3315     }
3316   }
3317 
3318   // Generate the subtype check
3319   Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3320 
3321   // Plug in the success path to the general merge in slot 1.
3322   region->init_req(_obj_path, control());
3323   phi   ->init_req(_obj_path, intcon(1));
3324 
3325   // Plug in the failing path to the general merge in slot 2.
3326   region->init_req(_fail_path, not_subtype_ctrl);
3327   phi   ->init_req(_fail_path, intcon(0));
3328 
3329   // Return final merged results
3330   set_control( _gvn.transform(region) );
3331   record_for_igvn(region);
3332 
3333   // If we know the type check always succeeds then we don't use the
3334   // profiling data at this bytecode. Don't lose it, feed it to the
3335   // type system as a speculative type.
3336   if (safe_for_replace) {
3337     Node* casted_obj = record_profiled_receiver_for_speculation(obj);
3338     replace_in_map(obj, casted_obj);
3339   }
3340 
3341   return _gvn.transform(phi);
3342 }
3343 
3344 //-------------------------------gen_checkcast---------------------------------
3345 // Generate a checkcast idiom.  Used by both the checkcast bytecode and the
3346 // array store bytecode.  Stack must be as-if BEFORE doing the bytecode so the
3347 // uncommon-trap paths work.  Adjust stack after this call.
3348 // If failure_control is supplied and not null, it is filled in with
3349 // the control edge for the cast failure.  Otherwise, an appropriate
3350 // uncommon trap or exception is thrown.
3351 Node* GraphKit::gen_checkcast(Node *obj, Node* superklass, Node* *failure_control, bool null_free) {
3352   kill_dead_locals();           // Benefit all the uncommon traps
3353   const TypeKlassPtr *tk = _gvn.type(superklass)->is_klassptr()->try_improve();
3354   const TypeOopPtr *toop = tk->cast_to_exactness(false)->as_instance_type();
3355   bool safe_for_replace = (failure_control == NULL);
3356   assert(!null_free || toop->is_inlinetypeptr(), "must be an inline type pointer");
3357 
3358   // Fast cutout:  Check the case that the cast is vacuously true.
3359   // This detects the common cases where the test will short-circuit
3360   // away completely.  We do this before we perform the null check,
3361   // because if the test is going to turn into zero code, we don't
3362   // want a residual null check left around.  (Causes a slowdown,
3363   // for example, in some objArray manipulations, such as a[i]=a[j].)
3364   if (tk->singleton()) {
3365     const TypeKlassPtr* kptr = NULL;
3366     const Type* t = _gvn.type(obj);
3367     if (t->isa_oop_ptr()) {
3368       kptr = t->is_oopptr()->as_klass_type();
3369     } else if (obj->is_InlineType()) {
3370       ciInlineKlass* vk = t->inline_klass();
3371       kptr = TypeInstKlassPtr::make(TypePtr::NotNull, vk, Type::Offset(0));
3372     }
3373     if (kptr != NULL) {
3374       switch (C->static_subtype_check(tk, kptr)) {
3375       case Compile::SSC_always_true:
3376         // If we know the type check always succeed then we don't use
3377         // the profiling data at this bytecode. Don't lose it, feed it
3378         // to the type system as a speculative type.
3379         obj = record_profiled_receiver_for_speculation(obj);
3380         if (null_free) {
3381           assert(safe_for_replace, "must be");
3382           obj = null_check(obj);
3383         }
3384         assert(stopped() || !toop->is_inlinetypeptr() || obj->is_InlineType(), "should have been scalarized");
3385         return obj;
3386       case Compile::SSC_always_false:
3387         if (null_free) {
3388           assert(safe_for_replace, "must be");
3389           obj = null_check(obj);
3390         }
3391         // It needs a null check because a null will *pass* the cast check.
3392         if (t->isa_oopptr() != NULL && !t->is_oopptr()->maybe_null()) {
3393           bool is_aastore = (java_bc() == Bytecodes::_aastore);
3394           Deoptimization::DeoptReason reason = is_aastore ?
3395             Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3396           builtin_throw(reason);
3397           return top();
3398         } else if (!too_many_traps_or_recompiles(Deoptimization::Reason_null_assert)) {
3399           return null_assert(obj);
3400         }
3401         break; // Fall through to full check
3402       default:
3403         break;
3404       }
3405     }
3406   }
3407 
3408   ciProfileData* data = NULL;
3409   if (failure_control == NULL) {        // use MDO in regular case only
3410     assert(java_bc() == Bytecodes::_aastore ||
3411            java_bc() == Bytecodes::_checkcast,
3412            "interpreter profiles type checks only for these BCs");
3413     if (method()->method_data()->is_mature()) {
3414       data = method()->method_data()->bci_to_data(bci());
3415     }
3416   }
3417 
3418   // Make the merge point
3419   enum { _obj_path = 1, _null_path, PATH_LIMIT };
3420   RegionNode* region = new RegionNode(PATH_LIMIT);
3421   Node*       phi    = new PhiNode(region, toop);
3422   _gvn.set_type(region, Type::CONTROL);
3423   _gvn.set_type(phi, toop);
3424 
3425   C->set_has_split_ifs(true); // Has chance for split-if optimization
3426 
3427   // Use null-cast information if it is available
3428   bool speculative_not_null = false;
3429   bool never_see_null = ((failure_control == NULL)  // regular case only
3430                          && seems_never_null(obj, data, speculative_not_null));
3431 
3432   if (obj->is_InlineType()) {
3433     // Re-execute if buffering during triggers deoptimization
3434     PreserveReexecuteState preexecs(this);
3435     jvms()->set_should_reexecute(true);
3436     obj = obj->as_InlineType()->buffer(this, safe_for_replace);
3437   }
3438 
3439   // Null check; get casted pointer; set region slot 3
3440   Node* null_ctl = top();
3441   Node* not_null_obj = NULL;
3442   if (null_free) {
3443     assert(safe_for_replace, "must be");
3444     not_null_obj = null_check(obj);
3445   } else {
3446     not_null_obj = null_check_oop(obj, &null_ctl, never_see_null, safe_for_replace, speculative_not_null);
3447   }
3448 
3449   // If not_null_obj is dead, only null-path is taken
3450   if (stopped()) {              // Doing instance-of on a NULL?
3451     set_control(null_ctl);
3452     if (toop->is_inlinetypeptr()) {
3453       return InlineTypeNode::make_null(_gvn, toop->inline_klass());
3454     }
3455     return null();
3456   }
3457   region->init_req(_null_path, null_ctl);
3458   phi   ->init_req(_null_path, null());  // Set null path value
3459   if (null_ctl == top()) {
3460     // Do this eagerly, so that pattern matches like is_diamond_phi
3461     // will work even during parsing.
3462     assert(_null_path == PATH_LIMIT-1, "delete last");
3463     region->del_req(_null_path);
3464     phi   ->del_req(_null_path);
3465   }
3466 
3467   Node* cast_obj = NULL;
3468   if (tk->klass_is_exact()) {
3469     // The following optimization tries to statically cast the speculative type of the object
3470     // (for example obtained during profiling) to the type of the superklass and then do a
3471     // dynamic check that the type of the object is what we expect. To work correctly
3472     // for checkcast and aastore the type of superklass should be exact.
3473     const TypeOopPtr* obj_type = _gvn.type(obj)->is_oopptr();
3474     // We may not have profiling here or it may not help us. If we have
3475     // a speculative type use it to perform an exact cast.
3476     ciKlass* spec_obj_type = obj_type->speculative_type();
3477     if (spec_obj_type != NULL || data != NULL) {
3478       cast_obj = maybe_cast_profiled_receiver(not_null_obj, tk, spec_obj_type, safe_for_replace);
3479       if (cast_obj != NULL) {
3480         if (failure_control != NULL) // failure is now impossible
3481           (*failure_control) = top();
3482         // adjust the type of the phi to the exact klass:
3483         phi->raise_bottom_type(_gvn.type(cast_obj)->meet_speculative(TypePtr::NULL_PTR));
3484       }
3485     }
3486   }
3487 
3488   if (cast_obj == NULL) {
3489     // Generate the subtype check
3490     Node* not_subtype_ctrl = gen_subtype_check(not_null_obj, superklass);
3491 
3492     // Plug in success path into the merge
3493     cast_obj = _gvn.transform(new CheckCastPPNode(control(), not_null_obj, toop));
3494     // Failure path ends in uncommon trap (or may be dead - failure impossible)
3495     if (failure_control == NULL) {
3496       if (not_subtype_ctrl != top()) { // If failure is possible
3497         PreserveJVMState pjvms(this);
3498         set_control(not_subtype_ctrl);
3499         Node* obj_klass = NULL;
3500         if (not_null_obj->is_InlineType()) {
3501           obj_klass = makecon(TypeKlassPtr::make(_gvn.type(not_null_obj)->inline_klass()));
3502         } else {
3503           obj_klass = load_object_klass(not_null_obj);
3504         }
3505         bool is_aastore = (java_bc() == Bytecodes::_aastore);
3506         Deoptimization::DeoptReason reason = is_aastore ?
3507           Deoptimization::Reason_array_check : Deoptimization::Reason_class_check;
3508         builtin_throw(reason);
3509       }
3510     } else {
3511       (*failure_control) = not_subtype_ctrl;
3512     }
3513   }
3514 
3515   region->init_req(_obj_path, control());
3516   phi   ->init_req(_obj_path, cast_obj);
3517 
3518   // A merge of NULL or Casted-NotNull obj
3519   Node* res = _gvn.transform(phi);
3520 
3521   // Note I do NOT always 'replace_in_map(obj,result)' here.
3522   //  if( tk->klass()->can_be_primary_super()  )
3523     // This means that if I successfully store an Object into an array-of-String
3524     // I 'forget' that the Object is really now known to be a String.  I have to
3525     // do this because we don't have true union types for interfaces - if I store
3526     // a Baz into an array-of-Interface and then tell the optimizer it's an
3527     // Interface, I forget that it's also a Baz and cannot do Baz-like field
3528     // references to it.  FIX THIS WHEN UNION TYPES APPEAR!
3529   //  replace_in_map( obj, res );
3530 
3531   // Return final merged results
3532   set_control( _gvn.transform(region) );
3533   record_for_igvn(region);
3534 
3535   bool not_inline = !toop->can_be_inline_type();
3536   bool not_flattened = !UseFlatArray || not_inline || (toop->is_inlinetypeptr() && !toop->inline_klass()->flatten_array());
3537   if (EnableValhalla && not_flattened) {
3538     // Check if obj has been loaded from an array
3539     obj = obj->isa_DecodeN() ? obj->in(1) : obj;
3540     Node* array = NULL;
3541     if (obj->isa_Load()) {
3542       Node* address = obj->in(MemNode::Address);
3543       if (address->isa_AddP()) {
3544         array = address->as_AddP()->in(AddPNode::Base);
3545       }
3546     } else if (obj->is_Phi()) {
3547       Node* region = obj->in(0);
3548       // TODO make this more robust (see JDK-8231346)
3549       if (region->req() == 3 && region->in(2) != NULL && region->in(2)->in(0) != NULL) {
3550         IfNode* iff = region->in(2)->in(0)->isa_If();
3551         if (iff != NULL) {
3552           iff->is_flat_array_check(&_gvn, &array);
3553         }
3554       }
3555     }
3556     if (array != NULL) {
3557       const TypeAryPtr* ary_t = _gvn.type(array)->isa_aryptr();
3558       if (ary_t != NULL) {
3559         if (!ary_t->is_not_null_free() && not_inline) {
3560           // Casting array element to a non-inline-type, mark array as not null-free.
3561           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_null_free()));
3562           replace_in_map(array, cast);
3563         } else if (!ary_t->is_not_flat()) {
3564           // Casting array element to a non-flattened type, mark array as not flat.
3565           Node* cast = _gvn.transform(new CheckCastPPNode(control(), array, ary_t->cast_to_not_flat()));
3566           replace_in_map(array, cast);
3567         }
3568       }
3569     }
3570   }
3571 
3572   if (!stopped() && !res->is_InlineType()) {
3573     res = record_profiled_receiver_for_speculation(res);
3574     if (toop->is_inlinetypeptr()) {
3575       Node* vt = InlineTypeNode::make_from_oop(this, res, toop->inline_klass(), !gvn().type(res)->maybe_null());
3576       res = vt;
3577       if (safe_for_replace) {
3578         replace_in_map(obj, vt);
3579         replace_in_map(not_null_obj, vt);
3580         replace_in_map(res, vt);
3581       }
3582     }
3583   }
3584   return res;
3585 }
3586 
3587 Node* GraphKit::inline_type_test(Node* obj, bool is_inline) {
3588   Node* mark_adr = basic_plus_adr(obj, oopDesc::mark_offset_in_bytes());
3589   Node* mark = make_load(NULL, mark_adr, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
3590   Node* mask = MakeConX(markWord::inline_type_pattern);
3591   Node* masked = _gvn.transform(new AndXNode(mark, mask));
3592   Node* cmp = _gvn.transform(new CmpXNode(masked, mask));
3593   return _gvn.transform(new BoolNode(cmp, is_inline ? BoolTest::eq : BoolTest::ne));
3594 }
3595 
3596 Node* GraphKit::is_val_mirror(Node* mirror) {
3597   Node* p = basic_plus_adr(mirror, java_lang_Class::secondary_mirror_offset());
3598   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);
3599   Node* cmp = _gvn.transform(new CmpPNode(mirror, secondary_mirror));
3600   return _gvn.transform(new BoolNode(cmp, BoolTest::eq));
3601 }
3602 
3603 Node* GraphKit::array_lh_test(Node* klass, jint mask, jint val, bool eq) {
3604   Node* lh_adr = basic_plus_adr(klass, in_bytes(Klass::layout_helper_offset()));
3605   // Make sure to use immutable memory here to enable hoisting the check out of loops
3606   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));
3607   Node* masked = _gvn.transform(new AndINode(lh_val, intcon(mask)));
3608   Node* cmp = _gvn.transform(new CmpINode(masked, intcon(val)));
3609   return _gvn.transform(new BoolNode(cmp, eq ? BoolTest::eq : BoolTest::ne));
3610 }
3611 
3612 Node* GraphKit::flat_array_test(Node* array_or_klass, bool flat) {
3613   // We can't use immutable memory here because the mark word is mutable.
3614   // PhaseIdealLoop::move_flat_array_check_out_of_loop will make sure the
3615   // check is moved out of loops (mainly to enable loop unswitching).
3616   Node* mem = UseArrayMarkWordCheck ? memory(Compile::AliasIdxRaw) : immutable_memory();
3617   Node* cmp = _gvn.transform(new FlatArrayCheckNode(C, mem, array_or_klass));
3618   record_for_igvn(cmp); // Give it a chance to be optimized out by IGVN
3619   return _gvn.transform(new BoolNode(cmp, flat ? BoolTest::eq : BoolTest::ne));
3620 }
3621 
3622 Node* GraphKit::null_free_array_test(Node* klass, bool null_free) {
3623   return array_lh_test(klass, Klass::_lh_null_free_array_bit_inplace, 0, !null_free);
3624 }
3625 
3626 // Deoptimize if 'ary' is a null-free inline type array and 'val' is null
3627 Node* GraphKit::inline_array_null_guard(Node* ary, Node* val, int nargs, bool safe_for_replace) {
3628   RegionNode* region = new RegionNode(3);
3629   Node* null_ctl = top();
3630   null_check_oop(val, &null_ctl);
3631   if (null_ctl != top()) {
3632     PreserveJVMState pjvms(this);
3633     set_control(null_ctl);
3634     {
3635       // Deoptimize if null-free array
3636       BuildCutout unless(this, null_free_array_test(load_object_klass(ary), /* null_free = */ false), PROB_MAX);
3637       inc_sp(nargs);
3638       uncommon_trap(Deoptimization::Reason_null_check,
3639                     Deoptimization::Action_none);
3640     }
3641     region->init_req(1, control());
3642   }
3643   region->init_req(2, control());
3644   set_control(_gvn.transform(region));
3645   record_for_igvn(region);
3646   if (_gvn.type(val) == TypePtr::NULL_PTR) {
3647     // Since we were just successfully storing null, the array can't be null free.
3648     const TypeAryPtr* ary_t = _gvn.type(ary)->is_aryptr();
3649     ary_t = ary_t->cast_to_not_null_free();
3650     Node* cast = _gvn.transform(new CheckCastPPNode(control(), ary, ary_t));
3651     if (safe_for_replace) {
3652       replace_in_map(ary, cast);
3653     }
3654     ary = cast;
3655   }
3656   return ary;
3657 }
3658 
3659 //------------------------------next_monitor-----------------------------------
3660 // What number should be given to the next monitor?
3661 int GraphKit::next_monitor() {
3662   int current = jvms()->monitor_depth()* C->sync_stack_slots();
3663   int next = current + C->sync_stack_slots();
3664   // Keep the toplevel high water mark current:
3665   if (C->fixed_slots() < next)  C->set_fixed_slots(next);
3666   return current;
3667 }
3668 
3669 //------------------------------insert_mem_bar---------------------------------
3670 // Memory barrier to avoid floating things around
3671 // The membar serves as a pinch point between both control and all memory slices.
3672 Node* GraphKit::insert_mem_bar(int opcode, Node* precedent) {
3673   MemBarNode* mb = MemBarNode::make(C, opcode, Compile::AliasIdxBot, precedent);
3674   mb->init_req(TypeFunc::Control, control());
3675   mb->init_req(TypeFunc::Memory,  reset_memory());
3676   Node* membar = _gvn.transform(mb);
3677   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3678   set_all_memory_call(membar);
3679   return membar;
3680 }
3681 
3682 //-------------------------insert_mem_bar_volatile----------------------------
3683 // Memory barrier to avoid floating things around
3684 // The membar serves as a pinch point between both control and memory(alias_idx).
3685 // If you want to make a pinch point on all memory slices, do not use this
3686 // function (even with AliasIdxBot); use insert_mem_bar() instead.
3687 Node* GraphKit::insert_mem_bar_volatile(int opcode, int alias_idx, Node* precedent) {
3688   // When Parse::do_put_xxx updates a volatile field, it appends a series
3689   // of MemBarVolatile nodes, one for *each* volatile field alias category.
3690   // The first membar is on the same memory slice as the field store opcode.
3691   // This forces the membar to follow the store.  (Bug 6500685 broke this.)
3692   // All the other membars (for other volatile slices, including AliasIdxBot,
3693   // which stands for all unknown volatile slices) are control-dependent
3694   // on the first membar.  This prevents later volatile loads or stores
3695   // from sliding up past the just-emitted store.
3696 
3697   MemBarNode* mb = MemBarNode::make(C, opcode, alias_idx, precedent);
3698   mb->set_req(TypeFunc::Control,control());
3699   if (alias_idx == Compile::AliasIdxBot) {
3700     mb->set_req(TypeFunc::Memory, merged_memory()->base_memory());
3701   } else {
3702     assert(!(opcode == Op_Initialize && alias_idx != Compile::AliasIdxRaw), "fix caller");
3703     mb->set_req(TypeFunc::Memory, memory(alias_idx));
3704   }
3705   Node* membar = _gvn.transform(mb);
3706   set_control(_gvn.transform(new ProjNode(membar, TypeFunc::Control)));
3707   if (alias_idx == Compile::AliasIdxBot) {
3708     merged_memory()->set_base_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)));
3709   } else {
3710     set_memory(_gvn.transform(new ProjNode(membar, TypeFunc::Memory)),alias_idx);
3711   }
3712   return membar;
3713 }
3714 
3715 //------------------------------shared_lock------------------------------------
3716 // Emit locking code.
3717 FastLockNode* GraphKit::shared_lock(Node* obj) {
3718   // bci is either a monitorenter bc or InvocationEntryBci
3719   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3720   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3721 
3722   if( !GenerateSynchronizationCode )
3723     return NULL;                // Not locking things?
3724 
3725   if (stopped())                // Dead monitor?
3726     return NULL;
3727 
3728   assert(dead_locals_are_killed(), "should kill locals before sync. point");
3729 
3730   // Box the stack location
3731   Node* box = _gvn.transform(new BoxLockNode(next_monitor()));
3732   Node* mem = reset_memory();
3733 
3734   FastLockNode * flock = _gvn.transform(new FastLockNode(0, obj, box) )->as_FastLock();
3735 
3736   // Create the rtm counters for this fast lock if needed.
3737   flock->create_rtm_lock_counter(sync_jvms()); // sync_jvms used to get current bci
3738 
3739   // Add monitor to debug info for the slow path.  If we block inside the
3740   // slow path and de-opt, we need the monitor hanging around
3741   map()->push_monitor( flock );
3742 
3743   const TypeFunc *tf = LockNode::lock_type();
3744   LockNode *lock = new LockNode(C, tf);
3745 
3746   lock->init_req( TypeFunc::Control, control() );
3747   lock->init_req( TypeFunc::Memory , mem );
3748   lock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3749   lock->init_req( TypeFunc::FramePtr, frameptr() );
3750   lock->init_req( TypeFunc::ReturnAdr, top() );
3751 
3752   lock->init_req(TypeFunc::Parms + 0, obj);
3753   lock->init_req(TypeFunc::Parms + 1, box);
3754   lock->init_req(TypeFunc::Parms + 2, flock);
3755   add_safepoint_edges(lock);
3756 
3757   lock = _gvn.transform( lock )->as_Lock();
3758 
3759   // lock has no side-effects, sets few values
3760   set_predefined_output_for_runtime_call(lock, mem, TypeRawPtr::BOTTOM);
3761 
3762   insert_mem_bar(Op_MemBarAcquireLock);
3763 
3764   // Add this to the worklist so that the lock can be eliminated
3765   record_for_igvn(lock);
3766 
3767 #ifndef PRODUCT
3768   if (PrintLockStatistics) {
3769     // Update the counter for this lock.  Don't bother using an atomic
3770     // operation since we don't require absolute accuracy.
3771     lock->create_lock_counter(map()->jvms());
3772     increment_counter(lock->counter()->addr());
3773   }
3774 #endif
3775 
3776   return flock;
3777 }
3778 
3779 
3780 //------------------------------shared_unlock----------------------------------
3781 // Emit unlocking code.
3782 void GraphKit::shared_unlock(Node* box, Node* obj) {
3783   // bci is either a monitorenter bc or InvocationEntryBci
3784   // %%% SynchronizationEntryBCI is redundant; use InvocationEntryBci in interfaces
3785   assert(SynchronizationEntryBCI == InvocationEntryBci, "");
3786 
3787   if( !GenerateSynchronizationCode )
3788     return;
3789   if (stopped()) {               // Dead monitor?
3790     map()->pop_monitor();        // Kill monitor from debug info
3791     return;
3792   }
3793   assert(!obj->is_InlineType(), "should not unlock on inline type");
3794 
3795   // Memory barrier to avoid floating things down past the locked region
3796   insert_mem_bar(Op_MemBarReleaseLock);
3797 
3798   const TypeFunc *tf = OptoRuntime::complete_monitor_exit_Type();
3799   UnlockNode *unlock = new UnlockNode(C, tf);
3800 #ifdef ASSERT
3801   unlock->set_dbg_jvms(sync_jvms());
3802 #endif
3803   uint raw_idx = Compile::AliasIdxRaw;
3804   unlock->init_req( TypeFunc::Control, control() );
3805   unlock->init_req( TypeFunc::Memory , memory(raw_idx) );
3806   unlock->init_req( TypeFunc::I_O    , top() )     ;   // does no i/o
3807   unlock->init_req( TypeFunc::FramePtr, frameptr() );
3808   unlock->init_req( TypeFunc::ReturnAdr, top() );
3809 
3810   unlock->init_req(TypeFunc::Parms + 0, obj);
3811   unlock->init_req(TypeFunc::Parms + 1, box);
3812   unlock = _gvn.transform(unlock)->as_Unlock();
3813 
3814   Node* mem = reset_memory();
3815 
3816   // unlock has no side-effects, sets few values
3817   set_predefined_output_for_runtime_call(unlock, mem, TypeRawPtr::BOTTOM);
3818 
3819   // Kill monitor from debug info
3820   map()->pop_monitor( );
3821 }
3822 
3823 //-------------------------------get_layout_helper-----------------------------
3824 // If the given klass is a constant or known to be an array,
3825 // fetch the constant layout helper value into constant_value
3826 // and return (Node*)NULL.  Otherwise, load the non-constant
3827 // layout helper value, and return the node which represents it.
3828 // This two-faced routine is useful because allocation sites
3829 // almost always feature constant types.
3830 Node* GraphKit::get_layout_helper(Node* klass_node, jint& constant_value) {
3831   const TypeKlassPtr* inst_klass = _gvn.type(klass_node)->isa_klassptr();
3832   if (!StressReflectiveCode && inst_klass != NULL) {
3833     bool xklass = inst_klass->klass_is_exact();
3834     bool can_be_flattened = false;
3835     const TypeAryPtr* ary_type = inst_klass->as_instance_type()->isa_aryptr();
3836     if (UseFlatArray && !xklass && ary_type != NULL && !ary_type->is_null_free()) {
3837       // The runtime type of [LMyValue might be [QMyValue due to [QMyValue <: [LMyValue. Don't constant fold.
3838       const TypeOopPtr* elem = ary_type->elem()->make_oopptr();
3839       can_be_flattened = ary_type->can_be_inline_array() && (!elem->is_inlinetypeptr() || elem->inline_klass()->flatten_array());
3840     }
3841     if (!can_be_flattened && (xklass || inst_klass->isa_aryklassptr())) {
3842       jint lhelper;
3843       if (inst_klass->is_flat()) {
3844         lhelper = ary_type->flat_layout_helper();
3845       } else if (inst_klass->isa_aryklassptr()) {
3846         BasicType elem = ary_type->elem()->array_element_basic_type();
3847         if (is_reference_type(elem, true)) {
3848           elem = T_OBJECT;
3849         }
3850         lhelper = Klass::array_layout_helper(elem);
3851       } else {
3852         lhelper = inst_klass->is_instklassptr()->exact_klass()->layout_helper();
3853       }
3854       if (lhelper != Klass::_lh_neutral_value) {
3855         constant_value = lhelper;
3856         return (Node*) NULL;
3857       }
3858     }
3859   }
3860   constant_value = Klass::_lh_neutral_value;  // put in a known value
3861   Node* lhp = basic_plus_adr(klass_node, klass_node, in_bytes(Klass::layout_helper_offset()));
3862   return make_load(NULL, lhp, TypeInt::INT, T_INT, MemNode::unordered);
3863 }
3864 
3865 // We just put in an allocate/initialize with a big raw-memory effect.
3866 // Hook selected additional alias categories on the initialization.
3867 static void hook_memory_on_init(GraphKit& kit, int alias_idx,
3868                                 MergeMemNode* init_in_merge,
3869                                 Node* init_out_raw) {
3870   DEBUG_ONLY(Node* init_in_raw = init_in_merge->base_memory());
3871   assert(init_in_merge->memory_at(alias_idx) == init_in_raw, "");
3872 
3873   Node* prevmem = kit.memory(alias_idx);
3874   init_in_merge->set_memory_at(alias_idx, prevmem);
3875   if (init_out_raw != NULL) {
3876     kit.set_memory(init_out_raw, alias_idx);
3877   }
3878 }
3879 
3880 //---------------------------set_output_for_allocation-------------------------
3881 Node* GraphKit::set_output_for_allocation(AllocateNode* alloc,
3882                                           const TypeOopPtr* oop_type,
3883                                           bool deoptimize_on_exception) {
3884   int rawidx = Compile::AliasIdxRaw;
3885   alloc->set_req( TypeFunc::FramePtr, frameptr() );
3886   add_safepoint_edges(alloc);
3887   Node* allocx = _gvn.transform(alloc);
3888   set_control( _gvn.transform(new ProjNode(allocx, TypeFunc::Control) ) );
3889   // create memory projection for i_o
3890   set_memory ( _gvn.transform( new ProjNode(allocx, TypeFunc::Memory, true) ), rawidx );
3891   make_slow_call_ex(allocx, env()->Throwable_klass(), true, deoptimize_on_exception);
3892 
3893   // create a memory projection as for the normal control path
3894   Node* malloc = _gvn.transform(new ProjNode(allocx, TypeFunc::Memory));
3895   set_memory(malloc, rawidx);
3896 
3897   // a normal slow-call doesn't change i_o, but an allocation does
3898   // we create a separate i_o projection for the normal control path
3899   set_i_o(_gvn.transform( new ProjNode(allocx, TypeFunc::I_O, false) ) );
3900   Node* rawoop = _gvn.transform( new ProjNode(allocx, TypeFunc::Parms) );
3901 
3902   // put in an initialization barrier
3903   InitializeNode* init = insert_mem_bar_volatile(Op_Initialize, rawidx,
3904                                                  rawoop)->as_Initialize();
3905   assert(alloc->initialization() == init,  "2-way macro link must work");
3906   assert(init ->allocation()     == alloc, "2-way macro link must work");
3907   {
3908     // Extract memory strands which may participate in the new object's
3909     // initialization, and source them from the new InitializeNode.
3910     // This will allow us to observe initializations when they occur,
3911     // and link them properly (as a group) to the InitializeNode.
3912     assert(init->in(InitializeNode::Memory) == malloc, "");
3913     MergeMemNode* minit_in = MergeMemNode::make(malloc);
3914     init->set_req(InitializeNode::Memory, minit_in);
3915     record_for_igvn(minit_in); // fold it up later, if possible
3916     _gvn.set_type(minit_in, Type::MEMORY);
3917     Node* minit_out = memory(rawidx);
3918     assert(minit_out->is_Proj() && minit_out->in(0) == init, "");
3919     // Add an edge in the MergeMem for the header fields so an access
3920     // to one of those has correct memory state
3921     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::mark_offset_in_bytes())));
3922     set_memory(minit_out, C->get_alias_index(oop_type->add_offset(oopDesc::klass_offset_in_bytes())));
3923     if (oop_type->isa_aryptr()) {
3924       const TypeAryPtr* arytype = oop_type->is_aryptr();
3925       if (arytype->is_flat()) {
3926         // Initially all flattened array accesses share a single slice
3927         // but that changes after parsing. Prepare the memory graph so
3928         // it can optimize flattened array accesses properly once they
3929         // don't share a single slice.
3930         assert(C->flattened_accesses_share_alias(), "should be set at parse time");
3931         C->set_flattened_accesses_share_alias(false);
3932         ciInlineKlass* vk = arytype->elem()->inline_klass();
3933         for (int i = 0, len = vk->nof_nonstatic_fields(); i < len; i++) {
3934           ciField* field = vk->nonstatic_field_at(i);
3935           if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3936             continue;  // do not bother to track really large numbers of fields
3937           int off_in_vt = field->offset() - vk->first_field_offset();
3938           const TypePtr* adr_type = arytype->with_field_offset(off_in_vt)->add_offset(Type::OffsetBot);
3939           int fieldidx = C->get_alias_index(adr_type, true);
3940           // Pass NULL for init_out. Having per flat array element field memory edges as uses of the Initialize node
3941           // can result in per flat array field Phis to be created which confuses the logic of
3942           // Compile::adjust_flattened_array_access_aliases().
3943           hook_memory_on_init(*this, fieldidx, minit_in, NULL);
3944         }
3945         C->set_flattened_accesses_share_alias(true);
3946         hook_memory_on_init(*this, C->get_alias_index(TypeAryPtr::INLINES), minit_in, minit_out);
3947       } else {
3948         const TypePtr* telemref = oop_type->add_offset(Type::OffsetBot);
3949         int            elemidx  = C->get_alias_index(telemref);
3950         hook_memory_on_init(*this, elemidx, minit_in, minit_out);
3951       }
3952     } else if (oop_type->isa_instptr()) {
3953       set_memory(minit_out, C->get_alias_index(oop_type)); // mark word
3954       ciInstanceKlass* ik = oop_type->is_instptr()->instance_klass();
3955       for (int i = 0, len = ik->nof_nonstatic_fields(); i < len; i++) {
3956         ciField* field = ik->nonstatic_field_at(i);
3957         if (field->offset() >= TrackedInitializationLimit * HeapWordSize)
3958           continue;  // do not bother to track really large numbers of fields
3959         // Find (or create) the alias category for this field:
3960         int fieldidx = C->alias_type(field)->index();
3961         hook_memory_on_init(*this, fieldidx, minit_in, minit_out);
3962       }
3963     }
3964   }
3965 
3966   // Cast raw oop to the real thing...
3967   Node* javaoop = new CheckCastPPNode(control(), rawoop, oop_type);
3968   javaoop = _gvn.transform(javaoop);
3969   C->set_recent_alloc(control(), javaoop);
3970   assert(just_allocated_object(control()) == javaoop, "just allocated");
3971 
3972 #ifdef ASSERT
3973   { // Verify that the AllocateNode::Ideal_allocation recognizers work:
3974     assert(AllocateNode::Ideal_allocation(rawoop, &_gvn) == alloc,
3975            "Ideal_allocation works");
3976     assert(AllocateNode::Ideal_allocation(javaoop, &_gvn) == alloc,
3977            "Ideal_allocation works");
3978     if (alloc->is_AllocateArray()) {
3979       assert(AllocateArrayNode::Ideal_array_allocation(rawoop, &_gvn) == alloc->as_AllocateArray(),
3980              "Ideal_allocation works");
3981       assert(AllocateArrayNode::Ideal_array_allocation(javaoop, &_gvn) == alloc->as_AllocateArray(),
3982              "Ideal_allocation works");
3983     } else {
3984       assert(alloc->in(AllocateNode::ALength)->is_top(), "no length, please");
3985     }
3986   }
3987 #endif //ASSERT
3988 
3989   return javaoop;
3990 }
3991 
3992 //---------------------------new_instance--------------------------------------
3993 // This routine takes a klass_node which may be constant (for a static type)
3994 // or may be non-constant (for reflective code).  It will work equally well
3995 // for either, and the graph will fold nicely if the optimizer later reduces
3996 // the type to a constant.
3997 // The optional arguments are for specialized use by intrinsics:
3998 //  - If 'extra_slow_test' if not null is an extra condition for the slow-path.
3999 //  - If 'return_size_val', report the total object size to the caller.
4000 //  - deoptimize_on_exception controls how Java exceptions are handled (rethrow vs deoptimize)
4001 Node* GraphKit::new_instance(Node* klass_node,
4002                              Node* extra_slow_test,
4003                              Node* *return_size_val,
4004                              bool deoptimize_on_exception,
4005                              InlineTypeNode* inline_type_node) {
4006   // Compute size in doublewords
4007   // The size is always an integral number of doublewords, represented
4008   // as a positive bytewise size stored in the klass's layout_helper.
4009   // The layout_helper also encodes (in a low bit) the need for a slow path.
4010   jint  layout_con = Klass::_lh_neutral_value;
4011   Node* layout_val = get_layout_helper(klass_node, layout_con);
4012   bool  layout_is_con = (layout_val == NULL);
4013 
4014   if (extra_slow_test == NULL)  extra_slow_test = intcon(0);
4015   // Generate the initial go-slow test.  It's either ALWAYS (return a
4016   // Node for 1) or NEVER (return a NULL) or perhaps (in the reflective
4017   // case) a computed value derived from the layout_helper.
4018   Node* initial_slow_test = NULL;
4019   if (layout_is_con) {
4020     assert(!StressReflectiveCode, "stress mode does not use these paths");
4021     bool must_go_slow = Klass::layout_helper_needs_slow_path(layout_con);
4022     initial_slow_test = must_go_slow ? intcon(1) : extra_slow_test;
4023   } else {   // reflective case
4024     // This reflective path is used by Unsafe.allocateInstance.
4025     // (It may be stress-tested by specifying StressReflectiveCode.)
4026     // Basically, we want to get into the VM is there's an illegal argument.
4027     Node* bit = intcon(Klass::_lh_instance_slow_path_bit);
4028     initial_slow_test = _gvn.transform( new AndINode(layout_val, bit) );
4029     if (extra_slow_test != intcon(0)) {
4030       initial_slow_test = _gvn.transform( new OrINode(initial_slow_test, extra_slow_test) );
4031     }
4032     // (Macro-expander will further convert this to a Bool, if necessary.)
4033   }
4034 
4035   // Find the size in bytes.  This is easy; it's the layout_helper.
4036   // The size value must be valid even if the slow path is taken.
4037   Node* size = NULL;
4038   if (layout_is_con) {
4039     size = MakeConX(Klass::layout_helper_size_in_bytes(layout_con));
4040   } else {   // reflective case
4041     // This reflective path is used by clone and Unsafe.allocateInstance.
4042     size = ConvI2X(layout_val);
4043 
4044     // Clear the low bits to extract layout_helper_size_in_bytes:
4045     assert((int)Klass::_lh_instance_slow_path_bit < BytesPerLong, "clear bit");
4046     Node* mask = MakeConX(~ (intptr_t)right_n_bits(LogBytesPerLong));
4047     size = _gvn.transform( new AndXNode(size, mask) );
4048   }
4049   if (return_size_val != NULL) {
4050     (*return_size_val) = size;
4051   }
4052 
4053   // This is a precise notnull oop of the klass.
4054   // (Actually, it need not be precise if this is a reflective allocation.)
4055   // It's what we cast the result to.
4056   const TypeKlassPtr* tklass = _gvn.type(klass_node)->isa_klassptr();
4057   if (!tklass)  tklass = TypeInstKlassPtr::OBJECT;
4058   const TypeOopPtr* oop_type = tklass->as_instance_type();
4059 
4060   // Now generate allocation code
4061 
4062   // The entire memory state is needed for slow path of the allocation
4063   // since GC and deoptimization can happen.
4064   Node *mem = reset_memory();
4065   set_all_memory(mem); // Create new memory state
4066 
4067   AllocateNode* alloc = new AllocateNode(C, AllocateNode::alloc_type(Type::TOP),
4068                                          control(), mem, i_o(),
4069                                          size, klass_node,
4070                                          initial_slow_test, inline_type_node);
4071 
4072   return set_output_for_allocation(alloc, oop_type, deoptimize_on_exception);
4073 }
4074 
4075 //-------------------------------new_array-------------------------------------
4076 // helper for newarray and anewarray
4077 // The 'length' parameter is (obviously) the length of the array.
4078 // See comments on new_instance for the meaning of the other arguments.
4079 Node* GraphKit::new_array(Node* klass_node,     // array klass (maybe variable)
4080                           Node* length,         // number of array elements
4081                           int   nargs,          // number of arguments to push back for uncommon trap
4082                           Node* *return_size_val,
4083                           bool deoptimize_on_exception) {
4084   jint  layout_con = Klass::_lh_neutral_value;
4085   Node* layout_val = get_layout_helper(klass_node, layout_con);
4086   bool  layout_is_con = (layout_val == NULL);
4087 
4088   if (!layout_is_con && !StressReflectiveCode &&
4089       !too_many_traps(Deoptimization::Reason_class_check)) {
4090     // This is a reflective array creation site.
4091     // Optimistically assume that it is a subtype of Object[],
4092     // so that we can fold up all the address arithmetic.
4093     layout_con = Klass::array_layout_helper(T_OBJECT);
4094     Node* cmp_lh = _gvn.transform( new CmpINode(layout_val, intcon(layout_con)) );
4095     Node* bol_lh = _gvn.transform( new BoolNode(cmp_lh, BoolTest::eq) );
4096     { BuildCutout unless(this, bol_lh, PROB_MAX);
4097       inc_sp(nargs);
4098       uncommon_trap(Deoptimization::Reason_class_check,
4099                     Deoptimization::Action_maybe_recompile);
4100     }
4101     layout_val = NULL;
4102     layout_is_con = true;
4103   }
4104 
4105   // Generate the initial go-slow test.  Make sure we do not overflow
4106   // if length is huge (near 2Gig) or negative!  We do not need
4107   // exact double-words here, just a close approximation of needed
4108   // double-words.  We can't add any offset or rounding bits, lest we
4109   // take a size -1 of bytes and make it positive.  Use an unsigned
4110   // compare, so negative sizes look hugely positive.
4111   int fast_size_limit = FastAllocateSizeLimit;
4112   if (layout_is_con) {
4113     assert(!StressReflectiveCode, "stress mode does not use these paths");
4114     // Increase the size limit if we have exact knowledge of array type.
4115     int log2_esize = Klass::layout_helper_log2_element_size(layout_con);
4116     fast_size_limit <<= MAX2(LogBytesPerLong - log2_esize, 0);
4117   }
4118 
4119   Node* initial_slow_cmp  = _gvn.transform( new CmpUNode( length, intcon( fast_size_limit ) ) );
4120   Node* initial_slow_test = _gvn.transform( new BoolNode( initial_slow_cmp, BoolTest::gt ) );
4121 
4122   // --- Size Computation ---
4123   // array_size = round_to_heap(array_header + (length << elem_shift));
4124   // where round_to_heap(x) == align_to(x, MinObjAlignmentInBytes)
4125   // and align_to(x, y) == ((x + y-1) & ~(y-1))
4126   // The rounding mask is strength-reduced, if possible.
4127   int round_mask = MinObjAlignmentInBytes - 1;
4128   Node* header_size = NULL;
4129   int   header_size_min  = arrayOopDesc::base_offset_in_bytes(T_BYTE);
4130   // (T_BYTE has the weakest alignment and size restrictions...)
4131   if (layout_is_con) {
4132     int       hsize  = Klass::layout_helper_header_size(layout_con);
4133     int       eshift = Klass::layout_helper_log2_element_size(layout_con);
4134     bool is_flat_array = Klass::layout_helper_is_flatArray(layout_con);
4135     if ((round_mask & ~right_n_bits(eshift)) == 0)
4136       round_mask = 0;  // strength-reduce it if it goes away completely
4137     assert(is_flat_array || (hsize & right_n_bits(eshift)) == 0, "hsize is pre-rounded");
4138     assert(header_size_min <= hsize, "generic minimum is smallest");
4139     header_size_min = hsize;
4140     header_size = intcon(hsize + round_mask);
4141   } else {
4142     Node* hss   = intcon(Klass::_lh_header_size_shift);
4143     Node* hsm   = intcon(Klass::_lh_header_size_mask);
4144     Node* hsize = _gvn.transform( new URShiftINode(layout_val, hss) );
4145     hsize       = _gvn.transform( new AndINode(hsize, hsm) );
4146     Node* mask  = intcon(round_mask);
4147     header_size = _gvn.transform( new AddINode(hsize, mask) );
4148   }
4149 
4150   Node* elem_shift = NULL;
4151   if (layout_is_con) {
4152     int eshift = Klass::layout_helper_log2_element_size(layout_con);
4153     if (eshift != 0)
4154       elem_shift = intcon(eshift);
4155   } else {
4156     // There is no need to mask or shift this value.
4157     // The semantics of LShiftINode include an implicit mask to 0x1F.
4158     assert(Klass::_lh_log2_element_size_shift == 0, "use shift in place");
4159     elem_shift = layout_val;
4160   }
4161 
4162   // Transition to native address size for all offset calculations:
4163   Node* lengthx = ConvI2X(length);
4164   Node* headerx = ConvI2X(header_size);
4165 #ifdef _LP64
4166   { const TypeInt* tilen = _gvn.find_int_type(length);
4167     if (tilen != NULL && tilen->_lo < 0) {
4168       // Add a manual constraint to a positive range.  Cf. array_element_address.
4169       jint size_max = fast_size_limit;
4170       if (size_max > tilen->_hi)  size_max = tilen->_hi;
4171       const TypeInt* tlcon = TypeInt::make(0, size_max, Type::WidenMin);
4172 
4173       // Only do a narrow I2L conversion if the range check passed.
4174       IfNode* iff = new IfNode(control(), initial_slow_test, PROB_MIN, COUNT_UNKNOWN);
4175       _gvn.transform(iff);
4176       RegionNode* region = new RegionNode(3);
4177       _gvn.set_type(region, Type::CONTROL);
4178       lengthx = new PhiNode(region, TypeLong::LONG);
4179       _gvn.set_type(lengthx, TypeLong::LONG);
4180 
4181       // Range check passed. Use ConvI2L node with narrow type.
4182       Node* passed = IfFalse(iff);
4183       region->init_req(1, passed);
4184       // Make I2L conversion control dependent to prevent it from
4185       // floating above the range check during loop optimizations.
4186       lengthx->init_req(1, C->constrained_convI2L(&_gvn, length, tlcon, passed));
4187 
4188       // Range check failed. Use ConvI2L with wide type because length may be invalid.
4189       region->init_req(2, IfTrue(iff));
4190       lengthx->init_req(2, ConvI2X(length));
4191 
4192       set_control(region);
4193       record_for_igvn(region);
4194       record_for_igvn(lengthx);
4195     }
4196   }
4197 #endif
4198 
4199   // Combine header size (plus rounding) and body size.  Then round down.
4200   // This computation cannot overflow, because it is used only in two
4201   // places, one where the length is sharply limited, and the other
4202   // after a successful allocation.
4203   Node* abody = lengthx;
4204   if (elem_shift != NULL)
4205     abody     = _gvn.transform( new LShiftXNode(lengthx, elem_shift) );
4206   Node* size  = _gvn.transform( new AddXNode(headerx, abody) );
4207   if (round_mask != 0) {
4208     Node* mask = MakeConX(~round_mask);
4209     size       = _gvn.transform( new AndXNode(size, mask) );
4210   }
4211   // else if round_mask == 0, the size computation is self-rounding
4212 
4213   if (return_size_val != NULL) {
4214     // This is the size
4215     (*return_size_val) = size;
4216   }
4217 
4218   // Now generate allocation code
4219 
4220   // The entire memory state is needed for slow path of the allocation
4221   // since GC and deoptimization can happen.
4222   Node *mem = reset_memory();
4223   set_all_memory(mem); // Create new memory state
4224 
4225   if (initial_slow_test->is_Bool()) {
4226     // Hide it behind a CMoveI, or else PhaseIdealLoop::split_up will get sick.
4227     initial_slow_test = initial_slow_test->as_Bool()->as_int_value(&_gvn);
4228   }
4229 
4230   const TypeKlassPtr* ary_klass = _gvn.type(klass_node)->isa_klassptr();
4231   const TypeOopPtr* ary_type = ary_klass->as_instance_type();
4232   const TypeAryPtr* ary_ptr = ary_type->isa_aryptr();
4233 
4234   // Inline type array variants:
4235   // - null-ok:              MyValue.ref[] (ciObjArrayKlass "[LMyValue")
4236   // - null-free:            MyValue.val[] (ciObjArrayKlass "[QMyValue")
4237   // - null-free, flattened: MyValue.val[] (ciFlatArrayKlass "[QMyValue")
4238   // Check if array is a null-free, non-flattened inline type array
4239   // that needs to be initialized with the default inline type.
4240   Node* default_value = NULL;
4241   Node* raw_default_value = NULL;
4242   if (ary_ptr != NULL && ary_ptr->klass_is_exact()) {
4243     // Array type is known
4244     if (ary_ptr->is_null_free() && !ary_ptr->is_flat()) {
4245       ciInlineKlass* vk = ary_ptr->elem()->inline_klass();
4246       default_value = InlineTypeNode::default_oop(gvn(), vk);
4247     }
4248   } else if (ary_type->can_be_inline_array()) {
4249     // Array type is not known, add runtime checks
4250     assert(!ary_klass->klass_is_exact(), "unexpected exact type");
4251     Node* r = new RegionNode(3);
4252     default_value = new PhiNode(r, TypeInstPtr::BOTTOM);
4253 
4254     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);
4255     IfNode* iff = create_and_map_if(control(), bol, PROB_FAIR, COUNT_UNKNOWN);
4256 
4257     // Null-free, non-flattened inline type array, initialize with the default value
4258     set_control(_gvn.transform(new IfTrueNode(iff)));
4259     Node* p = basic_plus_adr(klass_node, in_bytes(ArrayKlass::element_klass_offset()));
4260     Node* eklass = _gvn.transform(LoadKlassNode::make(_gvn, control(), immutable_memory(), p, TypeInstPtr::KLASS));
4261     Node* adr_fixed_block_addr = basic_plus_adr(eklass, in_bytes(InstanceKlass::adr_inlineklass_fixed_block_offset()));
4262     Node* adr_fixed_block = make_load(control(), adr_fixed_block_addr, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4263     Node* default_value_offset_addr = basic_plus_adr(adr_fixed_block, in_bytes(InlineKlass::default_value_offset_offset()));
4264     Node* default_value_offset = make_load(control(), default_value_offset_addr, TypeInt::INT, T_INT, MemNode::unordered);
4265     Node* elem_mirror = load_mirror_from_klass(eklass);
4266     Node* default_value_addr = basic_plus_adr(elem_mirror, ConvI2X(default_value_offset));
4267     Node* val = access_load_at(elem_mirror, default_value_addr, TypeInstPtr::MIRROR, TypeInstPtr::NOTNULL, T_OBJECT, IN_HEAP);
4268     r->init_req(1, control());
4269     default_value->init_req(1, val);
4270 
4271     // Otherwise initialize with all zero
4272     r->init_req(2, _gvn.transform(new IfFalseNode(iff)));
4273     default_value->init_req(2, null());
4274 
4275     set_control(_gvn.transform(r));
4276     default_value = _gvn.transform(default_value);
4277   }
4278   if (default_value != NULL) {
4279     if (UseCompressedOops) {
4280       // With compressed oops, the 64-bit init value is built from two 32-bit compressed oops
4281       default_value = _gvn.transform(new EncodePNode(default_value, default_value->bottom_type()->make_narrowoop()));
4282       Node* lower = _gvn.transform(new CastP2XNode(control(), default_value));
4283       Node* upper = _gvn.transform(new LShiftLNode(lower, intcon(32)));
4284       raw_default_value = _gvn.transform(new OrLNode(lower, upper));
4285     } else {
4286       raw_default_value = _gvn.transform(new CastP2XNode(control(), default_value));
4287     }
4288   }
4289 
4290   Node* valid_length_test = _gvn.intcon(1);
4291   if (ary_type->isa_aryptr()) {
4292     BasicType bt = ary_type->isa_aryptr()->elem()->array_element_basic_type();
4293     jint max = TypeAryPtr::max_array_length(bt);
4294     Node* valid_length_cmp  = _gvn.transform(new CmpUNode(length, intcon(max)));
4295     valid_length_test = _gvn.transform(new BoolNode(valid_length_cmp, BoolTest::le));
4296   }
4297 
4298   // Create the AllocateArrayNode and its result projections
4299   AllocateArrayNode* alloc
4300     = new AllocateArrayNode(C, AllocateArrayNode::alloc_type(TypeInt::INT),
4301                             control(), mem, i_o(),
4302                             size, klass_node,
4303                             initial_slow_test,
4304                             length, valid_length_test,
4305                             default_value, raw_default_value);
4306   // Cast to correct type.  Note that the klass_node may be constant or not,
4307   // and in the latter case the actual array type will be inexact also.
4308   // (This happens via a non-constant argument to inline_native_newArray.)
4309   // In any case, the value of klass_node provides the desired array type.
4310   const TypeInt* length_type = _gvn.find_int_type(length);
4311   if (ary_type->isa_aryptr() && length_type != NULL) {
4312     // Try to get a better type than POS for the size
4313     ary_type = ary_type->is_aryptr()->cast_to_size(length_type);
4314   }
4315 
4316   Node* javaoop = set_output_for_allocation(alloc, ary_type, deoptimize_on_exception);
4317 
4318   array_ideal_length(alloc, ary_type, true);
4319   return javaoop;
4320 }
4321 
4322 // The following "Ideal_foo" functions are placed here because they recognize
4323 // the graph shapes created by the functions immediately above.
4324 
4325 //---------------------------Ideal_allocation----------------------------------
4326 // Given an oop pointer or raw pointer, see if it feeds from an AllocateNode.
4327 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) {
4328   if (ptr == NULL) {     // reduce dumb test in callers
4329     return NULL;
4330   }
4331 
4332   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4333   ptr = bs->step_over_gc_barrier(ptr);
4334 
4335   if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast
4336     ptr = ptr->in(1);
4337     if (ptr == NULL) return NULL;
4338   }
4339   // Return NULL for allocations with several casts:
4340   //   j.l.reflect.Array.newInstance(jobject, jint)
4341   //   Object.clone()
4342   // to keep more precise type from last cast.
4343   if (ptr->is_Proj()) {
4344     Node* allo = ptr->in(0);
4345     if (allo != NULL && allo->is_Allocate()) {
4346       return allo->as_Allocate();
4347     }
4348   }
4349   // Report failure to match.
4350   return NULL;
4351 }
4352 
4353 // Fancy version which also strips off an offset (and reports it to caller).
4354 AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase,
4355                                              intptr_t& offset) {
4356   Node* base = AddPNode::Ideal_base_and_offset(ptr, phase, offset);
4357   if (base == NULL)  return NULL;
4358   return Ideal_allocation(base, phase);
4359 }
4360 
4361 // Trace Initialize <- Proj[Parm] <- Allocate
4362 AllocateNode* InitializeNode::allocation() {
4363   Node* rawoop = in(InitializeNode::RawAddress);
4364   if (rawoop->is_Proj()) {
4365     Node* alloc = rawoop->in(0);
4366     if (alloc->is_Allocate()) {
4367       return alloc->as_Allocate();
4368     }
4369   }
4370   return NULL;
4371 }
4372 
4373 // Trace Allocate -> Proj[Parm] -> Initialize
4374 InitializeNode* AllocateNode::initialization() {
4375   ProjNode* rawoop = proj_out_or_null(AllocateNode::RawAddress);
4376   if (rawoop == NULL)  return NULL;
4377   for (DUIterator_Fast imax, i = rawoop->fast_outs(imax); i < imax; i++) {
4378     Node* init = rawoop->fast_out(i);
4379     if (init->is_Initialize()) {
4380       assert(init->as_Initialize()->allocation() == this, "2-way link");
4381       return init->as_Initialize();
4382     }
4383   }
4384   return NULL;
4385 }
4386 
4387 //----------------------------- loop predicates ---------------------------
4388 
4389 //------------------------------add_predicate_impl----------------------------
4390 void GraphKit::add_empty_predicate_impl(Deoptimization::DeoptReason reason, int nargs) {
4391   // Too many traps seen?
4392   if (too_many_traps(reason)) {
4393 #ifdef ASSERT
4394     if (TraceLoopPredicate) {
4395       int tc = C->trap_count(reason);
4396       tty->print("too many traps=%s tcount=%d in ",
4397                     Deoptimization::trap_reason_name(reason), tc);
4398       method()->print(); // which method has too many predicate traps
4399       tty->cr();
4400     }
4401 #endif
4402     // We cannot afford to take more traps here,
4403     // do not generate predicate.
4404     return;
4405   }
4406 
4407   Node *cont    = _gvn.intcon(1);
4408   Node* opq     = _gvn.transform(new Opaque1Node(C, cont));
4409   Node *bol     = _gvn.transform(new Conv2BNode(opq));
4410   IfNode* iff   = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN);
4411   Node* iffalse = _gvn.transform(new IfFalseNode(iff));
4412   C->add_predicate_opaq(opq);
4413   {
4414     PreserveJVMState pjvms(this);
4415     set_control(iffalse);
4416     inc_sp(nargs);
4417     uncommon_trap(reason, Deoptimization::Action_maybe_recompile);
4418   }
4419   Node* iftrue = _gvn.transform(new IfTrueNode(iff));
4420   set_control(iftrue);
4421 }
4422 
4423 //------------------------------add_predicate---------------------------------
4424 void GraphKit::add_empty_predicates(int nargs) {
4425   // These loop predicates remain empty. All concrete loop predicates are inserted above the corresponding
4426   // empty loop predicate later by 'PhaseIdealLoop::create_new_if_for_predicate'. All concrete loop predicates of
4427   // a specific kind (normal, profile or limit check) share the same uncommon trap as the empty loop predicate.
4428   if (UseLoopPredicate) {
4429     add_empty_predicate_impl(Deoptimization::Reason_predicate, nargs);
4430   }
4431   if (UseProfiledLoopPredicate) {
4432     add_empty_predicate_impl(Deoptimization::Reason_profile_predicate, nargs);
4433   }
4434   // loop's limit check predicate should be near the loop.
4435   add_empty_predicate_impl(Deoptimization::Reason_loop_limit_check, nargs);
4436 }
4437 
4438 void GraphKit::sync_kit(IdealKit& ideal) {
4439   set_all_memory(ideal.merged_memory());
4440   set_i_o(ideal.i_o());
4441   set_control(ideal.ctrl());
4442 }
4443 
4444 void GraphKit::final_sync(IdealKit& ideal) {
4445   // Final sync IdealKit and graphKit.
4446   sync_kit(ideal);
4447 }
4448 
4449 Node* GraphKit::load_String_length(Node* str, bool set_ctrl) {
4450   Node* len = load_array_length(load_String_value(str, set_ctrl));
4451   Node* coder = load_String_coder(str, set_ctrl);
4452   // Divide length by 2 if coder is UTF16
4453   return _gvn.transform(new RShiftINode(len, coder));
4454 }
4455 
4456 Node* GraphKit::load_String_value(Node* str, bool set_ctrl) {
4457   int value_offset = java_lang_String::value_offset();
4458   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4459                                                      false, NULL, Type::Offset(0));
4460   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4461   const TypeAryPtr* value_type = TypeAryPtr::make(TypePtr::NotNull,
4462                                                   TypeAry::make(TypeInt::BYTE, TypeInt::POS, false, false, true, true),
4463                                                   ciTypeArrayKlass::make(T_BYTE), true, Type::Offset(0));
4464   Node* p = basic_plus_adr(str, str, value_offset);
4465   Node* load = access_load_at(str, p, value_field_type, value_type, T_OBJECT,
4466                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4467   return load;
4468 }
4469 
4470 Node* GraphKit::load_String_coder(Node* str, bool set_ctrl) {
4471   if (!CompactStrings) {
4472     return intcon(java_lang_String::CODER_UTF16);
4473   }
4474   int coder_offset = java_lang_String::coder_offset();
4475   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4476                                                      false, NULL, Type::Offset(0));
4477   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4478 
4479   Node* p = basic_plus_adr(str, str, coder_offset);
4480   Node* load = access_load_at(str, p, coder_field_type, TypeInt::BYTE, T_BYTE,
4481                               IN_HEAP | (set_ctrl ? C2_CONTROL_DEPENDENT_LOAD : 0) | MO_UNORDERED);
4482   return load;
4483 }
4484 
4485 void GraphKit::store_String_value(Node* str, Node* value) {
4486   int value_offset = java_lang_String::value_offset();
4487   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4488                                                      false, NULL, Type::Offset(0));
4489   const TypePtr* value_field_type = string_type->add_offset(value_offset);
4490 
4491   access_store_at(str,  basic_plus_adr(str, value_offset), value_field_type,
4492                   value, TypeAryPtr::BYTES, T_OBJECT, IN_HEAP | MO_UNORDERED);
4493 }
4494 
4495 void GraphKit::store_String_coder(Node* str, Node* value) {
4496   int coder_offset = java_lang_String::coder_offset();
4497   const TypeInstPtr* string_type = TypeInstPtr::make(TypePtr::NotNull, C->env()->String_klass(),
4498                                                      false, NULL, Type::Offset(0));
4499   const TypePtr* coder_field_type = string_type->add_offset(coder_offset);
4500 
4501   access_store_at(str, basic_plus_adr(str, coder_offset), coder_field_type,
4502                   value, TypeInt::BYTE, T_BYTE, IN_HEAP | MO_UNORDERED);
4503 }
4504 
4505 // Capture src and dst memory state with a MergeMemNode
4506 Node* GraphKit::capture_memory(const TypePtr* src_type, const TypePtr* dst_type) {
4507   if (src_type == dst_type) {
4508     // Types are equal, we don't need a MergeMemNode
4509     return memory(src_type);
4510   }
4511   MergeMemNode* merge = MergeMemNode::make(map()->memory());
4512   record_for_igvn(merge); // fold it up later, if possible
4513   int src_idx = C->get_alias_index(src_type);
4514   int dst_idx = C->get_alias_index(dst_type);
4515   merge->set_memory_at(src_idx, memory(src_idx));
4516   merge->set_memory_at(dst_idx, memory(dst_idx));
4517   return merge;
4518 }
4519 
4520 Node* GraphKit::compress_string(Node* src, const TypeAryPtr* src_type, Node* dst, Node* count) {
4521   assert(Matcher::match_rule_supported(Op_StrCompressedCopy), "Intrinsic not supported");
4522   assert(src_type == TypeAryPtr::BYTES || src_type == TypeAryPtr::CHARS, "invalid source type");
4523   // If input and output memory types differ, capture both states to preserve
4524   // the dependency between preceding and subsequent loads/stores.
4525   // For example, the following program:
4526   //  StoreB
4527   //  compress_string
4528   //  LoadB
4529   // has this memory graph (use->def):
4530   //  LoadB -> compress_string -> CharMem
4531   //             ... -> StoreB -> ByteMem
4532   // The intrinsic hides the dependency between LoadB and StoreB, causing
4533   // the load to read from memory not containing the result of the StoreB.
4534   // The correct memory graph should look like this:
4535   //  LoadB -> compress_string -> MergeMem(CharMem, StoreB(ByteMem))
4536   Node* mem = capture_memory(src_type, TypeAryPtr::BYTES);
4537   StrCompressedCopyNode* str = new StrCompressedCopyNode(control(), mem, src, dst, count);
4538   Node* res_mem = _gvn.transform(new SCMemProjNode(_gvn.transform(str)));
4539   set_memory(res_mem, TypeAryPtr::BYTES);
4540   return str;
4541 }
4542 
4543 void GraphKit::inflate_string(Node* src, Node* dst, const TypeAryPtr* dst_type, Node* count) {
4544   assert(Matcher::match_rule_supported(Op_StrInflatedCopy), "Intrinsic not supported");
4545   assert(dst_type == TypeAryPtr::BYTES || dst_type == TypeAryPtr::CHARS, "invalid dest type");
4546   // Capture src and dst memory (see comment in 'compress_string').
4547   Node* mem = capture_memory(TypeAryPtr::BYTES, dst_type);
4548   StrInflatedCopyNode* str = new StrInflatedCopyNode(control(), mem, src, dst, count);
4549   set_memory(_gvn.transform(str), dst_type);
4550 }
4551 
4552 void GraphKit::inflate_string_slow(Node* src, Node* dst, Node* start, Node* count) {
4553   /**
4554    * int i_char = start;
4555    * for (int i_byte = 0; i_byte < count; i_byte++) {
4556    *   dst[i_char++] = (char)(src[i_byte] & 0xff);
4557    * }
4558    */
4559   add_empty_predicates();
4560   C->set_has_loops(true);
4561 
4562   RegionNode* head = new RegionNode(3);
4563   head->init_req(1, control());
4564   gvn().set_type(head, Type::CONTROL);
4565   record_for_igvn(head);
4566 
4567   Node* i_byte = new PhiNode(head, TypeInt::INT);
4568   i_byte->init_req(1, intcon(0));
4569   gvn().set_type(i_byte, TypeInt::INT);
4570   record_for_igvn(i_byte);
4571 
4572   Node* i_char = new PhiNode(head, TypeInt::INT);
4573   i_char->init_req(1, start);
4574   gvn().set_type(i_char, TypeInt::INT);
4575   record_for_igvn(i_char);
4576 
4577   Node* mem = PhiNode::make(head, memory(TypeAryPtr::BYTES), Type::MEMORY, TypeAryPtr::BYTES);
4578   gvn().set_type(mem, Type::MEMORY);
4579   record_for_igvn(mem);
4580   set_control(head);
4581   set_memory(mem, TypeAryPtr::BYTES);
4582   Node* ch = load_array_element(src, i_byte, TypeAryPtr::BYTES, /* set_ctrl */ true);
4583   Node* st = store_to_memory(control(), array_element_address(dst, i_char, T_BYTE),
4584                              AndI(ch, intcon(0xff)), T_CHAR, TypeAryPtr::BYTES, MemNode::unordered,
4585                              false, false, true /* mismatched */);
4586 
4587   IfNode* iff = create_and_map_if(head, Bool(CmpI(i_byte, count), BoolTest::lt), PROB_FAIR, COUNT_UNKNOWN);
4588   head->init_req(2, IfTrue(iff));
4589   mem->init_req(2, st);
4590   i_byte->init_req(2, AddI(i_byte, intcon(1)));
4591   i_char->init_req(2, AddI(i_char, intcon(2)));
4592 
4593   set_control(IfFalse(iff));
4594   set_memory(st, TypeAryPtr::BYTES);
4595 }
4596 
4597 Node* GraphKit::make_constant_from_field(ciField* field, Node* obj) {
4598   if (!field->is_constant()) {
4599     return NULL; // Field not marked as constant.
4600   }
4601   ciInstance* holder = NULL;
4602   if (!field->is_static()) {
4603     ciObject* const_oop = obj->bottom_type()->is_oopptr()->const_oop();
4604     if (const_oop != NULL && const_oop->is_instance()) {
4605       holder = const_oop->as_instance();
4606     }
4607   }
4608   const Type* con_type = Type::make_constant_from_field(field, holder, field->layout_type(),
4609                                                         /*is_unsigned_load=*/false);
4610   if (con_type != NULL) {
4611     Node* con = makecon(con_type);
4612     if (field->type()->is_inlinetype()) {
4613       con = InlineTypeNode::make_from_oop(this, con, field->type()->as_inline_klass(), field->is_null_free());
4614     } else if (con_type->is_inlinetypeptr()) {
4615       con = InlineTypeNode::make_from_oop(this, con, con_type->inline_klass(), field->is_null_free());
4616     }
4617     return con;
4618   }
4619   return NULL;
4620 }
4621 
4622 //---------------------------load_mirror_from_klass----------------------------
4623 // Given a klass oop, load its java mirror (a java.lang.Class oop).
4624 Node* GraphKit::load_mirror_from_klass(Node* klass) {
4625   Node* p = basic_plus_adr(klass, in_bytes(Klass::java_mirror_offset()));
4626   Node* load = make_load(NULL, p, TypeRawPtr::NOTNULL, T_ADDRESS, MemNode::unordered);
4627   // mirror = ((OopHandle)mirror)->resolve();
4628   return access_load(load, TypeInstPtr::MIRROR, T_OBJECT, IN_NATIVE);
4629 }