escape.cpp 115.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34 35
#include "precompiled.hpp"
#include "ci/bcEscapeAnalyzer.hpp"
#include "libadt/vectset.hpp"
#include "memory/allocation.hpp"
#include "opto/c2compiler.hpp"
#include "opto/callnode.hpp"
#include "opto/cfgnode.hpp"
#include "opto/compile.hpp"
#include "opto/escape.hpp"
#include "opto/phaseX.hpp"
#include "opto/rootnode.hpp"
D
duke 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

void PointsToNode::add_edge(uint targIdx, PointsToNode::EdgeType et) {
  uint v = (targIdx << EdgeShift) + ((uint) et);
  if (_edges == NULL) {
     Arena *a = Compile::current()->comp_arena();
    _edges = new(a) GrowableArray<uint>(a, INITIAL_EDGE_COUNT, 0, 0);
  }
  _edges->append_if_missing(v);
}

void PointsToNode::remove_edge(uint targIdx, PointsToNode::EdgeType et) {
  uint v = (targIdx << EdgeShift) + ((uint) et);

  _edges->remove(v);
}

#ifndef PRODUCT
K
kvn 已提交
53
static const char *node_type_names[] = {
D
duke 已提交
54 55 56 57 58 59
  "UnknownType",
  "JavaObject",
  "LocalVar",
  "Field"
};

K
kvn 已提交
60
static const char *esc_names[] = {
D
duke 已提交
61
  "UnknownEscape",
62 63 64
  "NoEscape",
  "ArgEscape",
  "GlobalEscape"
D
duke 已提交
65 66
};

K
kvn 已提交
67
static const char *edge_type_suffix[] = {
D
duke 已提交
68 69 70 71 72 73
 "?", // UnknownEdge
 "P", // PointsToEdge
 "D", // DeferredEdge
 "F"  // FieldEdge
};

74
void PointsToNode::dump(bool print_state) const {
D
duke 已提交
75
  NodeType nt = node_type();
76 77 78 79 80 81
  tty->print("%s ", node_type_names[(int) nt]);
  if (print_state) {
    EscapeState es = escape_state();
    tty->print("%s %s ", esc_names[(int) es], _scalar_replaceable ? "":"NSR");
  }
  tty->print("[[");
D
duke 已提交
82 83 84 85 86 87 88 89 90 91 92
  for (uint i = 0; i < edge_count(); i++) {
    tty->print(" %d%s", edge_target(i), edge_type_suffix[(int) edge_type(i)]);
  }
  tty->print("]]  ");
  if (_node == NULL)
    tty->print_cr("<null>");
  else
    _node->dump();
}
#endif

93
ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn) :
94 95
  _nodes(C->comp_arena(), C->unique(), C->unique(), PointsToNode()),
  _processed(C->comp_arena()),
96 97 98
  pt_ptset(C->comp_arena()),
  pt_visited(C->comp_arena()),
  pt_worklist(C->comp_arena(), 4, 0, 0),
99
  _collecting(true),
K
kvn 已提交
100
  _progress(false),
101
  _compile(C),
102
  _igvn(igvn),
103 104
  _node_map(C->comp_arena()) {

105 106 107 108 109 110
  _phantom_object = C->top()->_idx,
  add_node(C->top(), PointsToNode::JavaObject, PointsToNode::GlobalEscape,true);

  // Add ConP(#NULL) and ConN(#NULL) nodes.
  Node* oop_null = igvn->zerocon(T_OBJECT);
  _oop_null = oop_null->_idx;
111
  assert(_oop_null < nodes_size(), "should be created already");
112 113 114 115 116
  add_node(oop_null, PointsToNode::JavaObject, PointsToNode::NoEscape, true);

  if (UseCompressedOops) {
    Node* noop_null = igvn->zerocon(T_NARROWOOP);
    _noop_null = noop_null->_idx;
117
    assert(_noop_null < nodes_size(), "should be created already");
118
    add_node(noop_null, PointsToNode::JavaObject, PointsToNode::NoEscape, true);
119 120
  } else {
    _noop_null = _oop_null; // Should be initialized
121
  }
122 123
  _pcmp_neq = NULL; // Should be initialized
  _pcmp_eq  = NULL;
D
duke 已提交
124 125 126 127 128 129 130 131 132
}

void ConnectionGraph::add_pointsto_edge(uint from_i, uint to_i) {
  PointsToNode *f = ptnode_adr(from_i);
  PointsToNode *t = ptnode_adr(to_i);

  assert(f->node_type() != PointsToNode::UnknownType && t->node_type() != PointsToNode::UnknownType, "node types must be set");
  assert(f->node_type() == PointsToNode::LocalVar || f->node_type() == PointsToNode::Field, "invalid source of PointsTo edge");
  assert(t->node_type() == PointsToNode::JavaObject, "invalid destination of PointsTo edge");
133 134 135 136 137 138 139
  if (to_i == _phantom_object) { // Quick test for most common object
    if (f->has_unknown_ptr()) {
      return;
    } else {
      f->set_has_unknown_ptr();
    }
  }
K
kvn 已提交
140
  add_edge(f, to_i, PointsToNode::PointsToEdge);
D
duke 已提交
141 142 143 144 145 146 147 148 149 150 151 152
}

void ConnectionGraph::add_deferred_edge(uint from_i, uint to_i) {
  PointsToNode *f = ptnode_adr(from_i);
  PointsToNode *t = ptnode_adr(to_i);

  assert(f->node_type() != PointsToNode::UnknownType && t->node_type() != PointsToNode::UnknownType, "node types must be set");
  assert(f->node_type() == PointsToNode::LocalVar || f->node_type() == PointsToNode::Field, "invalid source of Deferred edge");
  assert(t->node_type() == PointsToNode::LocalVar || t->node_type() == PointsToNode::Field, "invalid destination of Deferred edge");
  // don't add a self-referential edge, this can occur during removal of
  // deferred edges
  if (from_i != to_i)
K
kvn 已提交
153
    add_edge(f, to_i, PointsToNode::DeferredEdge);
D
duke 已提交
154 155
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169
int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
  const Type *adr_type = phase->type(adr);
  if (adr->is_AddP() && adr_type->isa_oopptr() == NULL &&
      adr->in(AddPNode::Address)->is_Proj() &&
      adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
    // We are computing a raw address for a store captured by an Initialize
    // compute an appropriate address type. AddP cases #3 and #5 (see below).
    int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
    assert(offs != Type::OffsetBot ||
           adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
           "offset must be a constant or it is initialization of array");
    return offs;
  }
  const TypePtr *t_ptr = adr_type->isa_ptr();
D
duke 已提交
170 171 172 173 174
  assert(t_ptr != NULL, "must be a pointer type");
  return t_ptr->offset();
}

void ConnectionGraph::add_field_edge(uint from_i, uint to_i, int offset) {
175 176 177
  // Don't add fields to NULL pointer.
  if (is_null_ptr(from_i))
    return;
D
duke 已提交
178 179 180 181 182 183 184 185 186
  PointsToNode *f = ptnode_adr(from_i);
  PointsToNode *t = ptnode_adr(to_i);

  assert(f->node_type() != PointsToNode::UnknownType && t->node_type() != PointsToNode::UnknownType, "node types must be set");
  assert(f->node_type() == PointsToNode::JavaObject, "invalid destination of Field edge");
  assert(t->node_type() == PointsToNode::Field, "invalid destination of Field edge");
  assert (t->offset() == -1 || t->offset() == offset, "conflicting field offsets");
  t->set_offset(offset);

K
kvn 已提交
187
  add_edge(f, to_i, PointsToNode::FieldEdge);
D
duke 已提交
188 189 190
}

void ConnectionGraph::set_escape_state(uint ni, PointsToNode::EscapeState es) {
191
  // Don't change non-escaping state of NULL pointer.
192
  if (is_null_ptr(ni))
193
    return;
D
duke 已提交
194 195 196 197 198 199
  PointsToNode *npt = ptnode_adr(ni);
  PointsToNode::EscapeState old_es = npt->escape_state();
  if (es > old_es)
    npt->set_escape_state(es);
}

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
void ConnectionGraph::add_node(Node *n, PointsToNode::NodeType nt,
                               PointsToNode::EscapeState es, bool done) {
  PointsToNode* ptadr = ptnode_adr(n->_idx);
  ptadr->_node = n;
  ptadr->set_node_type(nt);

  // inline set_escape_state(idx, es);
  PointsToNode::EscapeState old_es = ptadr->escape_state();
  if (es > old_es)
    ptadr->set_escape_state(es);

  if (done)
    _processed.set(n->_idx);
}

215
PointsToNode::EscapeState ConnectionGraph::escape_state(Node *n) {
D
duke 已提交
216 217 218
  uint idx = n->_idx;
  PointsToNode::EscapeState es;

219 220
  // If we are still collecting or there were no non-escaping allocations
  // we don't know the answer yet
221
  if (_collecting)
D
duke 已提交
222 223 224 225
    return PointsToNode::UnknownEscape;

  // if the node was created after the escape computation, return
  // UnknownEscape
226
  if (idx >= nodes_size())
D
duke 已提交
227 228
    return PointsToNode::UnknownEscape;

229
  es = ptnode_adr(idx)->escape_state();
D
duke 已提交
230 231

  // if we have already computed a value, return it
232 233
  if (es != PointsToNode::UnknownEscape &&
      ptnode_adr(idx)->node_type() == PointsToNode::JavaObject)
D
duke 已提交
234 235
    return es;

236 237 238 239
  // PointsTo() calls n->uncast() which can return a new ideal node.
  if (n->uncast()->_idx >= nodes_size())
    return PointsToNode::UnknownEscape;

240 241
  PointsToNode::EscapeState orig_es = es;

D
duke 已提交
242
  // compute max escape state of anything this node could point to
243
  for(VectorSetI i(PointsTo(n)); i.test() && es != PointsToNode::GlobalEscape; ++i) {
D
duke 已提交
244
    uint pt = i.elem;
245
    PointsToNode::EscapeState pes = ptnode_adr(pt)->escape_state();
D
duke 已提交
246 247 248
    if (pes > es)
      es = pes;
  }
249 250
  if (orig_es != es) {
    // cache the computed escape state
251 252
    assert(es > orig_es, "should have computed an escape state");
    set_escape_state(idx, es);
253
  } // orig_es could be PointsToNode::UnknownEscape
D
duke 已提交
254 255 256
  return es;
}

257 258 259 260
VectorSet* ConnectionGraph::PointsTo(Node * n) {
  pt_ptset.Reset();
  pt_visited.Reset();
  pt_worklist.clear();
D
duke 已提交
261

262 263 264 265
#ifdef ASSERT
  Node *orig_n = n;
#endif

266
  n = n->uncast();
267
  PointsToNode* npt = ptnode_adr(n->_idx);
D
duke 已提交
268 269

  // If we have a JavaObject, return just that object
270
  if (npt->node_type() == PointsToNode::JavaObject) {
271 272
    pt_ptset.set(n->_idx);
    return &pt_ptset;
D
duke 已提交
273
  }
274
#ifdef ASSERT
275
  if (npt->_node == NULL) {
276 277 278
    if (orig_n != n)
      orig_n->dump();
    n->dump();
279
    assert(npt->_node != NULL, "unregistered node");
280 281
  }
#endif
282 283 284 285
  pt_worklist.push(n->_idx);
  while(pt_worklist.length() > 0) {
    int ni = pt_worklist.pop();
    if (pt_visited.test_set(ni))
286 287 288 289 290 291 292 293 294 295 296 297
      continue;

    PointsToNode* pn = ptnode_adr(ni);
    // ensure that all inputs of a Phi have been processed
    assert(!_collecting || !pn->_node->is_Phi() || _processed.test(ni),"");

    int edges_processed = 0;
    uint e_cnt = pn->edge_count();
    for (uint e = 0; e < e_cnt; e++) {
      uint etgt = pn->edge_target(e);
      PointsToNode::EdgeType et = pn->edge_type(e);
      if (et == PointsToNode::PointsToEdge) {
298
        pt_ptset.set(etgt);
299 300
        edges_processed++;
      } else if (et == PointsToNode::DeferredEdge) {
301
        pt_worklist.push(etgt);
302 303 304
        edges_processed++;
      } else {
        assert(false,"neither PointsToEdge or DeferredEdge");
D
duke 已提交
305 306
      }
    }
307 308 309
    if (edges_processed == 0) {
      // no deferred or pointsto edges found.  Assume the value was set
      // outside this method.  Add the phantom object to the pointsto set.
310
      pt_ptset.set(_phantom_object);
311
    }
D
duke 已提交
312
  }
313
  return &pt_ptset;
D
duke 已提交
314 315
}

316 317 318 319
void ConnectionGraph::remove_deferred(uint ni, GrowableArray<uint>* deferred_edges, VectorSet* visited) {
  // This method is most expensive during ConnectionGraph construction.
  // Reuse vectorSet and an additional growable array for deferred edges.
  deferred_edges->clear();
320
  visited->Reset();
D
duke 已提交
321

322
  visited->set(ni);
D
duke 已提交
323
  PointsToNode *ptn = ptnode_adr(ni);
324 325 326
  assert(ptn->node_type() == PointsToNode::LocalVar ||
         ptn->node_type() == PointsToNode::Field, "sanity");
  assert(ptn->edge_count() != 0, "should have at least phantom_object");
D
duke 已提交
327

328
  // Mark current edges as visited and move deferred edges to separate array.
329
  for (uint i = 0; i < ptn->edge_count(); ) {
330
    uint t = ptn->edge_target(i);
331 332 333 334 335 336
#ifdef ASSERT
    assert(!visited->test_set(t), "expecting no duplications");
#else
    visited->set(t);
#endif
    if (ptn->edge_type(i) == PointsToNode::DeferredEdge) {
D
duke 已提交
337
      ptn->remove_edge(t, PointsToNode::DeferredEdge);
338
      deferred_edges->append(t);
339 340
    } else {
      i++;
341 342 343 344 345
    }
  }
  for (int next = 0; next < deferred_edges->length(); ++next) {
    uint t = deferred_edges->at(next);
    PointsToNode *ptt = ptnode_adr(t);
346
    uint e_cnt = ptt->edge_count();
347
    assert(e_cnt != 0, "should have at least phantom_object");
348 349 350
    for (uint e = 0; e < e_cnt; e++) {
      uint etgt = ptt->edge_target(e);
      if (visited->test_set(etgt))
351
        continue;
352 353 354 355 356 357 358 359

      PointsToNode::EdgeType et = ptt->edge_type(e);
      if (et == PointsToNode::PointsToEdge) {
        add_pointsto_edge(ni, etgt);
      } else if (et == PointsToNode::DeferredEdge) {
        deferred_edges->append(etgt);
      } else {
        assert(false,"invalid connection graph");
D
duke 已提交
360 361 362
      }
    }
  }
363 364 365 366 367 368 369 370 371 372 373 374 375 376
  if (ptn->edge_count() == 0) {
    // No pointsto edges found after deferred edges are removed.
    // For example, in the next case where call is replaced
    // with uncommon trap and as result array's load references
    // itself through deferred edges:
    //
    // A a = b[i];
    // if (c!=null) a = c.foo();
    // b[i] = a;
    //
    // Assume the value was set outside this method and
    // add edge to phantom object.
    add_pointsto_edge(ni, _phantom_object);
  }
D
duke 已提交
377 378 379 380 381 382 383 384
}


//  Add an edge to node given by "to_i" from any field of adr_i whose offset
//  matches "offset"  A deferred edge is added if to_i is a LocalVar, and
//  a pointsto edge is added if it is a JavaObject

