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