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