void ConnectionGraph::add_edge_from_fields(uint adr_i, uint to_i, int offs) {
385 386 387 388
  // No fields for NULL pointer.
  if (is_null_ptr(adr_i)) {
    return;
  }
389 390 391
  PointsToNode* an = ptnode_adr(adr_i);
  PointsToNode* to = ptnode_adr(to_i);
  bool deferred = (to->node_type() == PointsToNode::LocalVar);
392 393 394 395 396 397
  bool escaped  = (to_i == _phantom_object) && (offs == Type::OffsetTop);
  if (escaped) {
    // Values in fields escaped during call.
    assert(an->escape_state() >= PointsToNode::ArgEscape, "sanity");
    offs = Type::OffsetBot;
  }
398 399 400
  for (uint fe = 0; fe < an->edge_count(); fe++) {
    assert(an->edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge");
    int fi = an->edge_target(fe);
401 402 403
    if (escaped) {
      set_escape_state(fi, PointsToNode::GlobalEscape);
    }
404 405
    PointsToNode* pf = ptnode_adr(fi);
    int po = pf->offset();
D
duke 已提交
406 407 408 409 410 411 412 413 414
    if (po == offs || po == Type::OffsetBot || offs == Type::OffsetBot) {
      if (deferred)
        add_deferred_edge(fi, to_i);
      else
        add_pointsto_edge(fi, to_i);
    }
  }
}

415 416
// Add a deferred  edge from node given by "from_i" to any field of adr_i
// whose offset matches "offset".
D
duke 已提交
417
void ConnectionGraph::add_deferred_edge_to_fields(uint from_i, uint adr_i, int offs) {
418 419 420 421 422 423 424 425 426
  // No fields for NULL pointer.
  if (is_null_ptr(adr_i)) {
    return;
  }
  if (adr_i == _phantom_object) {
    // Add only one edge for unknown object.
    add_pointsto_edge(from_i, _phantom_object);
    return;
  }
427
  PointsToNode* an = ptnode_adr(adr_i);
428
  bool is_alloc = an->_node->is_Allocate();
429 430 431 432
  for (uint fe = 0; fe < an->edge_count(); fe++) {
    assert(an->edge_type(fe) == PointsToNode::FieldEdge, "expecting a field edge");
    int fi = an->edge_target(fe);
    PointsToNode* pf = ptnode_adr(fi);
433 434 435
    int offset = pf->offset();
    if (!is_alloc) {
      // Assume the field was set outside this method if it is not Allocation
D
duke 已提交
436 437
      add_pointsto_edge(fi, _phantom_object);
    }
438
    if (offset == offs || offset == Type::OffsetBot || offs == Type::OffsetBot) {
D
duke 已提交
439 440 441
      add_deferred_edge(from_i, fi);
    }
  }
442 443 444 445 446 447 448
  // Some fields references (AddP) may still be missing
  // until Connection Graph construction is complete.
  // For example, loads from RAW pointers with offset 0
  // which don't have AddP.
  // A reference to phantom_object will be added if
  // a field reference is still missing after completing
  // Connection Graph (see remove_deferred()).
D
duke 已提交
449 450
}

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
// Helper functions

static Node* get_addp_base(Node *addp) {
  assert(addp->is_AddP(), "must be AddP");
  //
  // AddP cases for Base and Address inputs:
  // case #1. Direct object's field reference:
  //     Allocate
  //       |
  //     Proj #5 ( oop result )
  //       |
  //     CheckCastPP (cast to instance type)
  //      | |
  //     AddP  ( base == address )
  //
  // case #2. Indirect object's field reference:
  //      Phi
  //       |
  //     CastPP (cast to instance type)
  //      | |
  //     AddP  ( base == address )
  //
  // case #3. Raw object's field reference for Initialize node:
  //      Allocate
  //        |
  //      Proj #5 ( oop result )
  //  top   |
  //     \  |
  //     AddP  ( base == top )
  //
  // case #4. Array's element reference:
  //   {CheckCastPP | CastPP}
  //     |  | |
  //     |  AddP ( array's element offset )
  //     |  |
  //     AddP ( array's offset )
  //
  // case #5. Raw object's field reference for arraycopy stub call:
  //          The inline_native_clone() case when the arraycopy stub is called
  //          after the allocation before Initialize and CheckCastPP nodes.
  //      Allocate
  //        |
  //      Proj #5 ( oop result )
  //       | |
  //       AddP  ( base == address )
  //
K
kvn 已提交
497 498 499
  // case #6. Constant Pool, ThreadLocal, CastX2P or
  //          Raw object's field reference:
  //      {ConP, ThreadLocal, CastX2P, raw Load}
500 501 502 503
  //  top   |
  //     \  |
  //     AddP  ( base == top )
  //
K
kvn 已提交
504 505 506 507 508
  // case #7. Klass's field reference.
  //      LoadKlass
  //       | |
  //       AddP  ( base == address )
  //
509 510 511 512 513 514 515
  // case #8. narrow Klass's field reference.
  //      LoadNKlass
  //       |
  //      DecodeN
  //       | |
  //       AddP  ( base == address )
  //
516 517 518
  Node *base = addp->in(AddPNode::Base)->uncast();
  if (base->is_top()) { // The AddP case #3 and #6.
    base = addp->in(AddPNode::Address)->uncast();
519 520 521 522 523
    while (base->is_AddP()) {
      // Case #6 (unsafe access) may have several chained AddP nodes.
      assert(base->in(AddPNode::Base)->is_top(), "expected unsafe access address only");
      base = base->in(AddPNode::Address)->uncast();
    }
524
    assert(base->Opcode() == Op_ConP || base->Opcode() == Op_ThreadLocal ||
525
           base->Opcode() == Op_CastX2P || base->is_DecodeN() ||
K
kvn 已提交
526 527
           (base->is_Mem() && base->bottom_type() == TypeRawPtr::NOTNULL) ||
           (base->is_Proj() && base->in(0)->is_Allocate()), "sanity");
D
duke 已提交
528
  }
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
  return base;
}

static Node* find_second_addp(Node* addp, Node* n) {
  assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");

  Node* addp2 = addp->raw_out(0);
  if (addp->outcnt() == 1 && addp2->is_AddP() &&
      addp2->in(AddPNode::Base) == n &&
      addp2->in(AddPNode::Address) == addp) {

    assert(addp->in(AddPNode::Base) == n, "expecting the same base");
    //
    // Find array's offset to push it on worklist first and
    // as result process an array's element offset first (pushed second)
    // to avoid CastPP for the array's offset.
    // Otherwise the inserted CastPP (LocalVar) will point to what
    // the AddP (Field) points to. Which would be wrong since
    // the algorithm expects the CastPP has the same point as
    // as AddP's base CheckCastPP (LocalVar).
    //
    //    ArrayAllocation
    //     |
    //    CheckCastPP
    //     |
    //    memProj (from ArrayAllocation CheckCastPP)
    //     |  ||
    //     |  ||   Int (element index)
    //     |  ||    |   ConI (log(element size))
    //     |  ||    |   /
    //     |  ||   LShift
    //     |  ||  /
    //     |  AddP (array's element offset)
    //     |  |
    //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
    //     | / /
    //     AddP (array's offset)
    //      |
    //     Load/Store (memory operation on array's element)
    //
    return addp2;
  }
  return NULL;
D
duke 已提交
572 573 574 575 576 577
}

//
// Adjust the type and inputs of an AddP which computes the
// address of a field of an instance
//
578
bool ConnectionGraph::split_AddP(Node *addp, Node *base,  PhaseGVN  *igvn) {
D
duke 已提交
579
  const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
580
  assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
581 582 583
  const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
  if (t == NULL) {
    // We are computing a raw address for a store captured by an Initialize
584
    // compute an appropriate address type (cases #3 and #5).
585 586
    assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
    assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
587
    intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
588 589 590
    assert(offs != Type::OffsetBot, "offset must be a constant");
    t = base_t->add_offset(offs)->is_oopptr();
  }
591 592
  int inst_id =  base_t->instance_id();
  assert(!t->is_known_instance() || t->instance_id() == inst_id,
D
duke 已提交
593
                             "old type must be non-instance or match new type");
594 595 596 597 598 599

  // The type 't' could be subclass of 'base_t'.
  // As result t->offset() could be large then base_t's size and it will
  // cause the failure in add_offset() with narrow oops since TypeOopPtr()
  // constructor verifies correctness of the offset.
  //
T
twisti 已提交
600
  // It could happened on subclass's branch (from the type profiling
601 602 603
  // inlining) which was not eliminated during parsing since the exactness
  // of the allocation type was not propagated to the subclass type check.
  //
604 605 606 607
  // Or the type 't' could be not related to 'base_t' at all.
  // It could happened when CHA type is different from MDO type on a dead path
  // (for example, from instanceof check) which is not collapsed during parsing.
  //
608 609 610 611
  // Do nothing for such AddP node and don't process its users since
  // this code branch will go away.
  //
  if (!t->is_known_instance() &&
612
      !base_t->klass()->is_subtype_of(t->klass())) {
613 614 615
     return false; // bail out
  }

D
duke 已提交
616
  const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
617 618 619
  // Do NOT remove the next line: ensure a new alias index is allocated
  // for the instance type. Note: C++ will not remove it since the call
  // has side effect.
D
duke 已提交
620 621 622
  int alias_idx = _compile->get_alias_index(tinst);
  igvn->set_type(addp, tinst);
  // record the allocation in the node map
623
  assert(ptnode_adr(addp->_idx)->_node != NULL, "should be registered");
D
duke 已提交
624
  set_map(addp->_idx, get_map(base->_idx));
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

  // Set addp's Base and Address to 'base'.
  Node *abase = addp->in(AddPNode::Base);
  Node *adr   = addp->in(AddPNode::Address);
  if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
      adr->in(0)->_idx == (uint)inst_id) {
    // Skip AddP cases #3 and #5.
  } else {
    assert(!abase->is_top(), "sanity"); // AddP case #3
    if (abase != base) {
      igvn->hash_delete(addp);
      addp->set_req(AddPNode::Base, base);
      if (abase == adr) {
        addp->set_req(AddPNode::Address, base);
      } else {
        // AddP case #4 (adr is array's element offset AddP node)
#ifdef ASSERT
        const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
        assert(adr->is_AddP() && atype != NULL &&
               atype->instance_id() == inst_id, "array's element offset should be processed first");
#endif
      }
      igvn->hash_insert(addp);
    }
D
duke 已提交
649
  }
650 651
  // Put on IGVN worklist since at least addp's type was changed above.
  record_for_optimizer(addp);
652
  return true;
D
duke 已提交
653 654 655 656
}

//
// Create a new version of orig_phi if necessary. Returns either the newly
657
// created phi or an existing phi.  Sets create_new to indicate whether a new
D
duke 已提交
658 659 660 661 662 663 664
// phi was created.  Cache the last newly created phi in the node map.
//
PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, PhaseGVN  *igvn, bool &new_created) {
  Compile *C = _compile;
  new_created = false;
  int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
  // nothing to do if orig_phi is bottom memory or matches alias_idx
665
  if (phi_alias_idx == alias_idx) {
D
duke 已提交
666 667
    return orig_phi;
  }
668
  // Have we recently created a Phi for this alias index?
D
duke 已提交
669 670 671 672
  PhiNode *result = get_map_phi(orig_phi->_idx);
  if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
    return result;
  }
673 674 675 676 677 678 679 680 681 682 683 684 685
  // Previous check may fail when the same wide memory Phi was split into Phis
  // for different memory slices. Search all Phis for this region.
  if (result != NULL) {
    Node* region = orig_phi->in(0);
    for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
      Node* phi = region->fast_out(i);
      if (phi->is_Phi() &&
          C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
        assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
        return phi->as_Phi();
      }
    }
  }
686 687 688 689 690 691 692 693 694
  if ((int)C->unique() + 2*NodeLimitFudgeFactor > MaxNodeLimit) {
    if (C->do_escape_analysis() == true && !C->failing()) {
      // Retry compilation without escape analysis.
      // If this is the first failure, the sentinel string will "stick"
      // to the Compile object, and the C2Compiler will see it and retry.
      C->record_failure(C2Compiler::retry_no_escape_analysis());
    }
    return NULL;
  }
D
duke 已提交
695
  orig_phi_worklist.append_if_missing(orig_phi);
696
  const TypePtr *atype = C->get_adr_type(alias_idx);
D
duke 已提交
697
  result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
698
  C->copy_node_notes_to(result, orig_phi);
D
duke 已提交
699 700
  igvn->set_type(result, result->bottom_type());
  record_for_optimizer(result);
701 702 703 704 705 706

  debug_only(Node* pn = ptnode_adr(orig_phi->_idx)->_node;)
  assert(pn == NULL || pn == orig_phi, "wrong node");
  set_map(orig_phi->_idx, result);
  ptnode_adr(orig_phi->_idx)->_node = orig_phi;

D
duke 已提交
707 708 709 710 711
  new_created = true;
  return result;
}

//
712
// Return a new version of Memory Phi "orig_phi" with the inputs having the
D
duke 已提交
713 714 715 716 717 718 719
// specified alias index.
//
PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, PhaseGVN  *igvn) {

  assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
  Compile *C = _compile;
  bool new_phi_created;
720
  PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, igvn, new_phi_created);
D
duke 已提交
721 722 723 724 725 726 727 728 729 730 731 732
  if (!new_phi_created) {
    return result;
  }

  GrowableArray<PhiNode *>  phi_list;
  GrowableArray<uint>  cur_input;

  PhiNode *phi = orig_phi;
  uint idx = 1;
  bool finished = false;
  while(!finished) {
    while (idx < phi->req()) {
733
      Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, igvn);
D
duke 已提交
734
      if (mem != NULL && mem->is_Phi()) {
735
        PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, igvn, new_phi_created);
D
duke 已提交
736 737 738 739 740 741
        if (new_phi_created) {
          // found an phi for which we created a new split, push current one on worklist and begin
          // processing new one
          phi_list.push(phi);
          cur_input.push(idx);
          phi = mem->as_Phi();
742
          result = newphi;
D
duke 已提交
743 744 745
          idx = 1;
          continue;
        } else {
746
          mem = newphi;
D
duke 已提交
747 748
        }
      }
749 750 751
      if (C->failing()) {
        return NULL;
      }
D
duke 已提交
752 753 754 755 756 757
      result->set_req(idx++, mem);
    }
#ifdef ASSERT
    // verify that the new Phi has an input for each input of the original
    assert( phi->req() == result->req(), "must have same number of inputs.");
    assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
758 759 760
#endif
    // Check if all new phi's inputs have specified alias index.
    // Otherwise use old phi.
D
duke 已提交
761
    for (uint i = 1; i < phi->req(); i++) {
762 763
      Node* in = result->in(i);
      assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
D
duke 已提交
764 765 766 767 768 769
    }
    // we have finished processing a Phi, see if there are any more to do
    finished = (phi_list.length() == 0 );
    if (!finished) {
      phi = phi_list.pop();
      idx = cur_input.pop();
770 771 772
      PhiNode *prev_result = get_map_phi(phi->_idx);
      prev_result->set_req(idx++, result);
      result = prev_result;
D
duke 已提交
773 774 775 776 777
    }
  }
  return result;
}

778 779 780 781

//
// The next methods are derived from methods in MemNode.
//
782
static Node *step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
783
  Node *mem = mmem;
784
  // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
785 786
  // means an array I have not precisely typed yet.  Do not do any
  // alias stuff with it any time soon.
787 788 789 790
  if( toop->base() != Type::AnyPtr &&
      !(toop->klass() != NULL &&
        toop->klass()->is_java_lang_Object() &&
        toop->offset() == Type::OffsetBot) ) {
791 792 793 794 795 796
    mem = mmem->memory_at(alias_idx);
    // Update input if it is progress over what we have now
  }
  return mem;
}

