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