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
43// Portions of code courtesy of Clifford Click
44
45// Optimization - Graph Style
46
47//=============================================================================
48uint StartNode::size_of() const { return sizeof(*this); }
49uint StartNode::cmp( const Node &n ) const
50{ return _domain == ((StartNode&)n)._domain; }
51const Type *StartNode::bottom_type() const { return _domain; }
52const Type* StartNode::Value(PhaseGVN* phase) const { return _domain; }
53#ifndef PRODUCT
54void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}
55void StartNode::dump_compact_spec(outputStream *st) const { /* empty */ }
56#endif
57
58//------------------------------Ideal------------------------------------------
59Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){
60  return remove_dead_region(phase, can_reshape) ? this : NULL;
61}
62
63//------------------------------calling_convention-----------------------------
64void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
65  Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );
66}
67
68//------------------------------Registers--------------------------------------
69const RegMask &StartNode::in_RegMask(uint) const {
70  return RegMask::Empty;
71}
72
73//------------------------------match------------------------------------------
74// Construct projections for incoming parameters, and their RegMask info
75Node *StartNode::match( const ProjNode *proj, const Matcher *match ) {
76  switch (proj->_con) {
77  case TypeFunc::Control:
78  case TypeFunc::I_O:
79  case TypeFunc::Memory:
80    return new MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);
81  case TypeFunc::FramePtr:
82    return new MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);
83  case TypeFunc::ReturnAdr:
84    return new MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);
85  case TypeFunc::Parms:
86  default: {
87      uint parm_num = proj->_con - TypeFunc::Parms;
88      const Type *t = _domain->field_at(proj->_con);
89      if (t->base() == Type::Half)  // 2nd half of Longs and Doubles
90        return new ConNode(Type::TOP);
91      uint ideal_reg = t->ideal_reg();
92      RegMask &rm = match->_calling_convention_mask[parm_num];
93      return new MachProjNode(this,proj->_con,rm,ideal_reg);
94    }
95  }
96  return NULL;
97}
98
99//------------------------------StartOSRNode----------------------------------
100// The method start node for an on stack replacement adapter
101
102//------------------------------osr_domain-----------------------------
103const TypeTuple *StartOSRNode::osr_domain() {
104  const Type **fields = TypeTuple::fields(2);
105  fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM;  // address of osr buffer
106
107  return TypeTuple::make(TypeFunc::Parms+1, fields);
108}
109
110//=============================================================================
111const char * const ParmNode::names[TypeFunc::Parms+1] = {
112  "Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"
113};
114
115#ifndef PRODUCT
116void ParmNode::dump_spec(outputStream *st) const {
117  if( _con < TypeFunc::Parms ) {
118    st->print("%s", names[_con]);
119  } else {
120    st->print("Parm%d: ",_con-TypeFunc::Parms);
121    // Verbose and WizardMode dump bottom_type for all nodes
122    if( !Verbose && !WizardMode )   bottom_type()->dump_on(st);
123  }
124}
125
126void ParmNode::dump_compact_spec(outputStream *st) const {
127  if (_con < TypeFunc::Parms) {
128    st->print("%s", names[_con]);
129  } else {
130    st->print("%d:", _con-TypeFunc::Parms);
131    // unconditionally dump bottom_type
132    bottom_type()->dump_on(st);
133  }
134}
135
136// For a ParmNode, all immediate inputs and outputs are considered relevant
137// both in compact and standard representation.
138void ParmNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
139  this->collect_nodes(in_rel, 1, false, false);
140  this->collect_nodes(out_rel, -1, false, false);
141}
142#endif
143
144uint ParmNode::ideal_reg() const {
145  switch( _con ) {
146  case TypeFunc::Control  : // fall through
147  case TypeFunc::I_O      : // fall through
148  case TypeFunc::Memory   : return 0;
149  case TypeFunc::FramePtr : // fall through
150  case TypeFunc::ReturnAdr: return Op_RegP;
151  default                 : assert( _con > TypeFunc::Parms, "" );
152    // fall through
153  case TypeFunc::Parms    : {
154    // Type of argument being passed
155    const Type *t = in(0)->as_Start()->_domain->field_at(_con);
156    return t->ideal_reg();
157  }
158  }
159  ShouldNotReachHere();
160  return 0;
161}
162
163//=============================================================================
164ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {
165  init_req(TypeFunc::Control,cntrl);
166  init_req(TypeFunc::I_O,i_o);
167  init_req(TypeFunc::Memory,memory);
168  init_req(TypeFunc::FramePtr,frameptr);
169  init_req(TypeFunc::ReturnAdr,retadr);
170}
171
172Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){
173  return remove_dead_region(phase, can_reshape) ? this : NULL;
174}
175
176const Type* ReturnNode::Value(PhaseGVN* phase) const {
177  return ( phase->type(in(TypeFunc::Control)) == Type::TOP)
178    ? Type::TOP
179    : Type::BOTTOM;
180}
181
182// Do we Match on this edge index or not?  No edges on return nodes
183uint ReturnNode::match_edge(uint idx) const {
184  return 0;
185}
186
187
188#ifndef PRODUCT
189void ReturnNode::dump_req(outputStream *st) const {
190  // Dump the required inputs, enclosed in '(' and ')'
191  uint i;                       // Exit value of loop
192  for (i = 0; i < req(); i++) {    // For all required inputs
193    if (i == TypeFunc::Parms) st->print("returns");
194    if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
195    else st->print("_ ");
196  }
197}
198#endif
199
200//=============================================================================
201RethrowNode::RethrowNode(
202  Node* cntrl,
203  Node* i_o,
204  Node* memory,
205  Node* frameptr,
206  Node* ret_adr,
207  Node* exception
208) : Node(TypeFunc::Parms + 1) {
209  init_req(TypeFunc::Control  , cntrl    );
210  init_req(TypeFunc::I_O      , i_o      );
211  init_req(TypeFunc::Memory   , memory   );
212  init_req(TypeFunc::FramePtr , frameptr );
213  init_req(TypeFunc::ReturnAdr, ret_adr);
214  init_req(TypeFunc::Parms    , exception);
215}
216
217Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){
218  return remove_dead_region(phase, can_reshape) ? this : NULL;
219}
220
221const Type* RethrowNode::Value(PhaseGVN* phase) const {
222  return (phase->type(in(TypeFunc::Control)) == Type::TOP)
223    ? Type::TOP
224    : Type::BOTTOM;
225}
226
227uint RethrowNode::match_edge(uint idx) const {
228  return 0;
229}
230
231#ifndef PRODUCT
232void RethrowNode::dump_req(outputStream *st) const {
233  // Dump the required inputs, enclosed in '(' and ')'
234  uint i;                       // Exit value of loop
235  for (i = 0; i < req(); i++) {    // For all required inputs
236    if (i == TypeFunc::Parms) st->print("exception");
237    if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);
238    else st->print("_ ");
239  }
240}
241#endif
242
243//=============================================================================
244// Do we Match on this edge index or not?  Match only target address & method
245uint TailCallNode::match_edge(uint idx) const {
246  return TypeFunc::Parms <= idx  &&  idx <= TypeFunc::Parms+1;
247}
248
249//=============================================================================
250// Do we Match on this edge index or not?  Match only target address & oop
251uint TailJumpNode::match_edge(uint idx) const {
252  return TypeFunc::Parms <= idx  &&  idx <= TypeFunc::Parms+1;
253}
254
255//=============================================================================
256JVMState::JVMState(ciMethod* method, JVMState* caller) :
257  _method(method) {
258  assert(method != NULL, "must be valid call site");
259  _bci = InvocationEntryBci;
260  _reexecute = Reexecute_Undefined;
261  debug_only(_bci = -99);  // random garbage value
262  debug_only(_map = (SafePointNode*)-1);
263  _caller = caller;
264  _depth  = 1 + (caller == 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}
272JVMState::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-------------------------------------
288JVMState* 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-----------------------------------
299bool 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------------------------------------
317uint 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-------------------------------------
324uint 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------------------------------------
331uint 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.
344static 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-----------------------------------------
405void 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
514void 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
547void 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.
580void dump_jvms(JVMState* jvms) {
581  jvms->dump();
582}
583#endif
584
585//--------------------------clone_shallow--------------------------------------
586JVMState* 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----------------------------------------
601JVMState* 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 */
614void 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.
622void 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?
635int 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//=============================================================================
666uint CallNode::cmp( const Node &n ) const
667{ return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }
668#ifndef PRODUCT
669void 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
680void 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
688const Type *CallNode::bottom_type() const { return tf()->range(); }
689const 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-----------------------------
695void 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
704Node *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
736uint 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//
744bool 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();
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      Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;
788      if (proj != NULL) {
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();
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?
810bool CallNode::has_non_debug_use(Node *n) {
811  const TypeTuple * d = tf()->domain();
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// Returns the unique CheckCastPP of a call
822// or 'this' if there are several CheckCastPP or unexpected uses
823// or returns NULL if there is no one.
824Node *CallNode::result_cast() {
825  Node *cast = NULL;
826
827  Node *p = proj_out(TypeFunc::Parms);
828  if (p == NULL)
829    return NULL;
830
831  for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {
832    Node *use = p->fast_out(i);
833    if (use->is_CheckCastPP()) {
834      if (cast != NULL) {
835        return this;  // more than 1 CheckCastPP
836      }
837      cast = use;
838    } else if (!use->is_Initialize() &&
839               !use->is_AddP() &&
840               use->Opcode() != Op_MemBarStoreStore) {
841      // Expected uses are restricted to a CheckCastPP, an Initialize
842      // node, a MemBarStoreStore (clone) and AddP nodes. If we
843      // encounter any other use (a Phi node can be seen in rare
844      // cases) return this to prevent incorrect optimizations.
845      return this;
846    }
847  }
848  return cast;
849}
850
851
852void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj, bool do_asserts) {
853  projs->fallthrough_proj      = NULL;
854  projs->fallthrough_catchproj = NULL;
855  projs->fallthrough_ioproj    = NULL;
856  projs->catchall_ioproj       = NULL;
857  projs->catchall_catchproj    = NULL;
858  projs->fallthrough_memproj   = NULL;
859  projs->catchall_memproj      = NULL;
860  projs->resproj               = NULL;
861  projs->exobj                 = NULL;
862
863  for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {
864    ProjNode *pn = fast_out(i)->as_Proj();
865    if (pn->outcnt() == 0) continue;
866    switch (pn->_con) {
867    case TypeFunc::Control:
868      {
869        // For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj
870        projs->fallthrough_proj = pn;
871        DUIterator_Fast jmax, j = pn->fast_outs(jmax);
872        const Node *cn = pn->fast_out(j);
873        if (cn->is_Catch()) {
874          ProjNode *cpn = NULL;
875          for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {
876            cpn = cn->fast_out(k)->as_Proj();
877            assert(cpn->is_CatchProj(), "must be a CatchProjNode");
878            if (cpn->_con == CatchProjNode::fall_through_index)
879              projs->fallthrough_catchproj = cpn;
880            else {
881              assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");
882              projs->catchall_catchproj = cpn;
883            }
884          }
885        }
886        break;
887      }
888    case TypeFunc::I_O:
889      if (pn->_is_io_use)
890        projs->catchall_ioproj = pn;
891      else
892        projs->fallthrough_ioproj = pn;
893      for (DUIterator j = pn->outs(); pn->has_out(j); j++) {
894        Node* e = pn->out(j);
895        if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {
896          assert(projs->exobj == NULL, "only one");
897          projs->exobj = e;
898        }
899      }
900      break;
901    case TypeFunc::Memory:
902      if (pn->_is_io_use)
903        projs->catchall_memproj = pn;
904      else
905        projs->fallthrough_memproj = pn;
906      break;
907    case TypeFunc::Parms:
908      projs->resproj = pn;
909      break;
910    default:
911      assert(false, "unexpected projection from allocation node.");
912    }
913  }
914
915  // The resproj may not exist because the result could be ignored
916  // and the exception object may not exist if an exception handler
917  // swallows the exception but all the other must exist and be found.
918  assert(projs->fallthrough_proj      != NULL, "must be found");
919  do_asserts = do_asserts && !Compile::current()->inlining_incrementally();
920  assert(!do_asserts || projs->fallthrough_catchproj != NULL, "must be found");
921  assert(!do_asserts || projs->fallthrough_memproj   != NULL, "must be found");
922  assert(!do_asserts || projs->fallthrough_ioproj    != NULL, "must be found");
923  assert(!do_asserts || projs->catchall_catchproj    != NULL, "must be found");
924  if (separate_io_proj) {
925    assert(!do_asserts || projs->catchall_memproj    != NULL, "must be found");
926    assert(!do_asserts || projs->catchall_ioproj     != NULL, "must be found");
927  }
928}
929
930Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {
931  CallGenerator* cg = generator();
932  if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {
933    // Check whether this MH handle call becomes a candidate for inlining
934    ciMethod* callee = cg->method();
935    vmIntrinsics::ID iid = callee->intrinsic_id();
936    if (iid == vmIntrinsics::_invokeBasic) {
937      if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {
938        phase->C->prepend_late_inline(cg);
939        set_generator(NULL);
940      }
941    } else {
942      assert(callee->has_member_arg(), "wrong type of call?");
943      if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {
944        phase->C->prepend_late_inline(cg);
945        set_generator(NULL);
946      }
947    }
948  }
949  return SafePointNode::Ideal(phase, can_reshape);
950}
951
952bool CallNode::is_call_to_arraycopystub() const {
953  if (_name != NULL && strstr(_name, "arraycopy") != 0) {
954    return true;
955  }
956  return false;
957}
958
959//=============================================================================
960uint CallJavaNode::size_of() const { return sizeof(*this); }
961uint CallJavaNode::cmp( const Node &n ) const {
962  CallJavaNode &call = (CallJavaNode&)n;
963  return CallNode::cmp(call) && _method == call._method &&
964         _override_symbolic_info == call._override_symbolic_info;
965}
966#ifndef PRODUCT
967void CallJavaNode::dump_spec(outputStream *st) const {
968  if( _method ) _method->print_short_name(st);
969  CallNode::dump_spec(st);
970}
971
972void CallJavaNode::dump_compact_spec(outputStream* st) const {
973  if (_method) {
974    _method->print_short_name(st);
975  } else {
976    st->print("<?>");
977  }
978}
979#endif
980
981//=============================================================================
982uint CallStaticJavaNode::size_of() const { return sizeof(*this); }
983uint CallStaticJavaNode::cmp( const Node &n ) const {
984  CallStaticJavaNode &call = (CallStaticJavaNode&)n;
985  return CallJavaNode::cmp(call);
986}
987
988//----------------------------uncommon_trap_request----------------------------
989// If this is an uncommon trap, return the request code, else zero.
990int CallStaticJavaNode::uncommon_trap_request() const {
991  if (_name != NULL && !strcmp(_name, "uncommon_trap")) {
992    return extract_uncommon_trap_request(this);
993  }
994  return 0;
995}
996int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {
997#ifndef PRODUCT
998  if (!(call->req() > TypeFunc::Parms &&
999        call->in(TypeFunc::Parms) != NULL &&
1000        call->in(TypeFunc::Parms)->is_Con() &&
1001        call->in(TypeFunc::Parms)->bottom_type()->isa_int())) {
1002    assert(in_dump() != 0, "OK if dumping");
1003    tty->print("[bad uncommon trap]");
1004    return 0;
1005  }
1006#endif
1007  return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();
1008}
1009
1010#ifndef PRODUCT
1011void CallStaticJavaNode::dump_spec(outputStream *st) const {
1012  st->print("# Static ");
1013  if (_name != NULL) {
1014    st->print("%s", _name);
1015    int trap_req = uncommon_trap_request();
1016    if (trap_req != 0) {
1017      char buf[100];
1018      st->print("(%s)",
1019                 Deoptimization::format_trap_request(buf, sizeof(buf),
1020                                                     trap_req));
1021    }
1022    st->print(" ");
1023  }
1024  CallJavaNode::dump_spec(st);
1025}
1026
1027void CallStaticJavaNode::dump_compact_spec(outputStream* st) const {
1028  if (_method) {
1029    _method->print_short_name(st);
1030  } else if (_name) {
1031    st->print("%s", _name);
1032  } else {
1033    st->print("<?>");
1034  }
1035}
1036#endif
1037
1038//=============================================================================
1039uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }
1040uint CallDynamicJavaNode::cmp( const Node &n ) const {
1041  CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;
1042  return CallJavaNode::cmp(call);
1043}
1044#ifndef PRODUCT
1045void CallDynamicJavaNode::dump_spec(outputStream *st) const {
1046  st->print("# Dynamic ");
1047  CallJavaNode::dump_spec(st);
1048}
1049#endif
1050
1051//=============================================================================
1052uint CallRuntimeNode::size_of() const { return sizeof(*this); }
1053uint CallRuntimeNode::cmp( const Node &n ) const {
1054  CallRuntimeNode &call = (CallRuntimeNode&)n;
1055  return CallNode::cmp(call) && !strcmp(_name,call._name);
1056}
1057#ifndef PRODUCT
1058void CallRuntimeNode::dump_spec(outputStream *st) const {
1059  st->print("# ");
1060  st->print("%s", _name);
1061  CallNode::dump_spec(st);
1062}
1063#endif
1064
1065//------------------------------calling_convention-----------------------------
1066void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {
1067  Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );
1068}
1069
1070//=============================================================================
1071//------------------------------calling_convention-----------------------------
1072
1073
1074//=============================================================================
1075#ifndef PRODUCT
1076void CallLeafNode::dump_spec(outputStream *st) const {
1077  st->print("# ");
1078  st->print("%s", _name);
1079  CallNode::dump_spec(st);
1080}
1081#endif
1082
1083//=============================================================================
1084
1085void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {
1086  assert(verify_jvms(jvms), "jvms must match");
1087  int loc = jvms->locoff() + idx;
1088  if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {
1089    // If current local idx is top then local idx - 1 could
1090    // be a long/double that needs to be killed since top could
1091    // represent the 2nd half ofthe long/double.
1092    uint ideal = in(loc -1)->ideal_reg();
1093    if (ideal == Op_RegD || ideal == Op_RegL) {
1094      // set other (low index) half to top
1095      set_req(loc - 1, in(loc));
1096    }
1097  }
1098  set_req(loc, c);
1099}
1100
1101uint SafePointNode::size_of() const { return sizeof(*this); }
1102uint SafePointNode::cmp( const Node &n ) const {
1103  return (&n == this);          // Always fail except on self
1104}
1105
1106//-------------------------set_next_exception----------------------------------
1107void SafePointNode::set_next_exception(SafePointNode* n) {
1108  assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");
1109  if (len() == req()) {
1110    if (n != NULL)  add_prec(n);
1111  } else {
1112    set_prec(req(), n);
1113  }
1114}
1115
1116
1117//----------------------------next_exception-----------------------------------
1118SafePointNode* SafePointNode::next_exception() const {
1119  if (len() == req()) {
1120    return NULL;
1121  } else {
1122    Node* n = in(req());
1123    assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");
1124    return (SafePointNode*) n;
1125  }
1126}
1127
1128
1129//------------------------------Ideal------------------------------------------
1130// Skip over any collapsed Regions
1131Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1132  return remove_dead_region(phase, can_reshape) ? this : NULL;
1133}
1134
1135//------------------------------Identity---------------------------------------
1136// Remove obviously duplicate safepoints
1137Node* SafePointNode::Identity(PhaseGVN* phase) {
1138
1139  // If you have back to back safepoints, remove one
1140  if( in(TypeFunc::Control)->is_SafePoint() )
1141    return in(TypeFunc::Control);
1142
1143  if( in(0)->is_Proj() ) {
1144    Node *n0 = in(0)->in(0);
1145    // Check if he is a call projection (except Leaf Call)
1146    if( n0->is_Catch() ) {
1147      n0 = n0->in(0)->in(0);
1148      assert( n0->is_Call(), "expect a call here" );
1149    }
1150    if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {
1151      // Useless Safepoint, so remove it
1152      return in(TypeFunc::Control);
1153    }
1154  }
1155
1156  return this;
1157}
1158
1159//------------------------------Value------------------------------------------
1160const Type* SafePointNode::Value(PhaseGVN* phase) const {
1161  if( phase->type(in(0)) == Type::TOP ) return Type::TOP;
1162  if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop
1163  return Type::CONTROL;
1164}
1165
1166#ifndef PRODUCT
1167void SafePointNode::dump_spec(outputStream *st) const {
1168  st->print(" SafePoint ");
1169  _replaced_nodes.dump(st);
1170}
1171
1172// The related nodes of a SafepointNode are all data inputs, excluding the
1173// control boundary, as well as all outputs till level 2 (to include projection
1174// nodes and targets). In compact mode, just include inputs till level 1 and
1175// outputs as before.
1176void SafePointNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1177  if (compact) {
1178    this->collect_nodes(in_rel, 1, false, false);
1179  } else {
1180    this->collect_nodes_in_all_data(in_rel, false);
1181  }
1182  this->collect_nodes(out_rel, -2, false, false);
1183}
1184#endif
1185
1186const RegMask &SafePointNode::in_RegMask(uint idx) const {
1187  if( idx < TypeFunc::Parms ) return RegMask::Empty;
1188  // Values outside the domain represent debug info
1189  return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1190}
1191const RegMask &SafePointNode::out_RegMask() const {
1192  return RegMask::Empty;
1193}
1194
1195
1196void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {
1197  assert((int)grow_by > 0, "sanity");
1198  int monoff = jvms->monoff();
1199  int scloff = jvms->scloff();
1200  int endoff = jvms->endoff();
1201  assert(endoff == (int)req(), "no other states or debug info after me");
1202  Node* top = Compile::current()->top();
1203  for (uint i = 0; i < grow_by; i++) {
1204    ins_req(monoff, top);
1205  }
1206  jvms->set_monoff(monoff + grow_by);
1207  jvms->set_scloff(scloff + grow_by);
1208  jvms->set_endoff(endoff + grow_by);
1209}
1210
1211void SafePointNode::push_monitor(const FastLockNode *lock) {
1212  // Add a LockNode, which points to both the original BoxLockNode (the
1213  // stack space for the monitor) and the Object being locked.
1214  const int MonitorEdges = 2;
1215  assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1216  assert(req() == jvms()->endoff(), "correct sizing");
1217  int nextmon = jvms()->scloff();
1218  if (GenerateSynchronizationCode) {
1219    ins_req(nextmon,   lock->box_node());
1220    ins_req(nextmon+1, lock->obj_node());
1221  } else {
1222    Node* top = Compile::current()->top();
1223    ins_req(nextmon, top);
1224    ins_req(nextmon, top);
1225  }
1226  jvms()->set_scloff(nextmon + MonitorEdges);
1227  jvms()->set_endoff(req());
1228}
1229
1230void SafePointNode::pop_monitor() {
1231  // Delete last monitor from debug info
1232  debug_only(int num_before_pop = jvms()->nof_monitors());
1233  const int MonitorEdges = 2;
1234  assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");
1235  int scloff = jvms()->scloff();
1236  int endoff = jvms()->endoff();
1237  int new_scloff = scloff - MonitorEdges;
1238  int new_endoff = endoff - MonitorEdges;
1239  jvms()->set_scloff(new_scloff);
1240  jvms()->set_endoff(new_endoff);
1241  while (scloff > new_scloff)  del_req_ordered(--scloff);
1242  assert(jvms()->nof_monitors() == num_before_pop-1, "");
1243}
1244
1245Node *SafePointNode::peek_monitor_box() const {
1246  int mon = jvms()->nof_monitors() - 1;
1247  assert(mon >= 0, "must have a monitor");
1248  return monitor_box(jvms(), mon);
1249}
1250
1251Node *SafePointNode::peek_monitor_obj() const {
1252  int mon = jvms()->nof_monitors() - 1;
1253  assert(mon >= 0, "must have a monitor");
1254  return monitor_obj(jvms(), mon);
1255}
1256
1257// Do we Match on this edge index or not?  Match no edges
1258uint SafePointNode::match_edge(uint idx) const {
1259  if( !needs_polling_address_input() )
1260    return 0;
1261
1262  return (TypeFunc::Parms == idx);
1263}
1264
1265//==============  SafePointScalarObjectNode  ==============
1266
1267SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,
1268#ifdef ASSERT
1269                                                     AllocateNode* alloc,
1270#endif
1271                                                     uint first_index,
1272                                                     uint n_fields) :
1273  TypeNode(tp, 1), // 1 control input -- seems required.  Get from root.
1274#ifdef ASSERT
1275  _alloc(alloc),
1276#endif
1277  _first_index(first_index),
1278  _n_fields(n_fields)
1279{
1280  init_class_id(Class_SafePointScalarObject);
1281}
1282
1283// Do not allow value-numbering for SafePointScalarObject node.
1284uint SafePointScalarObjectNode::hash() const { return NO_HASH; }
1285uint SafePointScalarObjectNode::cmp( const Node &n ) const {
1286  return (&n == this); // Always fail except on self
1287}
1288
1289uint SafePointScalarObjectNode::ideal_reg() const {
1290  return 0; // No matching to machine instruction
1291}
1292
1293const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {
1294  return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);
1295}
1296
1297const RegMask &SafePointScalarObjectNode::out_RegMask() const {
1298  return RegMask::Empty;
1299}
1300
1301uint SafePointScalarObjectNode::match_edge(uint idx) const {
1302  return 0;
1303}
1304
1305SafePointScalarObjectNode*
1306SafePointScalarObjectNode::clone(Dict* sosn_map) const {
1307  void* cached = (*sosn_map)[(void*)this];
1308  if (cached != NULL) {
1309    return (SafePointScalarObjectNode*)cached;
1310  }
1311  SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();
1312  sosn_map->Insert((void*)this, (void*)res);
1313  return res;
1314}
1315
1316
1317#ifndef PRODUCT
1318void SafePointScalarObjectNode::dump_spec(outputStream *st) const {
1319  st->print(" # fields@[%d..%d]", first_index(),
1320             first_index() + n_fields() - 1);
1321}
1322
1323#endif
1324
1325//=============================================================================
1326uint AllocateNode::size_of() const { return sizeof(*this); }
1327
1328AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,
1329                           Node *ctrl, Node *mem, Node *abio,
1330                           Node *size, Node *klass_node, Node *initial_test)
1331  : CallNode(atype, NULL, TypeRawPtr::BOTTOM)
1332{
1333  init_class_id(Class_Allocate);
1334  init_flags(Flag_is_macro);
1335  _is_scalar_replaceable = false;
1336  _is_non_escaping = false;
1337  _is_allocation_MemBar_redundant = false;
1338  Node *topnode = C->top();
1339
1340  init_req( TypeFunc::Control  , ctrl );
1341  init_req( TypeFunc::I_O      , abio );
1342  init_req( TypeFunc::Memory   , mem );
1343  init_req( TypeFunc::ReturnAdr, topnode );
1344  init_req( TypeFunc::FramePtr , topnode );
1345  init_req( AllocSize          , size);
1346  init_req( KlassNode          , klass_node);
1347  init_req( InitialTest        , initial_test);
1348  init_req( ALength            , topnode);
1349  C->add_macro_node(this);
1350}
1351
1352void AllocateNode::compute_MemBar_redundancy(ciMethod* initializer)
1353{
1354  assert(initializer != NULL &&
1355         initializer->is_initializer() &&
1356         !initializer->is_static(),
1357             "unexpected initializer method");
1358  BCEscapeAnalyzer* analyzer = initializer->get_bcea();
1359  if (analyzer == NULL) {
1360    return;
1361  }
1362
1363  // Allocation node is first parameter in its initializer
1364  if (analyzer->is_arg_stack(0) || analyzer->is_arg_local(0)) {
1365    _is_allocation_MemBar_redundant = true;
1366  }
1367}
1368
1369//=============================================================================
1370Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1371  if (remove_dead_region(phase, can_reshape))  return this;
1372  // Don't bother trying to transform a dead node
1373  if (in(0) && in(0)->is_top())  return NULL;
1374
1375  const Type* type = phase->type(Ideal_length());
1376  if (type->isa_int() && type->is_int()->_hi < 0) {
1377    if (can_reshape) {
1378      PhaseIterGVN *igvn = phase->is_IterGVN();
1379      // Unreachable fall through path (negative array length),
1380      // the allocation can only throw so disconnect it.
1381      Node* proj = proj_out(TypeFunc::Control);
1382      Node* catchproj = NULL;
1383      if (proj != NULL) {
1384        for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {
1385          Node *cn = proj->fast_out(i);
1386          if (cn->is_Catch()) {
1387            catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);
1388            break;
1389          }
1390        }
1391      }
1392      if (catchproj != NULL && catchproj->outcnt() > 0 &&
1393          (catchproj->outcnt() > 1 ||
1394           catchproj->unique_out()->Opcode() != Op_Halt)) {
1395        assert(catchproj->is_CatchProj(), "must be a CatchProjNode");
1396        Node* nproj = catchproj->clone();
1397        igvn->register_new_node_with_optimizer(nproj);
1398
1399        Node *frame = new ParmNode( phase->C->start(), TypeFunc::FramePtr );
1400        frame = phase->transform(frame);
1401        // Halt & Catch Fire
1402        Node *halt = new HaltNode( nproj, frame );
1403        phase->C->root()->add_req(halt);
1404        phase->transform(halt);
1405
1406        igvn->replace_node(catchproj, phase->C->top());
1407        return this;
1408      }
1409    } else {
1410      // Can't correct it during regular GVN so register for IGVN
1411      phase->C->record_for_igvn(this);
1412    }
1413  }
1414  return NULL;
1415}
1416
1417// Retrieve the length from the AllocateArrayNode. Narrow the type with a
1418// CastII, if appropriate.  If we are not allowed to create new nodes, and
1419// a CastII is appropriate, return NULL.
1420Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {
1421  Node *length = in(AllocateNode::ALength);
1422  assert(length != NULL, "length is not null");
1423
1424  const TypeInt* length_type = phase->find_int_type(length);
1425  const TypeAryPtr* ary_type = oop_type->isa_aryptr();
1426
1427  if (ary_type != NULL && length_type != NULL) {
1428    const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);
1429    if (narrow_length_type != length_type) {
1430      // Assert one of:
1431      //   - the narrow_length is 0
1432      //   - the narrow_length is not wider than length
1433      assert(narrow_length_type == TypeInt::ZERO ||
1434             length_type->is_con() && narrow_length_type->is_con() &&
1435                (narrow_length_type->_hi <= length_type->_lo) ||
1436             (narrow_length_type->_hi <= length_type->_hi &&
1437              narrow_length_type->_lo >= length_type->_lo),
1438             "narrow type must be narrower than length type");
1439
1440      // Return NULL if new nodes are not allowed
1441      if (!allow_new_nodes) return NULL;
1442      // Create a cast which is control dependent on the initialization to
1443      // propagate the fact that the array length must be positive.
1444      length = new CastIINode(length, narrow_length_type);
1445      length->set_req(0, initialization()->proj_out(0));
1446    }
1447  }
1448
1449  return length;
1450}
1451
1452//=============================================================================
1453uint LockNode::size_of() const { return sizeof(*this); }
1454
1455// Redundant lock elimination
1456//
1457// There are various patterns of locking where we release and
1458// immediately reacquire a lock in a piece of code where no operations
1459// occur in between that would be observable.  In those cases we can
1460// skip releasing and reacquiring the lock without violating any
1461// fairness requirements.  Doing this around a loop could cause a lock
1462// to be held for a very long time so we concentrate on non-looping
1463// control flow.  We also require that the operations are fully
1464// redundant meaning that we don't introduce new lock operations on
1465// some paths so to be able to eliminate it on others ala PRE.  This
1466// would probably require some more extensive graph manipulation to
1467// guarantee that the memory edges were all handled correctly.
1468//
1469// Assuming p is a simple predicate which can't trap in any way and s
1470// is a synchronized method consider this code:
1471//
1472//   s();
1473//   if (p)
1474//     s();
1475//   else
1476//     s();
1477//   s();
1478//
1479// 1. The unlocks of the first call to s can be eliminated if the
1480// locks inside the then and else branches are eliminated.
1481//
1482// 2. The unlocks of the then and else branches can be eliminated if
1483// the lock of the final call to s is eliminated.
1484//
1485// Either of these cases subsumes the simple case of sequential control flow
1486//
1487// Addtionally we can eliminate versions without the else case:
1488//
1489//   s();
1490//   if (p)
1491//     s();
1492//   s();
1493//
1494// 3. In this case we eliminate the unlock of the first s, the lock
1495// and unlock in the then case and the lock in the final s.
1496//
1497// Note also that in all these cases the then/else pieces don't have
1498// to be trivial as long as they begin and end with synchronization
1499// operations.
1500//
1501//   s();
1502//   if (p)
1503//     s();
1504//     f();
1505//     s();
1506//   s();
1507//
1508// The code will work properly for this case, leaving in the unlock
1509// before the call to f and the relock after it.
1510//
1511// A potentially interesting case which isn't handled here is when the
1512// locking is partially redundant.
1513//
1514//   s();
1515//   if (p)
1516//     s();
1517//
1518// This could be eliminated putting unlocking on the else case and
1519// eliminating the first unlock and the lock in the then side.
1520// Alternatively the unlock could be moved out of the then side so it
1521// was after the merge and the first unlock and second lock
1522// eliminated.  This might require less manipulation of the memory
1523// state to get correct.
1524//
1525// Additionally we might allow work between a unlock and lock before
1526// giving up eliminating the locks.  The current code disallows any
1527// conditional control flow between these operations.  A formulation
1528// similar to partial redundancy elimination computing the
1529// availability of unlocking and the anticipatability of locking at a
1530// program point would allow detection of fully redundant locking with
1531// some amount of work in between.  I'm not sure how often I really
1532// think that would occur though.  Most of the cases I've seen
1533// indicate it's likely non-trivial work would occur in between.
1534// There may be other more complicated constructs where we could
1535// eliminate locking but I haven't seen any others appear as hot or
1536// interesting.
1537//
1538// Locking and unlocking have a canonical form in ideal that looks
1539// roughly like this:
1540//
1541//              <obj>
1542//                | \\------+
1543//                |  \       \
1544//                | BoxLock   \
1545//                |  |   |     \
1546//                |  |    \     \
1547//                |  |   FastLock
1548//                |  |   /
1549//                |  |  /
1550//                |  |  |
1551//
1552//               Lock
1553//                |
1554//            Proj #0
1555//                |
1556//            MembarAcquire
1557//                |
1558//            Proj #0
1559//
1560//            MembarRelease
1561//                |
1562//            Proj #0
1563//                |
1564//              Unlock
1565//                |
1566//            Proj #0
1567//
1568//
1569// This code proceeds by processing Lock nodes during PhaseIterGVN
1570// and searching back through its control for the proper code
1571// patterns.  Once it finds a set of lock and unlock operations to
1572// eliminate they are marked as eliminatable which causes the
1573// expansion of the Lock and Unlock macro nodes to make the operation a NOP
1574//
1575//=============================================================================
1576
1577//
1578// Utility function to skip over uninteresting control nodes.  Nodes skipped are:
1579//   - copy regions.  (These may not have been optimized away yet.)
1580//   - eliminated locking nodes
1581//
1582static Node *next_control(Node *ctrl) {
1583  if (ctrl == NULL)
1584    return NULL;
1585  while (1) {
1586    if (ctrl->is_Region()) {
1587      RegionNode *r = ctrl->as_Region();
1588      Node *n = r->is_copy();
1589      if (n == NULL)
1590        break;  // hit a region, return it
1591      else
1592        ctrl = n;
1593    } else if (ctrl->is_Proj()) {
1594      Node *in0 = ctrl->in(0);
1595      if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {
1596        ctrl = in0->in(0);
1597      } else {
1598        break;
1599      }
1600    } else {
1601      break; // found an interesting control
1602    }
1603  }
1604  return ctrl;
1605}
1606//
1607// Given a control, see if it's the control projection of an Unlock which
1608// operating on the same object as lock.
1609//
1610bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,
1611                                            GrowableArray<AbstractLockNode*> &lock_ops) {
1612  ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;
1613  if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {
1614    Node *n = ctrl_proj->in(0);
1615    if (n != NULL && n->is_Unlock()) {
1616      UnlockNode *unlock = n->as_Unlock();
1617      if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1618          BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&
1619          !unlock->is_eliminated()) {
1620        lock_ops.append(unlock);
1621        return true;
1622      }
1623    }
1624  }
1625  return false;
1626}
1627
1628//
1629// Find the lock matching an unlock.  Returns null if a safepoint
1630// or complicated control is encountered first.
1631LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {
1632  LockNode *lock_result = NULL;
1633  // find the matching lock, or an intervening safepoint
1634  Node *ctrl = next_control(unlock->in(0));
1635  while (1) {
1636    assert(ctrl != NULL, "invalid control graph");
1637    assert(!ctrl->is_Start(), "missing lock for unlock");
1638    if (ctrl->is_top()) break;  // dead control path
1639    if (ctrl->is_Proj()) ctrl = ctrl->in(0);
1640    if (ctrl->is_SafePoint()) {
1641        break;  // found a safepoint (may be the lock we are searching for)
1642    } else if (ctrl->is_Region()) {
1643      // Check for a simple diamond pattern.  Punt on anything more complicated
1644      if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {
1645        Node *in1 = next_control(ctrl->in(1));
1646        Node *in2 = next_control(ctrl->in(2));
1647        if (((in1->is_IfTrue() && in2->is_IfFalse()) ||
1648             (in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {
1649          ctrl = next_control(in1->in(0)->in(0));
1650        } else {
1651          break;
1652        }
1653      } else {
1654        break;
1655      }
1656    } else {
1657      ctrl = next_control(ctrl->in(0));  // keep searching
1658    }
1659  }
1660  if (ctrl->is_Lock()) {
1661    LockNode *lock = ctrl->as_Lock();
1662    if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&
1663        BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {
1664      lock_result = lock;
1665    }
1666  }
1667  return lock_result;
1668}
1669
1670// This code corresponds to case 3 above.
1671
1672bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,
1673                                                       GrowableArray<AbstractLockNode*> &lock_ops) {
1674  Node* if_node = node->in(0);
1675  bool  if_true = node->is_IfTrue();
1676
1677  if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {
1678    Node *lock_ctrl = next_control(if_node->in(0));
1679    if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {
1680      Node* lock1_node = NULL;
1681      ProjNode* proj = if_node->as_If()->proj_out(!if_true);
1682      if (if_true) {
1683        if (proj->is_IfFalse() && proj->outcnt() == 1) {
1684          lock1_node = proj->unique_out();
1685        }
1686      } else {
1687        if (proj->is_IfTrue() && proj->outcnt() == 1) {
1688          lock1_node = proj->unique_out();
1689        }
1690      }
1691      if (lock1_node != NULL && lock1_node->is_Lock()) {
1692        LockNode *lock1 = lock1_node->as_Lock();
1693        if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&
1694            BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&
1695            !lock1->is_eliminated()) {
1696          lock_ops.append(lock1);
1697          return true;
1698        }
1699      }
1700    }
1701  }
1702
1703  lock_ops.trunc_to(0);
1704  return false;
1705}
1706
1707bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,
1708                               GrowableArray<AbstractLockNode*> &lock_ops) {
1709  // check each control merging at this point for a matching unlock.
1710  // in(0) should be self edge so skip it.
1711  for (int i = 1; i < (int)region->req(); i++) {
1712    Node *in_node = next_control(region->in(i));
1713    if (in_node != NULL) {
1714      if (find_matching_unlock(in_node, lock, lock_ops)) {
1715        // found a match so keep on checking.
1716        continue;
1717      } else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {
1718        continue;
1719      }
1720
1721      // If we fall through to here then it was some kind of node we
1722      // don't understand or there wasn't a matching unlock, so give
1723      // up trying to merge locks.
1724      lock_ops.trunc_to(0);
1725      return false;
1726    }
1727  }
1728  return true;
1729
1730}
1731
1732#ifndef PRODUCT
1733//
1734// Create a counter which counts the number of times this lock is acquired
1735//
1736void AbstractLockNode::create_lock_counter(JVMState* state) {
1737  _counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);
1738}
1739
1740void AbstractLockNode::set_eliminated_lock_counter() {
1741  if (_counter) {
1742    // Update the counter to indicate that this lock was eliminated.
1743    // The counter update code will stay around even though the
1744    // optimizer will eliminate the lock operation itself.
1745    _counter->set_tag(NamedCounter::EliminatedLockCounter);
1746  }
1747}
1748
1749const char* AbstractLockNode::_kind_names[] = {"Regular", "NonEscObj", "Coarsened", "Nested"};
1750
1751void AbstractLockNode::dump_spec(outputStream* st) const {
1752  st->print("%s ", _kind_names[_kind]);
1753  CallNode::dump_spec(st);
1754}
1755
1756void AbstractLockNode::dump_compact_spec(outputStream* st) const {
1757  st->print("%s", _kind_names[_kind]);
1758}
1759
1760// The related set of lock nodes includes the control boundary.
1761void AbstractLockNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1762  if (compact) {
1763      this->collect_nodes(in_rel, 1, false, false);
1764    } else {
1765      this->collect_nodes_in_all_data(in_rel, true);
1766    }
1767    this->collect_nodes(out_rel, -2, false, false);
1768}
1769#endif
1770
1771//=============================================================================
1772Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1773
1774  // perform any generic optimizations first (returns 'this' or NULL)
1775  Node *result = SafePointNode::Ideal(phase, can_reshape);
1776  if (result != NULL)  return result;
1777  // Don't bother trying to transform a dead node
1778  if (in(0) && in(0)->is_top())  return NULL;
1779
1780  // Now see if we can optimize away this lock.  We don't actually
1781  // remove the locking here, we simply set the _eliminate flag which
1782  // prevents macro expansion from expanding the lock.  Since we don't
1783  // modify the graph, the value returned from this function is the
1784  // one computed above.
1785  if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
1786    //
1787    // If we are locking an unescaped object, the lock/unlock is unnecessary
1788    //
1789    ConnectionGraph *cgr = phase->C->congraph();
1790    if (cgr != NULL && cgr->not_global_escape(obj_node())) {
1791      assert(!is_eliminated() || is_coarsened(), "sanity");
1792      // The lock could be marked eliminated by lock coarsening
1793      // code during first IGVN before EA. Replace coarsened flag
1794      // to eliminate all associated locks/unlocks.
1795#ifdef ASSERT
1796      this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");
1797#endif
1798      this->set_non_esc_obj();
1799      return result;
1800    }
1801
1802    //
1803    // Try lock coarsening
1804    //
1805    PhaseIterGVN* iter = phase->is_IterGVN();
1806    if (iter != NULL && !is_eliminated()) {
1807
1808      GrowableArray<AbstractLockNode*>   lock_ops;
1809
1810      Node *ctrl = next_control(in(0));
1811
1812      // now search back for a matching Unlock
1813      if (find_matching_unlock(ctrl, this, lock_ops)) {
1814        // found an unlock directly preceding this lock.  This is the
1815        // case of single unlock directly control dependent on a
1816        // single lock which is the trivial version of case 1 or 2.
1817      } else if (ctrl->is_Region() ) {
1818        if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {
1819        // found lock preceded by multiple unlocks along all paths
1820        // joining at this point which is case 3 in description above.
1821        }
1822      } else {
1823        // see if this lock comes from either half of an if and the
1824        // predecessors merges unlocks and the other half of the if
1825        // performs a lock.
1826        if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {
1827          // found unlock splitting to an if with locks on both branches.
1828        }
1829      }
1830
1831      if (lock_ops.length() > 0) {
1832        // add ourselves to the list of locks to be eliminated.
1833        lock_ops.append(this);
1834
1835  #ifndef PRODUCT
1836        if (PrintEliminateLocks) {
1837          int locks = 0;
1838          int unlocks = 0;
1839          for (int i = 0; i < lock_ops.length(); i++) {
1840            AbstractLockNode* lock = lock_ops.at(i);
1841            if (lock->Opcode() == Op_Lock)
1842              locks++;
1843            else
1844              unlocks++;
1845            if (Verbose) {
1846              lock->dump(1);
1847            }
1848          }
1849          tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);
1850        }
1851  #endif
1852
1853        // for each of the identified locks, mark them
1854        // as eliminatable
1855        for (int i = 0; i < lock_ops.length(); i++) {
1856          AbstractLockNode* lock = lock_ops.at(i);
1857
1858          // Mark it eliminated by coarsening and update any counters
1859#ifdef ASSERT
1860          lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");
1861#endif
1862          lock->set_coarsened();
1863        }
1864      } else if (ctrl->is_Region() &&
1865                 iter->_worklist.member(ctrl)) {
1866        // We weren't able to find any opportunities but the region this
1867        // lock is control dependent on hasn't been processed yet so put
1868        // this lock back on the worklist so we can check again once any
1869        // region simplification has occurred.
1870        iter->_worklist.push(this);
1871      }
1872    }
1873  }
1874
1875  return result;
1876}
1877
1878//=============================================================================
1879bool LockNode::is_nested_lock_region() {
1880  return is_nested_lock_region(NULL);
1881}
1882
1883// p is used for access to compilation log; no logging if NULL
1884bool LockNode::is_nested_lock_region(Compile * c) {
1885  BoxLockNode* box = box_node()->as_BoxLock();
1886  int stk_slot = box->stack_slot();
1887  if (stk_slot <= 0) {
1888#ifdef ASSERT
1889    this->log_lock_optimization(c, "eliminate_lock_INLR_1");
1890#endif
1891    return false; // External lock or it is not Box (Phi node).
1892  }
1893
1894  // Ignore complex cases: merged locks or multiple locks.
1895  Node* obj = obj_node();
1896  LockNode* unique_lock = NULL;
1897  if (!box->is_simple_lock_region(&unique_lock, obj)) {
1898#ifdef ASSERT
1899    this->log_lock_optimization(c, "eliminate_lock_INLR_2a");
1900#endif
1901    return false;
1902  }
1903  if (unique_lock != this) {
1904#ifdef ASSERT
1905    this->log_lock_optimization(c, "eliminate_lock_INLR_2b");
1906#endif
1907    return false;
1908  }
1909
1910  // Look for external lock for the same object.
1911  SafePointNode* sfn = this->as_SafePoint();
1912  JVMState* youngest_jvms = sfn->jvms();
1913  int max_depth = youngest_jvms->depth();
1914  for (int depth = 1; depth <= max_depth; depth++) {
1915    JVMState* jvms = youngest_jvms->of_depth(depth);
1916    int num_mon  = jvms->nof_monitors();
1917    // Loop over monitors
1918    for (int idx = 0; idx < num_mon; idx++) {
1919      Node* obj_node = sfn->monitor_obj(jvms, idx);
1920      BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();
1921      if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {
1922        return true;
1923      }
1924    }
1925  }
1926#ifdef ASSERT
1927  this->log_lock_optimization(c, "eliminate_lock_INLR_3");
1928#endif
1929  return false;
1930}
1931
1932//=============================================================================
1933uint UnlockNode::size_of() const { return sizeof(*this); }
1934
1935//=============================================================================
1936Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1937
1938  // perform any generic optimizations first (returns 'this' or NULL)
1939  Node *result = SafePointNode::Ideal(phase, can_reshape);
1940  if (result != NULL)  return result;
1941  // Don't bother trying to transform a dead node
1942  if (in(0) && in(0)->is_top())  return NULL;
1943
1944  // Now see if we can optimize away this unlock.  We don't actually
1945  // remove the unlocking here, we simply set the _eliminate flag which
1946  // prevents macro expansion from expanding the unlock.  Since we don't
1947  // modify the graph, the value returned from this function is the
1948  // one computed above.
1949  // Escape state is defined after Parse phase.
1950  if (can_reshape && EliminateLocks && !is_non_esc_obj()) {
1951    //
1952    // If we are unlocking an unescaped object, the lock/unlock is unnecessary.
1953    //
1954    ConnectionGraph *cgr = phase->C->congraph();
1955    if (cgr != NULL && cgr->not_global_escape(obj_node())) {
1956      assert(!is_eliminated() || is_coarsened(), "sanity");
1957      // The lock could be marked eliminated by lock coarsening
1958      // code during first IGVN before EA. Replace coarsened flag
1959      // to eliminate all associated locks/unlocks.
1960#ifdef ASSERT
1961      this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");
1962#endif
1963      this->set_non_esc_obj();
1964    }
1965  }
1966  return result;
1967}
1968
1969const char * AbstractLockNode::kind_as_string() const {
1970  return is_coarsened()   ? "coarsened" :
1971         is_nested()      ? "nested" :
1972         is_non_esc_obj() ? "non_escaping" :
1973         "?";
1974}
1975
1976void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag)  const {
1977  if (C == NULL) {
1978    return;
1979  }
1980  CompileLog* log = C->log();
1981  if (log != NULL) {
1982    log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",
1983          tag, is_Lock(), C->compile_id(),
1984          is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",
1985          kind_as_string());
1986    log->stamp();
1987    log->end_head();
1988    JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();
1989    while (p != NULL) {
1990      log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));
1991      p = p->caller();
1992    }
1993    log->tail(tag);
1994  }
1995}
1996
1997bool CallNode::may_modify_arraycopy_helper(const TypeOopPtr* dest_t, const TypeOopPtr *t_oop, PhaseTransform *phase) {
1998  if (dest_t->is_known_instance() && t_oop->is_known_instance()) {
1999    return dest_t->instance_id() == t_oop->instance_id();
2000  }
2001
2002  if (dest_t->isa_instptr() && !dest_t->klass()->equals(phase->C->env()->Object_klass())) {
2003    // clone
2004    if (t_oop->isa_aryptr()) {
2005      return false;
2006    }
2007    if (!t_oop->isa_instptr()) {
2008      return true;
2009    }
2010    if (dest_t->klass()->is_subtype_of(t_oop->klass()) || t_oop->klass()->is_subtype_of(dest_t->klass())) {
2011      return true;
2012    }
2013    // unrelated
2014    return false;
2015  }
2016
2017  if (dest_t->isa_aryptr()) {
2018    // arraycopy or array clone
2019    if (t_oop->isa_instptr()) {
2020      return false;
2021    }
2022    if (!t_oop->isa_aryptr()) {
2023      return true;
2024    }
2025
2026    const Type* elem = dest_t->is_aryptr()->elem();
2027    if (elem == Type::BOTTOM) {
2028      // An array but we don't know what elements are
2029      return true;
2030    }
2031
2032    dest_t = dest_t->add_offset(Type::OffsetBot)->is_oopptr();
2033    uint dest_alias = phase->C->get_alias_index(dest_t);
2034    uint t_oop_alias = phase->C->get_alias_index(t_oop);
2035
2036    return dest_alias == t_oop_alias;
2037  }
2038
2039  return true;
2040}
2041
2042