797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
//
// Move memory users to their memory slices.
//
void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis, PhaseGVN *igvn) {
  Compile* C = _compile;

  const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
  assert(tp != NULL, "ptr type");
  int alias_idx = C->get_alias_index(tp);
  int general_idx = C->get_general_index(alias_idx);

  // Move users first
  for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
    Node* use = n->fast_out(i);
    if (use->is_MergeMem()) {
      MergeMemNode* mmem = use->as_MergeMem();
      assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
      if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
        continue; // Nothing to do
      }
      // Replace previous general reference to mem node.
      uint orig_uniq = C->unique();
      Node* m = find_inst_mem(n, general_idx, orig_phis, igvn);
      assert(orig_uniq == C->unique(), "no new nodes");
      mmem->set_memory_at(general_idx, m);
      --imax;
      --i;
    } else if (use->is_MemBar()) {
      assert(!use->is_Initialize(), "initializing stores should not be moved");
      if (use->req() > MemBarNode::Precedent &&
          use->in(MemBarNode::Precedent) == n) {
        // Don't move related membars.
        record_for_optimizer(use);
        continue;
      }
      tp = use->as_MemBar()->adr_type()->isa_ptr();
      if (tp != NULL && C->get_alias_index(tp) == alias_idx ||
          alias_idx == general_idx) {
        continue; // Nothing to do
      }
      // Move to general memory slice.
      uint orig_uniq = C->unique();
      Node* m = find_inst_mem(n, general_idx, orig_phis, igvn);
      assert(orig_uniq == C->unique(), "no new nodes");
      igvn->hash_delete(use);
      imax -= use->replace_edge(n, m);
      igvn->hash_insert(use);
      record_for_optimizer(use);
      --i;
#ifdef ASSERT
    } else if (use->is_Mem()) {
      if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
        // Don't move related cardmark.
        continue;
      }
      // Memory nodes should have new memory input.
      tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
      assert(tp != NULL, "ptr type");
      int idx = C->get_alias_index(tp);
      assert(get_map(use->_idx) != NULL || idx == alias_idx,
             "Following memory nodes should have new memory input or be on the same memory slice");
    } else if (use->is_Phi()) {
      // Phi nodes should be split and moved already.
      tp = use->as_Phi()->adr_type()->isa_ptr();
      assert(tp != NULL, "ptr type");
      int idx = C->get_alias_index(tp);
      assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
    } else {
      use->dump();
      assert(false, "should not be here");
#endif
    }
  }
}

872 873 874 875 876 877 878 879
//
// Search memory chain of "mem" to find a MemNode whose address
// is the specified alias index.
//
Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis, PhaseGVN *phase) {
  if (orig_mem == NULL)
    return orig_mem;
  Compile* C = phase->C;
880 881
  const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
  bool is_instance = (toop != NULL) && toop->is_known_instance();
882
  Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
883 884 885 886
  Node *prev = NULL;
  Node *result = orig_mem;
  while (prev != result) {
    prev = result;
887
    if (result == start_mem)
T
twisti 已提交
888
      break;  // hit one of our sentinels
889
    if (result->is_Mem()) {
890
      const Type *at = phase->type(result->in(MemNode::Address));
891 892 893 894 895 896 897 898 899
      if (at == Type::TOP)
        break; // Dead
      assert (at->isa_ptr() != NULL, "pointer type required.");
      int idx = C->get_alias_index(at->is_ptr());
      if (idx == alias_idx)
        break; // Found
      if (!is_instance && (at->isa_oopptr() == NULL ||
                           !at->is_oopptr()->is_known_instance())) {
        break; // Do not skip store to general memory slice.
900
      }
901
      result = result->in(MemNode::Memory);
902 903 904 905 906 907
    }
    if (!is_instance)
      continue;  // don't search further for non-instance types
    // skip over a call which does not affect this memory slice
    if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
      Node *proj_in = result->in(0);
908
      if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
T
twisti 已提交
909
        break;  // hit one of our sentinels
910
      } else if (proj_in->is_Call()) {
911
        CallNode *call = proj_in->as_Call();
912
        if (!call->may_modify(toop, phase)) {
913 914 915 916 917 918
          result = call->in(TypeFunc::Memory);
        }
      } else if (proj_in->is_Initialize()) {
        AllocateNode* alloc = proj_in->as_Initialize()->allocation();
        // Stop if this is the initialization for the object instance which
        // which contains this memory slice, otherwise skip over it.
919
        if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
920 921 922 923 924 925 926
          result = proj_in->in(TypeFunc::Memory);
        }
      } else if (proj_in->is_MemBar()) {
        result = proj_in->in(TypeFunc::Memory);
      }
    } else if (result->is_MergeMem()) {
      MergeMemNode *mmem = result->as_MergeMem();
927
      result = step_through_mergemem(mmem, alias_idx, toop);
928 929 930 931 932 933 934 935 936 937 938 939 940
      if (result == mmem->base_memory()) {
        // Didn't find instance memory, search through general slice recursively.
        result = mmem->memory_at(C->get_general_index(alias_idx));
        result = find_inst_mem(result, alias_idx, orig_phis, phase);
        if (C->failing()) {
          return NULL;
        }
        mmem->set_memory_at(alias_idx, result);
      }
    } else if (result->is_Phi() &&
               C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
      Node *un = result->as_Phi()->unique_input(phase);
      if (un != NULL) {
941
        orig_phis.append_if_missing(result->as_Phi());
942 943 944 945
        result = un;
      } else {
        break;
      }
946
    } else if (result->is_ClearArray()) {
947
      if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), phase)) {
948 949 950 951 952
        // Can not bypass initialization of the instance
        // we are looking for.
        break;
      }
      // Otherwise skip it (the call updated 'result' value).
953 954 955 956 957 958 959 960 961 962
    } else if (result->Opcode() == Op_SCMemProj) {
      assert(result->in(0)->is_LoadStore(), "sanity");
      const Type *at = phase->type(result->in(0)->in(MemNode::Address));
      if (at != Type::TOP) {
        assert (at->isa_ptr() != NULL, "pointer type required.");
        int idx = C->get_alias_index(at->is_ptr());
        assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
        break;
      }
      result = result->in(0)->in(MemNode::Memory);
963 964
    }
  }
965
  if (result->is_Phi()) {
966 967 968
    PhiNode *mphi = result->as_Phi();
    assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
    const TypePtr *t = mphi->adr_type();
969
    if (!is_instance) {
970 971 972
      // Push all non-instance Phis on the orig_phis worklist to update inputs
      // during Phase 4 if needed.
      orig_phis.append_if_missing(mphi);
973 974 975
    } else if (C->get_alias_index(t) != alias_idx) {
      // Create a new Phi with the specified alias index type.
      result = split_memory_phi(mphi, alias_idx, orig_phis, phase);
976 977 978 979 980 981
    }
  }
  // the result is either MemNode, PhiNode, InitializeNode.
  return result;
}

D
duke 已提交
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
//
//  Convert the types of unescaped object to instance types where possible,
//  propagate the new type information through the graph, and update memory
//  edges and MergeMem inputs to reflect the new type.
//
//  We start with allocations (and calls which may be allocations)  on alloc_worklist.
//  The processing is done in 4 phases:
//
//  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
//            types for the CheckCastPP for allocations where possible.
//            Propagate the the new types through users as follows:
//               casts and Phi:  push users on alloc_worklist
//               AddP:  cast Base and Address inputs to the instance type
//                      push any AddP users on alloc_worklist and push any memnode
//                      users onto memnode_worklist.
//  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
//            search the Memory chain for a store with the appropriate type
//            address type.  If a Phi is found, create a new version with
T
twisti 已提交
1000
//            the appropriate memory slices from each of the Phi inputs.
D
duke 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
//            For stores, process the users as follows:
//               MemNode:  push on memnode_worklist
//               MergeMem: push on mergemem_worklist
//  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
//            moving the first node encountered of each  instance type to the
//            the input corresponding to its alias index.
//            appropriate memory slice.
//  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
//
// In the following example, the CheckCastPP nodes are the cast of allocation
// results and the allocation of node 29 is unescaped and eligible to be an
// instance type.
//
// We start with:
//
//     7 Parm #memory
//    10  ConI  "12"
//    19  CheckCastPP   "Foo"
//    20  AddP  _ 19 19 10  Foo+12  alias_index=4
//    29  CheckCastPP   "Foo"
//    30  AddP  _ 29 29 10  Foo+12  alias_index=4
//
//    40  StoreP  25   7  20   ... alias_index=4
//    50  StoreP  35  40  30   ... alias_index=4
//    60  StoreP  45  50  20   ... alias_index=4
//    70  LoadP    _  60  30   ... alias_index=4
//    80  Phi     75  50  60   Memory alias_index=4
//    90  LoadP    _  80  30   ... alias_index=4
//   100  LoadP    _  80  20   ... alias_index=4
//
//
// Phase 1 creates an instance type for node 29 assigning it an instance id of 24
// and creating a new alias index for node 30.  This gives:
//
//     7 Parm #memory
//    10  ConI  "12"
//    19  CheckCastPP   "Foo"
//    20  AddP  _ 19 19 10  Foo+12  alias_index=4
//    29  CheckCastPP   "Foo"  iid=24
//    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
//
//    40  StoreP  25   7  20   ... alias_index=4
//    50  StoreP  35  40  30   ... alias_index=6
//    60  StoreP  45  50  20   ... alias_index=4
//    70  LoadP    _  60  30   ... alias_index=6
//    80  Phi     75  50  60   Memory alias_index=4
//    90  LoadP    _  80  30   ... alias_index=6
//   100  LoadP    _  80  20   ... alias_index=4
//
// In phase 2, new memory inputs are computed for the loads and stores,
// And a new version of the phi is created.  In phase 4, the inputs to
// node 80 are updated and then the memory nodes are updated with the
// values computed in phase 2.  This results in:
//
//     7 Parm #memory
//    10  ConI  "12"
//    19  CheckCastPP   "Foo"
//    20  AddP  _ 19 19 10  Foo+12  alias_index=4
//    29  CheckCastPP   "Foo"  iid=24
//    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
//
//    40  StoreP  25  7   20   ... alias_index=4
//    50  StoreP  35  7   30   ... alias_index=6
//    60  StoreP  45  40  20   ... alias_index=4
//    70  LoadP    _  50  30   ... alias_index=6
//    80  Phi     75  40  60   Memory alias_index=4
//   120  Phi     75  50  50   Memory alias_index=6
//    90  LoadP    _ 120  30   ... alias_index=6
//   100  LoadP    _  80  20   ... alias_index=4
//
void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist) {
  GrowableArray<Node *>  memnode_worklist;
  GrowableArray<PhiNode *>  orig_phis;
1074

K
kvn 已提交
1075
  PhaseIterGVN  *igvn = _igvn;
D
duke 已提交
1076
  uint new_index_start = (uint) _compile->num_alias_types();
1077 1078
  Arena* arena = Thread::current()->resource_area();
  VectorSet visited(arena);
D
duke 已提交
1079

1080 1081 1082

  //  Phase 1:  Process possible allocations from alloc_worklist.
  //  Create instance types for the CheckCastPP for allocations where possible.
1083 1084 1085 1086 1087
  //
  // (Note: don't forget to change the order of the second AddP node on
  //  the alloc_worklist if the order of the worklist processing is changed,
  //  see the comment in find_second_addp().)
  //
D
duke 已提交
1088 1089 1090
  while (alloc_worklist.length() != 0) {
    Node *n = alloc_worklist.pop();
    uint ni = n->_idx;
1091
    const TypeOopPtr* tinst = NULL;
D
duke 已提交
1092 1093 1094
    if (n->is_Call()) {
      CallNode *alloc = n->as_Call();
      // copy escape information to call node
1095
      PointsToNode* ptn = ptnode_adr(alloc->_idx);
1096
      PointsToNode::EscapeState es = escape_state(alloc);
1097 1098
      // We have an allocation or call which returns a Java object,
      // see if it is unescaped.
1099
      if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable())
D
duke 已提交
1100
        continue;
1101 1102

      // Find CheckCastPP for the allocate or for the return value of a call
1103
      n = alloc->result_cast();
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
      if (n == NULL) {            // No uses except Initialize node
        if (alloc->is_Allocate()) {
          // Set the scalar_replaceable flag for allocation
          // so it could be eliminated if it has no uses.
          alloc->as_Allocate()->_is_scalar_replaceable = true;
        }
        continue;
      }
      if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
        assert(!alloc->is_Allocate(), "allocation should have unique type");
1114
        continue;
1115 1116
      }

1117
      // The inline code for Object.clone() casts the allocation result to
1118
      // java.lang.Object and then to the actual type of the allocated
1119
      // object. Detect this case and use the second cast.
1120 1121 1122
      // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
      // the allocation result is cast to java.lang.Object and then
      // to the actual Array type.
1123
      if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
1124 1125
          && (alloc->is_AllocateArray() ||
              igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) {
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
        Node *cast2 = NULL;
        for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
          Node *use = n->fast_out(i);
          if (use->is_CheckCastPP()) {
            cast2 = use;
            break;
          }
        }
        if (cast2 != NULL) {
          n = cast2;
        } else {
1137 1138 1139
          // Non-scalar replaceable if the allocation type is unknown statically
          // (reflection allocation), the object can't be restored during
          // deoptimization without precise type.
1140 1141 1142
          continue;
        }
      }
1143 1144 1145 1146 1147
      if (alloc->is_Allocate()) {
        // Set the scalar_replaceable flag for allocation
        // so it could be eliminated.
        alloc->as_Allocate()->_is_scalar_replaceable = true;
      }
1148
      set_escape_state(n->_idx, es); // CheckCastPP escape state
1149
      // in order for an object to be scalar-replaceable, it must be:
1150 1151 1152 1153
      //   - a direct allocation (not a call returning an object)
      //   - non-escaping
      //   - eligible to be a unique type
      //   - not determined to be ineligible by escape analysis
1154 1155
      assert(ptnode_adr(alloc->_idx)->_node != NULL &&
             ptnode_adr(n->_idx)->_node != NULL, "should be registered");
D
duke 已提交
1156 1157
      set_map(alloc->_idx, n);
      set_map(n->_idx, alloc);
1158 1159
      const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
      if (t == NULL)
1160
        continue;  // not a TypeOopPtr
1161
      tinst = t->cast_to_exactness(true)->is_oopptr()->cast_to_instance_id(ni);
D
duke 已提交
1162 1163 1164 1165
      igvn->hash_delete(n);
      igvn->set_type(n,  tinst);
      n->raise_bottom_type(tinst);
      igvn->hash_insert(n);
1166
      record_for_optimizer(n);
1167
      if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
1168 1169 1170 1171

        // First, put on the worklist all Field edges from Connection Graph
        // which is more accurate then putting immediate users from Ideal Graph.
        for (uint e = 0; e < ptn->edge_count(); e++) {
1172
          Node *use = ptnode_adr(ptn->edge_target(e))->_node;
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
          assert(ptn->edge_type(e) == PointsToNode::FieldEdge && use->is_AddP(),
                 "only AddP nodes are Field edges in CG");
          if (use->outcnt() > 0) { // Don't process dead nodes
            Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
            if (addp2 != NULL) {
              assert(alloc->is_AllocateArray(),"array allocation was expected");
              alloc_worklist.append_if_missing(addp2);
            }
            alloc_worklist.append_if_missing(use);
          }
        }

1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
        // An allocation may have an Initialize which has raw stores. Scan
        // the users of the raw allocation result and push AddP users
        // on alloc_worklist.
        Node *raw_result = alloc->proj_out(TypeFunc::Parms);
        assert (raw_result != NULL, "must have an allocation result");
        for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
          Node *use = raw_result->fast_out(i);
          if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
            Node* addp2 = find_second_addp(use, raw_result);
            if (addp2 != NULL) {
              assert(alloc->is_AllocateArray(),"array allocation was expected");
              alloc_worklist.append_if_missing(addp2);
            }
            alloc_worklist.append_if_missing(use);
1199
          } else if (use->is_MemBar()) {
1200 1201 1202 1203
            memnode_worklist.append_if_missing(use);
          }
        }
      }
