1 /*
   2  * Copyright (c) 1997, 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 "compiler/compileLog.hpp"
  27 #include "ci/bcEscapeAnalyzer.hpp"
  28 #include "compiler/oopMap.hpp"
  29 #include "gc/shared/barrierSet.hpp"
  30 #include "gc/shared/c2/barrierSetC2.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "opto/callGenerator.hpp"
  33 #include "opto/callnode.hpp"
  34 #include "opto/castnode.hpp"
  35 #include "opto/convertnode.hpp"
  36 #include "opto/escape.hpp"
  37 #include "opto/locknode.hpp"
  38 #include "opto/machnode.hpp"
  39 #include "opto/matcher.hpp"
  40 #include "opto/parse.hpp"
  41 #include "opto/regalloc.hpp"
  42 #include "opto/regmask.hpp"
  43 #include "opto/rootnode.hpp"
  44 #include "opto/runtime.hpp"
  45 #include "opto/valuetypenode.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 
  48 // Portions of code courtesy of Clifford Click
  49 
  50 // Optimization - Graph Style
  51 
  52 //=============================================================================
  53 uint StartNode::size_of() const { return sizeof(*this); }
  54 bool StartNode::cmp( const Node &n ) const
  55 { return _domain == ((StartNode&)n)._domain; }
  56 const Type *StartNode::bottom_type() const { return _domain; }
  57 const Type* StartNode::Value(PhaseGVN* phase) const { return _domain; }
  58 #ifndef PRODUCT
  59 void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
  60 void StartNode::dump_compact_spec(outputStream *st) const { /* empty */ }
  61 #endif
  62 
  63 //------------------------------Ideal------------------------------------------
  64 Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
  65   return remove_dead_region(phase, can_reshape) ? this : NULL;
  66 }
  67 
  68 //------------------------------calling_convention-----------------------------
  69 void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
  70   Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );
  71 }
  72 
  73 //------------------------------Registers--------------------------------------
  74 const RegMask &StartNode::in_RegMask(uint) const {
  75   return RegMask::Empty;
  76 }
  77 
  78 //------------------------------match------------------------------------------
  79 // Construct projections for incoming parameters, and their RegMask info
  80 Node *StartNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
  81   switch (proj->_con) {
  82   case TypeFunc::Control:
  83   case TypeFunc::I_O:
  84   case TypeFunc::Memory:
  85     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
  86   case TypeFunc::FramePtr:
  87     return new MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
  88   case TypeFunc::ReturnAdr:
  89     return new MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
  90   case TypeFunc::Parms:
  91   default: {
  92       uint parm_num = proj->_con - TypeFunc::Parms;
  93       const Type *t = _domain->field_at(proj->_con);
  94       if (t->base() == Type::Half)  // 2nd half of Longs and Doubles
  95         return new ConNode(Type::TOP);
  96       uint ideal_reg = t->ideal_reg();
  97       RegMask &rm = match->_calling_convention_mask[parm_num];
  98       return new MachProjNode(this,proj->_con,rm,ideal_reg);
  99     }
 100   }
 101   return NULL;
 102 }
 103 
 104 //------------------------------StartOSRNode----------------------------------
 105 // The method start node for an on stack replacement adapter
 106 
 107 //------------------------------osr_domain-----------------------------
 108 const TypeTuple *StartOSRNode::osr_domain() {
 109   const Type **fields = TypeTuple::fields(2);
 110   fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM;  // address of osr buffer
 111 
 112   return TypeTuple::make(TypeFunc::Parms+1, fields);
 113 }
 114 
 115 //=============================================================================
 116 const char * const ParmNode::names[TypeFunc::Parms+1] = {
 117   "Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
 118 };
 119 
 120 #ifndef PRODUCT
 121 void ParmNode::dump_spec(outputStream *st) const {
 122   if( _con < TypeFunc::Parms ) {
 123     st->print("%s", names[_con]);
 124   } else {
 125     st->print("Parm%d: ",_con-TypeFunc::Parms);
 126     // Verbose and WizardMode dump bottom_type for all nodes
 127     if( !Verbose && !WizardMode )   bottom_type()->dump_on(st);
 128   }
 129 }
 130 
 131 void ParmNode::dump_compact_spec(outputStream *st) const {
 132   if (_con < TypeFunc::Parms) {
 133     st->print("%s", names[_con]);
 134   } else {
 135     st->print("%d:", _con-TypeFunc::Parms);
 136     // unconditionally dump bottom_type
 137     bottom_type()->dump_on(st);
 138   }
 139 }
 140 
 141 // For a ParmNode, all immediate inputs and outputs are considered relevant
 142 // both in compact and standard representation.
 143 void ParmNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
 144   this->collect_nodes(in_rel, 1, false, false);
 145   this->collect_nodes(out_rel, -1, false, false);
 146 }
 147 #endif
 148 
 149 uint ParmNode::ideal_reg() const {
 150   switch( _con ) {
 151   case TypeFunc::Control  : // fall through
 152   case TypeFunc::I_O      : // fall through
 153   case TypeFunc::Memory   : return 0;
 154   case TypeFunc::FramePtr : // fall through
 155   case TypeFunc::ReturnAdr: return Op_RegP;
 156   default                 : assert( _con > TypeFunc::Parms, "" );
 157     // fall through
 158   case TypeFunc::Parms    : {
 159     // Type of argument being passed
 160     const Type *t = in(0)->as_Start()->_domain->field_at(_con);
 161     return t->ideal_reg();
 162   }
 163   }
 164   ShouldNotReachHere();
 165   return 0;
 166 }
 167 
 168 //=============================================================================
 169 ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
 170   init_req(TypeFunc::Control,cntrl);
 171   init_req(TypeFunc::I_O,i_o);
 172   init_req(TypeFunc::Memory,memory);
 173   init_req(TypeFunc::FramePtr,frameptr);
 174   init_req(TypeFunc::ReturnAdr,retadr);
 175 }
 176 
 177 Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
 178   return remove_dead_region(phase, can_reshape) ? this : NULL;
 179 }
 180 
 181 const Type* ReturnNode::Value(PhaseGVN* phase) const {
 182   return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
 183     ? Type::TOP
 184     : Type::BOTTOM;
 185 }
 186 
 187 // Do we Match on this edge index or not?  No edges on return nodes
 188 uint ReturnNode::match_edge(uint idx) const {
 189   return 0;
 190 }
 191 
 192 
 193 #ifndef PRODUCT
 194 void ReturnNode::dump_req(outputStream *st) const {
 195   // Dump the required inputs, enclosed in '(' and ')'
 196   uint i;                       // Exit value of loop
 197   for (i = 0; i < req(); i++) {    // For all required inputs
 198     if (i == TypeFunc::Parms) st->print("returns");
 199     if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
 200     else st->print("_ ");
 201   }
 202 }
 203 #endif
 204 
 205 //=============================================================================
 206 RethrowNode::RethrowNode(
 207   Node* cntrl,
 208   Node* i_o,
 209   Node* memory,
 210   Node* frameptr,
 211   Node* ret_adr,
 212   Node* exception
 213 ) : Node(TypeFunc::Parms + 1) {
 214   init_req(TypeFunc::Control  , cntrl    );
 215   init_req(TypeFunc::I_O      , i_o      );
 216   init_req(TypeFunc::Memory   , memory   );
 217   init_req(TypeFunc::FramePtr , frameptr );
 218   init_req(TypeFunc::ReturnAdr, ret_adr);
 219   init_req(TypeFunc::Parms    , exception);
 220 }
 221 
 222 Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
 223   return remove_dead_region(phase, can_reshape) ? this : NULL;
 224 }
 225 
 226 const Type* RethrowNode::Value(PhaseGVN* phase) const {
 227   return (phase->type(in(TypeFunc::Control)) == Type::TOP)
 228     ? Type::TOP
 229     : Type::BOTTOM;
 230 }
 231 
 232 uint RethrowNode::match_edge(uint idx) const {
 233   return 0;
 234 }
 235 
 236 #ifndef PRODUCT
 237 void RethrowNode::dump_req(outputStream *st) const {
 238   // Dump the required inputs, enclosed in '(' and ')'
 239   uint i;                       // Exit value of loop
 240   for (i = 0; i < req(); i++) {    // For all required inputs
 241     if (i == TypeFunc::Parms) st->print("exception");
 242     if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
 243     else st->print("_ ");
 244   }
 245 }
 246 #endif
 247 
 248 //=============================================================================
 249 // Do we Match on this edge index or not?  Match only target address & method
 250 uint TailCallNode::match_edge(uint idx) const {
 251   return TypeFunc::Parms <= idx  &&  idx <= TypeFunc::Parms+1;
 252 }
 253 
 254 //=============================================================================
 255 // Do we Match on this edge index or not?  Match only target address & oop
 256 uint TailJumpNode::match_edge(uint idx) const {
 257   return TypeFunc::Parms <= idx  &&  idx <= TypeFunc::Parms+1;
 258 }
 259 
 260 //=============================================================================
 261 JVMState::JVMState(ciMethod* method, JVMState* caller) :
 262   _method(method) {
 263   assert(method != NULL, "must be valid call site");
 264   _bci = InvocationEntryBci;
 265   _reexecute = Reexecute_Undefined;
 266   debug_only(_bci = -99);  // random garbage value
 267   debug_only(_map = (SafePointNode*)-1);
 268   _caller = caller;
 269   _depth  = 1 + (caller == NULL ? 0 : caller->depth());
 270   _locoff = TypeFunc::Parms;
 271   _stkoff = _locoff + _method->max_locals();
 272   _monoff = _stkoff + _method->max_stack();
 273   _scloff = _monoff;
 274   _endoff = _monoff;
 275   _sp = 0;
 276 }
 277 JVMState::JVMState(int stack_size) :
 278   _method(NULL) {
 279   _bci = InvocationEntryBci;
 280   _reexecute = Reexecute_Undefined;
 281   debug_only(_map = (SafePointNode*)-1);
 282   _caller = NULL;
 283   _depth  = 1;
 284   _locoff = TypeFunc::Parms;
 285   _stkoff = _locoff;
 286   _monoff = _stkoff + stack_size;
 287   _scloff = _monoff;
 288   _endoff = _monoff;
 289   _sp = 0;
 290 }
 291 
 292 //--------------------------------of_depth-------------------------------------
 293 JVMState* JVMState::of_depth(int d) const {
 294   const JVMState* jvmp = this;
 295   assert(0 < d && (uint)d <= depth(), "oob");
 296   for (int skip = depth() - d; skip > 0; skip--) {
 297     jvmp = jvmp->caller();
 298   }
 299   assert(jvmp->depth() == (uint)d, "found the right one");
 300   return (JVMState*)jvmp;
 301 }
 302 
 303 //-----------------------------same_calls_as-----------------------------------
 304 bool JVMState::same_calls_as(const JVMState* that) const {
 305   if (this == that)                    return true;
 306   if (this->depth() != that->depth())  return false;
 307   const JVMState* p = this;
 308   const JVMState* q = that;
 309   for (;;) {
 310     if (p->_method != q->_method)    return false;
 311     if (p->_method == NULL)          return true;   // bci is irrelevant
 312     if (p->_bci    != q->_bci)       return false;
 313     if (p->_reexecute != q->_reexecute)  return false;
 314     p = p->caller();
 315     q = q->caller();
 316     if (p == q)                      return true;
 317     assert(p != NULL && q != NULL, "depth check ensures we don't run off end");
 318   }
 319 }
 320 
 321 //------------------------------debug_start------------------------------------
 322 uint JVMState::debug_start()  const {
 323   debug_only(JVMState* jvmroot = of_depth(1));
 324   assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");
 325   return of_depth(1)->locoff();
 326 }
 327 
 328 //-------------------------------debug_end-------------------------------------
 329 uint JVMState::debug_end() const {
 330   debug_only(JVMState* jvmroot = of_depth(1));
 331   assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");
 332   return endoff();
 333 }
 334 
 335 //------------------------------debug_depth------------------------------------
 336 uint JVMState::debug_depth() const {
 337   uint total = 0;
 338   for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {
 339     total += jvmp->debug_size();
 340   }
 341   return total;
 342 }
 343 
 344 #ifndef PRODUCT
 345 
 346 //------------------------------format_helper----------------------------------
 347 // Given an allocation (a Chaitin object) and a Node decide if the Node carries
 348 // any defined value or not.  If it does, print out the register or constant.
 349 static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {
 350   if (n == NULL) { st->print(" NULL"); return; }
 351   if (n->is_SafePointScalarObject()) {
 352     // Scalar replacement.
 353     SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();
 354     scobjs->append_if_missing(spobj);
 355     int sco_n = scobjs->find(spobj);
 356     assert(sco_n >= 0, "");
 357     st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);
 358     return;
 359   }
 360   if (regalloc->node_regs_max_index() > 0 &&
 361       OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined
 362     char buf[50];
 363     regalloc->dump_register(n,buf);
 364     st->print(" %s%d]=%s",msg,i,buf);
 365   } else {                      // No register, but might be constant
 366     const Type *t = n->bottom_type();
 367     switch (t->base()) {
 368     case Type::Int:
 369       st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con());
 370       break;
 371     case Type::AnyPtr:
 372       assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );
 373       st->print(" %s%d]=#NULL",msg,i);
 374       break;
 375     case Type::AryPtr:
 376     case Type::InstPtr:
 377       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));
 378       break;
 379     case Type::KlassPtr:
 380       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));
 381       break;
 382     case Type::MetadataPtr:
 383       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));
 384       break;
 385     case Type::NarrowOop:
 386       st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));
 387       break;
 388     case Type::RawPtr:
 389       st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));
 390       break;
 391     case Type::DoubleCon:
 392       st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);
 393       break;
 394     case Type::FloatCon:
 395       st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);
 396       break;
 397     case Type::Long:
 398       st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));
 399       break;
 400     case Type::Half:
 401     case Type::Top:
 402       st->print(" %s%d]=_",msg,i);
 403       break;
 404     default: ShouldNotReachHere();
 405     }
 406   }
 407 }
 408 
 409 //------------------------------format-----------------------------------------
 410 void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {
 411   st->print("        #");
 412   if (_method) {
 413     _method->print_short_name(st);
 414     st->print(" @ bci:%d ",_bci);
 415   } else {
 416     st->print_cr(" runtime stub ");
 417     return;
 418   }
 419   if (n->is_MachSafePoint()) {
 420     GrowableArray<SafePointScalarObjectNode*> scobjs;
 421     MachSafePointNode *mcall = n->as_MachSafePoint();
 422     uint i;
 423     // Print locals
 424     for (i = 0; i < (uint)loc_size(); i++)
 425       format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);
 426     // Print stack
 427     for (i = 0; i < (uint)stk_size(); i++) {
 428       if ((uint)(_stkoff + i) >= mcall->len())
 429         st->print(" oob ");
 430       else
 431        format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);
 432     }
 433     for (i = 0; (int)i < nof_monitors(); i++) {
 434       Node *box = mcall->monitor_box(this, i);
 435       Node *obj = mcall->monitor_obj(this, i);
 436       if (regalloc->node_regs_max_index() > 0 &&
 437           OptoReg::is_valid(regalloc->get_reg_first(box))) {
 438         box = BoxLockNode::box_node(box);
 439         format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);
 440       } else {
 441         OptoReg::Name box_reg = BoxLockNode::reg(box);
 442         st->print(" MON-BOX%d=%s+%d",
 443                    i,
 444                    OptoReg::regname(OptoReg::c_frame_pointer),
 445                    regalloc->reg2offset(box_reg));
 446       }
 447       const char* obj_msg = "MON-OBJ[";
 448       if (EliminateLocks) {
 449         if (BoxLockNode::box_node(box)->is_eliminated())
 450           obj_msg = "MON-OBJ(LOCK ELIMINATED)[";
 451       }
 452       format_helper(regalloc, st, obj, obj_msg, i, &scobjs);
 453     }
 454 
 455     for (i = 0; i < (uint)scobjs.length(); i++) {
 456       // Scalar replaced objects.
 457       st->cr();
 458       st->print("        # ScObj" INT32_FORMAT " ", i);
 459       SafePointScalarObjectNode* spobj = scobjs.at(i);
 460       ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();
 461       assert(cik->is_instance_klass() ||
 462              cik->is_array_klass(), "Not supported allocation.");
 463       ciInstanceKlass *iklass = NULL;
 464       if (cik->is_instance_klass()) {
 465         cik->print_name_on(st);
 466         iklass = cik->as_instance_klass();
 467       } else if (cik->is_type_array_klass()) {
 468         cik->as_array_klass()->base_element_type()->print_name_on(st);
 469         st->print("[%d]", spobj->n_fields());
 470       } else if (cik->is_obj_array_klass()) {
 471         ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();
 472         if (cie->is_instance_klass()) {
 473           cie->print_name_on(st);
 474         } else if (cie->is_type_array_klass()) {
 475           cie->as_array_klass()->base_element_type()->print_name_on(st);
 476         } else {
 477           ShouldNotReachHere();
 478         }
 479         st->print("[%d]", spobj->n_fields());
 480         int ndim = cik->as_array_klass()->dimension() - 1;
 481         while (ndim-- > 0) {
 482           st->print("[]");
 483         }
 484       } else if (cik->is_value_array_klass()) {
 485         ciKlass* cie = cik->as_value_array_klass()->base_element_klass();
 486         cie->print_name_on(st);
 487         st->print("[%d]", spobj->n_fields());
 488         int ndim = cik->as_array_klass()->dimension() - 1;
 489         while (ndim-- > 0) {
 490           st->print("[]");
 491         }
 492       }
 493       st->print("={");
 494       uint nf = spobj->n_fields();
 495       if (nf > 0) {
 496         uint first_ind = spobj->first_index(mcall->jvms());
 497         Node* fld_node = mcall->in(first_ind);
 498         ciField* cifield;
 499         if (iklass != NULL) {
 500           st->print(" [");
 501           cifield = iklass->nonstatic_field_at(0);
 502           cifield->print_name_on(st);
 503           format_helper(regalloc, st, fld_node, ":", 0, &scobjs);
 504         } else {
 505           format_helper(regalloc, st, fld_node, "[", 0, &scobjs);
 506         }
 507         for (uint j = 1; j < nf; j++) {
 508           fld_node = mcall->in(first_ind+j);
 509           if (iklass != NULL) {
 510             st->print(", [");
 511             cifield = iklass->nonstatic_field_at(j);
 512             cifield->print_name_on(st);
 513             format_helper(regalloc, st, fld_node, ":", j, &scobjs);
 514           } else {
 515             format_helper(regalloc, st, fld_node, ", [", j, &scobjs);
 516           }
 517         }
 518       }
 519       st->print(" }");
 520     }
 521   }
 522   st->cr();
 523   if (caller() != NULL) caller()->format(regalloc, n, st);
 524 }
 525 
 526 
 527 void JVMState::dump_spec(outputStream *st) const {
 528   if (_method != NULL) {
 529     bool printed = false;
 530     if (!Verbose) {
 531       // The JVMS dumps make really, really long lines.
 532       // Take out the most boring parts, which are the package prefixes.
 533       char buf[500];
 534       stringStream namest(buf, sizeof(buf));
 535       _method->print_short_name(&namest);
 536       if (namest.count() < sizeof(buf)) {
 537         const char* name = namest.base();
 538         if (name[0] == ' ')  ++name;
 539         const char* endcn = strchr(name, ':');  // end of class name
 540         if (endcn == NULL)  endcn = strchr(name, '(');
 541         if (endcn == NULL)  endcn = name + strlen(name);
 542         while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')
 543           --endcn;
 544         st->print(" %s", endcn);
 545         printed = true;
 546       }
 547     }
 548     if (!printed)
 549       _method->print_short_name(st);
 550     st->print(" @ bci:%d",_bci);
 551     if(_reexecute == Reexecute_True)
 552       st->print(" reexecute");
 553   } else {
 554     st->print(" runtime stub");
 555   }
 556   if (caller() != NULL)  caller()->dump_spec(st);
 557 }
 558 
 559 
 560 void JVMState::dump_on(outputStream* st) const {
 561   bool print_map = _map && !((uintptr_t)_map & 1) &&
 562                   ((caller() == NULL) || (caller()->map() != _map));
 563   if (print_map) {
 564     if (_map->len() > _map->req()) {  // _map->has_exceptions()
 565       Node* ex = _map->in(_map->req());  // _map->next_exception()
 566       // skip the first one; it's already being printed
 567       while (ex != NULL && ex->len() > ex->req()) {
 568         ex = ex->in(ex->req());  // ex->next_exception()
 569         ex->dump(1);
 570       }
 571     }
 572     _map->dump(Verbose ? 2 : 1);
 573   }
 574   if (caller() != NULL) {
 575     caller()->dump_on(st);
 576   }
 577   st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",
 578              depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");
 579   if (_method == NULL) {
 580     st->print_cr("(none)");
 581   } else {
 582     _method->print_name(st);
 583     st->cr();
 584     if (bci() >= 0 && bci() < _method->code_size()) {
 585       st->print("    bc: ");
 586       _method->print_codes_on(bci(), bci()+1, st);
 587     }
 588   }
 589 }
 590 
 591 // Extra way to dump a jvms from the debugger,
 592 // to avoid a bug with C++ member function calls.
 593 void dump_jvms(JVMState* jvms) {
 594   jvms->dump();
 595 }
 596 #endif
 597 
 598 //--------------------------clone_shallow--------------------------------------
 599 JVMState* JVMState::clone_shallow(Compile* C) const {
 600   JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);
 601   n->set_bci(_bci);
 602   n->_reexecute = _reexecute;
 603   n->set_locoff(_locoff);
 604   n->set_stkoff(_stkoff);
 605   n->set_monoff(_monoff);
 606   n->set_scloff(_scloff);
 607   n->set_endoff(_endoff);
 608   n->set_sp(_sp);
 609   n->set_map(_map);
 610   return n;
 611 }
 612 
 613 //---------------------------clone_deep----------------------------------------
 614 JVMState* JVMState::clone_deep(Compile* C) const {
 615   JVMState* n = clone_shallow(C);
 616   for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {
 617     p->_caller = p->_caller->clone_shallow(C);
 618   }
 619   assert(n->depth() == depth(), "sanity");
 620   assert(n->debug_depth() == debug_depth(), "sanity");
 621   return n;
 622 }
 623 
 624 /**
 625  * Reset map for all callers
 626  */
 627 void JVMState::set_map_deep(SafePointNode* map) {
 628   for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {
 629     p->set_map(map);
 630   }
 631 }
 632 
 633 // Adapt offsets in in-array after adding or removing an edge.
 634 // Prerequisite is that the JVMState is used by only one node.
 635 void JVMState::adapt_position(int delta) {
 636   for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {
 637     jvms->set_locoff(jvms->locoff() + delta);
 638     jvms->set_stkoff(jvms->stkoff() + delta);
 639     jvms->set_monoff(jvms->monoff() + delta);
 640     jvms->set_scloff(jvms->scloff() + delta);
 641     jvms->set_endoff(jvms->endoff() + delta);
 642   }
 643 }
 644 
 645 // Mirror the stack size calculation in the deopt code
 646 // How much stack space would we need at this point in the program in
 647 // case of deoptimization?
 648 int JVMState::interpreter_frame_size() const {
 649   const JVMState* jvms = this;
 650   int size = 0;
 651   int callee_parameters = 0;
 652   int callee_locals = 0;
 653   int extra_args = method()->max_stack() - stk_size();
 654 
 655   while (jvms != NULL) {
 656     int locks = jvms->nof_monitors();
 657     int temps = jvms->stk_size();
 658     bool is_top_frame = (jvms == this);
 659     ciMethod* method = jvms->method();
 660 
 661     int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),
 662                                                                  temps + callee_parameters,
 663                                                                  extra_args,
 664                                                                  locks,
 665                                                                  callee_parameters,
 666                                                                  callee_locals,
 667                                                                  is_top_frame);
 668     size += frame_size;
 669 
 670     callee_parameters = method->size_of_parameters();
 671     callee_locals = method->max_locals();
 672     extra_args = 0;
 673     jvms = jvms->caller();
 674   }
 675   return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;
 676 }
 677 
 678 //=============================================================================
 679 bool CallNode::cmp( const Node &n ) const
 680 { return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
 681 #ifndef PRODUCT
 682 void CallNode::dump_req(outputStream *st) const {
 683   // Dump the required inputs, enclosed in '(' and ')'
 684   uint i;                       // Exit value of loop
 685   for (i = 0; i < req(); i++) {    // For all required inputs
 686     if (i == TypeFunc::Parms) st->print("(");
 687     if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
 688     else st->print("_ ");
 689   }
 690   st->print(")");
 691 }
 692 
 693 void CallNode::dump_spec(outputStream *st) const {
 694   st->print(" ");
 695   if (tf() != NULL)  tf()->dump_on(st);
 696   if (_cnt != COUNT_UNKNOWN)  st->print(" C=%f",_cnt);
 697   if (jvms() != NULL)  jvms()->dump_spec(st);
 698 }
 699 #endif
 700 
 701 const Type *CallNode::bottom_type() const { return tf()->range_cc(); }
 702 const Type* CallNode::Value(PhaseGVN* phase) const {
 703   if (!in(0) || phase->type(in(0)) == Type::TOP) {
 704     return Type::TOP;
 705   }
 706   return tf()->range_cc();
 707 }
 708 
 709 //------------------------------calling_convention-----------------------------
 710 void CallNode::calling_convention(BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt) const {
 711   if (_entry_point == StubRoutines::store_value_type_fields_to_buf()) {
 712     // The call to that stub is a special case: its inputs are
 713     // multiple values returned from a call and so it should follow
 714     // the return convention.
 715     SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
 716     return;
 717   }
 718   // Use the standard compiler calling convention
 719   Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );
 720 }
 721 
 722 
 723 //------------------------------match------------------------------------------
 724 // Construct projections for control, I/O, memory-fields, ..., and
 725 // return result(s) along with their RegMask info
 726 Node *CallNode::match(const ProjNode *proj, const Matcher *match, const RegMask* mask) {
 727   uint con = proj->_con;
 728   const TypeTuple *range_cc = tf()->range_cc();
 729   if (con >= TypeFunc::Parms) {
 730     if (is_CallRuntime()) {
 731       if (con == TypeFunc::Parms) {
 732         uint ideal_reg = range_cc->field_at(TypeFunc::Parms)->ideal_reg();
 733         OptoRegPair regs = match->c_return_value(ideal_reg,true);
 734         RegMask rm = RegMask(regs.first());
 735         if (OptoReg::is_valid(regs.second())) {
 736           rm.Insert(regs.second());
 737         }
 738         return new MachProjNode(this,con,rm,ideal_reg);
 739       } else {
 740         assert(con == TypeFunc::Parms+1, "only one return value");
 741         assert(range_cc->field_at(TypeFunc::Parms+1) == Type::HALF, "");
 742         return new MachProjNode(this,con, RegMask::Empty, (uint)OptoReg::Bad);
 743       }
 744     } else {
 745       // The Call may return multiple values (value type fields): we
 746       // create one projection per returned values.
 747       assert(con <= TypeFunc::Parms+1 || ValueTypeReturnedAsFields, "only for multi value return");
 748       uint ideal_reg = range_cc->field_at(con)->ideal_reg();
 749       return new MachProjNode(this, con, mask[con-TypeFunc::Parms], ideal_reg);
 750     }
 751   }
 752 
 753   switch (con) {
 754   case TypeFunc::Control:
 755   case TypeFunc::I_O:
 756   case TypeFunc::Memory:
 757     return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
 758 
 759   case TypeFunc::ReturnAdr:
 760   case TypeFunc::FramePtr:
 761   default:
 762     ShouldNotReachHere();
 763   }
 764   return NULL;
 765 }
 766 
 767 // Do we Match on this edge index or not?  Match no edges
 768 uint CallNode::match_edge(uint idx) const {
 769   return 0;
 770 }
 771 
 772 //
 773 // Determine whether the call could modify the field of the specified
 774 // instance at the specified offset.
 775 //
 776 bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {
 777   assert((t_oop != NULL), "sanity");
 778   if (is_call_to_arraycopystub() && strcmp(_name, "unsafe_arraycopy") != 0) {
 779     const TypeTuple* args = _tf->domain_sig();
 780     Node* dest = NULL;
 781     // Stubs that can be called once an ArrayCopyNode is expanded have
 782     // different signatures. Look for the second pointer argument,
 783     // that is the destination of the copy.
 784     for (uint i = TypeFunc::Parms, j = 0; i < args->cnt(); i++) {
 785       if (args->field_at(i)->isa_ptr()) {
 786         j++;
 787         if (j == 2) {
 788           dest = in(i);
 789           break;
 790         }
 791       }
 792     }
 793     guarantee(dest != NULL, "Call had only one ptr in, broken IR!");
 794     if (!dest->is_top() && may_modify_arraycopy_helper(phase->type(dest)->is_oopptr(), t_oop, phase)) {
 795       return true;
 796     }
 797     return false;
 798   }
 799   if (t_oop->is_known_instance()) {
 800     // The instance_id is set only for scalar-replaceable allocations which
 801     // are not passed as arguments according to Escape Analysis.
 802     return false;
 803   }
 804   if (t_oop->is_ptr_to_boxed_value()) {
 805     ciKlass* boxing_klass = t_oop->klass();
 806     if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {
 807       // Skip unrelated boxing methods.
 808       Node* proj = proj_out_or_null(TypeFunc::Parms);
 809       if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {
 810         return false;
 811       }
 812     }
 813     if (is_CallJava() && as_CallJava()->method() != NULL) {
 814       ciMethod* meth = as_CallJava()->method();
 815       if (meth->is_getter()) {
 816         return false;
 817       }
 818       // May modify (by reflection) if an boxing object is passed
 819       // as argument or returned.
 820       Node* proj = returns_pointer() ? proj_out_or_null(TypeFunc::Parms) : NULL;
 821       if (proj != NULL) {
 822         const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();
 823         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
 824                                  (inst_t->klass() == boxing_klass))) {
 825           return true;
 826         }
 827       }
 828       const TypeTuple* d = tf()->domain_cc();
 829       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 830         const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();
 831         if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||
 832                                  (inst_t->klass() == boxing_klass))) {
 833           return true;
 834         }
 835       }
 836       return false;
 837     }
 838   }
 839   return true;
 840 }
 841 
 842 // Does this call have a direct reference to n other than debug information?
 843 bool CallNode::has_non_debug_use(Node *n) {
 844   const TypeTuple * d = tf()->domain_cc();
 845   for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 846     Node *arg = in(i);
 847     if (arg == n) {
 848       return true;
 849     }
 850   }
 851   return false;
 852 }
 853 
 854 bool CallNode::has_debug_use(Node *n) {
 855   assert(jvms() != NULL, "jvms should not be null");
 856   for (uint i = jvms()->debug_start(); i < jvms()->debug_end(); i++) {
 857     Node *arg = in(i);
 858     if (arg == n) {
 859       return true;
 860     }
 861   }
 862   return false;
 863 }
 864 
 865 // Returns the unique CheckCastPP of a call
 866 // or 'this' if there are several CheckCastPP or unexpected uses
 867 // or returns NULL if there is no one.
 868 Node *CallNode::result_cast() {
 869   Node *cast = NULL;
 870 
 871   Node *p = proj_out_or_null(TypeFunc::Parms);
 872   if (p == NULL)
 873     return NULL;
 874 
 875   for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
 876     Node *use = p->fast_out(i);
 877     if (use->is_CheckCastPP()) {
 878       if (cast != NULL) {
 879         return this;  // more than 1 CheckCastPP
 880       }
 881       cast = use;
 882     } else if (!use->is_Initialize() &&
 883                !use->is_AddP() &&
 884                use->Opcode() != Op_MemBarStoreStore) {
 885       // Expected uses are restricted to a CheckCastPP, an Initialize
 886       // node, a MemBarStoreStore (clone) and AddP nodes. If we
 887       // encounter any other use (a Phi node can be seen in rare
 888       // cases) return this to prevent incorrect optimizations.
 889       return this;
 890     }
 891   }
 892   return cast;
 893 }
 894 
 895 
 896 CallProjections* CallNode::extract_projections(bool separate_io_proj, bool do_asserts) {
 897   uint max_res = TypeFunc::Parms-1;
 898   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 899     ProjNode *pn = fast_out(i)->as_Proj();
 900     max_res = MAX2(max_res, pn->_con);
 901   }
 902 
 903   assert(max_res < _tf->range_cc()->cnt(), "result out of bounds");
 904 
 905   uint projs_size = sizeof(CallProjections);
 906   if (max_res > TypeFunc::Parms) {
 907     projs_size += (max_res-TypeFunc::Parms)*sizeof(Node*);
 908   }
 909   char* projs_storage = resource_allocate_bytes(projs_size);
 910   CallProjections* projs = new(projs_storage)CallProjections(max_res - TypeFunc::Parms + 1);
 911 
 912   for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
 913     ProjNode *pn = fast_out(i)->as_Proj();
 914     if (pn->outcnt() == 0) continue;
 915     switch (pn->_con) {
 916     case TypeFunc::Control:
 917       {
 918         // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
 919         projs->fallthrough_proj = pn;
 920         DUIterator_Fast jmax, j = pn->fast_outs(jmax);
 921         const Node *cn = pn->fast_out(j);
 922         if (cn->is_Catch()) {
 923           ProjNode *cpn = NULL;
 924           for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
 925             cpn = cn->fast_out(k)->as_Proj();
 926             assert(cpn->is_CatchProj(), "must be a CatchProjNode");
 927             if (cpn->_con == CatchProjNode::fall_through_index)
 928               projs->fallthrough_catchproj = cpn;
 929             else {
 930               assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
 931               projs->catchall_catchproj = cpn;
 932             }
 933           }
 934         }
 935         break;
 936       }
 937     case TypeFunc::I_O:
 938       if (pn->_is_io_use)
 939         projs->catchall_ioproj = pn;
 940       else
 941         projs->fallthrough_ioproj = pn;
 942       for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
 943         Node* e = pn->out(j);
 944         if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
 945           assert(projs->exobj == NULL, "only one");
 946           projs->exobj = e;
 947         }
 948       }
 949       break;
 950     case TypeFunc::Memory:
 951       if (pn->_is_io_use)
 952         projs->catchall_memproj = pn;
 953       else
 954         projs->fallthrough_memproj = pn;
 955       break;
 956     case TypeFunc::Parms:
 957       projs->resproj[0] = pn;
 958       break;
 959     default:
 960       assert(pn->_con <= max_res, "unexpected projection from allocation node.");
 961       projs->resproj[pn->_con-TypeFunc::Parms] = pn;
 962       break;
 963     }
 964   }
 965 
 966   // The resproj may not exist because the result could be ignored
 967   // and the exception object may not exist if an exception handler
 968   // swallows the exception but all the other must exist and be found.
 969   do_asserts = do_asserts && !Compile::current()->inlining_incrementally();
 970   assert(!do_asserts || projs->fallthrough_proj      != NULL, "must be found");
 971   assert(!do_asserts || projs->fallthrough_catchproj != NULL, "must be found");
 972   assert(!do_asserts || projs->fallthrough_memproj   != NULL, "must be found");
 973   assert(!do_asserts || projs->fallthrough_ioproj    != NULL, "must be found");
 974   assert(!do_asserts || projs->catchall_catchproj    != NULL, "must be found");
 975   if (separate_io_proj) {
 976     assert(!do_asserts || projs->catchall_memproj    != NULL, "must be found");
 977     assert(!do_asserts || projs->catchall_ioproj     != NULL, "must be found");
 978   }
 979   return projs;
 980 }
 981 
 982 Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
 983   CallGenerator* cg = generator();
 984   if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
 985     // Check whether this MH handle call becomes a candidate for inlining
 986     ciMethod* callee = cg->method();
 987     vmIntrinsics::ID iid = callee->intrinsic_id();
 988     if (iid == vmIntrinsics::_invokeBasic) {
 989       if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
 990         phase->C->prepend_late_inline(cg);
 991         set_generator(NULL);
 992       }
 993     } else {
 994       assert(callee->has_member_arg(), "wrong type of call?");
 995       if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
 996         phase->C->prepend_late_inline(cg);
 997         set_generator(NULL);
 998       }
 999     }
