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