D
duke 已提交
1204
    } else if (n->is_AddP()) {
1205 1206 1207
      VectorSet* ptset = PointsTo(get_addp_base(n));
      assert(ptset->Size() == 1, "AddP address is unique");
      uint elem = ptset->getelem(); // Allocation node's index
1208 1209
      if (elem == _phantom_object) {
        assert(false, "escaped allocation");
1210
        continue; // Assume the value was set outside this method.
1211
      }
1212
      Node *base = get_map(elem);  // CheckCastPP node
1213
      if (!split_AddP(n, base, igvn)) continue; // wrong type from dead path
1214 1215 1216
      tinst = igvn->type(base)->isa_oopptr();
    } else if (n->is_Phi() ||
               n->is_CheckCastPP() ||
1217 1218
               n->is_EncodeP() ||
               n->is_DecodeN() ||
1219
               (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
D
duke 已提交
1220 1221 1222 1223
      if (visited.test_set(n->_idx)) {
        assert(n->is_Phi(), "loops only through Phi's");
        continue;  // already processed
      }
1224 1225 1226
      VectorSet* ptset = PointsTo(n);
      if (ptset->Size() == 1) {
        uint elem = ptset->getelem(); // Allocation node's index
1227 1228
        if (elem == _phantom_object) {
          assert(false, "escaped allocation");
1229
          continue; // Assume the value was set outside this method.
1230
        }
1231
        Node *val = get_map(elem);   // CheckCastPP node
D
duke 已提交
1232
        TypeNode *tn = n->as_Type();
1233
        tinst = igvn->type(val)->isa_oopptr();
1234 1235
        assert(tinst != NULL && tinst->is_known_instance() &&
               (uint)tinst->instance_id() == elem , "instance type expected.");
1236 1237

        const Type *tn_type = igvn->type(tn);
1238
        const TypeOopPtr *tn_t;
1239
        if (tn_type->isa_narrowoop()) {
1240
          tn_t = tn_type->make_ptr()->isa_oopptr();
1241 1242 1243
        } else {
          tn_t = tn_type->isa_oopptr();
        }
D
duke 已提交
1244

1245
        if (tn_t != NULL && tinst->klass()->is_subtype_of(tn_t->klass())) {
1246 1247 1248 1249 1250
          if (tn_type->isa_narrowoop()) {
            tn_type = tinst->make_narrowoop();
          } else {
            tn_type = tinst;
          }
D
duke 已提交
1251
          igvn->hash_delete(tn);
1252 1253
          igvn->set_type(tn, tn_type);
          tn->set_type(tn_type);
D
duke 已提交
1254
          igvn->hash_insert(tn);
1255
          record_for_optimizer(n);
1256
        } else {
1257 1258 1259 1260
          assert(tn_type == TypePtr::NULL_PTR ||
                 tn_t != NULL && !tinst->klass()->is_subtype_of(tn_t->klass()),
                 "unexpected type");
          continue; // Skip dead path with different type
D
duke 已提交
1261 1262 1263
        }
      }
    } else {
1264 1265
      debug_only(n->dump();)
      assert(false, "EA: unexpected node");
D
duke 已提交
1266 1267
      continue;
    }
1268
    // push allocation's users on appropriate worklist
D
duke 已提交
1269 1270 1271
    for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
      Node *use = n->fast_out(i);
      if(use->is_Mem() && use->in(MemNode::Address) == n) {
1272
        // Load/store to instance's field
1273
        memnode_worklist.append_if_missing(use);
1274
      } else if (use->is_MemBar()) {
1275 1276 1277 1278 1279 1280 1281 1282 1283
        memnode_worklist.append_if_missing(use);
      } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
        Node* addp2 = find_second_addp(use, n);
        if (addp2 != NULL) {
          alloc_worklist.append_if_missing(addp2);
        }
        alloc_worklist.append_if_missing(use);
      } else if (use->is_Phi() ||
                 use->is_CheckCastPP() ||
1284 1285
                 use->is_EncodeP() ||
                 use->is_DecodeN() ||
1286 1287
                 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
        alloc_worklist.append_if_missing(use);
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
#ifdef ASSERT
      } else if (use->is_Mem()) {
        assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
      } else if (use->is_MergeMem()) {
        assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
      } else if (use->is_SafePoint()) {
        // Look for MergeMem nodes for calls which reference unique allocation
        // (through CheckCastPP nodes) even for debug info.
        Node* m = use->in(TypeFunc::Memory);
        if (m->is_MergeMem()) {
          assert(_mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
        }
      } else {
        uint op = use->Opcode();
        if (!(op == Op_CmpP || op == Op_Conv2B ||
              op == Op_CastP2X || op == Op_StoreCM ||
              op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
              op == Op_StrEquals || op == Op_StrIndexOf)) {
          n->dump();
          use->dump();
          assert(false, "EA: missing allocation reference path");
        }
#endif
D
duke 已提交
1311 1312 1313 1314
      }
    }

  }
1315
  // New alias types were created in split_AddP().
D
duke 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
  uint new_index_end = (uint) _compile->num_alias_types();

  //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
  //            compute new values for Memory inputs  (the Memory inputs are not
  //            actually updated until phase 4.)
  if (memnode_worklist.length() == 0)
    return;  // nothing to do

  while (memnode_worklist.length() != 0) {
    Node *n = memnode_worklist.pop();
1326 1327
    if (visited.test_set(n->_idx))
      continue;
1328 1329 1330 1331 1332
    if (n->is_Phi() || n->is_ClearArray()) {
      // we don't need to do anything, but the users must be pushed
    } else if (n->is_MemBar()) { // Initialize, MemBar nodes
      // we don't need to do anything, but the users must be pushed
      n = n->as_MemBar()->proj_out(TypeFunc::Memory);
1333
      if (n == NULL)
D
duke 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342
        continue;
    } else {
      assert(n->is_Mem(), "memory node required.");
      Node *addr = n->in(MemNode::Address);
      const Type *addr_t = igvn->type(addr);
      if (addr_t == Type::TOP)
        continue;
      assert (addr_t->isa_ptr() != NULL, "pointer type required.");
      int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
1343 1344
      assert ((uint)alias_idx < new_index_end, "wrong alias index");
      Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis, igvn);
1345 1346 1347
      if (_compile->failing()) {
        return;
      }
1348
      if (mem != n->in(MemNode::Memory)) {
1349 1350 1351 1352
        // We delay the memory edge update since we need old one in
        // MergeMem code below when instances memory slices are separated.
        debug_only(Node* pn = ptnode_adr(n->_idx)->_node;)
        assert(pn == NULL || pn == n, "wrong node");
D
duke 已提交
1353
        set_map(n->_idx, mem);
1354
        ptnode_adr(n->_idx)->_node = n;
1355
      }
D
duke 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
      if (n->is_Load()) {
        continue;  // don't push users
      } else if (n->is_LoadStore()) {
        // get the memory projection
        for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
          Node *use = n->fast_out(i);
          if (use->Opcode() == Op_SCMemProj) {
            n = use;
            break;
          }
        }
        assert(n->Opcode() == Op_SCMemProj, "memory projection required");
      }
    }
    // push user on appropriate worklist
    for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
      Node *use = n->fast_out(i);
1373
      if (use->is_Phi() || use->is_ClearArray()) {
1374
        memnode_worklist.append_if_missing(use);
D
duke 已提交
1375
      } else if(use->is_Mem() && use->in(MemNode::Memory) == n) {
1376 1377
        if (use->Opcode() == Op_StoreCM) // Ignore cardmark stores
          continue;
1378
        memnode_worklist.append_if_missing(use);
1379
      } else if (use->is_MemBar()) {
1380
        memnode_worklist.append_if_missing(use);
1381 1382 1383
#ifdef ASSERT
      } else if(use->is_Mem()) {
        assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
D
duke 已提交
1384
      } else if (use->is_MergeMem()) {
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
        assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
      } else {
        uint op = use->Opcode();
        if (!(op == Op_StoreCM ||
              (op == Op_CallLeaf && use->as_CallLeaf()->_name != NULL &&
               strcmp(use->as_CallLeaf()->_name, "g1_wb_pre") == 0) ||
              op == Op_AryEq || op == Op_StrComp ||
              op == Op_StrEquals || op == Op_StrIndexOf)) {
          n->dump();
          use->dump();
          assert(false, "EA: missing memory path");
        }
#endif
D
duke 已提交
1398 1399 1400 1401
      }
    }
  }

1402
  //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
1403
  //            Walk each memory slice moving the first node encountered of each
1404
  //            instance type to the the input corresponding to its alias index.
1405 1406 1407 1408
  uint length = _mergemem_worklist.length();
  for( uint next = 0; next < length; ++next ) {
    MergeMemNode* nmm = _mergemem_worklist.at(next);
    assert(!visited.test_set(nmm->_idx), "should not be visited before");
D
duke 已提交
1409
    // Note: we don't want to use MergeMemStream here because we only want to
1410 1411 1412
    // scan inputs which exist at the start, not ones we add during processing.
    // Note 2: MergeMem may already contains instance memory slices added
    // during find_inst_mem() call when memory nodes were processed above.
D
duke 已提交
1413
    igvn->hash_delete(nmm);
1414
    uint nslices = nmm->req();
D
duke 已提交
1415
    for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
1416 1417
      Node* mem = nmm->in(i);
      Node* cur = NULL;
D
duke 已提交
1418 1419
      if (mem == NULL || mem->is_top())
        continue;
1420 1421
      // First, update mergemem by moving memory nodes to corresponding slices
      // if their type became more precise since this mergemem was created.
D
duke 已提交
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
      while (mem->is_Mem()) {
        const Type *at = igvn->type(mem->in(MemNode::Address));
        if (at != Type::TOP) {
          assert (at->isa_ptr() != NULL, "pointer type required.");
          uint idx = (uint)_compile->get_alias_index(at->is_ptr());
          if (idx == i) {
            if (cur == NULL)
              cur = mem;
          } else {
            if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
              nmm->set_memory_at(idx, mem);
            }
          }
        }
        mem = mem->in(MemNode::Memory);
      }
      nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
1439
      // Find any instance of the current type if we haven't encountered
1440
      // already a memory slice of the instance along the memory chain.
1441 1442 1443 1444 1445 1446 1447
      for (uint ni = new_index_start; ni < new_index_end; ni++) {
        if((uint)_compile->get_general_index(ni) == i) {
          Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
          if (nmm->is_empty_memory(m)) {
            Node* result = find_inst_mem(mem, ni, orig_phis, igvn);
            if (_compile->failing()) {
              return;
D
duke 已提交
1448
            }
1449
            nmm->set_memory_at(ni, result);
D
duke 已提交
1450 1451 1452 1453
          }
        }
      }
    }
1454 1455
    // Find the rest of instances values
    for (uint ni = new_index_start; ni < new_index_end; ni++) {
1456
      const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
1457 1458 1459
      Node* result = step_through_mergemem(nmm, ni, tinst);
      if (result == nmm->base_memory()) {
        // Didn't find instance memory, search through general slice recursively.
1460
        result = nmm->memory_at(_compile->get_general_index(ni));
1461 1462 1463 1464 1465 1466 1467
        result = find_inst_mem(result, ni, orig_phis, igvn);
        if (_compile->failing()) {
          return;
        }
        nmm->set_memory_at(ni, result);
      }
    }
D
duke 已提交
1468 1469 1470 1471
    igvn->hash_insert(nmm);
    record_for_optimizer(nmm);
  }

1472 1473
  //  Phase 4:  Update the inputs of non-instance memory Phis and
  //            the Memory input of memnodes
D
duke 已提交
1474 1475 1476 1477 1478
  // First update the inputs of any non-instance Phi's from
  // which we split out an instance Phi.  Note we don't have
  // to recursively process Phi's encounted on the input memory
  // chains as is done in split_memory_phi() since they  will
  // also be processed here.
1479 1480
  for (int j = 0; j < orig_phis.length(); j++) {
    PhiNode *phi = orig_phis.at(j);
D
duke 已提交
1481 1482 1483 1484
    int alias_idx = _compile->get_alias_index(phi->adr_type());
    igvn->hash_delete(phi);
    for (uint i = 1; i < phi->req(); i++) {
      Node *mem = phi->in(i);
1485 1486 1487 1488
      Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis, igvn);
      if (_compile->failing()) {
        return;
      }
D
duke 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497
      if (mem != new_mem) {
        phi->set_req(i, new_mem);
      }
    }
    igvn->hash_insert(phi);
    record_for_optimizer(phi);
  }

  // Update the memory inputs of MemNodes with the value we computed
1498
  // in Phase 2 and move stores memory users to corresponding memory slices.
1499 1500 1501 1502

  // Disable memory split verification code until the fix for 6984348.
  // Currently it produces false negative results since it does not cover all cases.
#if 0 // ifdef ASSERT
1503
  visited.Reset();
1504 1505
  Node_Stack old_mems(arena, _compile->unique() >> 2);
#endif
1506
  for (uint i = 0; i < nodes_size(); i++) {
D
duke 已提交
1507 1508
    Node *nmem = get_map(i);
    if (nmem != NULL) {
1509
      Node *n = ptnode_adr(i)->_node;
1510 1511
      assert(n != NULL, "sanity");
      if (n->is_Mem()) {
1512
#if 0 // ifdef ASSERT
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
        Node* old_mem = n->in(MemNode::Memory);
        if (!visited.test_set(old_mem->_idx)) {
          old_mems.push(old_mem, old_mem->outcnt());
        }
#endif
        assert(n->in(MemNode::Memory) != nmem, "sanity");
        if (!n->is_Load()) {
          // Move memory users of a store first.
          move_inst_mem(n, orig_phis, igvn);
        }
        // Now update memory input
D
duke 已提交
1524 1525 1526 1527
        igvn->hash_delete(n);
        n->set_req(MemNode::Memory, nmem);
        igvn->hash_insert(n);
        record_for_optimizer(n);
1528 1529 1530
      } else {
        assert(n->is_Allocate() || n->is_CheckCastPP() ||
               n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
D
duke 已提交
1531 1532 1533
      }
    }
  }
1534
#if 0 // ifdef ASSERT
1535 1536 1537 1538 1539
  // Verify that memory was split correctly
  while (old_mems.is_nonempty()) {
    Node* old_mem = old_mems.node();
    uint  old_cnt = old_mems.index();
    old_mems.pop();
1540
    assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
1541 1542
  }
#endif
D
duke 已提交
1543 1544
}

1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
bool ConnectionGraph::has_candidates(Compile *C) {
  // EA brings benefits only when the code has allocations and/or locks which
  // are represented by ideal Macro nodes.
  int cnt = C->macro_count();
  for( int i=0; i < cnt; i++ ) {
    Node *n = C->macro_node(i);
    if ( n->is_Allocate() )
      return true;
    if( n->is_Lock() ) {
      Node* obj = n->as_Lock()->obj_node()->uncast();
      if( !(obj->is_Parm() || obj->is_Con()) )
        return true;
    }
  }
  return false;
}

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
  // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction
  // to create space for them in ConnectionGraph::_nodes[].
  Node* oop_null = igvn->zerocon(T_OBJECT);
  Node* noop_null = igvn->zerocon(T_NARROWOOP);

  ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn);
  // Perform escape analysis
  if (congraph->compute_escape()) {
    // There are non escaping objects.
    C->set_congraph(congraph);
  }

  // Cleanup.
  if (oop_null->outcnt() == 0)
    igvn->hash_delete(oop_null);
  if (noop_null->outcnt() == 0)
    igvn->hash_delete(noop_null);
}

1582 1583
bool ConnectionGraph::compute_escape() {
  Compile* C = _compile;
D
duke 已提交
1584

1585
  // 1. Populate Connection Graph (CG) with Ideal nodes.
D
duke 已提交
1586

1587
  Unique_Node_List worklist_init;
1588
  worklist_init.map(C->unique(), NULL);  // preallocate space
1589 1590

  // Initialize worklist
1591 1592
  if (C->root() != NULL) {
    worklist_init.push(C->root());
1593 1594
  }

1595 1596
  GrowableArray<Node*> alloc_worklist;
  GrowableArray<Node*> addp_worklist;
1597
  GrowableArray<Node*> ptr_cmp_worklist;
1598
  GrowableArray<Node*> storestore_worklist;
1599
  PhaseGVN* igvn = _igvn;
1600 1601 1602 1603 1604

  // Push all useful nodes onto CG list and set their type.
  for( uint next = 0; next < worklist_init.size(); ++next ) {
    Node* n = worklist_init.at(next);
    record_for_escape_analysis(n, igvn);
1605 1606 1607 1608
    // Only allocations and java static calls results are checked
    // for an escape status. See process_call_result() below.
    if (n->is_Allocate() || n->is_CallStaticJava() &&
        ptnode_adr(n->_idx)->node_type() == PointsToNode::JavaObject) {
1609
      alloc_worklist.append(n);
1610
    } else if(n->is_AddP()) {
K
kvn 已提交
1611 1612
      // Collect address nodes. Use them during stage 3 below
      // to build initial connection graph field edges.
1613
      addp_worklist.append(n);
1614 1615 1616 1617
    } else if (n->is_MergeMem()) {
      // Collect all MergeMem nodes to add memory slices for
      // scalar replaceable objects in split_unique_types().
      _mergemem_worklist.append(n->as_MergeMem());
1618 1619 1620 1621
    } else if (OptimizePtrCompare && n->is_Cmp() &&
               (n->Opcode() == Op_CmpP || n->Opcode() == Op_CmpN)) {
      // Compare pointers nodes
      ptr_cmp_worklist.append(n);
1622 1623 1624 1625 1626
    } else if (n->is_MemBarStoreStore()) {
      // Collect all MemBarStoreStore nodes so that depending on the
      // escape status of the associated Allocate node some of them
      // may be eliminated.
      storestore_worklist.append(n);
1627
    }
1628 1629 1630 1631 1632 1633
    for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
      Node* m = n->fast_out(i);   // Get user
      worklist_init.push(m);
    }
  }

