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