1000   }
1001   return SafePointNode::Ideal(phase, can_reshape);
1002 }
1003 
1004 bool CallNode::is_call_to_arraycopystub() const {
1005   if (_name != NULL && strstr(_name, "arraycopy") != 0) {
1006     return true;
1007   }
1008   return false;
1009 }
1010 
1011 //=============================================================================
1012 uint CallJavaNode::size_of() const { return sizeof(*this); }
1013 bool CallJavaNode::cmp( const Node &n ) const {
1014   CallJavaNode &call = (CallJavaNode&)n;
1015   return CallNode::cmp(call) && _method == call._method &&
1016          _override_symbolic_info == call._override_symbolic_info;
1017 }
1018 
1019 void CallJavaNode::copy_call_debug_info(PhaseIterGVN* phase, CallNode *oldcall) {
1020   // Copy debug information and adjust JVMState information
1021   uint old_dbg_start = oldcall->tf()->domain_sig()->cnt();
1022   uint new_dbg_start = tf()->domain_sig()->cnt();
1023   int jvms_adj  = new_dbg_start - old_dbg_start;
1024   assert (new_dbg_start == req(), "argument count mismatch");
1025   Compile* C = phase->C;
1026   
1027   // SafePointScalarObject node could be referenced several times in debug info.
1028   // Use Dict to record cloned nodes.
1029   Dict* sosn_map = new Dict(cmpkey,hashkey);
1030   for (uint i = old_dbg_start; i < oldcall->req(); i++) {
1031     Node* old_in = oldcall->in(i);
1032     // Clone old SafePointScalarObjectNodes, adjusting their field contents.
1033     if (old_in != NULL && old_in->is_SafePointScalarObject()) {
1034       SafePointScalarObjectNode* old_sosn = old_in->as_SafePointScalarObject();
1035       uint old_unique = C->unique();
1036       Node* new_in = old_sosn->clone(sosn_map);
1037       if (old_unique != C->unique()) { // New node?
1038         new_in->set_req(0, C->root()); // reset control edge
1039         new_in = phase->transform(new_in); // Register new node.
1040       }
1041       old_in = new_in;
1042     }
1043     add_req(old_in);
1044   }
1045 
1046   // JVMS may be shared so clone it before we modify it
1047   set_jvms(oldcall->jvms() != NULL ? oldcall->jvms()->clone_deep(C) : NULL);
1048   for (JVMState *jvms = this->jvms(); jvms != NULL; jvms = jvms->caller()) {
1049     jvms->set_map(this);
1050     jvms->set_locoff(jvms->locoff()+jvms_adj);
1051     jvms->set_stkoff(jvms->stkoff()+jvms_adj);
1052     jvms->set_monoff(jvms->monoff()+jvms_adj);
1053     jvms->set_scloff(jvms->scloff()+jvms_adj);
1054     jvms->set_endoff(jvms->endoff()+jvms_adj);
1055   }
1056 }
1057 
1058 #ifdef ASSERT
1059 bool CallJavaNode::validate_symbolic_info() const {
1060   if (method() == NULL) {
1061     return true; // call into runtime or uncommon trap
1062   }
1063   Bytecodes::Code bc = jvms()->method()->java_code_at_bci(_bci);
1064   if (EnableValhalla && (bc == Bytecodes::_if_acmpeq || bc == Bytecodes::_if_acmpne)) {
1065     return true;
1066   }
1067   ciMethod* symbolic_info = jvms()->method()->get_method_at_bci(_bci);
1068   ciMethod* callee = method();
1069   if (symbolic_info->is_method_handle_intrinsic() && !callee->is_method_handle_intrinsic()) {
1070     assert(override_symbolic_info(), "should be set");
1071   }
1072   assert(ciMethod::is_consistent_info(symbolic_info, callee), "inconsistent info");
1073   return true;
1074 }
1075 #endif
1076 
1077 #ifndef PRODUCT
1078 void CallJavaNode::dump_spec(outputStream *st) const {
1079   if( _method ) _method->print_short_name(st);
1080   CallNode::dump_spec(st);
1081 }
1082 
1083 void CallJavaNode::dump_compact_spec(outputStream* st) const {
1084   if (_method) {
1085     _method->print_short_name(st);
1086   } else {
1087     st->print("<?>");
1088   }
1089 }
1090 #endif
1091 
1092 //=============================================================================
1093 uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
1094 bool CallStaticJavaNode::cmp( const Node &n ) const {
1095   CallStaticJavaNode &call = (CallStaticJavaNode&)n;
1096   return CallJavaNode::cmp(call);
1097 }
1098 
1099 //----------------------------uncommon_trap_request----------------------------
1100 // If this is an uncommon trap, return the request code, else zero.
1101 int CallStaticJavaNode::uncommon_trap_request() const {
1102   if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
1103     return extract_uncommon_trap_request(this);
1104   }
1105   return 0;
1106 }
1107 int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
1108 #ifndef PRODUCT
1109   if (!(call->req() > TypeFunc::Parms &&
1110         call->in(TypeFunc::Parms) != NULL &&
1111         call->in(TypeFunc::Parms)->is_Con() &&
1112         call->in(TypeFunc::Parms)->bottom_type()->isa_int())) {
1113     assert(in_dump() != 0, "OK if dumping");
1114     tty->print("[bad uncommon trap]");
1115     return 0;
1116   }
1117 #endif
1118   return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
1119 }
1120 
1121 bool CallStaticJavaNode::remove_useless_allocation(PhaseGVN *phase, Node* ctl, Node* mem, Node* unc_arg) {
1122   // Split if can cause the flattened array branch of an array load to
1123   // end in an uncommon trap. In that case, the allocation of the
1124   // loaded value and its initialization is useless. Eliminate it. use
1125   // the jvm state of the allocation to create a new uncommon trap
1126   // call at the load.
1127   if (ctl == NULL || ctl->is_top() || mem == NULL || mem->is_top() || !mem->is_MergeMem()) {
1128     return false;
1129   }
1130   PhaseIterGVN* igvn = phase->is_IterGVN();
1131   if (ctl->is_Region()) {
1132     bool res = false;
1133     for (uint i = 1; i < ctl->req(); i++) {
1134       MergeMemNode* mm = mem->clone()->as_MergeMem();
1135       for (MergeMemStream mms(mm); mms.next_non_empty(); ) {
1136         Node* m = mms.memory();
1137         if (m->is_Phi() && m->in(0) == ctl) {
1138           mms.set_memory(m->in(i));
1139         }
1140       }
1141       if (remove_useless_allocation(phase, ctl->in(i), mm, unc_arg)) {
1142         res = true;
1143         if (!ctl->in(i)->is_Region()) {
1144           igvn->replace_input_of(ctl, i, phase->C->top());
1145         }
1146       }
1147       igvn->remove_dead_node(mm);
1148     }
1149     return res;
1150   }
1151   // verify the control flow is ok
1152   Node* c = ctl;
1153   Node* copy = NULL;
1154   Node* alloc = NULL;
1155   for (;;) {
1156     if (c == NULL || c->is_top()) {
1157       return false;
1158     }
1159     if (c->is_Proj() || c->is_Catch() || c->is_MemBar()) {
1160       c = c->in(0);
1161     } else if (c->Opcode() == Op_CallLeaf &&
1162                c->as_Call()->entry_point() == CAST_FROM_FN_PTR(address, OptoRuntime::load_unknown_value)) {
1163       copy = c;
1164       c = c->in(0);
1165     } else if (c->is_Allocate()) {
1166       Node* new_obj = c->as_Allocate()->result_cast();
1167       if (copy == NULL || new_obj == NULL) {
1168         return false;
1169       }
1170       Node* copy_dest = copy->in(TypeFunc::Parms + 2);
1171       if (copy_dest != new_obj) {
1172         return false;
1173       }
1174       alloc = c;
1175       break;
1176     } else {
1177       return false;
1178     }
1179   }
1180   
1181   JVMState* jvms = alloc->jvms();
1182   if (phase->C->too_many_traps(jvms->method(), jvms->bci(), Deoptimization::trap_request_reason(uncommon_trap_request()))) {
1183     return false;
1184   }
1185   
1186   Node* alloc_mem = alloc->in(TypeFunc::Memory);
1187   if (alloc_mem == NULL || alloc_mem->is_top()) {
1188     return false;
1189   }
1190   if (!alloc_mem->is_MergeMem()) {
1191     alloc_mem = MergeMemNode::make(alloc_mem);
1192   }
1193   
1194   // and that there's no unexpected side effect
1195   for (MergeMemStream mms2(mem->as_MergeMem(), alloc_mem->as_MergeMem()); mms2.next_non_empty2(); ) {
1196     Node* m1 = mms2.is_empty() ? mms2.base_memory() : mms2.memory();
1197     Node* m2 = mms2.memory2();
1198     
1199     for (uint i = 0; i < 100; i++) {
1200       if (m1 == m2) {
1201         break;
1202       } else if (m1->is_Proj()) {
1203         m1 = m1->in(0);
1204       } else if (m1->is_MemBar()) {
1205         m1 = m1->in(TypeFunc::Memory);
1206       } else if (m1->Opcode() == Op_CallLeaf &&
1207                  m1->as_Call()->entry_point() == CAST_FROM_FN_PTR(address, OptoRuntime::load_unknown_value)) {
1208         if (m1 != copy) {
1209           return false;
1210         }
1211         m1 = m1->in(TypeFunc::Memory);
1212       } else if (m1->is_Allocate()) {
1213         if (m1 != alloc) {
1214           return false;
1215         }
1216         break;
1217       } else if (m1->is_MergeMem()) {
1218         MergeMemNode* mm = m1->as_MergeMem();
1219         int idx = mms2.alias_idx();
1220         if (idx == Compile::AliasIdxBot) {
1221           m1 = mm->base_memory();
1222         } else {
1223           m1 = mm->memory_at(idx);
1224         }
1225       } else {
1226         return false;
1227       }
1228     }
1229   }
1230   if (alloc_mem->outcnt() == 0) {
1231     igvn->remove_dead_node(alloc_mem);
1232   }
1233 
1234   address call_addr = SharedRuntime::uncommon_trap_blob()->entry_point();
1235   CallNode* unc = new CallStaticJavaNode(OptoRuntime::uncommon_trap_Type(), call_addr, "uncommon_trap",
1236                                          jvms->bci(), NULL);
1237   unc->init_req(TypeFunc::Control, alloc->in(0));
1238   unc->init_req(TypeFunc::I_O, alloc->in(TypeFunc::I_O));
1239   unc->init_req(TypeFunc::Memory, alloc->in(TypeFunc::Memory));
1240   unc->init_req(TypeFunc::FramePtr,  alloc->in(TypeFunc::FramePtr));
1241   unc->init_req(TypeFunc::ReturnAdr, alloc->in(TypeFunc::ReturnAdr));
1242   unc->init_req(TypeFunc::Parms+0, unc_arg);
1243   unc->set_cnt(PROB_UNLIKELY_MAG(4));
1244   unc->copy_call_debug_info(igvn, alloc->as_Allocate());
1245   
1246   igvn->replace_input_of(alloc, 0, phase->C->top());
1247   
1248   igvn->register_new_node_with_optimizer(unc);
1249   
1250   Node* ctrl = phase->transform(new ProjNode(unc, TypeFunc::Control));
1251   Node* halt = phase->transform(new HaltNode(ctrl, alloc->in(TypeFunc::FramePtr)));
1252   phase->C->root()->add_req(halt);
1253 
1254   return true;
1255 }
1256 
1257 
1258 Node* CallStaticJavaNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1259   if (can_reshape && uncommon_trap_request() != 0) {
1260     if (remove_useless_allocation(phase, in(0), in(TypeFunc::Memory), in(TypeFunc::Parms))) {
1261       if (!in(0)->is_Region()) {
1262         PhaseIterGVN* igvn = phase->is_IterGVN();
1263         igvn->replace_input_of(this, 0, phase->C->top());
1264       }
1265       return this;
1266     }
1267   }
1268   return CallNode::Ideal(phase, can_reshape);
1269 }
1270 
1271 
1272 #ifndef PRODUCT
1273 void CallStaticJavaNode::dump_spec(outputStream *st) const {
1274   st->print("# Static ");
1275   if (_name != NULL) {
1276     st->print("%s", _name);
1277     int trap_req = uncommon_trap_request();
1278     if (trap_req != 0) {
1279       char buf[100];
1280       st->print("(%s)",
1281                  Deoptimization::format_trap_request(buf, sizeof(buf),
1282                                                      trap_req));
1283     }
1284     st->print(" ");
1285   }
1286   CallJavaNode::dump_spec(st);
1287 }
1288 
1289 void CallStaticJavaNode::dump_compact_spec(outputStream* st) const {
1290   if (_method) {
1291     _method->print_short_name(st);
1292   } else if (_name) {
1293     st->print("%s", _name);
1294   } else {
1295     st->print("<?>");
1296   }
1297 }
1298 #endif
1299 
1300 //=============================================================================
1301 uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
1302 bool CallDynamicJavaNode::cmp( const Node &n ) const {
1303   CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
1304   return CallJavaNode::cmp(call);
1305 }
1306 #ifndef PRODUCT
1307 void CallDynamicJavaNode::dump_spec(outputStream *st) const {
1308   st->print("# Dynamic ");
1309   CallJavaNode::dump_spec(st);
1310 }
1311 #endif
1312 
1313 //=============================================================================
1314 uint CallRuntimeNode::size_of() const { return sizeof(*this); }
1315 bool CallRuntimeNode::cmp( const Node &n ) const {
1316   CallRuntimeNode &call = (CallRuntimeNode&)n;
1317   return CallNode::cmp(call) && !strcmp(_name,call._name);
1318 }
1319 #ifndef PRODUCT
1320 void CallRuntimeNode::dump_spec(outputStream *st) const {
1321   st->print("# ");
1322   st->print("%s", _name);
1323   CallNode::dump_spec(st);
1324 }
1325 #endif
1326 
1327 //------------------------------calling_convention-----------------------------
1328 void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
1329   if (_entry_point == NULL) {
1330     // The call to that stub is a special case: its inputs are
1331     // multiple values returned from a call and so it should follow
1332     // the return convention.
1333     SharedRuntime::java_return_convention(sig_bt, parm_regs, argcnt);
1334     return;
1335   }
1336   Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
1337 }
1338 
1339 //=============================================================================
1340 //------------------------------calling_convention-----------------------------
1341 
1342 
1343 //=============================================================================
1344 #ifndef PRODUCT
1345 void CallLeafNode::dump_spec(outputStream *st) const {
1346   st->print("# ");
1347   st->print("%s", _name);
1348   CallNode::dump_spec(st);
1349 }
1350 #endif
1351 
1352 uint CallLeafNoFPNode::match_edge(uint idx) const {
1353   // Null entry point is a special case for which the target is in a
1354   // register. Need to match that edge.
1355   return entry_point() == NULL && idx == TypeFunc::Parms;
1356 }
1357 
1358 //=============================================================================
1359 
1360 void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
1361   assert(verify_jvms(jvms), "jvms must match");
1362   int loc = jvms->locoff() + idx;
1363   if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
1364     // If current local idx is top then local idx - 1 could
1365     // be a long/double that needs to be killed since top could
1366     // represent the 2nd half ofthe long/double.
1367     uint ideal = in(loc -1)->ideal_reg();
1368     if (ideal == Op_RegD || ideal == Op_RegL) {
1369       // set other (low index) half to top
1370       set_req(loc - 1, in(loc));
1371     }
1372   }
1373   set_req(loc, c);
1374 }
1375 
1376 uint SafePointNode::size_of() const { return sizeof(*this); }
1377 bool SafePointNode::cmp( const Node &n ) const {
1378   return (&n == this);          // Always fail except on self
1379 }
1380 
1381 //-------------------------set_next_exception----------------------------------
1382 void SafePointNode::set_next_exception(SafePointNode* n) {
1383   assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
1384   if (len() == req()) {
1385     if (n != NULL)  add_prec(n);
1386   } else {
1387     set_prec(req(), n);
1388   }
1389 }
1390 
1391 
1392 //----------------------------next_exception-----------------------------------
1393 SafePointNode* SafePointNode::next_exception() const {
1394   if (len() == req()) {
1395     return NULL;
1396   } else {
1397     Node* n = in(req());
1398     assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
1399     return (SafePointNode*) n;
1400   }
1401 }
1402 
1403 
1404 //------------------------------Ideal------------------------------------------
1405 // Skip over any collapsed Regions
1406 Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1407   return remove_dead_region(phase, can_reshape) ? this : NULL;
1408 }
1409 
1410 //------------------------------Identity---------------------------------------
1411 // Remove obviously duplicate safepoints
1412 Node* SafePointNode::Identity(PhaseGVN* phase) {
1413 
1414   // If you have back to back safepoints, remove one
1415   if( in(TypeFunc::Control)->is_SafePoint() )
1416     return in(TypeFunc::Control);
1417 
1418   if( in(0)->is_Proj() ) {
1419     Node *n0 = in(0)->in(0);
1420     // Check if he is a call projection (except Leaf Call)
1421     if( n0->is_Catch() ) {
1422       n0 = n0->in(0)->in(0);
1423       assert( n0->is_Call(), "expect a call here" );
1424     }
1425     if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
1426       // Don't remove a safepoint belonging to an OuterStripMinedLoopEndNode.
1427       // If the loop dies, they will be removed together.
1428       if (has_out_with(Op_OuterStripMinedLoopEnd)) {
1429         return this;
1430       }
1431       // Useless Safepoint, so remove it
1432       return in(TypeFunc::Control);
1433     }
1434   }
1435 
1436   return this;
1437 }
1438 
1439 //------------------------------Value------------------------------------------
1440 const Type* SafePointNode::Value(PhaseGVN* phase) const {
1441   if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
1442   if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
1443   return Type::CONTROL;
1444 }
1445 
1446 #ifndef PRODUCT
1447 void SafePointNode::dump_spec(outputStream *st) const {
1448   st->print(" SafePoint ");
1449   _replaced_nodes.dump(st);
1450 }
1451 
1452 // The related nodes of a SafepointNode are all data inputs, excluding the
1453 // control boundary, as well as all outputs till level 2 (to include projection
1454 // nodes and targets). In compact mode, just include inputs till level 1 and
1455 // outputs as before.
1456 void SafePointNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1457   if (compact) {
1458     this->collect_nodes(in_rel, 1, false, false);
1459   } else {
1460     this->collect_nodes_in_all_data(in_rel, false);
1461   }
1462   this->collect_nodes(out_rel, -2, false, false);
1463 }
1464 #endif
1465 
1466 const RegMask &SafePointNode::in_RegMask(uint idx) const {
1467   if( idx < TypeFunc::Parms ) return RegMask::Empty;
1468   // Values outside the domain represent debug info
1469   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1470 }
1471 const RegMask &SafePointNode::out_RegMask() const {
1472   return RegMask::Empty;
1473 }
1474 
1475 
1476 void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
1477   assert((int)grow_by > 0, "sanity");
1478   int monoff = jvms->monoff();
1479   int scloff = jvms->scloff();
1480   int endoff = jvms->endoff();
1481   assert(endoff == (int)req(), "no other states or debug info after me");
1482   Node* top = Compile::current()->top();
1483   for (uint i = 0; i < grow_by; i++) {
1484     ins_req(monoff, top);
1485   }
1486   jvms->set_monoff(monoff + grow_by);
1487   jvms->set_scloff(scloff + grow_by);
1488   jvms->set_endoff(endoff + grow_by);
1489 }
1490 
1491 void SafePointNode::push_monitor(const FastLockNode *lock) {
1492   // Add a LockNode, which points to both the original BoxLockNode (the
1493   // stack space for the monitor) and the Object being locked.
1494   const int MonitorEdges = 2;
1495   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1496   assert(req() == jvms()->endoff(), "correct sizing");
1497   int nextmon = jvms()->scloff();
1498   if (GenerateSynchronizationCode) {
1499     ins_req(nextmon,   lock->box_node());
1500     ins_req(nextmon+1, lock->obj_node());
1501   } else {
1502     Node* top = Compile::current()->top();
1503     ins_req(nextmon, top);
1504     ins_req(nextmon, top);
1505   }
1506   jvms()->set_scloff(nextmon + MonitorEdges);
1507   jvms()->set_endoff(req());
1508 }
1509 
1510 void SafePointNode::pop_monitor() {
1511   // Delete last monitor from debug info
1512   debug_only(int num_before_pop = jvms()->nof_monitors());
1513   const int MonitorEdges = 2;
1514   assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1515   int scloff = jvms()->scloff();
1516   int endoff = jvms()->endoff();
1517   int new_scloff = scloff - MonitorEdges;
1518   int new_endoff = endoff - MonitorEdges;
1519   jvms()->set_scloff(new_scloff);
1520   jvms()->set_endoff(new_endoff);
1521   while (scloff > new_scloff)  del_req_ordered(--scloff);
1522   assert(jvms()->nof_monitors() == num_before_pop-1, "");
1523 }
1524 
1525 Node *SafePointNode::peek_monitor_box() const {
1526   int mon = jvms()->nof_monitors() - 1;
1527   assert(mon >= 0, "must have a monitor");
1528   return monitor_box(jvms(), mon);
1529 }
1530 
1531 Node *SafePointNode::peek_monitor_obj() const {
1532   int mon = jvms()->nof_monitors() - 1;
1533   assert(mon >= 0, "must have a monitor");
1534   return monitor_obj(jvms(), mon);
1535 }
1536 
1537 // Do we Match on this edge index or not?  Match no edges
1538 uint SafePointNode::match_edge(uint idx) const {
1539   if( !needs_polling_address_input() )
1540     return 0;
1541 
1542   return (TypeFunc::Parms == idx);
1543 }
1544 
1545 void SafePointNode::disconnect_from_root(PhaseIterGVN *igvn) {
1546   assert(Opcode() == Op_SafePoint, "only value for safepoint in loops");
1547   int nb = igvn->C->root()->find_prec_edge(this);
1548   if (nb != -1) {
1549     igvn->C->root()->rm_prec(nb);
1550   }
1551 }
1552 
1553 //==============  SafePointScalarObjectNode  ==============
1554 
1555 SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
1556 #ifdef ASSERT
1557                                                      AllocateNode* alloc,
1558 #endif
1559                                                      uint first_index,
1560                                                      uint n_fields) :
1561   TypeNode(tp, 1), // 1 control input -- seems required.  Get from root.
1562   _first_index(first_index),
1563   _n_fields(n_fields)
1564 #ifdef ASSERT
1565   , _alloc(alloc)
1566 #endif
1567 {
1568   init_class_id(Class_SafePointScalarObject);
1569 }
1570 
1571 // Do not allow value-numbering for SafePointScalarObject node.
1572 uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
1573 bool SafePointScalarObjectNode::cmp( const Node &n ) const {
1574   return (&n == this); // Always fail except on self
1575 }
1576 
1577 uint SafePointScalarObjectNode::ideal_reg() const {
1578   return 0; // No matching to machine instruction
1579 }
1580 
1581 const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
1582   return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1583 }
1584 
1585 const RegMask &SafePointScalarObjectNode::out_RegMask() const {
1586   return RegMask::Empty;
1587 }
1588 
1589 uint SafePointScalarObjectNode::match_edge(uint idx) const {
1590   return 0;
1591 }
1592 
1593 SafePointScalarObjectNode*
1594 SafePointScalarObjectNode::clone(Dict* sosn_map) const {
1595   void* cached = (*sosn_map)[(void*)this];
1596   if (cached != NULL) {
1597     return (SafePointScalarObjectNode*)cached;
1598   }
1599   SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
1600   sosn_map->Insert((void*)this, (void*)res);
1601   return res;
1602 }
1603 
1604 
1605 #ifndef PRODUCT
1606 void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
1607   st->print(" # fields@[%d..%d]", first_index(),
1608              first_index() + n_fields() - 1);
1609 }
1610 
1611 #endif
1612 
1613 //=============================================================================
1614 uint AllocateNode::size_of() const { return sizeof(*this); }
1615 
1616 AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
1617                            Node *ctrl, Node *mem, Node *abio,
1618                            Node *size, Node *klass_node,
1619                            Node* initial_test,
1620                            ValueTypeBaseNode* value_node)
1621   : CallNode(atype, NULL, TypeRawPtr::BOTTOM)
1622 {
1623   init_class_id(Class_Allocate);
1624   init_flags(Flag_is_macro);
1625   _is_scalar_replaceable = false;
1626   _is_non_escaping = false;
1627   _is_allocation_MemBar_redundant = false;
1628   _larval = false;
1629   Node *topnode = C->top();
1630 
1631   init_req( TypeFunc::Control  , ctrl );
1632   init_req( TypeFunc::I_O      , abio );
1633   init_req( TypeFunc::Memory   , mem );
1634   init_req( TypeFunc::ReturnAdr, topnode );
1635   init_req( TypeFunc::FramePtr , topnode );
1636   init_req( AllocSize          , size);
1637   init_req( KlassNode          , klass_node);
1638   init_req( InitialTest        , initial_test);
1639   init_req( ALength            , topnode);
1640   init_req( ValueNode          , value_node);
1641   // DefaultValue defaults to NULL
1642   // RawDefaultValue defaults to NULL
1643   // StorageProperties defaults to NULL
1644   C->add_macro_node(this);
1645 }
1646 
1647 void AllocateNode::compute_MemBar_redundancy(ciMethod* initializer)
1648 {
1649   assert(initializer != NULL &&
1650          initializer->is_object_constructor_or_class_initializer(),
1651          "unexpected initializer method");
1652   BCEscapeAnalyzer* analyzer = initializer->get_bcea();
1653   if (analyzer == NULL) {
1654     return;
1655   }
1656 
1657   // Allocation node is first parameter in its initializer
1658   if (analyzer->is_arg_stack(0) || analyzer->is_arg_local(0)) {
1659     _is_allocation_MemBar_redundant = true;
1660   }
1661 }
1662 
1663 Node* AllocateNode::Ideal(PhaseGVN* phase, bool can_reshape) {
1664   // Check for unused value type allocation
1665   if (can_reshape && in(AllocateNode::ValueNode) != NULL &&
1666       outcnt() != 0 && result_cast() == NULL) {
1667     // Remove allocation by replacing the projection nodes with its inputs
1668     InitializeNode* init = initialization();
1669     PhaseIterGVN* igvn = phase->is_IterGVN();
1670     CallProjections* projs = extract_projections(true, false);
1671     assert(projs->nb_resproj <= 1, "unexpected number of results");
1672     if (projs->fallthrough_catchproj != NULL) {
1673       igvn->replace_node(projs->fallthrough_catchproj, in(TypeFunc::Control));
1674     }
1675     if (projs->fallthrough_memproj != NULL) {
1676       igvn->replace_node(projs->fallthrough_memproj, in(TypeFunc::Memory));
1677     }
1678     if (projs->catchall_memproj != NULL) {
1679       igvn->replace_node(projs->catchall_memproj, phase->C->top());
1680     }
1681     if (projs->fallthrough_ioproj != NULL) {
1682       igvn->replace_node(projs->fallthrough_ioproj, in(TypeFunc::I_O));
1683     }
1684     if (projs->catchall_ioproj != NULL) {
1685       igvn->replace_node(projs->catchall_ioproj, phase->C->top());
1686     }
1687     if (projs->catchall_catchproj != NULL) {
1688       igvn->replace_node(projs->catchall_catchproj, phase->C->top());
1689     }
1690     if (projs->resproj[0] != NULL) {
1691       igvn->replace_node(projs->resproj[0], phase->C->top());
1692     }
1693     igvn->replace_node(this, phase->C->top());
1694     if (init != NULL) {
1695       Node* ctrl_proj = init->proj_out_or_null(TypeFunc::Control);
1696       Node* mem_proj = init->proj_out_or_null(TypeFunc::Memory);
1697       if (ctrl_proj != NULL) {
1698         igvn->replace_node(ctrl_proj, init->in(TypeFunc::Control));
1699       }
1700       if (mem_proj != NULL) {
1701         igvn->replace_node(mem_proj, init->in(TypeFunc::Memory));
1702       }
1703     }
1704     return NULL;
1705   }
1706 
1707   return CallNode::Ideal(phase, can_reshape);
1708 }
1709 
1710 Node *AllocateNode::make_ideal_mark(PhaseGVN *phase, Node* obj, Node* control, Node* mem, Node* klass_node) {
1711   Node* mark_node = NULL;
1712   // For now only enable fast locking for non-array types
1713   if ((EnableValhalla || UseBiasedLocking) && Opcode() == Op_Allocate) {
1714     if (klass_node == NULL) {
1715       Node* k_adr = phase->transform(new AddPNode(obj, obj, phase->MakeConX(oopDesc::klass_offset_in_bytes())));
1716       klass_node = phase->transform(LoadKlassNode::make(*phase, NULL, phase->C->immutable_memory(), k_adr, phase->type(k_adr)->is_ptr()));
1717     }
1718     Node* proto_adr = phase->transform(new AddPNode(klass_node, klass_node, phase->MakeConX(in_bytes(Klass::prototype_header_offset()))));
1719     mark_node = LoadNode::make(*phase, control, mem, proto_adr, TypeRawPtr::BOTTOM, TypeX_X, TypeX_X->basic_type(), MemNode::unordered);
1720   } else {
1721     mark_node = phase->MakeConX((jlong)markWord::prototype().value());
1722   }
1723   mark_node = phase->transform(mark_node);
1724   // Avoid returning a constant (old node) here because this method is used by LoadNode::Ideal
1725   return new OrXNode(mark_node, phase->MakeConX(_larval ? markWord::larval_state_pattern : 0));
1726 }
1727 
1728 
1729 //=============================================================================
1730 Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1731   Node* res = SafePointNode::Ideal(phase, can_reshape);
1732   if (res != NULL) {
1733     return res;
1734   }
1735   // Don't bother trying to transform a dead node
1736   if (in(0) && in(0)->is_top())  return NULL;
1737 
1738   const Type* type = phase->type(Ideal_length());
1739   if (type->isa_int() && type->is_int()->_hi < 0) {
1740     if (can_reshape) {
1741       PhaseIterGVN *igvn = phase->is_IterGVN();
1742       // Unreachable fall through path (negative array length),
1743       // the allocation can only throw so disconnect it.
1744       Node* proj = proj_out_or_null(TypeFunc::Control);
1745       Node* catchproj = NULL;
1746       if (proj != NULL) {
1747         for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
1748           Node *cn = proj->fast_out(i);
1749           if (cn->is_Catch()) {
1750             catchproj = cn->as_Multi()->proj_out_or_null(CatchProjNode::fall_through_index);
1751             break;
1752           }
1753         }
1754       }
1755       if (catchproj != NULL && catchproj->outcnt() > 0 &&
1756           (catchproj->outcnt() > 1 ||
1757            catchproj->unique_out()->Opcode() != Op_Halt)) {
1758         assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
1759         Node* nproj = catchproj->clone();
1760         igvn->register_new_node_with_optimizer(nproj);
1761 
1762         Node *frame = new ParmNode( phase->C->start(), TypeFunc::FramePtr );
1763         frame = phase->transform(frame);
1764         // Halt & Catch Fire
1765         Node *halt = new HaltNode( nproj, frame );
1766         phase->C->root()->add_req(halt);
1767         phase->transform(halt);
1768 
1769         igvn->replace_node(catchproj, phase->C->top());
1770         return this;
1771       }
1772     } else {
1773       // Can't correct it during regular GVN so register for IGVN
1774       phase->C->record_for_igvn(this);
1775     }
1776   }
1777   return NULL;
1778 }
1779 
1780 // Retrieve the length from the AllocateArrayNode. Narrow the type with a
1781 // CastII, if appropriate.  If we are not allowed to create new nodes, and
1782 // a CastII is appropriate, return NULL.
1783 Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
1784   Node *length = in(AllocateNode::ALength);
1785   assert(length != NULL, "length is not null");
1786 
1787   const TypeInt* length_type = phase->find_int_type(length);
1788   const TypeAryPtr* ary_type = oop_type->isa_aryptr();
1789 
1790   if (ary_type != NULL && length_type != NULL) {
1791     const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
1792     if (narrow_length_type != length_type) {
1793       // Assert one of:
1794       //   - the narrow_length is 0
1795       //   - the narrow_length is not wider than length
1796       assert(narrow_length_type == TypeInt::ZERO ||
1797              length_type->is_con() && narrow_length_type->is_con() &&
1798                 (narrow_length_type->_hi <= length_type->_lo) ||
1799              (narrow_length_type->_hi <= length_type->_hi &&
1800               narrow_length_type->_lo >= length_type->_lo),
1801              "narrow type must be narrower than length type");
1802 
1803       // Return NULL if new nodes are not allowed
1804       if (!allow_new_nodes) return NULL;
1805       // Create a cast which is control dependent on the initialization to
1806       // propagate the fact that the array length must be positive.
1807       InitializeNode* init = initialization();
1808       assert(init != NULL, "initialization not found");
1809       length = new CastIINode(length, narrow_length_type);
1810       length->set_req(0, init->proj_out_or_null(0));
1811     }
1812   }
1813 
1814   return length;
1815 }
1816 
1817 //=============================================================================
1818 uint LockNode::size_of() const { return sizeof(*this); }
1819 
1820 // Redundant lock elimination
1821 //
1822 // There are various patterns of locking where we release and
1823 // immediately reacquire a lock in a piece of code where no operations
1824 // occur in between that would be observable.  In those cases we can
1825 // skip releasing and reacquiring the lock without violating any
1826 // fairness requirements.  Doing this around a loop could cause a lock
1827 // to be held for a very long time so we concentrate on non-looping
1828 // control flow.  We also require that the operations are fully
1829 // redundant meaning that we don't introduce new lock operations on
1830 // some paths so to be able to eliminate it on others ala PRE.  This
1831 // would probably require some more extensive graph manipulation to
1832 // guarantee that the memory edges were all handled correctly.
1833 //
1834 // Assuming p is a simple predicate which can't trap in any way and s
1835 // is a synchronized method consider this code:
1836 //
1837 //   s();
1838 //   if (p)
1839 //     s();
1840 //   else
1841 //     s();
1842 //   s();
1843 //
1844 // 1. The unlocks of the first call to s can be eliminated if the
1845 // locks inside the then and else branches are eliminated.
1846 //
1847 // 2. The unlocks of the then and else branches can be eliminated if
1848 // the lock of the final call to s is eliminated.
1849 //
1850 // Either of these cases subsumes the simple case of sequential control flow
1851 //
1852 // Addtionally we can eliminate versions without the else case:
1853 //
1854 //   s();
1855 //   if (p)
1856 //     s();
1857 //   s();
1858 //
1859 // 3. In this case we eliminate the unlock of the first s, the lock
1860 // and unlock in the then case and the lock in the final s.
1861 //
1862 // Note also that in all these cases the then/else pieces don't have
1863 // to be trivial as long as they begin and end with synchronization
1864 // operations.
1865 //
1866 //   s();
1867 //   if (p)
1868 //     s();
1869 //     f();
1870 //     s();
1871 //   s();
1872 //
1873 // The code will work properly for this case, leaving in the unlock
1874 // before the call to f and the relock after it.
1875 //
1876 // A potentially interesting case which isn't handled here is when the
1877 // locking is partially redundant.
1878 //
1879 //   s();
1880 //   if (p)
1881 //     s();
1882 //
1883 // This could be eliminated putting unlocking on the else case and
1884 // eliminating the first unlock and the lock in the then side.
1885 // Alternatively the unlock could be moved out of the then side so it
1886 // was after the merge and the first unlock and second lock
1887 // eliminated.  This might require less manipulation of the memory
1888 // state to get correct.
1889 //
1890 // Additionally we might allow work between a unlock and lock before
1891 // giving up eliminating the locks.  The current code disallows any
1892 // conditional control flow between these operations.  A formulation
1893 // similar to partial redundancy elimination computing the
1894 // availability of unlocking and the anticipatability of locking at a
1895 // program point would allow detection of fully redundant locking with
1896 // some amount of work in between.  I'm not sure how often I really
1897 // think that would occur though.  Most of the cases I've seen
1898 // indicate it's likely non-trivial work would occur in between.
1899 // There may be other more complicated constructs where we could
1900 // eliminate locking but I haven't seen any others appear as hot or
1901 // interesting.
1902 //
1903 // Locking and unlocking have a canonical form in ideal that looks
1904 // roughly like this:
1905 //
1906 //              <obj>
1907 //                | \\------+
1908 //                |  \       \
1909 //                | BoxLock   \
1910 //                |  |   |     \
1911 //                |  |    \     \
1912 //                |  |   FastLock
1913 //                |  |   /
1914 //                |  |  /
1915 //                |  |  |
1916 //
1917 //               Lock
1918 //                |
1919 //            Proj #0
1920 //                |
1921 //            MembarAcquire
1922 //                |
1923 //            Proj #0
1924 //
1925 //            MembarRelease
1926 //                |
1927 //            Proj #0
1928 //                |
1929 //              Unlock
1930 //                |
1931 //            Proj #0
1932 //
1933 //
1934 // This code proceeds by processing Lock nodes during PhaseIterGVN
1935 // and searching back through its control for the proper code
1936 // patterns.  Once it finds a set of lock and unlock operations to
1937 // eliminate they are marked as eliminatable which causes the
1938 // expansion of the Lock and Unlock macro nodes to make the operation a NOP
1939 //
1940 //=============================================================================
1941 
1942 //
1943 // Utility function to skip over uninteresting control nodes.  Nodes skipped are:
1944 //   - copy regions.  (These may not have been optimized away yet.)
1945 //   - eliminated locking nodes
1946 //
1947 static Node *next_control(Node *ctrl) {
1948   if (ctrl == NULL)
1949     return NULL;
1950   while (1) {
1951     if (ctrl->is_Region()) {
1952       RegionNode *r = ctrl->as_Region();
1953       Node *n = r->is_copy();
1954       if (n == NULL)
1955         break;  // hit a region, return it
1956       else
1957         ctrl = n;
1958     } else if (ctrl->is_Proj()) {
1959       Node *in0 = ctrl->in(0);
1960       if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
1961         ctrl = in0->in(0);
1962       } else {
1963         break;
1964       }
1965     } else {
1966       break; // found an interesting control
1967     }
1968   }
1969   return ctrl;
1970 }
1971 //
1972 // Given a control, see if it's the control projection of an Unlock which
1973 // operating on the same object as lock.
1974 //
1975 bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
1976                                             GrowableArray<AbstractLockNode*> &lock_ops) {
1977   ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
1978   if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
1979     Node *n = ctrl_proj->in(0);
1980     if (n != NULL && n->is_Unlock()) {
1981       UnlockNode *unlock = n->as_Unlock();
1982       BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
1983       Node* lock_obj = bs->step_over_gc_barrier(lock->obj_node());
1984       Node* unlock_obj = bs->step_over_gc_barrier(unlock->obj_node());
1985       if (lock_obj->eqv_uncast(unlock_obj) &&
1986           BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
1987           !unlock->is_eliminated()) {
1988         lock_ops.append(unlock);
1989         return true;
1990       }
1991     }
1992   }
1993   return false;
1994 }
1995 
1996 //
1997 // Find the lock matching an unlock.  Returns null if a safepoint
1998 // or complicated control is encountered first.
1999 LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
2000   LockNode *lock_result = NULL;
2001   // find the matching lock, or an intervening safepoint
2002   Node *ctrl = next_control(unlock->in(0));
2003   while (1) {
2004     assert(ctrl != NULL, "invalid control graph");
2005     assert(!ctrl->is_Start(), "missing lock for unlock");
2006     if (ctrl->is_top()) break;  // dead control path
2007     if (ctrl->is_Proj()) ctrl = ctrl->in(0);
2008     if (ctrl->is_SafePoint()) {
2009         break;  // found a safepoint (may be the lock we are searching for)
2010     } else if (ctrl->is_Region()) {
2011       // Check for a simple diamond pattern.  Punt on anything more complicated
2012       if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
2013         Node *in1 = next_control(ctrl->in(1));
2014         Node *in2 = next_control(ctrl->in(2));
2015         if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
2016              (in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
2017           ctrl = next_control(in1->in(0)->in(0));
2018         } else {
2019           break;
2020         }
2021       } else {
2022         break;
2023       }
2024     } else {
2025       ctrl = next_control(ctrl->in(0));  // keep searching
2026     }
2027   }
2028   if (ctrl->is_Lock()) {
2029     LockNode *lock = ctrl->as_Lock();
2030     BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2031     Node* lock_obj = bs->step_over_gc_barrier(lock->obj_node());
2032     Node* unlock_obj = bs->step_over_gc_barrier(unlock->obj_node());
2033     if (lock_obj->eqv_uncast(unlock_obj) &&
2034         BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
2035       lock_result = lock;
2036     }
2037   }
2038   return lock_result;
2039 }
2040 
2041 // This code corresponds to case 3 above.
2042 
2043 bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
2044                                                        GrowableArray<AbstractLockNode*> &lock_ops) {
2045   Node* if_node = node->in(0);
2046   bool  if_true = node->is_IfTrue();
2047 
2048   if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
2049     Node *lock_ctrl = next_control(if_node->in(0));
2050     if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
2051       Node* lock1_node = NULL;
2052       ProjNode* proj = if_node->as_If()->proj_out(!if_true);
2053       if (if_true) {
2054         if (proj->is_IfFalse() && proj->outcnt() == 1) {
2055           lock1_node = proj->unique_out();
2056         }
2057       } else {
2058         if (proj->is_IfTrue() && proj->outcnt() == 1) {
2059           lock1_node = proj->unique_out();
2060         }
2061       }
2062       if (lock1_node != NULL && lock1_node->is_Lock()) {
2063         LockNode *lock1 = lock1_node->as_Lock();
2064         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2065         Node* lock_obj = bs->step_over_gc_barrier(lock->obj_node());
2066         Node* lock1_obj = bs->step_over_gc_barrier(lock1->obj_node());
2067         if (lock_obj->eqv_uncast(lock1_obj) &&
2068             BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
2069             !lock1->is_eliminated()) {
2070           lock_ops.append(lock1);
2071           return true;
2072         }
2073       }
2074     }
2075   }
2076 
2077   lock_ops.trunc_to(0);
2078   return false;
2079 }
2080 
2081 bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
2082                                GrowableArray<AbstractLockNode*> &lock_ops) {
2083   // check each control merging at this point for a matching unlock.
2084   // in(0) should be self edge so skip it.
2085   for (int i = 1; i < (int)region->req(); i++) {
2086     Node *in_node = next_control(region->in(i));
2087     if (in_node != NULL) {
2088       if (find_matching_unlock(in_node, lock, lock_ops)) {
2089         // found a match so keep on checking.
2090         continue;
2091       } else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
2092         continue;
2093       }
2094 
2095       // If we fall through to here then it was some kind of node we
2096       // don't understand or there wasn't a matching unlock, so give
2097       // up trying to merge locks.
2098       lock_ops.trunc_to(0);
2099       return false;
2100     }
2101   }
2102   return true;
2103 
2104 }
2105 
2106 #ifndef PRODUCT
2107 //
2108 // Create a counter which counts the number of times this lock is acquired
2109 //
2110 void AbstractLockNode::create_lock_counter(JVMState* state) {
2111   _counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
2112 }
2113 
2114 void AbstractLockNode::set_eliminated_lock_counter() {
2115   if (_counter) {
2116     // Update the counter to indicate that this lock was eliminated.
2117     // The counter update code will stay around even though the
2118     // optimizer will eliminate the lock operation itself.
2119     _counter->set_tag(NamedCounter::EliminatedLockCounter);
2120   }
2121 }
2122 
2123 const char* AbstractLockNode::_kind_names[] = {"Regular", "NonEscObj", "Coarsened", "Nested"};
2124 
2125 void AbstractLockNode::dump_spec(outputStream* st) const {
2126   st->print("%s ", _kind_names[_kind]);
2127   CallNode::dump_spec(st);
2128 }
2129 
2130 void AbstractLockNode::dump_compact_spec(outputStream* st) const {
2131   st->print("%s", _kind_names[_kind]);
2132 }
2133 
2134 // The related set of lock nodes includes the control boundary.
2135 void AbstractLockNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
2136   if (compact) {
2137       this->collect_nodes(in_rel, 1, false, false);
2138     } else {
2139       this->collect_nodes_in_all_data(in_rel, true);
2140     }
2141     this->collect_nodes(out_rel, -2, false, false);
2142 }
2143 #endif
2144 
2145 //=============================================================================
2146 Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2147 
2148   // perform any generic optimizations first (returns 'this' or NULL)
2149   Node *result = SafePointNode::Ideal(phase, can_reshape);
2150   if (result != NULL)  return result;
2151   // Don't bother trying to transform a dead node
2152   if (in(0) && in(0)->is_top())  return NULL;
2153 
2154   // Now see if we can optimize away this lock.  We don't actually
2155   // remove the locking here, we simply set the _eliminate flag which
2156   // prevents macro expansion from expanding the lock.  Since we don't
2157   // modify the graph, the value returned from this function is the
2158   // one computed above.
2159   const Type* obj_type = phase->type(obj_node());
2160   if (can_reshape && EliminateLocks && !is_non_esc_obj() &&
2161       !obj_type->isa_valuetype() && !obj_type->is_valuetypeptr()) {
2162     //
2163     // If we are locking an unescaped object, the lock/unlock is unnecessary
2164     //
2165     ConnectionGraph *cgr = phase->C->congraph();
2166     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
2167       assert(!is_eliminated() || is_coarsened(), "sanity");
2168       // The lock could be marked eliminated by lock coarsening
2169       // code during first IGVN before EA. Replace coarsened flag
2170       // to eliminate all associated locks/unlocks.
2171 #ifdef ASSERT
2172       this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");
2173 #endif
2174       this->set_non_esc_obj();
2175       return result;
2176     }
2177 
2178     //
2179     // Try lock coarsening
2180     //
2181     PhaseIterGVN* iter = phase->is_IterGVN();
2182     if (iter != NULL && !is_eliminated()) {
2183 
2184       GrowableArray<AbstractLockNode*>   lock_ops;
2185 
2186       Node *ctrl = next_control(in(0));
2187 
2188       // now search back for a matching Unlock
2189       if (find_matching_unlock(ctrl, this, lock_ops)) {
2190         // found an unlock directly preceding this lock.  This is the
2191         // case of single unlock directly control dependent on a
2192         // single lock which is the trivial version of case 1 or 2.
2193       } else if (ctrl->is_Region() ) {
2194         if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
2195         // found lock preceded by multiple unlocks along all paths
2196         // joining at this point which is case 3 in description above.
2197         }
2198       } else {
2199         // see if this lock comes from either half of an if and the
2200         // predecessors merges unlocks and the other half of the if
2201         // performs a lock.
2202         if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
2203           // found unlock splitting to an if with locks on both branches.
2204         }
2205       }
2206 
2207       if (lock_ops.length() > 0) {
2208         // add ourselves to the list of locks to be eliminated.
2209         lock_ops.append(this);
2210 
2211   #ifndef PRODUCT
2212         if (PrintEliminateLocks) {
2213           int locks = 0;
2214           int unlocks = 0;
2215           for (int i = 0; i < lock_ops.length(); i++) {
2216             AbstractLockNode* lock = lock_ops.at(i);
2217             if (lock->Opcode() == Op_Lock)
2218               locks++;
2219             else
2220               unlocks++;
2221             if (Verbose) {
2222               lock->dump(1);
2223             }
2224           }
2225           tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
2226         }
2227   #endif
2228 
2229         // for each of the identified locks, mark them
2230         // as eliminatable
2231         for (int i = 0; i < lock_ops.length(); i++) {
2232           AbstractLockNode* lock = lock_ops.at(i);
2233 
2234           // Mark it eliminated by coarsening and update any counters
2235 #ifdef ASSERT
2236           lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");
2237 #endif
2238           lock->set_coarsened();
2239         }
2240       } else if (ctrl->is_Region() &&
2241                  iter->_worklist.member(ctrl)) {
2242         // We weren't able to find any opportunities but the region this
2243         // lock is control dependent on hasn't been processed yet so put
2244         // this lock back on the worklist so we can check again once any
2245         // region simplification has occurred.
2246         iter->_worklist.push(this);
2247       }
2248     }
2249   }
2250 
2251   return result;
2252 }
2253 
2254 //=============================================================================
2255 bool LockNode::is_nested_lock_region() {
2256   return is_nested_lock_region(NULL);
2257 }
2258 
2259 // p is used for access to compilation log; no logging if NULL
2260 bool LockNode::is_nested_lock_region(Compile * c) {
2261   BoxLockNode* box = box_node()->as_BoxLock();
2262   int stk_slot = box->stack_slot();
2263   if (stk_slot <= 0) {
2264 #ifdef ASSERT
2265     this->log_lock_optimization(c, "eliminate_lock_INLR_1");
2266 #endif
2267     return false; // External lock or it is not Box (Phi node).
2268   }
2269 
2270   // Ignore complex cases: merged locks or multiple locks.
2271   Node* obj = obj_node();
2272   LockNode* unique_lock = NULL;
2273   if (!box->is_simple_lock_region(&unique_lock, obj)) {
2274 #ifdef ASSERT
2275     this->log_lock_optimization(c, "eliminate_lock_INLR_2a");
2276 #endif
2277     return false;
2278   }
2279   if (unique_lock != this) {
2280 #ifdef ASSERT
2281     this->log_lock_optimization(c, "eliminate_lock_INLR_2b");
2282 #endif
2283     return false;
2284   }
2285 
2286   BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
2287   obj = bs->step_over_gc_barrier(obj);
2288   // Look for external lock for the same object.
2289   SafePointNode* sfn = this->as_SafePoint();
2290   JVMState* youngest_jvms = sfn->jvms();
2291   int max_depth = youngest_jvms->depth();
2292   for (int depth = 1; depth <= max_depth; depth++) {
2293     JVMState* jvms = youngest_jvms->of_depth(depth);
2294     int num_mon  = jvms->nof_monitors();
2295     // Loop over monitors
2296     for (int idx = 0; idx < num_mon; idx++) {
2297       Node* obj_node = sfn->monitor_obj(jvms, idx);
2298       obj_node = bs->step_over_gc_barrier(obj_node);
2299       BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
2300       if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
2301         return true;
2302       }
2303     }
2304   }
2305 #ifdef ASSERT
2306   this->log_lock_optimization(c, "eliminate_lock_INLR_3");
2307 #endif
2308   return false;
2309 }
2310 
2311 //=============================================================================
2312 uint UnlockNode::size_of() const { return sizeof(*this); }
2313 
2314 //=============================================================================
2315 Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
2316 
2317   // perform any generic optimizations first (returns 'this' or NULL)
2318   Node *result = SafePointNode::Ideal(phase, can_reshape);
2319   if (result != NULL)  return result;
2320   // Don't bother trying to transform a dead node
2321   if (in(0) && in(0)->is_top())  return NULL;
2322 
2323   // Now see if we can optimize away this unlock.  We don't actually
2324   // remove the unlocking here, we simply set the _eliminate flag which
2325   // prevents macro expansion from expanding the unlock.  Since we don't
2326   // modify the graph, the value returned from this function is the
2327   // one computed above.
2328   // Escape state is defined after Parse phase.
2329   const Type* obj_type = phase->type(obj_node());
2330   if (can_reshape && EliminateLocks && !is_non_esc_obj() &&
2331       !obj_type->isa_valuetype() && !obj_type->is_valuetypeptr()) {
2332     //
2333     // If we are unlocking an unescaped object, the lock/unlock is unnecessary.
2334     //
2335     ConnectionGraph *cgr = phase->C->congraph();
2336     if (cgr != NULL && cgr->not_global_escape(obj_node())) {
2337       assert(!is_eliminated() || is_coarsened(), "sanity");
2338       // The lock could be marked eliminated by lock coarsening
2339       // code during first IGVN before EA. Replace coarsened flag
2340       // to eliminate all associated locks/unlocks.
2341 #ifdef ASSERT
2342       this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");
2343 #endif
2344       this->set_non_esc_obj();
2345     }
2346   }
2347   return result;
2348 }
2349 
2350 const char * AbstractLockNode::kind_as_string() const {
2351   return is_coarsened()   ? "coarsened" :
2352          is_nested()      ? "nested" :
2353          is_non_esc_obj() ? "non_escaping" :
2354          "?";
2355 }
2356 
2357 void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag)  const {
2358   if (C == NULL) {
2359     return;
2360   }
2361   CompileLog* log = C->log();
2362   if (log != NULL) {
2363     log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",
2364           tag, is_Lock(), C->compile_id(),
2365           is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",
2366           kind_as_string());
2367     log->stamp();
2368     log->end_head();
2369     JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();
2370     while (p != NULL) {
2371       log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
2372       p = p->caller();
2373     }
2374     log->tail(tag);
2375   }
2376 }
2377 
2378 bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeOopPtr *t_oop, PhaseTransform *phase) {
2379   if (dest_t->is_known_instance() && t_oop->is_known_instance()) {
2380     return dest_t->instance_id() == t_oop->instance_id();
2381   }
2382 
2383   if (dest_t->isa_instptr() && !dest_t->klass()->equals(phase->C->env()->Object_klass())) {
2384     // clone
2385     if (t_oop->isa_aryptr()) {
2386       return false;
2387     }
2388     if (!t_oop->isa_instptr()) {
2389       return true;
2390     }
2391     if (dest_t->klass()->is_subtype_of(t_oop->klass()) || t_oop->klass()->is_subtype_of(dest_t->klass())) {
2392       return true;
2393     }
2394     // unrelated
2395     return false;
2396   }
2397 
2398   if (dest_t->isa_aryptr()) {
2399     // arraycopy or array clone
2400     if (t_oop->isa_instptr()) {
2401       return false;
2402     }
2403     if (!t_oop->isa_aryptr()) {
2404       return true;
2405     }
2406 
2407     const Type* elem = dest_t->is_aryptr()->elem();
2408     if (elem == Type::BOTTOM) {
2409       // An array but we don't know what elements are
2410       return true;
2411     }
2412 
2413     dest_t = dest_t->is_aryptr()->with_field_offset(Type::OffsetBot)->add_offset(Type::OffsetBot)->is_oopptr();
2414     t_oop = t_oop->is_aryptr()->with_field_offset(Type::OffsetBot);
2415     uint dest_alias = phase->C->get_alias_index(dest_t);
2416     uint t_oop_alias = phase->C->get_alias_index(t_oop);
2417 
2418     return dest_alias == t_oop_alias;
2419   }
2420 
2421   return true;
2422 }