1634
  if (alloc_worklist.length() == 0) {
1635
    _collecting = false;
1636
    return false; // Nothing to do.
1637 1638 1639
  }

  // 2. First pass to create simple CG edges (doesn't require to walk CG).
1640 1641
  uint delayed_size = _delayed_worklist.size();
  for( uint next = 0; next < delayed_size; ++next ) {
1642 1643 1644 1645
    Node* n = _delayed_worklist.at(next);
    build_connection_graph(n, igvn);
  }

K
kvn 已提交
1646 1647
  // 3. Pass to create initial fields edges (JavaObject -F-> AddP)
  //    to reduce number of iterations during stage 4 below.
1648 1649 1650
  uint addp_length = addp_worklist.length();
  for( uint next = 0; next < addp_length; ++next ) {
    Node* n = addp_worklist.at(next);
K
kvn 已提交
1651
    Node* base = get_addp_base(n);
1652
    if (base->is_Proj() && base->in(0)->is_Call())
K
kvn 已提交
1653 1654 1655 1656 1657
      base = base->in(0);
    PointsToNode::NodeType nt = ptnode_adr(base->_idx)->node_type();
    if (nt == PointsToNode::JavaObject) {
      build_connection_graph(n, igvn);
    }
1658 1659
  }

1660
  GrowableArray<int> cg_worklist;
1661
  cg_worklist.append(_phantom_object);
K
kvn 已提交
1662
  GrowableArray<uint>  worklist;
1663 1664 1665

  // 4. Build Connection Graph which need
  //    to walk the connection graph.
K
kvn 已提交
1666
  _progress = false;
1667 1668
  for (uint ni = 0; ni < nodes_size(); ni++) {
    PointsToNode* ptn = ptnode_adr(ni);
1669 1670 1671 1672 1673
    Node *n = ptn->_node;
    if (n != NULL) { // Call, AddP, LoadP, StoreP
      build_connection_graph(n, igvn);
      if (ptn->node_type() != PointsToNode::UnknownType)
        cg_worklist.append(n->_idx); // Collect CG nodes
K
kvn 已提交
1674 1675
      if (!_processed.test(n->_idx))
        worklist.append(n->_idx); // Collect C/A/L/S nodes
1676
    }
D
duke 已提交
1677 1678
  }

K
kvn 已提交
1679 1680 1681 1682 1683 1684 1685 1686
  // After IGVN user nodes may have smaller _idx than
  // their inputs so they will be processed first in
  // previous loop. Because of that not all Graph
  // edges will be created. Walk over interesting
  // nodes again until no new edges are created.
  //
  // Normally only 1-3 passes needed to build
  // Connection Graph depending on graph complexity.
1687 1688
  // Observed 8 passes in jvm2008 compiler.compiler.
  // Set limit to 20 to catch situation when something
K
kvn 已提交
1689 1690
  // did go wrong and recompile the method without EA.

1691
#define CG_BUILD_ITER_LIMIT 20
K
kvn 已提交
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716

  uint length = worklist.length();
  int iterations = 0;
  while(_progress && (iterations++ < CG_BUILD_ITER_LIMIT)) {
    _progress = false;
    for( uint next = 0; next < length; ++next ) {
      int ni = worklist.at(next);
      PointsToNode* ptn = ptnode_adr(ni);
      Node* n = ptn->_node;
      assert(n != NULL, "should be known node");
      build_connection_graph(n, igvn);
    }
  }
  if (iterations >= CG_BUILD_ITER_LIMIT) {
    assert(iterations < CG_BUILD_ITER_LIMIT,
           err_msg("infinite EA connection graph build with %d nodes and worklist size %d",
           nodes_size(), length));
    // Possible infinite build_connection_graph loop,
    // retry compilation without escape analysis.
    C->record_failure(C2Compiler::retry_no_escape_analysis());
    _collecting = false;
    return false;
  }
#undef CG_BUILD_ITER_LIMIT

1717 1718 1719 1720 1721 1722 1723 1724 1725
  // 5. Propagate escaped states.
  worklist.clear();

  // mark all nodes reachable from GlobalEscape nodes
  (void)propagate_escape_state(&cg_worklist, &worklist, PointsToNode::GlobalEscape);

  // mark all nodes reachable from ArgEscape nodes
  bool has_non_escaping_obj = propagate_escape_state(&cg_worklist, &worklist, PointsToNode::ArgEscape);

1726 1727
  Arena* arena = Thread::current()->resource_area();
  VectorSet visited(arena);
1728

1729
  // 6. Find fields initializing values for not escaped allocations
1730 1731 1732
  uint alloc_length = alloc_worklist.length();
  for (uint next = 0; next < alloc_length; ++next) {
    Node* n = alloc_worklist.at(next);
1733 1734
    PointsToNode::EscapeState es = ptnode_adr(n->_idx)->escape_state();
    if (es == PointsToNode::NoEscape) {
1735 1736 1737
      has_non_escaping_obj = true;
      if (n->is_Allocate()) {
        find_init_values(n, &visited, igvn);
1738 1739 1740 1741
        // The object allocated by this Allocate node will never be
        // seen by an other thread. Mark it so that when it is
        // expanded no MemBarStoreStore is added.
        n->as_Allocate()->initialization()->set_does_not_escape();
1742
      }
1743 1744 1745 1746
    } else if ((es == PointsToNode::ArgEscape) && n->is_Allocate()) {
      // Same as above. Mark this Allocate node so that when it is
      // expanded no MemBarStoreStore is added.
      n->as_Allocate()->initialization()->set_does_not_escape();
1747 1748 1749 1750
    }
  }

  uint cg_length = cg_worklist.length();
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771

  // Skip the rest of code if all objects escaped.
  if (!has_non_escaping_obj) {
    cg_length = 0;
    addp_length = 0;
  }

  for (uint next = 0; next < cg_length; ++next) {
    int ni = cg_worklist.at(next);
    PointsToNode* ptn = ptnode_adr(ni);
    PointsToNode::NodeType nt = ptn->node_type();
    if (nt == PointsToNode::LocalVar || nt == PointsToNode::Field) {
      if (ptn->edge_count() == 0) {
        // No values were found. Assume the value was set
        // outside this method - add edge to phantom object.
        add_pointsto_edge(ni, _phantom_object);
      }
    }
  }

  // 7. Remove deferred edges from the graph.
1772
  for (uint next = 0; next < cg_length; ++next) {
1773
    int ni = cg_worklist.at(next);
1774
    PointsToNode* ptn = ptnode_adr(ni);
D
duke 已提交
1775 1776
    PointsToNode::NodeType nt = ptn->node_type();
    if (nt == PointsToNode::LocalVar || nt == PointsToNode::Field) {
K
kvn 已提交
1777
      remove_deferred(ni, &worklist, &visited);
D
duke 已提交
1778 1779
    }
  }
1780

1781
  // 8. Adjust escape state of nonescaping objects.
1782 1783 1784 1785 1786
  for (uint next = 0; next < addp_length; ++next) {
    Node* n = addp_worklist.at(next);
    adjust_escape_state(n);
  }

1787
  // push all NoEscape nodes on the worklist
1788
  worklist.clear();
1789
  for( uint next = 0; next < cg_length; ++next ) {
1790
    int nk = cg_worklist.at(next);
1791 1792
    if (ptnode_adr(nk)->escape_state() == PointsToNode::NoEscape &&
        !is_null_ptr(nk))
1793 1794
      worklist.push(nk);
  }
1795

1796
  alloc_worklist.clear();
1797
  // Propagate scalar_replaceable value.
1798
  while(worklist.length() > 0) {
1799 1800
    uint nk = worklist.pop();
    PointsToNode* ptn = ptnode_adr(nk);
1801
    Node* n = ptn->_node;
1802 1803
    bool scalar_replaceable = ptn->scalar_replaceable();
    if (n->is_Allocate() && scalar_replaceable) {
T
twisti 已提交
1804
      // Push scalar replaceable allocations on alloc_worklist
1805 1806
      // for processing in split_unique_types(). Note,
      // following code may change scalar_replaceable value.
1807 1808 1809 1810 1811
      alloc_worklist.append(n);
    }
    uint e_cnt = ptn->edge_count();
    for (uint ei = 0; ei < e_cnt; ei++) {
      uint npi = ptn->edge_target(ei);
1812 1813
      if (is_null_ptr(npi))
        continue;
1814 1815
      PointsToNode *np = ptnode_adr(npi);
      if (np->escape_state() < PointsToNode::NoEscape) {
1816
        set_escape_state(npi, PointsToNode::NoEscape);
1817 1818 1819 1820 1821 1822
        if (!scalar_replaceable) {
          np->set_scalar_replaceable(false);
        }
        worklist.push(npi);
      } else if (np->scalar_replaceable() && !scalar_replaceable) {
        np->set_scalar_replaceable(false);
1823
        worklist.push(npi);
1824 1825 1826
      }
    }
  }
1827

1828
  _collecting = false;
1829
  assert(C->unique() == nodes_size(), "there should be no new ideal nodes during ConnectionGraph build");
D
duke 已提交
1830

1831 1832
  assert(ptnode_adr(_oop_null)->escape_state() == PointsToNode::NoEscape &&
         ptnode_adr(_oop_null)->edge_count() == 0, "sanity");
1833
  if (UseCompressedOops) {
1834 1835
    assert(ptnode_adr(_noop_null)->escape_state() == PointsToNode::NoEscape &&
           ptnode_adr(_noop_null)->edge_count() == 0, "sanity");
1836 1837
  }

1838
  if (EliminateLocks && has_non_escaping_obj) {
1839 1840 1841 1842 1843 1844
    // Mark locks before changing ideal graph.
    int cnt = C->macro_count();
    for( int i=0; i < cnt; i++ ) {
      Node *n = C->macro_node(i);
      if (n->is_AbstractLock()) { // Lock and Unlock nodes
        AbstractLockNode* alock = n->as_AbstractLock();
K
kvn 已提交
1845
        if (!alock->is_non_esc_obj()) {
1846 1847 1848
          PointsToNode::EscapeState es = escape_state(alock->obj_node());
          assert(es != PointsToNode::UnknownEscape, "should know");
          if (es != PointsToNode::UnknownEscape && es != PointsToNode::GlobalEscape) {
K
kvn 已提交
1849 1850 1851 1852 1853
            assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
            // The lock could be marked eliminated by lock coarsening
            // code during first IGVN before EA. Replace coarsened flag
            // to eliminate all associated locks/unlocks.
            alock->set_non_esc_obj();
1854 1855 1856 1857 1858 1859
          }
        }
      }
    }
  }

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
  if (OptimizePtrCompare && has_non_escaping_obj) {
    // Add ConI(#CC_GT) and ConI(#CC_EQ).
    _pcmp_neq = igvn->makecon(TypeInt::CC_GT);
    _pcmp_eq = igvn->makecon(TypeInt::CC_EQ);
    // Optimize objects compare.
    while (ptr_cmp_worklist.length() != 0) {
      Node *n = ptr_cmp_worklist.pop();
      Node *res = optimize_ptr_compare(n);
      if (res != NULL) {
#ifndef PRODUCT
        if (PrintOptimizePtrCompare) {
          tty->print_cr("++++ Replaced: %d %s(%d,%d) --> %s", n->_idx, (n->Opcode() == Op_CmpP ? "CmpP" : "CmpN"), n->in(1)->_idx, n->in(2)->_idx, (res == _pcmp_eq ? "EQ" : "NotEQ"));
          if (Verbose) {
            n->dump(1);
          }
        }
#endif
        _igvn->replace_node(n, res);
      }
    }
    // cleanup
    if (_pcmp_neq->outcnt() == 0)
      igvn->hash_delete(_pcmp_neq);
    if (_pcmp_eq->outcnt()  == 0)
      igvn->hash_delete(_pcmp_eq);
  }

1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
  // For MemBarStoreStore nodes added in library_call.cpp, check
  // escape status of associated AllocateNode and optimize out
  // MemBarStoreStore node if the allocated object never escapes.
  while (storestore_worklist.length() != 0) {
    Node *n = storestore_worklist.pop();
    MemBarStoreStoreNode *storestore = n ->as_MemBarStoreStore();
    Node *alloc = storestore->in(MemBarNode::Precedent)->in(0);
    assert (alloc->is_Allocate(), "storestore should point to AllocateNode");
    PointsToNode::EscapeState es = ptnode_adr(alloc->_idx)->escape_state();
    if (es == PointsToNode::NoEscape || es == PointsToNode::ArgEscape) {
      MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
      mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
      mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));

      _igvn->register_new_node_with_optimizer(mb);
      _igvn->replace_node(storestore, mb);
    }
  }

1906 1907 1908 1909 1910 1911
#ifndef PRODUCT
  if (PrintEscapeAnalysis) {
    dump(); // Dump ConnectionGraph
  }
#endif

1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
  bool has_scalar_replaceable_candidates = false;
  alloc_length = alloc_worklist.length();
  for (uint next = 0; next < alloc_length; ++next) {
    Node* n = alloc_worklist.at(next);
    PointsToNode* ptn = ptnode_adr(n->_idx);
    assert(ptn->escape_state() == PointsToNode::NoEscape, "sanity");
    if (ptn->scalar_replaceable()) {
      has_scalar_replaceable_candidates = true;
      break;
    }
  }

1924 1925
  if ( has_scalar_replaceable_candidates &&
       C->AliasLevel() >= 3 && EliminateAllocations ) {
D
duke 已提交
1926

1927
    // Now use the escape information to create unique types for
1928
    // scalar replaceable objects.
1929
    split_unique_types(alloc_worklist);
1930 1931

    if (C->failing())  return false;
D
duke 已提交
1932

1933
    C->print_method("After Escape Analysis", 2);
D
duke 已提交
1934

1935
#ifdef ASSERT
1936
  } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
1937
    tty->print("=== No allocations eliminated for ");
1938
    C->method()->print_short_name();
1939 1940
    if(!EliminateAllocations) {
      tty->print(" since EliminateAllocations is off ===");
1941 1942 1943
    } else if(!has_scalar_replaceable_candidates) {
      tty->print(" since there are no scalar replaceable candidates ===");
    } else if(C->AliasLevel() < 3) {
1944
      tty->print(" since AliasLevel < 3 ===");
D
duke 已提交
1945
    }
1946 1947
    tty->cr();
#endif
D
duke 已提交
1948
  }
1949
  return has_non_escaping_obj;
D
duke 已提交
1950 1951
}

