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