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