1952 1953 1954 1955 1956 1957
// Find fields initializing values for allocations.
void ConnectionGraph::find_init_values(Node* alloc, VectorSet* visited, PhaseTransform* phase) {
  assert(alloc->is_Allocate(), "Should be called for Allocate nodes only");
  PointsToNode* pta = ptnode_adr(alloc->_idx);
  assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
  InitializeNode* ini = alloc->as_Allocate()->initialization();
1958 1959

  Compile* C = _compile;
1960
  visited->Reset();
1961 1962 1963 1964 1965
  // Check if a oop field's initializing value is recorded and add
  // a corresponding NULL field's value if it is not recorded.
  // Connection Graph does not record a default initialization by NULL
  // captured by Initialize node.
  //
1966
  uint null_idx = UseCompressedOops ? _noop_null : _oop_null;
1967
  uint ae_cnt = pta->edge_count();
1968
  bool visited_bottom_offset = false;
1969 1970 1971 1972 1973
  for (uint ei = 0; ei < ae_cnt; ei++) {
    uint nidx = pta->edge_target(ei); // Field (AddP)
    PointsToNode* ptn = ptnode_adr(nidx);
    assert(ptn->_node->is_AddP(), "Should be AddP nodes only");
    int offset = ptn->offset();
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
    if (offset == Type::OffsetBot) {
      if (!visited_bottom_offset) {
        visited_bottom_offset = true;
        // Check only oop fields.
        const Type* adr_type = ptn->_node->as_AddP()->bottom_type();
        if (!adr_type->isa_aryptr() ||
            (adr_type->isa_aryptr()->klass() == NULL) ||
             adr_type->isa_aryptr()->klass()->is_obj_array_klass()) {
          // OffsetBot is used to reference array's element,
          // always add reference to NULL since we don't
          // known which element is referenced.
          add_edge_from_fields(alloc->_idx, null_idx, offset);
        }
      }
    } else if (offset != oopDesc::klass_offset_in_bytes() &&
               !visited->test_set(offset)) {
1990 1991

      // Check only oop fields.
1992
      const Type* adr_type = ptn->_node->as_AddP()->bottom_type();
1993 1994 1995 1996 1997 1998 1999 2000 2001
      BasicType basic_field_type = T_INT;
      if (adr_type->isa_instptr()) {
        ciField* field = C->alias_type(adr_type->isa_instptr())->field();
        if (field != NULL) {
          basic_field_type = field->layout_type();
        } else {
          // Ignore non field load (for example, klass load)
        }
      } else if (adr_type->isa_aryptr()) {
2002 2003 2004 2005 2006 2007 2008
        if (offset != arrayOopDesc::length_offset_in_bytes()) {
          const Type* elemtype = adr_type->isa_aryptr()->elem();
          basic_field_type = elemtype->array_element_basic_type();
        } else {
          // Ignore array length load
        }
#ifdef ASSERT
2009
      } else {
2010 2011 2012
        // Raw pointers are used for initializing stores so skip it
        // since it should be recorded already
        Node* base = get_addp_base(ptn->_node);
2013 2014
        assert(adr_type->isa_rawptr() && base->is_Proj() &&
               (base->in(0) == alloc),"unexpected pointer type");
2015
#endif
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
      }
      if (basic_field_type == T_OBJECT ||
          basic_field_type == T_NARROWOOP ||
          basic_field_type == T_ARRAY) {
        Node* value = NULL;
        if (ini != NULL) {
          BasicType ft = UseCompressedOops ? T_NARROWOOP : T_OBJECT;
          Node* store = ini->find_captured_store(offset, type2aelembytes(ft), phase);
          if (store != NULL && store->is_Store()) {
            value = store->in(MemNode::ValueIn);
          } else if (ptn->edge_count() > 0) { // Are there oop stores?
            // Check for a store which follows allocation without branches.
            // For example, a volatile field store is not collected
            // by Initialize node. TODO: it would be nice to use idom() here.
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
            //
            // Search all references to the same field which use different
            // AddP nodes, for example, in the next case:
            //
            //    Point p[] = new Point[1];
            //    if ( x ) { p[0] = new Point(); p[0].x = x; }
            //    if ( p[0] != null ) { y = p[0].x; } // has CastPP
            //
            for (uint next = ei; (next < ae_cnt) && (value == NULL); next++) {
              uint fpi = pta->edge_target(next); // Field (AddP)
              PointsToNode *ptf = ptnode_adr(fpi);
              if (ptf->offset() == offset) {
                Node* nf = ptf->_node;
                for (DUIterator_Fast imax, i = nf->fast_outs(imax); i < imax; i++) {
                  store = nf->fast_out(i);
                  if (store->is_Store() && store->in(0) != NULL) {
                    Node* ctrl = store->in(0);
                    while(!(ctrl == ini || ctrl == alloc || ctrl == NULL ||
                            ctrl == C->root() || ctrl == C->top() || ctrl->is_Region() ||
                            ctrl->is_IfTrue() || ctrl->is_IfFalse())) {
                       ctrl = ctrl->in(0);
                    }
                    if (ctrl == ini || ctrl == alloc) {
                      value = store->in(MemNode::ValueIn);
                      break;
                    }
                  }
2057 2058 2059 2060 2061 2062 2063
                }
              }
            }
          }
        }
        if (value == NULL || value != ptnode_adr(value->_idx)->_node) {
          // A field's initializing value was not recorded. Add NULL.
2064
          add_edge_from_fields(alloc->_idx, null_idx, offset);
2065 2066 2067 2068
        }
      }
    }
  }
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
}

// Adjust escape state after Connection Graph is built.
void ConnectionGraph::adjust_escape_state(Node* n) {
  PointsToNode* ptn = ptnode_adr(n->_idx);
  assert(n->is_AddP(), "Should be called for AddP nodes only");
  // Search for objects which are not scalar replaceable
  // and mark them to propagate the state to referenced objects.
  //

  int offset = ptn->offset();
  Node* base = get_addp_base(n);
  VectorSet* ptset = PointsTo(base);
  int ptset_size = ptset->Size();
2083 2084 2085 2086

  // An object is not scalar replaceable if the field which may point
  // to it has unknown offset (unknown element of an array of objects).
  //
2087

2088 2089 2090 2091
  if (offset == Type::OffsetBot) {
    uint e_cnt = ptn->edge_count();
    for (uint ei = 0; ei < e_cnt; ei++) {
      uint npi = ptn->edge_target(ei);
2092
      ptnode_adr(npi)->set_scalar_replaceable(false);
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
    }
  }

  // Currently an object is not scalar replaceable if a LoadStore node
  // access its field since the field value is unknown after it.
  //
  bool has_LoadStore = false;
  for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
    Node *use = n->fast_out(i);
    if (use->is_LoadStore()) {
      has_LoadStore = true;
      break;
    }
  }
  // An object is not scalar replaceable if the address points
  // to unknown field (unknown element for arrays, offset is OffsetBot).
  //
  // Or the address may point to more then one object. This may produce
2111
  // the false positive result (set not scalar replaceable)
2112 2113 2114 2115
  // since the flow-insensitive escape analysis can't separate
  // the case when stores overwrite the field's value from the case
  // when stores happened on different control branches.
  //
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
  // Note: it will disable scalar replacement in some cases:
  //
  //    Point p[] = new Point[1];
  //    p[0] = new Point(); // Will be not scalar replaced
  //
  // but it will save us from incorrect optimizations in next cases:
  //
  //    Point p[] = new Point[1];
  //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
  //
2126 2127
  if (ptset_size > 1 || ptset_size != 0 &&
      (has_LoadStore || offset == Type::OffsetBot)) {
2128
    for( VectorSetI j(ptset); j.test(); ++j ) {
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
      ptnode_adr(j.elem)->set_scalar_replaceable(false);
    }
  }
}

// Propagate escape states to referenced nodes.
bool ConnectionGraph::propagate_escape_state(GrowableArray<int>* cg_worklist,
                                             GrowableArray<uint>* worklist,
                                             PointsToNode::EscapeState esc_state) {
  bool has_java_obj = false;

  // push all nodes with the same escape state on the worklist
  uint cg_length = cg_worklist->length();
  for (uint next = 0; next < cg_length; ++next) {
    int nk = cg_worklist->at(next);
    if (ptnode_adr(nk)->escape_state() == esc_state)
      worklist->push(nk);
  }
  // mark all reachable nodes
  while (worklist->length() > 0) {
2149 2150 2151 2152
    int pt = worklist->pop();
    PointsToNode* ptn = ptnode_adr(pt);
    if (ptn->node_type() == PointsToNode::JavaObject &&
        !is_null_ptr(pt)) {
2153
      has_java_obj = true;
2154 2155 2156 2157
      if (esc_state > PointsToNode::NoEscape) {
        // fields values are unknown if object escapes
        add_edge_from_fields(pt, _phantom_object, Type::OffsetBot);
      }
2158 2159 2160 2161
    }
    uint e_cnt = ptn->edge_count();
    for (uint ei = 0; ei < e_cnt; ei++) {
      uint npi = ptn->edge_target(ei);
2162 2163
      if (is_null_ptr(npi))
        continue;
2164 2165 2166 2167 2168
      PointsToNode *np = ptnode_adr(npi);
      if (np->escape_state() < esc_state) {
        set_escape_state(npi, esc_state);
        worklist->push(npi);
      }
2169 2170
    }
  }
2171 2172
  // Has not escaping java objects
  return has_java_obj && (esc_state < PointsToNode::GlobalEscape);
2173 2174
}

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
// Optimize objects compare.
Node* ConnectionGraph::optimize_ptr_compare(Node* n) {
  assert(OptimizePtrCompare, "sanity");
  // Clone returned Set since PointsTo() returns pointer
  // to the same structure ConnectionGraph.pt_ptset.
  VectorSet ptset1 = *PointsTo(n->in(1));
  VectorSet ptset2 = *PointsTo(n->in(2));

  // Check simple cases first.
  if (ptset1.Size() == 1) {
    uint pt1 = ptset1.getelem();
    PointsToNode* ptn1 = ptnode_adr(pt1);
    if (ptn1->escape_state() == PointsToNode::NoEscape) {
      if (ptset2.Size() == 1 && ptset2.getelem() == pt1) {
        // Comparing the same not escaping object.
        return _pcmp_eq;
      }
      Node* obj = ptn1->_node;
      // Comparing not escaping allocation.
      if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
          !ptset2.test(pt1)) {
        return _pcmp_neq; // This includes nullness check.
      }
    }
  } else if (ptset2.Size() == 1) {
    uint pt2 = ptset2.getelem();
    PointsToNode* ptn2 = ptnode_adr(pt2);
    if (ptn2->escape_state() == PointsToNode::NoEscape) {
      Node* obj = ptn2->_node;
      // Comparing not escaping allocation.
      if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
          !ptset1.test(pt2)) {
        return _pcmp_neq; // This includes nullness check.
      }
    }
  }

  if (!ptset1.disjoint(ptset2)) {
    return NULL; // Sets are not disjoint
  }

  // Sets are disjoint.
  bool set1_has_unknown_ptr = ptset1.test(_phantom_object) != 0;
  bool set2_has_unknown_ptr = ptset2.test(_phantom_object) != 0;
  bool set1_has_null_ptr   = (ptset1.test(_oop_null) | ptset1.test(_noop_null)) != 0;
  bool set2_has_null_ptr   = (ptset2.test(_oop_null) | ptset2.test(_noop_null)) != 0;

  if (set1_has_unknown_ptr && set2_has_null_ptr ||
      set2_has_unknown_ptr && set1_has_null_ptr) {
    // Check nullness of unknown object.
    return NULL;
  }

  // Disjointness by itself is not sufficient since
  // alias analysis is not complete for escaped objects.
  // Disjoint sets are definitely unrelated only when
  // at least one set has only not escaping objects.
  if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
    bool has_only_non_escaping_alloc = true;
    for (VectorSetI i(&ptset1); i.test(); ++i) {
      uint pt = i.elem;
      PointsToNode* ptn = ptnode_adr(pt);
      Node* obj = ptn->_node;
      if (ptn->escape_state() != PointsToNode::NoEscape ||
          !(obj->is_Allocate() || obj->is_CallStaticJava())) {
        has_only_non_escaping_alloc = false;
        break;
      }
    }
    if (has_only_non_escaping_alloc) {
      return _pcmp_neq;
    }
  }
  if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
    bool has_only_non_escaping_alloc = true;
    for (VectorSetI i(&ptset2); i.test(); ++i) {
      uint pt = i.elem;
      PointsToNode* ptn = ptnode_adr(pt);
      Node* obj = ptn->_node;
      if (ptn->escape_state() != PointsToNode::NoEscape ||
          !(obj->is_Allocate() || obj->is_CallStaticJava())) {
        has_only_non_escaping_alloc = false;
        break;
      }
    }
    if (has_only_non_escaping_alloc) {
      return _pcmp_neq;
    }
  }
  return NULL;
}

D
duke 已提交
2267
void ConnectionGraph::process_call_arguments(CallNode *call, PhaseTransform *phase) {
2268
    bool is_arraycopy = false;
D
duke 已提交
2269
    switch (call->Opcode()) {
2270
#ifdef ASSERT
D
duke 已提交
2271 2272 2273 2274
    case Op_Allocate:
    case Op_AllocateArray:
    case Op_Lock:
    case Op_Unlock:
2275 2276 2277 2278
      assert(false, "should be done already");
      break;
#endif
    case Op_CallLeafNoFP:
2279 2280 2281 2282
      is_arraycopy = (call->as_CallLeaf()->_name != NULL &&
                      strstr(call->as_CallLeaf()->_name, "arraycopy") != 0);
      // fall through
    case Op_CallLeaf:
2283 2284 2285 2286
    {
      // Stub calls, objects do not escape but they are not scale replaceable.
      // Adjust escape state for outgoing arguments.
      const TypeTuple * d = call->tf()->domain();
2287
      bool src_has_oops = false;
2288 2289 2290 2291
      for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
        const Type* at = d->field_at(i);
        Node *arg = call->in(i)->uncast();
        const Type *aat = phase->type(arg);
2292
        PointsToNode::EscapeState arg_esc = ptnode_adr(arg->_idx)->escape_state();
2293
        if (!arg->is_top() && at->isa_ptr() && aat->isa_ptr() &&
2294
            (is_arraycopy || arg_esc < PointsToNode::ArgEscape)) {
2295

2296 2297
          assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
                 aat->isa_ptr() != NULL, "expecting an Ptr");
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
          bool arg_has_oops = aat->isa_oopptr() &&
                              (aat->isa_oopptr()->klass() == NULL || aat->isa_instptr() ||
                               (aat->isa_aryptr() && aat->isa_aryptr()->klass()->is_obj_array_klass()));
          if (i == TypeFunc::Parms) {
            src_has_oops = arg_has_oops;
          }
          //
          // src or dst could be j.l.Object when other is basic type array:
          //
          //   arraycopy(char[],0,Object*,0,size);
          //   arraycopy(Object*,0,char[],0,size);
          //
          // Don't add edges from dst's fields in such cases.
          //
          bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
                                       arg_has_oops && (i > TypeFunc::Parms);
2314
#ifdef ASSERT
2315
          if (!(is_arraycopy ||
2316 2317 2318 2319 2320 2321 2322 2323
                call->as_CallLeaf()->_name != NULL &&
                (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre")  == 0 ||
                 strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 ))
          ) {
            call->dump();
            assert(false, "EA: unexpected CallLeaf");
          }
#endif
2324 2325 2326 2327 2328 2329 2330
          // Always process arraycopy's destination object since
          // we need to add all possible edges to references in
          // source object.
          if (arg_esc >= PointsToNode::ArgEscape &&
              !arg_is_arraycopy_dest) {
            continue;
          }
2331
          set_escape_state(arg->_idx, PointsToNode::ArgEscape);
2332
          Node* arg_base = arg;
2333 2334 2335 2336
          if (arg->is_AddP()) {
            //
            // The inline_native_clone() case when the arraycopy stub is called
            // after the allocation before Initialize and CheckCastPP nodes.
2337
            // Or normal arraycopy for object arrays case.
2338 2339 2340 2341
            //
            // Set AddP's base (Allocate) as not scalar replaceable since
            // pointer to the base (with offset) is passed as argument.
            //
2342
            arg_base = get_addp_base(arg);
2343
          }
2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
          VectorSet argset = *PointsTo(arg_base); // Clone set
          for( VectorSetI j(&argset); j.test(); ++j ) {
            uint pd = j.elem; // Destination object
            set_escape_state(pd, PointsToNode::ArgEscape);

            if (arg_is_arraycopy_dest) {
              PointsToNode* ptd = ptnode_adr(pd);
              // Conservatively reference an unknown object since
              // not all source's fields/elements may be known.
              add_edge_from_fields(pd, _phantom_object, Type::OffsetBot);

              Node *src = call->in(TypeFunc::Parms)->uncast();
              Node* src_base = src;
              if (src->is_AddP()) {
                src_base  = get_addp_base(src);
              }
              // Create edges from destination's fields to
              // everything known source's fields could point to.
              for( VectorSetI s(PointsTo(src_base)); s.test(); ++s ) {
                uint ps = s.elem;
                bool has_bottom_offset = false;
                for (uint fd = 0; fd < ptd->edge_count(); fd++) {
                  assert(ptd->edge_type(fd) == PointsToNode::FieldEdge, "expecting a field edge");
                  int fdi = ptd->edge_target(fd);
                  PointsToNode* pfd = ptnode_adr(fdi);
                  int offset = pfd->offset();
                  if (offset == Type::OffsetBot)
                    has_bottom_offset = true;
                  assert(offset != -1, "offset should be set");
                  add_deferred_edge_to_fields(fdi, ps, offset);
                }
                // Destination object may not have access (no field edge)
                // to fields which are accessed in source object.
                // As result no edges will be created to those source's
                // fields and escape state of destination object will
                // not be propagated to those fields.
                //
                // Mark source object as global escape except in
                // the case with Type::OffsetBot field (which is
                // common case for array elements access) when
                // edges are created to all source's fields.
                if (!has_bottom_offset) {
                  set_escape_state(ps, PointsToNode::GlobalEscape);
                }
              }
            }
2390 2391 2392
          }
        }
      }
D
duke 已提交
2393
      break;
2394
    }
D
duke 已提交
2395 2396 2397 2398 2399 2400

    case Op_CallStaticJava:
    // For a static call, we know exactly what method is being called.
    // Use bytecode estimator to record the call's escape affects
    {
      ciMethod *meth = call->as_CallJava()->method();
2401 2402 2403
      BCEscapeAnalyzer *call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
      // fall-through if not a Java method or no analyzer information
      if (call_analyzer != NULL) {
D
duke 已提交
2404
        const TypeTuple * d = call->tf()->domain();
2405
        bool copy_dependencies = false;
D
duke 已提交
2406 2407 2408
        for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
          const Type* at = d->field_at(i);
          int k = i - TypeFunc::Parms;
2409
          Node *arg = call->in(i)->uncast();
D
duke 已提交
2410

2411
          if (at->isa_oopptr() != NULL &&
2412
              ptnode_adr(arg->_idx)->escape_state() < PointsToNode::GlobalEscape) {
D
duke 已提交
2413

2414 2415 2416
            bool global_escapes = false;
            bool fields_escapes = false;
            if (!call_analyzer->is_arg_stack(k)) {
D
duke 已提交
2417
              // The argument global escapes, mark everything it could point to
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
              set_escape_state(arg->_idx, PointsToNode::GlobalEscape);
              global_escapes = true;
            } else {
              if (!call_analyzer->is_arg_local(k)) {
                // The argument itself doesn't escape, but any fields might
                fields_escapes = true;
              }
              set_escape_state(arg->_idx, PointsToNode::ArgEscape);
              copy_dependencies = true;
            }
D
duke 已提交
2428

2429
            for( VectorSetI j(PointsTo(arg)); j.test(); ++j ) {
2430 2431
              uint pt = j.elem;
              if (global_escapes) {
2432
                // The argument global escapes, mark everything it could point to
D
duke 已提交
2433
                set_escape_state(pt, PointsToNode::GlobalEscape);
2434
                add_edge_from_fields(pt, _phantom_object, Type::OffsetBot);
2435
              } else {
2436
                set_escape_state(pt, PointsToNode::ArgEscape);
2437
                if (fields_escapes) {
2438 2439 2440
                  // The argument itself doesn't escape, but any fields might.
                  // Use OffsetTop to indicate such case.
                  add_edge_from_fields(pt, _phantom_object, Type::OffsetTop);
2441
                }
D
duke 已提交
2442 2443 2444 2445
              }
            }
          }
        }
2446
        if (copy_dependencies)
2447
          call_analyzer->copy_dependencies(_compile->dependencies());
D
duke 已提交
2448 2449 2450 2451 2452
        break;
      }
    }

    default:
2453 2454
    // Fall-through here if not a Java method or no analyzer information
    // or some other type of call, assume the worst case: all arguments
D
duke 已提交
2455 2456 2457 2458 2459 2460 2461
    // globally escape.
    {
      // adjust escape state for  outgoing arguments
      const TypeTuple * d = call->tf()->domain();
      for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
        const Type* at = d->field_at(i);
        if (at->isa_oopptr() != NULL) {
2462 2463
          Node *arg = call->in(i)->uncast();
          set_escape_state(arg->_idx, PointsToNode::GlobalEscape);
2464
          for( VectorSetI j(PointsTo(arg)); j.test(); ++j ) {
D
duke 已提交
2465 2466
            uint pt = j.elem;
            set_escape_state(pt, PointsToNode::GlobalEscape);
2467
            add_edge_from_fields(pt, _phantom_object, Type::OffsetBot);
D
duke 已提交
2468 2469 2470 2471 2472 2473 2474
          }
        }
      }
    }
  }
}
void ConnectionGraph::process_call_result(ProjNode *resproj, PhaseTransform *phase) {
2475 2476 2477
  CallNode   *call = resproj->in(0)->as_Call();
  uint    call_idx = call->_idx;
  uint resproj_idx = resproj->_idx;
D
duke 已提交
2478 2479 2480 2481 2482

  switch (call->Opcode()) {
    case Op_Allocate:
    {
      Node *k = call->in(AllocateNode::KlassNode);
2483
      const TypeKlassPtr *kt = k->bottom_type()->isa_klassptr();
D
duke 已提交
2484 2485 2486
      assert(kt != NULL, "TypeKlassPtr  required.");
      ciKlass* cik = kt->klass();

2487 2488
      PointsToNode::EscapeState es;
      uint edge_to;
2489 2490 2491
      if (cik->is_subclass_of(_compile->env()->Thread_klass()) ||
         !cik->is_instance_klass() || // StressReflectiveCode
          cik->as_instance_klass()->has_finalizer()) {
2492 2493
        es = PointsToNode::GlobalEscape;
        edge_to = _phantom_object; // Could not be worse
D
duke 已提交
2494
      } else {
2495
        es = PointsToNode::NoEscape;
2496
        edge_to = call_idx;
2497
        assert(ptnode_adr(call_idx)->scalar_replaceable(), "sanity");
D
duke 已提交
2498
      }
2499 2500 2501
      set_escape_state(call_idx, es);
      add_pointsto_edge(resproj_idx, edge_to);
      _processed.set(resproj_idx);
D
duke 已提交
2502 2503 2504 2505 2506
      break;
    }

    case Op_AllocateArray:
    {
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520

      Node *k = call->in(AllocateNode::KlassNode);
      const TypeKlassPtr *kt = k->bottom_type()->isa_klassptr();
      assert(kt != NULL, "TypeKlassPtr  required.");
      ciKlass* cik = kt->klass();

      PointsToNode::EscapeState es;
      uint edge_to;
      if (!cik->is_array_klass()) { // StressReflectiveCode
        es = PointsToNode::GlobalEscape;
        edge_to = _phantom_object;
      } else {
        es = PointsToNode::NoEscape;
        edge_to = call_idx;
2521
        assert(ptnode_adr(call_idx)->scalar_replaceable(), "sanity");
2522 2523 2524
        int length = call->in(AllocateNode::ALength)->find_int_con(-1);
        if (length < 0 || length > EliminateAllocationArraySizeLimit) {
          // Not scalar replaceable if the length is not constant or too big.
2525
          ptnode_adr(call_idx)->set_scalar_replaceable(false);
2526
        }
2527
      }
2528 2529
      set_escape_state(call_idx, es);
      add_pointsto_edge(resproj_idx, edge_to);
2530
      _processed.set(resproj_idx);
D
duke 已提交
2531 2532 2533 2534 2535 2536 2537
      break;
    }

    case Op_CallStaticJava:
    // For a static call, we know exactly what method is being called.
    // Use bytecode estimator to record whether the call's return value escapes
    {
2538
      bool done = true;
D
duke 已提交
2539 2540 2541 2542 2543 2544 2545 2546
      const TypeTuple *r = call->tf()->range();
      const Type* ret_type = NULL;

      if (r->cnt() > TypeFunc::Parms)
        ret_type = r->field_at(TypeFunc::Parms);

      // Note:  we use isa_ptr() instead of isa_oopptr()  here because the
      //        _multianewarray functions return a TypeRawPtr.
2547
      if (ret_type == NULL || ret_type->isa_ptr() == NULL) {
2548
        _processed.set(resproj_idx);
D
duke 已提交
2549
        break;  // doesn't return a pointer type
2550
      }
D
duke 已提交
2551
      ciMethod *meth = call->as_CallJava()->method();
2552
      const TypeTuple * d = call->tf()->domain();
D
duke 已提交
2553 2554
      if (meth == NULL) {
        // not a Java method, assume global escape
2555 2556
        set_escape_state(call_idx, PointsToNode::GlobalEscape);
        add_pointsto_edge(resproj_idx, _phantom_object);
D
duke 已提交
2557
      } else {
2558 2559
        BCEscapeAnalyzer *call_analyzer = meth->get_bcea();
        bool copy_dependencies = false;
D
duke 已提交
2560

2561 2562 2563 2564 2565
        if (call_analyzer->is_return_allocated()) {
          // Returns a newly allocated unescaped object, simply
          // update dependency information.
          // Mark it as NoEscape so that objects referenced by
          // it's fields will be marked as NoEscape at least.
2566
          set_escape_state(call_idx, PointsToNode::NoEscape);
2567
          ptnode_adr(call_idx)->set_scalar_replaceable(false);
2568 2569
          // Fields values are unknown
          add_edge_from_fields(call_idx, _phantom_object, Type::OffsetBot);
2570
          add_pointsto_edge(resproj_idx, call_idx);
2571
          copy_dependencies = true;
2572
        } else {
D
duke 已提交
2573
          // determine whether any arguments are returned
2574
          set_escape_state(call_idx, PointsToNode::ArgEscape);
2575
          bool ret_arg = false;
D
duke 已提交
2576 2577 2578
          for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
            const Type* at = d->field_at(i);
            if (at->isa_oopptr() != NULL) {
2579
              Node *arg = call->in(i)->uncast();
D
duke 已提交
2580

2581
              if (call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2582
                ret_arg = true;
2583
                PointsToNode *arg_esp = ptnode_adr(arg->_idx);
2584 2585 2586
                if (arg_esp->node_type() == PointsToNode::UnknownType)
                  done = false;
                else if (arg_esp->node_type() == PointsToNode::JavaObject)
2587
                  add_pointsto_edge(resproj_idx, arg->_idx);
D
duke 已提交
2588
                else
2589
                  add_deferred_edge(resproj_idx, arg->_idx);
D
duke 已提交
2590 2591 2592
              }
            }
          }
2593 2594
          if (done) {
            copy_dependencies = true;
2595 2596 2597 2598 2599
            // is_return_local() is true when only arguments are returned.
            if (!ret_arg || !call_analyzer->is_return_local()) {
              // Returns unknown object.
              add_pointsto_edge(resproj_idx, _phantom_object);
            }
2600
          }
D
duke 已提交
2601
        }
2602
        if (copy_dependencies)
2603
          call_analyzer->copy_dependencies(_compile->dependencies());
D
duke 已提交
2604
      }
2605
      if (done)
2606
        _processed.set(resproj_idx);
D
duke 已提交
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
      break;
    }

    default:
    // Some other type of call, assume the worst case that the
    // returned value, if any, globally escapes.
    {
      const TypeTuple *r = call->tf()->range();
      if (r->cnt() > TypeFunc::Parms) {
        const Type* ret_type = r->field_at(TypeFunc::Parms);

        // Note:  we use isa_ptr() instead of isa_oopptr()  here because the
        //        _multianewarray functions return a TypeRawPtr.
        if (ret_type->isa_ptr() != NULL) {
2621 2622
          set_escape_state(call_idx, PointsToNode::GlobalEscape);
          add_pointsto_edge(resproj_idx, _phantom_object);
D
duke 已提交
2623 2624
        }
      }
2625
      _processed.set(resproj_idx);
D
duke 已提交
2626 2627 2628 2629
    }
  }
}

2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
// Populate Connection Graph with Ideal nodes and create simple
// connection graph edges (do not need to check the node_type of inputs
// or to call PointsTo() to walk the connection graph).
void ConnectionGraph::record_for_escape_analysis(Node *n, PhaseTransform *phase) {
  if (_processed.test(n->_idx))
    return; // No need to redefine node's state.

  if (n->is_Call()) {
    // Arguments to allocation and locking don't escape.
    if (n->is_Allocate()) {
      add_node(n, PointsToNode::JavaObject, PointsToNode::UnknownEscape, true);
      record_for_optimizer(n);
    } else if (n->is_Lock() || n->is_Unlock()) {
      // Put Lock and Unlock nodes on IGVN worklist to process them during
      // the first IGVN optimization when escape information is still available.
      record_for_optimizer(n);
      _processed.set(n->_idx);
    } else {
2648
      // Don't mark as processed since call's arguments have to be processed.
2649
      PointsToNode::NodeType nt = PointsToNode::UnknownType;
2650
      PointsToNode::EscapeState es = PointsToNode::UnknownEscape;
2651 2652 2653

      // Check if a call returns an object.
      const TypeTuple *r = n->as_Call()->tf()->range();
2654 2655
      if (r->cnt() > TypeFunc::Parms &&
          r->field_at(TypeFunc::Parms)->isa_ptr() &&
2656
          n->as_Call()->proj_out(TypeFunc::Parms) != NULL) {
2657 2658 2659 2660 2661
        nt = PointsToNode::JavaObject;
        if (!n->is_CallStaticJava()) {
          // Since the called mathod is statically unknown assume
          // the worst case that the returned value globally escapes.
          es = PointsToNode::GlobalEscape;
2662
        }
D
duke 已提交
2663
      }
2664
      add_node(n, nt, es, false);
D
duke 已提交
2665
    }
2666
    return;
D
duke 已提交
2667 2668
  }

2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683
  // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
  // ThreadLocal has RawPrt type.
  switch (n->Opcode()) {
    case Op_AddP:
    {
      add_node(n, PointsToNode::Field, PointsToNode::UnknownEscape, false);
      break;
    }
    case Op_CastX2P:
    { // "Unsafe" memory access.
      add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true);
      break;
    }
    case Op_CastPP:
    case Op_CheckCastPP:
2684 2685
    case Op_EncodeP:
    case Op_DecodeN:
2686 2687 2688
    {
      add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
      int ti = n->in(1)->_idx;
2689
      PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
      if (nt == PointsToNode::UnknownType) {
        _delayed_worklist.push(n); // Process it later.
        break;
      } else if (nt == PointsToNode::JavaObject) {
        add_pointsto_edge(n->_idx, ti);
      } else {
        add_deferred_edge(n->_idx, ti);
      }
      _processed.set(n->_idx);
      break;
    }
    case Op_ConP:
    {
      // assume all pointer constants globally escape except for null
      PointsToNode::EscapeState es;
      if (phase->type(n) == TypePtr::NULL_PTR)
        es = PointsToNode::NoEscape;
      else
        es = PointsToNode::GlobalEscape;
D
duke 已提交
2709

2710 2711 2712
      add_node(n, PointsToNode::JavaObject, es, true);
      break;
    }
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    case Op_ConN:
    {
      // assume all narrow oop constants globally escape except for null
      PointsToNode::EscapeState es;
      if (phase->type(n) == TypeNarrowOop::NULL_PTR)
        es = PointsToNode::NoEscape;
      else
        es = PointsToNode::GlobalEscape;

      add_node(n, PointsToNode::JavaObject, es, true);
      break;
    }
2725 2726 2727 2728 2729 2730
    case Op_CreateEx:
    {
      // assume that all exception objects globally escape
      add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true);
      break;
    }
2731
    case Op_LoadKlass:
2732
    case Op_LoadNKlass:
2733 2734 2735 2736 2737
    {
      add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, true);
      break;
    }
    case Op_LoadP:
2738
    case Op_LoadN:
2739 2740
    {
      const Type *t = phase->type(n);
2741
      if (t->make_ptr() == NULL) {
2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
        _processed.set(n->_idx);
        return;
      }
      add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
      break;
    }
    case Op_Parm:
    {
      _processed.set(n->_idx); // No need to redefine it state.
      uint con = n->as_Proj()->_con;
      if (con < TypeFunc::Parms)
        return;
      const Type *t = n->in(0)->as_Start()->_domain->field_at(con);
      if (t->isa_ptr() == NULL)
        return;
      // We have to assume all input parameters globally escape
      // (Note: passing 'false' since _processed is already set).
      add_node(n, PointsToNode::JavaObject, PointsToNode::GlobalEscape, false);
      break;
    }
2762 2763 2764 2765 2766
    case Op_PartialSubtypeCheck:
    { // Produces Null or notNull and is used in CmpP.
      add_node(n, PointsToNode::JavaObject, PointsToNode::ArgEscape, true);
      break;
    }
2767 2768
    case Op_Phi:
    {
2769 2770 2771
      const Type *t = n->as_Phi()->type();
      if (t->make_ptr() == NULL) {
        // nothing to do if not an oop or narrow oop
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
        _processed.set(n->_idx);
        return;
      }
      add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
      uint i;
      for (i = 1; i < n->req() ; i++) {
        Node* in = n->in(i);
        if (in == NULL)
          continue;  // ignore NULL
        in = in->uncast();
        if (in->is_top() || in == n)
          continue;  // ignore top or inputs which go back this node
        int ti = in->_idx;
2785
        PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
        if (nt == PointsToNode::UnknownType) {
          break;
        } else if (nt == PointsToNode::JavaObject) {
          add_pointsto_edge(n->_idx, ti);
        } else {
          add_deferred_edge(n->_idx, ti);
        }
      }
      if (i >= n->req())
        _processed.set(n->_idx);
      else
        _delayed_worklist.push(n);
      break;
    }
    case Op_Proj:
    {
2802
      // we are only interested in the oop result projection from a call
2803
      if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) {
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819
        const TypeTuple *r = n->in(0)->as_Call()->tf()->range();
        assert(r->cnt() > TypeFunc::Parms, "sanity");
        if (r->field_at(TypeFunc::Parms)->isa_ptr() != NULL) {
          add_node(n, PointsToNode::LocalVar, PointsToNode::UnknownEscape, false);
          int ti = n->in(0)->_idx;
          // The call may not be registered yet (since not all its inputs are registered)
          // if this is the projection from backbranch edge of Phi.
          if (ptnode_adr(ti)->node_type() != PointsToNode::UnknownType) {
            process_call_result(n->as_Proj(), phase);
          }
          if (!_processed.test(n->_idx)) {
            // The call's result may need to be processed later if the call
            // returns it's argument and the argument is not processed yet.
            _delayed_worklist.push(n);
          }
          break;
2820 2821
        }
      }
2822
      _processed.set(n->_idx);
2823 2824 2825 2826 2827 2828 2829 2830 2831
      break;
    }
    case Op_Return:
    {
      if( n->req() > TypeFunc::Parms &&
          phase->type(n->in(TypeFunc::Parms))->isa_oopptr() ) {
        // Treat Return value as LocalVar with GlobalEscape escape state.
        add_node(n, PointsToNode::LocalVar, PointsToNode::GlobalEscape, false);
        int ti = n->in(TypeFunc::Parms)->_idx;
2832
        PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
        if (nt == PointsToNode::UnknownType) {
          _delayed_worklist.push(n); // Process it later.
          break;
        } else if (nt == PointsToNode::JavaObject) {
          add_pointsto_edge(n->_idx, ti);
        } else {
          add_deferred_edge(n->_idx, ti);
        }
      }
      _processed.set(n->_idx);
      break;
    }
    case Op_StoreP:
2846
    case Op_StoreN:
2847 2848
    {
      const Type *adr_type = phase->type(n->in(MemNode::Address));
2849
      adr_type = adr_type->make_ptr();
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
      if (adr_type->isa_oopptr()) {
        add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
      } else {
        Node* adr = n->in(MemNode::Address);
        if (adr->is_AddP() && phase->type(adr) == TypeRawPtr::NOTNULL &&
            adr->in(AddPNode::Address)->is_Proj() &&
            adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
          add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
          // We are computing a raw address for a store captured
          // by an Initialize compute an appropriate address type.
          int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
          assert(offs != Type::OffsetBot, "offset must be a constant");
        } else {
          _processed.set(n->_idx);
          return;
        }
      }
      break;
    }
    case Op_StorePConditional:
    case Op_CompareAndSwapP:
2871
    case Op_CompareAndSwapN:
2872 2873
    {
      const Type *adr_type = phase->type(n->in(MemNode::Address));
2874
      adr_type = adr_type->make_ptr();
2875 2876 2877 2878 2879 2880 2881 2882
      if (adr_type->isa_oopptr()) {
        add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
      } else {
        _processed.set(n->_idx);
        return;
      }
      break;
    }
2883 2884 2885 2886 2887 2888 2889 2890 2891
    case Op_AryEq:
    case Op_StrComp:
    case Op_StrEquals:
    case Op_StrIndexOf:
    {
      // char[] arrays passed to string intrinsics are not scalar replaceable.
      add_node(n, PointsToNode::UnknownType, PointsToNode::UnknownEscape, false);
      break;
    }
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902
    case Op_ThreadLocal:
    {
      add_node(n, PointsToNode::JavaObject, PointsToNode::ArgEscape, true);
      break;
    }
    default:
      ;
      // nothing to do
  }
  return;
}
D
duke 已提交
2903

2904
void ConnectionGraph::build_connection_graph(Node *n, PhaseTransform *phase) {
2905
  uint n_idx = n->_idx;
2906
  assert(ptnode_adr(n_idx)->_node != NULL, "node should be registered");
2907

2908 2909
  // Don't set processed bit for AddP, LoadP, StoreP since
  // they may need more then one pass to process.
K
kvn 已提交
2910 2911
  // Also don't mark as processed Call nodes since their
  // arguments may need more then one pass to process.
2912
  if (_processed.test(n_idx))
2913 2914
    return; // No need to redefine node's state.

D
duke 已提交
2915 2916 2917 2918 2919 2920
  if (n->is_Call()) {
    CallNode *call = n->as_Call();
    process_call_arguments(call, phase);
    return;
  }

2921
  switch (n->Opcode()) {
D
duke 已提交
2922 2923
    case Op_AddP:
    {
2924
      Node *base = get_addp_base(n);
2925
      int offset = address_offset(n, phase);
2926
      // Create a field edge to this node from everything base could point to.
2927
      for( VectorSetI i(PointsTo(base)); i.test(); ++i ) {
D
duke 已提交
2928
        uint pt = i.elem;
2929
        add_field_edge(pt, n_idx, offset);
D
duke 已提交
2930 2931 2932
      }
      break;
    }
2933
    case Op_CastX2P:
D
duke 已提交
2934
    {
2935 2936 2937 2938 2939
      assert(false, "Op_CastX2P");
      break;
    }
    case Op_CastPP:
    case Op_CheckCastPP:
2940 2941
    case Op_EncodeP:
    case Op_DecodeN:
2942 2943
    {
      int ti = n->in(1)->_idx;
2944
      assert(ptnode_adr(ti)->node_type() != PointsToNode::UnknownType, "all nodes should be registered");
2945 2946
      if (ptnode_adr(ti)->node_type() == PointsToNode::JavaObject) {
        add_pointsto_edge(n_idx, ti);
D
duke 已提交
2947
      } else {
2948
        add_deferred_edge(n_idx, ti);
D
duke 已提交
2949
      }
2950
      _processed.set(n_idx);
D
duke 已提交
2951 2952
      break;
    }
2953
    case Op_ConP:
D
duke 已提交
2954
    {
2955
      assert(false, "Op_ConP");
D
duke 已提交
2956 2957
      break;
    }
2958 2959 2960 2961 2962
    case Op_ConN:
    {
      assert(false, "Op_ConN");
      break;
    }
D
duke 已提交
2963 2964
    case Op_CreateEx:
    {
2965
      assert(false, "Op_CreateEx");
D
duke 已提交
2966 2967 2968
      break;
    }
    case Op_LoadKlass:
2969
    case Op_LoadNKlass:
D
duke 已提交
2970
    {
2971
      assert(false, "Op_LoadKlass");
D
duke 已提交
2972 2973 2974
      break;
    }
    case Op_LoadP:
2975
    case Op_LoadN:
D
duke 已提交
2976 2977
    {
      const Type *t = phase->type(n);
2978
#ifdef ASSERT
2979
      if (t->make_ptr() == NULL)
2980 2981
        assert(false, "Op_LoadP");
#endif
D
duke 已提交
2982

2983 2984 2985 2986 2987 2988 2989
      Node* adr = n->in(MemNode::Address)->uncast();
      Node* adr_base;
      if (adr->is_AddP()) {
        adr_base = get_addp_base(adr);
      } else {
        adr_base = adr;
      }
D
duke 已提交
2990

2991 2992 2993
      // For everything "adr_base" could point to, create a deferred edge from
      // this node to each field with the same offset.
      int offset = address_offset(adr, phase);
2994
      for( VectorSetI i(PointsTo(adr_base)); i.test(); ++i ) {
D
duke 已提交
2995
        uint pt = i.elem;
2996 2997 2998 2999
        if (adr->is_AddP()) {
          // Add field edge if it is missing.
          add_field_edge(pt, adr->_idx, offset);
        }
3000
        add_deferred_edge_to_fields(n_idx, pt, offset);
D
duke 已提交
3001 3002 3003
      }
      break;
    }
3004 3005 3006 3007 3008
    case Op_Parm:
    {
      assert(false, "Op_Parm");
      break;
    }
3009 3010 3011 3012 3013
    case Op_PartialSubtypeCheck:
    {
      assert(false, "Op_PartialSubtypeCheck");
      break;
    }
3014 3015 3016
    case Op_Phi:
    {
#ifdef ASSERT
3017 3018
      const Type *t = n->as_Phi()->type();
      if (t->make_ptr() == NULL)
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
        assert(false, "Op_Phi");
#endif
      for (uint i = 1; i < n->req() ; i++) {
        Node* in = n->in(i);
        if (in == NULL)
          continue;  // ignore NULL
        in = in->uncast();
        if (in->is_top() || in == n)
          continue;  // ignore top or inputs which go back this node
        int ti = in->_idx;
3029 3030 3031
        PointsToNode::NodeType nt = ptnode_adr(ti)->node_type();
        assert(nt != PointsToNode::UnknownType, "all nodes should be known");
        if (nt == PointsToNode::JavaObject) {
3032
          add_pointsto_edge(n_idx, ti);
3033
        } else {
3034
          add_deferred_edge(n_idx, ti);
3035 3036
        }
      }
3037
      _processed.set(n_idx);
3038 3039 3040 3041
      break;
    }
    case Op_Proj:
    {
3042
      // we are only interested in the oop result projection from a call
3043
      if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() ) {
3044 3045 3046 3047 3048 3049 3050 3051 3052
        assert(ptnode_adr(n->in(0)->_idx)->node_type() != PointsToNode::UnknownType,
               "all nodes should be registered");
        const TypeTuple *r = n->in(0)->as_Call()->tf()->range();
        assert(r->cnt() > TypeFunc::Parms, "sanity");
        if (r->field_at(TypeFunc::Parms)->isa_ptr() != NULL) {
          process_call_result(n->as_Proj(), phase);
          assert(_processed.test(n_idx), "all call results should be processed");
          break;
        }
3053
      }
3054
      assert(false, "Op_Proj");
3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
      break;
    }
    case Op_Return:
    {
#ifdef ASSERT
      if( n->req() <= TypeFunc::Parms ||
          !phase->type(n->in(TypeFunc::Parms))->isa_oopptr() ) {
        assert(false, "Op_Return");
      }
#endif
      int ti = n->in(TypeFunc::Parms)->_idx;
3066
      assert(ptnode_adr(ti)->node_type() != PointsToNode::UnknownType, "node should be registered");
3067 3068
      if (ptnode_adr(ti)->node_type() == PointsToNode::JavaObject) {
        add_pointsto_edge(n_idx, ti);
3069
      } else {
3070
        add_deferred_edge(n_idx, ti);
3071
      }
3072
      _processed.set(n_idx);
3073 3074
      break;
    }
D
duke 已提交
3075
    case Op_StoreP:
3076
    case Op_StoreN:
D
duke 已提交
3077 3078
    case Op_StorePConditional:
    case Op_CompareAndSwapP:
3079
    case Op_CompareAndSwapN:
D
duke 已提交
3080 3081
    {
      Node *adr = n->in(MemNode::Address);
3082
      const Type *adr_type = phase->type(adr)->make_ptr();
3083
#ifdef ASSERT
D
duke 已提交
3084
      if (!adr_type->isa_oopptr())
3085 3086
        assert(phase->type(adr) == TypeRawPtr::NOTNULL, "Op_StoreP");
#endif
D
duke 已提交
3087

3088 3089 3090
      assert(adr->is_AddP(), "expecting an AddP");
      Node *adr_base = get_addp_base(adr);
      Node *val = n->in(MemNode::ValueIn)->uncast();
3091
      int offset = address_offset(adr, phase);
3092 3093
      // For everything "adr_base" could point to, create a deferred edge
      // to "val" from each field with the same offset.
3094
      for( VectorSetI i(PointsTo(adr_base)); i.test(); ++i ) {
D
duke 已提交
3095
        uint pt = i.elem;
3096 3097 3098
        // Add field edge if it is missing.
        add_field_edge(pt, adr->_idx, offset);
        add_edge_from_fields(pt, val->_idx, offset);
D
duke 已提交
3099 3100 3101
      }
      break;
    }
3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
    case Op_AryEq:
    case Op_StrComp:
    case Op_StrEquals:
    case Op_StrIndexOf:
    {
      // char[] arrays passed to string intrinsic do not escape but
      // they are not scalar replaceable. Adjust escape state for them.
      // Start from in(2) edge since in(1) is memory edge.
      for (uint i = 2; i < n->req(); i++) {
        Node* adr = n->in(i)->uncast();
        const Type *at = phase->type(adr);
        if (!adr->is_top() && at->isa_ptr()) {
          assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
                 at->isa_ptr() != NULL, "expecting an Ptr");
          if (adr->is_AddP()) {
            adr = get_addp_base(adr);
          }
          // Mark as ArgEscape everything "adr" could point to.
          set_escape_state(adr->_idx, PointsToNode::ArgEscape);
        }
      }
      _processed.set(n_idx);
      break;
    }
3126
    case Op_ThreadLocal:
D
duke 已提交
3127
    {
3128
      assert(false, "Op_ThreadLocal");
D
duke 已提交
3129 3130 3131
      break;
    }
    default:
3132 3133
      // This method should be called only for EA specific nodes.
      ShouldNotReachHere();
D
duke 已提交
3134 3135 3136 3137 3138 3139 3140
  }
}

#ifndef PRODUCT
void ConnectionGraph::dump() {
  bool first = true;

3141
  uint size = nodes_size();
3142
  for (uint ni = 0; ni < size; ni++) {
3143
    PointsToNode *ptn = ptnode_adr(ni);
3144 3145 3146
    PointsToNode::NodeType ptn_type = ptn->node_type();

    if (ptn_type != PointsToNode::JavaObject || ptn->_node == NULL)
D
duke 已提交
3147
      continue;
3148
    PointsToNode::EscapeState es = escape_state(ptn->_node);
3149 3150 3151 3152
    if (ptn->_node->is_Allocate() && (es == PointsToNode::NoEscape || Verbose)) {
      if (first) {
        tty->cr();
        tty->print("======== Connection graph for ");
3153
        _compile->method()->print_short_name();
3154 3155 3156 3157 3158 3159 3160
        tty->cr();
        first = false;
      }
      tty->print("%6d ", ni);
      ptn->dump();
      // Print all locals which reference this allocation
      for (uint li = ni; li < size; li++) {
3161
        PointsToNode *ptn_loc = ptnode_adr(li);
3162 3163 3164
        PointsToNode::NodeType ptn_loc_type = ptn_loc->node_type();
        if ( ptn_loc_type == PointsToNode::LocalVar && ptn_loc->_node != NULL &&
             ptn_loc->edge_count() == 1 && ptn_loc->edge_target(0) == ni ) {
3165
          ptnode_adr(li)->dump(false);
3166 3167 3168 3169 3170 3171
        }
      }
      if (Verbose) {
        // Print all fields which reference this allocation
        for (uint i = 0; i < ptn->edge_count(); i++) {
          uint ei = ptn->edge_target(i);
3172
          ptnode_adr(ei)->dump(false);
D
duke 已提交
3173 3174
        }
      }
3175
      tty->cr();
D
duke 已提交
3176 3177 3178 3179
    }
  }
}
#endif