src/share/vm/opto/escape.cpp

Mon, 12 Mar 2012 10:46:47 -0700

author
kvn
date
Mon, 12 Mar 2012 10:46:47 -0700
changeset 3651
ee138854b3a6
parent 3604
9a72c7ece7fb
child 3657
ed4c92f54c2d
permissions
-rw-r--r--

7147744: CTW: assert(false) failed: infinite EA connection graph build
Summary: rewrote Connection graph construction code in EA to reduce time spent there.
Reviewed-by: never

     1 /*
     2  * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    25 #include "precompiled.hpp"
    26 #include "ci/bcEscapeAnalyzer.hpp"
    27 #include "compiler/compileLog.hpp"
    28 #include "libadt/vectset.hpp"
    29 #include "memory/allocation.hpp"
    30 #include "opto/c2compiler.hpp"
    31 #include "opto/callnode.hpp"
    32 #include "opto/cfgnode.hpp"
    33 #include "opto/compile.hpp"
    34 #include "opto/escape.hpp"
    35 #include "opto/phaseX.hpp"
    36 #include "opto/rootnode.hpp"
    38 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn) :
    39   _nodes(C->comp_arena(), C->unique(), C->unique(), NULL),
    40   _collecting(true),
    41   _verify(false),
    42   _compile(C),
    43   _igvn(igvn),
    44   _node_map(C->comp_arena()) {
    45   // Add unknown java object.
    46   add_java_object(C->top(), PointsToNode::GlobalEscape);
    47   phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
    48   // Add ConP(#NULL) and ConN(#NULL) nodes.
    49   Node* oop_null = igvn->zerocon(T_OBJECT);
    50   assert(oop_null->_idx < nodes_size(), "should be created already");
    51   add_java_object(oop_null, PointsToNode::NoEscape);
    52   null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
    53   if (UseCompressedOops) {
    54     Node* noop_null = igvn->zerocon(T_NARROWOOP);
    55     assert(noop_null->_idx < nodes_size(), "should be created already");
    56     map_ideal_node(noop_null, null_obj);
    57   }
    58   _pcmp_neq = NULL; // Should be initialized
    59   _pcmp_eq  = NULL;
    60 }
    62 bool ConnectionGraph::has_candidates(Compile *C) {
    63   // EA brings benefits only when the code has allocations and/or locks which
    64   // are represented by ideal Macro nodes.
    65   int cnt = C->macro_count();
    66   for( int i=0; i < cnt; i++ ) {
    67     Node *n = C->macro_node(i);
    68     if ( n->is_Allocate() )
    69       return true;
    70     if( n->is_Lock() ) {
    71       Node* obj = n->as_Lock()->obj_node()->uncast();
    72       if( !(obj->is_Parm() || obj->is_Con()) )
    73         return true;
    74     }
    75   }
    76   return false;
    77 }
    79 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
    80   Compile::TracePhase t2("escapeAnalysis", &Phase::_t_escapeAnalysis, true);
    81   ResourceMark rm;
    83   // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction
    84   // to create space for them in ConnectionGraph::_nodes[].
    85   Node* oop_null = igvn->zerocon(T_OBJECT);
    86   Node* noop_null = igvn->zerocon(T_NARROWOOP);
    87   ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn);
    88   // Perform escape analysis
    89   if (congraph->compute_escape()) {
    90     // There are non escaping objects.
    91     C->set_congraph(congraph);
    92   }
    93   // Cleanup.
    94   if (oop_null->outcnt() == 0)
    95     igvn->hash_delete(oop_null);
    96   if (noop_null->outcnt() == 0)
    97     igvn->hash_delete(noop_null);
    98 }
   100 bool ConnectionGraph::compute_escape() {
   101   Compile* C = _compile;
   102   PhaseGVN* igvn = _igvn;
   104   // Worklists used by EA.
   105   Unique_Node_List delayed_worklist;
   106   GrowableArray<Node*> alloc_worklist;
   107   GrowableArray<Node*> ptr_cmp_worklist;
   108   GrowableArray<Node*> storestore_worklist;
   109   GrowableArray<PointsToNode*>   ptnodes_worklist;
   110   GrowableArray<JavaObjectNode*> java_objects_worklist;
   111   GrowableArray<JavaObjectNode*> non_escaped_worklist;
   112   GrowableArray<FieldNode*>      oop_fields_worklist;
   113   DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
   115   { Compile::TracePhase t3("connectionGraph", &Phase::_t_connectionGraph, true);
   117   // 1. Populate Connection Graph (CG) with PointsTo nodes.
   118   ideal_nodes.map(C->unique(), NULL);  // preallocate space
   119   // Initialize worklist
   120   if (C->root() != NULL) {
   121     ideal_nodes.push(C->root());
   122   }
   123   for( uint next = 0; next < ideal_nodes.size(); ++next ) {
   124     Node* n = ideal_nodes.at(next);
   125     // Create PointsTo nodes and add them to Connection Graph. Called
   126     // only once per ideal node since ideal_nodes is Unique_Node list.
   127     add_node_to_connection_graph(n, &delayed_worklist);
   128     PointsToNode* ptn = ptnode_adr(n->_idx);
   129     if (ptn != NULL) {
   130       ptnodes_worklist.append(ptn);
   131       if (ptn->is_JavaObject()) {
   132         java_objects_worklist.append(ptn->as_JavaObject());
   133         if ((n->is_Allocate() || n->is_CallStaticJava()) &&
   134             (ptn->escape_state() < PointsToNode::GlobalEscape)) {
   135           // Only allocations and java static calls results are interesting.
   136           non_escaped_worklist.append(ptn->as_JavaObject());
   137         }
   138       } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
   139         oop_fields_worklist.append(ptn->as_Field());
   140       }
   141     }
   142     if (n->is_MergeMem()) {
   143       // Collect all MergeMem nodes to add memory slices for
   144       // scalar replaceable objects in split_unique_types().
   145       _mergemem_worklist.append(n->as_MergeMem());
   146     } else if (OptimizePtrCompare && n->is_Cmp() &&
   147                (n->Opcode() == Op_CmpP || n->Opcode() == Op_CmpN)) {
   148       // Collect compare pointers nodes.
   149       ptr_cmp_worklist.append(n);
   150     } else if (n->is_MemBarStoreStore()) {
   151       // Collect all MemBarStoreStore nodes so that depending on the
   152       // escape status of the associated Allocate node some of them
   153       // may be eliminated.
   154       storestore_worklist.append(n);
   155 #ifdef ASSERT
   156     } else if(n->is_AddP()) {
   157       // Collect address nodes for graph verification.
   158       addp_worklist.append(n);
   159 #endif
   160     }
   161     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
   162       Node* m = n->fast_out(i);   // Get user
   163       ideal_nodes.push(m);
   164     }
   165   }
   166   if (non_escaped_worklist.length() == 0) {
   167     _collecting = false;
   168     return false; // Nothing to do.
   169   }
   170   // Add final simple edges to graph.
   171   while(delayed_worklist.size() > 0) {
   172     Node* n = delayed_worklist.pop();
   173     add_final_edges(n);
   174   }
   175   int ptnodes_length = ptnodes_worklist.length();
   177 #ifdef ASSERT
   178   if (VerifyConnectionGraph) {
   179     // Verify that no new simple edges could be created and all
   180     // local vars has edges.
   181     _verify = true;
   182     for (int next = 0; next < ptnodes_length; ++next) {
   183       PointsToNode* ptn = ptnodes_worklist.at(next);
   184       add_final_edges(ptn->ideal_node());
   185       if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
   186         ptn->dump();
   187         assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
   188       }
   189     }
   190     _verify = false;
   191   }
   192 #endif
   194   // 2. Finish Graph construction by propagating references to all
   195   //    java objects through graph.
   196   if (!complete_connection_graph(ptnodes_worklist, non_escaped_worklist,
   197                                  java_objects_worklist, oop_fields_worklist)) {
   198     // All objects escaped or hit time or iterations limits.
   199     _collecting = false;
   200     return false;
   201   }
   203   // 3. Adjust scalar_replaceable state of nonescaping objects and push
   204   //    scalar replaceable allocations on alloc_worklist for processing
   205   //    in split_unique_types().
   206   int non_escaped_length = non_escaped_worklist.length();
   207   for (int next = 0; next < non_escaped_length; next++) {
   208     JavaObjectNode* ptn = non_escaped_worklist.at(next);
   209     if (ptn->escape_state() == PointsToNode::NoEscape &&
   210         ptn->scalar_replaceable()) {
   211       adjust_scalar_replaceable_state(ptn);
   212       if (ptn->scalar_replaceable()) {
   213         alloc_worklist.append(ptn->ideal_node());
   214       }
   215     }
   216   }
   218 #ifdef ASSERT
   219   if (VerifyConnectionGraph) {
   220     // Verify that graph is complete - no new edges could be added or needed.
   221     verify_connection_graph(ptnodes_worklist, non_escaped_worklist,
   222                             java_objects_worklist, addp_worklist);
   223   }
   224   assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
   225   assert(null_obj->escape_state() == PointsToNode::NoEscape &&
   226          null_obj->edge_count() == 0 &&
   227          !null_obj->arraycopy_src() &&
   228          !null_obj->arraycopy_dst(), "sanity");
   229 #endif
   231   _collecting = false;
   233   } // TracePhase t3("connectionGraph")
   235   // 4. Optimize ideal graph based on EA information.
   236   bool has_non_escaping_obj = (non_escaped_worklist.length() > 0);
   237   if (has_non_escaping_obj) {
   238     optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
   239   }
   241 #ifndef PRODUCT
   242   if (PrintEscapeAnalysis) {
   243     dump(ptnodes_worklist); // Dump ConnectionGraph
   244   }
   245 #endif
   247   bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
   248 #ifdef ASSERT
   249   if (VerifyConnectionGraph) {
   250     int alloc_length = alloc_worklist.length();
   251     for (int next = 0; next < alloc_length; ++next) {
   252       Node* n = alloc_worklist.at(next);
   253       PointsToNode* ptn = ptnode_adr(n->_idx);
   254       assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
   255     }
   256   }
   257 #endif
   259   // 5. Separate memory graph for scalar replaceable allcations.
   260   if (has_scalar_replaceable_candidates &&
   261       C->AliasLevel() >= 3 && EliminateAllocations) {
   262     // Now use the escape information to create unique types for
   263     // scalar replaceable objects.
   264     split_unique_types(alloc_worklist);
   265     if (C->failing())  return false;
   266     C->print_method("After Escape Analysis", 2);
   268 #ifdef ASSERT
   269   } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
   270     tty->print("=== No allocations eliminated for ");
   271     C->method()->print_short_name();
   272     if(!EliminateAllocations) {
   273       tty->print(" since EliminateAllocations is off ===");
   274     } else if(!has_scalar_replaceable_candidates) {
   275       tty->print(" since there are no scalar replaceable candidates ===");
   276     } else if(C->AliasLevel() < 3) {
   277       tty->print(" since AliasLevel < 3 ===");
   278     }
   279     tty->cr();
   280 #endif
   281   }
   282   return has_non_escaping_obj;
   283 }
   285 // Populate Connection Graph with PointsTo nodes and create simple
   286 // connection graph edges.
   287 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
   288   assert(!_verify, "this method sould not be called for verification");
   289   PhaseGVN* igvn = _igvn;
   290   uint n_idx = n->_idx;
   291   PointsToNode* n_ptn = ptnode_adr(n_idx);
   292   if (n_ptn != NULL)
   293     return; // No need to redefine PointsTo node during first iteration.
   295   if (n->is_Call()) {
   296     // Arguments to allocation and locking don't escape.
   297     if (n->is_AbstractLock()) {
   298       // Put Lock and Unlock nodes on IGVN worklist to process them during
   299       // first IGVN optimization when escape information is still available.
   300       record_for_optimizer(n);
   301     } else if (n->is_Allocate()) {
   302       add_call_node(n->as_Call());
   303       record_for_optimizer(n);
   304     } else {
   305       if (n->is_CallStaticJava()) {
   306         const char* name = n->as_CallStaticJava()->_name;
   307         if (name != NULL && strcmp(name, "uncommon_trap") == 0)
   308           return; // Skip uncommon traps
   309       }
   310       // Don't mark as processed since call's arguments have to be processed.
   311       delayed_worklist->push(n);
   312       // Check if a call returns an object.
   313       if (n->as_Call()->returns_pointer() &&
   314           n->as_Call()->proj_out(TypeFunc::Parms) != NULL) {
   315         add_call_node(n->as_Call());
   316       }
   317     }
   318     return;
   319   }
   320   // Put this check here to process call arguments since some call nodes
   321   // point to phantom_obj.
   322   if (n_ptn == phantom_obj || n_ptn == null_obj)
   323     return; // Skip predefined nodes.
   325   int opcode = n->Opcode();
   326   switch (opcode) {
   327     case Op_AddP: {
   328       Node* base = get_addp_base(n);
   329       PointsToNode* ptn_base = ptnode_adr(base->_idx);
   330       // Field nodes are created for all field types. They are used in
   331       // adjust_scalar_replaceable_state() and split_unique_types().
   332       // Note, non-oop fields will have only base edges in Connection
   333       // Graph because such fields are not used for oop loads and stores.
   334       int offset = address_offset(n, igvn);
   335       add_field(n, PointsToNode::NoEscape, offset);
   336       if (ptn_base == NULL) {
   337         delayed_worklist->push(n); // Process it later.
   338       } else {
   339         n_ptn = ptnode_adr(n_idx);
   340         add_base(n_ptn->as_Field(), ptn_base);
   341       }
   342       break;
   343     }
   344     case Op_CastX2P: {
   345       map_ideal_node(n, phantom_obj);
   346       break;
   347     }
   348     case Op_CastPP:
   349     case Op_CheckCastPP:
   350     case Op_EncodeP:
   351     case Op_DecodeN: {
   352       add_local_var_and_edge(n, PointsToNode::NoEscape,
   353                              n->in(1), delayed_worklist);
   354       break;
   355     }
   356     case Op_CMoveP: {
   357       add_local_var(n, PointsToNode::NoEscape);
   358       // Do not add edges during first iteration because some could be
   359       // not defined yet.
   360       delayed_worklist->push(n);
   361       break;
   362     }
   363     case Op_ConP:
   364     case Op_ConN: {
   365       // assume all oop constants globally escape except for null
   366       PointsToNode::EscapeState es;
   367       if (igvn->type(n) == TypePtr::NULL_PTR ||
   368           igvn->type(n) == TypeNarrowOop::NULL_PTR) {
   369         es = PointsToNode::NoEscape;
   370       } else {
   371         es = PointsToNode::GlobalEscape;
   372       }
   373       add_java_object(n, es);
   374       break;
   375     }
   376     case Op_CreateEx: {
   377       // assume that all exception objects globally escape
   378       add_java_object(n, PointsToNode::GlobalEscape);
   379       break;
   380     }
   381     case Op_LoadKlass:
   382     case Op_LoadNKlass: {
   383       // Unknown class is loaded
   384       map_ideal_node(n, phantom_obj);
   385       break;
   386     }
   387     case Op_LoadP:
   388     case Op_LoadN:
   389     case Op_LoadPLocked: {
   390       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   391       // ThreadLocal has RawPrt type.
   392       const Type* t = igvn->type(n);
   393       if (t->make_ptr() != NULL) {
   394         Node* adr = n->in(MemNode::Address);
   395 #ifdef ASSERT
   396         if (!adr->is_AddP()) {
   397           assert(igvn->type(adr)->isa_rawptr(), "sanity");
   398         } else {
   399           assert((ptnode_adr(adr->_idx) == NULL ||
   400                   ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
   401         }
   402 #endif
   403         add_local_var_and_edge(n, PointsToNode::NoEscape,
   404                                adr, delayed_worklist);
   405       }
   406       break;
   407     }
   408     case Op_Parm: {
   409       map_ideal_node(n, phantom_obj);
   410       break;
   411     }
   412     case Op_PartialSubtypeCheck: {
   413       // Produces Null or notNull and is used in only in CmpP so
   414       // phantom_obj could be used.
   415       map_ideal_node(n, phantom_obj); // Result is unknown
   416       break;
   417     }
   418     case Op_Phi: {
   419       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   420       // ThreadLocal has RawPrt type.
   421       const Type* t = n->as_Phi()->type();
   422       if (t->make_ptr() != NULL) {
   423         add_local_var(n, PointsToNode::NoEscape);
   424         // Do not add edges during first iteration because some could be
   425         // not defined yet.
   426         delayed_worklist->push(n);
   427       }
   428       break;
   429     }
   430     case Op_Proj: {
   431       // we are only interested in the oop result projection from a call
   432       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
   433           n->in(0)->as_Call()->returns_pointer()) {
   434         add_local_var_and_edge(n, PointsToNode::NoEscape,
   435                                n->in(0), delayed_worklist);
   436       }
   437       break;
   438     }
   439     case Op_Rethrow: // Exception object escapes
   440     case Op_Return: {
   441       if (n->req() > TypeFunc::Parms &&
   442           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
   443         // Treat Return value as LocalVar with GlobalEscape escape state.
   444         add_local_var_and_edge(n, PointsToNode::GlobalEscape,
   445                                n->in(TypeFunc::Parms), delayed_worklist);
   446       }
   447       break;
   448     }
   449     case Op_StoreP:
   450     case Op_StoreN:
   451     case Op_StorePConditional:
   452     case Op_CompareAndSwapP:
   453     case Op_CompareAndSwapN: {
   454       Node* adr = n->in(MemNode::Address);
   455       const Type *adr_type = igvn->type(adr);
   456       adr_type = adr_type->make_ptr();
   457       if (adr_type->isa_oopptr() ||
   458           (opcode == Op_StoreP || opcode == Op_StoreN) &&
   459                         (adr_type == TypeRawPtr::NOTNULL &&
   460                          adr->in(AddPNode::Address)->is_Proj() &&
   461                          adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
   462         delayed_worklist->push(n); // Process it later.
   463 #ifdef ASSERT
   464         assert(adr->is_AddP(), "expecting an AddP");
   465         if (adr_type == TypeRawPtr::NOTNULL) {
   466           // Verify a raw address for a store captured by Initialize node.
   467           int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
   468           assert(offs != Type::OffsetBot, "offset must be a constant");
   469         }
   470       } else {
   471         // Ignore copy the displaced header to the BoxNode (OSR compilation).
   472         if (adr->is_BoxLock())
   473           break;
   475         if (!adr->is_AddP()) {
   476           n->dump(1);
   477           assert(adr->is_AddP(), "expecting an AddP");
   478         }
   479         // Ignore G1 barrier's stores.
   480         if (!UseG1GC || (opcode != Op_StoreP) ||
   481             (adr_type != TypeRawPtr::BOTTOM)) {
   482           n->dump(1);
   483           assert(false, "not G1 barrier raw StoreP");
   484         }
   485 #endif
   486       }
   487       break;
   488     }
   489     case Op_AryEq:
   490     case Op_StrComp:
   491     case Op_StrEquals:
   492     case Op_StrIndexOf: {
   493       add_local_var(n, PointsToNode::ArgEscape);
   494       delayed_worklist->push(n); // Process it later.
   495       break;
   496     }
   497     case Op_ThreadLocal: {
   498       add_java_object(n, PointsToNode::ArgEscape);
   499       break;
   500     }
   501     default:
   502       ; // Do nothing for nodes not related to EA.
   503   }
   504   return;
   505 }
   507 #ifdef ASSERT
   508 #define ELSE_FAIL(name)                               \
   509       /* Should not be called for not pointer type. */  \
   510       n->dump(1);                                       \
   511       assert(false, name);                              \
   512       break;
   513 #else
   514 #define ELSE_FAIL(name) \
   515       break;
   516 #endif
   518 // Add final simple edges to graph.
   519 void ConnectionGraph::add_final_edges(Node *n) {
   520   PointsToNode* n_ptn = ptnode_adr(n->_idx);
   521 #ifdef ASSERT
   522   if (_verify && n_ptn->is_JavaObject())
   523     return; // This method does not change graph for JavaObject.
   524 #endif
   526   if (n->is_Call()) {
   527     process_call_arguments(n->as_Call());
   528     return;
   529   }
   530   assert(n->is_Store() || n->is_LoadStore() ||
   531          (n_ptn != NULL) && (n_ptn->ideal_node() != NULL),
   532          "node should be registered already");
   533   int opcode = n->Opcode();
   534   switch (opcode) {
   535     case Op_AddP: {
   536       Node* base = get_addp_base(n);
   537       PointsToNode* ptn_base = ptnode_adr(base->_idx);
   538       assert(ptn_base != NULL, "field's base should be registered");
   539       add_base(n_ptn->as_Field(), ptn_base);
   540       break;
   541     }
   542     case Op_CastPP:
   543     case Op_CheckCastPP:
   544     case Op_EncodeP:
   545     case Op_DecodeN: {
   546       add_local_var_and_edge(n, PointsToNode::NoEscape,
   547                              n->in(1), NULL);
   548       break;
   549     }
   550     case Op_CMoveP: {
   551       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
   552         Node* in = n->in(i);
   553         if (in == NULL)
   554           continue;  // ignore NULL
   555         Node* uncast_in = in->uncast();
   556         if (uncast_in->is_top() || uncast_in == n)
   557           continue;  // ignore top or inputs which go back this node
   558         PointsToNode* ptn = ptnode_adr(in->_idx);
   559         assert(ptn != NULL, "node should be registered");
   560         add_edge(n_ptn, ptn);
   561       }
   562       break;
   563     }
   564     case Op_LoadP:
   565     case Op_LoadN:
   566     case Op_LoadPLocked: {
   567       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   568       // ThreadLocal has RawPrt type.
   569       const Type* t = _igvn->type(n);
   570       if (t->make_ptr() != NULL) {
   571         Node* adr = n->in(MemNode::Address);
   572         add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
   573         break;
   574       }
   575       ELSE_FAIL("Op_LoadP");
   576     }
   577     case Op_Phi: {
   578       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
   579       // ThreadLocal has RawPrt type.
   580       const Type* t = n->as_Phi()->type();
   581       if (t->make_ptr() != NULL) {
   582         for (uint i = 1; i < n->req(); i++) {
   583           Node* in = n->in(i);
   584           if (in == NULL)
   585             continue;  // ignore NULL
   586           Node* uncast_in = in->uncast();
   587           if (uncast_in->is_top() || uncast_in == n)
   588             continue;  // ignore top or inputs which go back this node
   589           PointsToNode* ptn = ptnode_adr(in->_idx);
   590           assert(ptn != NULL, "node should be registered");
   591           add_edge(n_ptn, ptn);
   592         }
   593         break;
   594       }
   595       ELSE_FAIL("Op_Phi");
   596     }
   597     case Op_Proj: {
   598       // we are only interested in the oop result projection from a call
   599       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
   600           n->in(0)->as_Call()->returns_pointer()) {
   601         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), NULL);
   602         break;
   603       }
   604       ELSE_FAIL("Op_Proj");
   605     }
   606     case Op_Rethrow: // Exception object escapes
   607     case Op_Return: {
   608       if (n->req() > TypeFunc::Parms &&
   609           _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
   610         // Treat Return value as LocalVar with GlobalEscape escape state.
   611         add_local_var_and_edge(n, PointsToNode::GlobalEscape,
   612                                n->in(TypeFunc::Parms), NULL);
   613         break;
   614       }
   615       ELSE_FAIL("Op_Return");
   616     }
   617     case Op_StoreP:
   618     case Op_StoreN:
   619     case Op_StorePConditional:
   620     case Op_CompareAndSwapP:
   621     case Op_CompareAndSwapN: {
   622       Node* adr = n->in(MemNode::Address);
   623       const Type *adr_type = _igvn->type(adr);
   624       adr_type = adr_type->make_ptr();
   625       if (adr_type->isa_oopptr() ||
   626           (opcode == Op_StoreP || opcode == Op_StoreN) &&
   627                         (adr_type == TypeRawPtr::NOTNULL &&
   628                          adr->in(AddPNode::Address)->is_Proj() &&
   629                          adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
   630         // Point Address to Value
   631         PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
   632         assert(adr_ptn != NULL &&
   633                adr_ptn->as_Field()->is_oop(), "node should be registered");
   634         Node *val = n->in(MemNode::ValueIn);
   635         PointsToNode* ptn = ptnode_adr(val->_idx);
   636         assert(ptn != NULL, "node should be registered");
   637         add_edge(adr_ptn, ptn);
   638         break;
   639       }
   640       ELSE_FAIL("Op_StoreP");
   641     }
   642     case Op_AryEq:
   643     case Op_StrComp:
   644     case Op_StrEquals:
   645     case Op_StrIndexOf: {
   646       // char[] arrays passed to string intrinsic do not escape but
   647       // they are not scalar replaceable. Adjust escape state for them.
   648       // Start from in(2) edge since in(1) is memory edge.
   649       for (uint i = 2; i < n->req(); i++) {
   650         Node* adr = n->in(i);
   651         const Type* at = _igvn->type(adr);
   652         if (!adr->is_top() && at->isa_ptr()) {
   653           assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
   654                  at->isa_ptr() != NULL, "expecting a pointer");
   655           if (adr->is_AddP()) {
   656             adr = get_addp_base(adr);
   657           }
   658           PointsToNode* ptn = ptnode_adr(adr->_idx);
   659           assert(ptn != NULL, "node should be registered");
   660           add_edge(n_ptn, ptn);
   661         }
   662       }
   663       break;
   664     }
   665     default: {
   666       // This method should be called only for EA specific nodes which may
   667       // miss some edges when they were created.
   668 #ifdef ASSERT
   669       n->dump(1);
   670 #endif
   671       guarantee(false, "unknown node");
   672     }
   673   }
   674   return;
   675 }
   677 void ConnectionGraph::add_call_node(CallNode* call) {
   678   assert(call->returns_pointer(), "only for call which returns pointer");
   679   uint call_idx = call->_idx;
   680   if (call->is_Allocate()) {
   681     Node* k = call->in(AllocateNode::KlassNode);
   682     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
   683     assert(kt != NULL, "TypeKlassPtr  required.");
   684     ciKlass* cik = kt->klass();
   685     PointsToNode::EscapeState es = PointsToNode::NoEscape;
   686     bool scalar_replaceable = true;
   687     if (call->is_AllocateArray()) {
   688       if (!cik->is_array_klass()) { // StressReflectiveCode
   689         es = PointsToNode::GlobalEscape;
   690       } else {
   691         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
   692         if (length < 0 || length > EliminateAllocationArraySizeLimit) {
   693           // Not scalar replaceable if the length is not constant or too big.
   694           scalar_replaceable = false;
   695         }
   696       }
   697     } else {  // Allocate instance
   698       if (cik->is_subclass_of(_compile->env()->Thread_klass()) ||
   699          !cik->is_instance_klass() || // StressReflectiveCode
   700           cik->as_instance_klass()->has_finalizer()) {
   701         es = PointsToNode::GlobalEscape;
   702       }
   703     }
   704     add_java_object(call, es);
   705     PointsToNode* ptn = ptnode_adr(call_idx);
   706     if (!scalar_replaceable && ptn->scalar_replaceable()) {
   707       ptn->set_scalar_replaceable(false);
   708     }
   709   } else if (call->is_CallStaticJava()) {
   710     // Call nodes could be different types:
   711     //
   712     // 1. CallDynamicJavaNode (what happened during call is unknown):
   713     //
   714     //    - mapped to GlobalEscape JavaObject node if oop is returned;
   715     //
   716     //    - all oop arguments are escaping globally;
   717     //
   718     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
   719     //
   720     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
   721     //
   722     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
   723     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
   724     //      during call is returned;
   725     //    - mapped to ArgEscape LocalVar node pointed to object arguments
   726     //      which are returned and does not escape during call;
   727     //
   728     //    - oop arguments escaping status is defined by bytecode analysis;
   729     //
   730     // For a static call, we know exactly what method is being called.
   731     // Use bytecode estimator to record whether the call's return value escapes.
   732     ciMethod* meth = call->as_CallJava()->method();
   733     if (meth == NULL) {
   734       const char* name = call->as_CallStaticJava()->_name;
   735       assert(strncmp(name, "_multianewarray", 15) == 0, "TODO: add failed case check");
   736       // Returns a newly allocated unescaped object.
   737       add_java_object(call, PointsToNode::NoEscape);
   738       ptnode_adr(call_idx)->set_scalar_replaceable(false);
   739     } else {
   740       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
   741       call_analyzer->copy_dependencies(_compile->dependencies());
   742       if (call_analyzer->is_return_allocated()) {
   743         // Returns a newly allocated unescaped object, simply
   744         // update dependency information.
   745         // Mark it as NoEscape so that objects referenced by
   746         // it's fields will be marked as NoEscape at least.
   747         add_java_object(call, PointsToNode::NoEscape);
   748         ptnode_adr(call_idx)->set_scalar_replaceable(false);
   749       } else {
   750         // Determine whether any arguments are returned.
   751         const TypeTuple* d = call->tf()->domain();
   752         bool ret_arg = false;
   753         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   754           if (d->field_at(i)->isa_ptr() != NULL &&
   755               call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
   756             ret_arg = true;
   757             break;
   758           }
   759         }
   760         if (ret_arg) {
   761           add_local_var(call, PointsToNode::ArgEscape);
   762         } else {
   763           // Returns unknown object.
   764           map_ideal_node(call, phantom_obj);
   765         }
   766       }
   767     }
   768   } else {
   769     // An other type of call, assume the worst case:
   770     // returned value is unknown and globally escapes.
   771     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
   772     map_ideal_node(call, phantom_obj);
   773   }
   774 }
   776 void ConnectionGraph::process_call_arguments(CallNode *call) {
   777     bool is_arraycopy = false;
   778     switch (call->Opcode()) {
   779 #ifdef ASSERT
   780     case Op_Allocate:
   781     case Op_AllocateArray:
   782     case Op_Lock:
   783     case Op_Unlock:
   784       assert(false, "should be done already");
   785       break;
   786 #endif
   787     case Op_CallLeafNoFP:
   788       is_arraycopy = (call->as_CallLeaf()->_name != NULL &&
   789                       strstr(call->as_CallLeaf()->_name, "arraycopy") != 0);
   790       // fall through
   791     case Op_CallLeaf: {
   792       // Stub calls, objects do not escape but they are not scale replaceable.
   793       // Adjust escape state for outgoing arguments.
   794       const TypeTuple * d = call->tf()->domain();
   795       bool src_has_oops = false;
   796       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   797         const Type* at = d->field_at(i);
   798         Node *arg = call->in(i);
   799         const Type *aat = _igvn->type(arg);
   800         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr())
   801           continue;
   802         if (arg->is_AddP()) {
   803           //
   804           // The inline_native_clone() case when the arraycopy stub is called
   805           // after the allocation before Initialize and CheckCastPP nodes.
   806           // Or normal arraycopy for object arrays case.
   807           //
   808           // Set AddP's base (Allocate) as not scalar replaceable since
   809           // pointer to the base (with offset) is passed as argument.
   810           //
   811           arg = get_addp_base(arg);
   812         }
   813         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
   814         assert(arg_ptn != NULL, "should be registered");
   815         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
   816         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
   817           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
   818                  aat->isa_ptr() != NULL, "expecting an Ptr");
   819           bool arg_has_oops = aat->isa_oopptr() &&
   820                               (aat->isa_oopptr()->klass() == NULL || aat->isa_instptr() ||
   821                                (aat->isa_aryptr() && aat->isa_aryptr()->klass()->is_obj_array_klass()));
   822           if (i == TypeFunc::Parms) {
   823             src_has_oops = arg_has_oops;
   824           }
   825           //
   826           // src or dst could be j.l.Object when other is basic type array:
   827           //
   828           //   arraycopy(char[],0,Object*,0,size);
   829           //   arraycopy(Object*,0,char[],0,size);
   830           //
   831           // Don't add edges in such cases.
   832           //
   833           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
   834                                        arg_has_oops && (i > TypeFunc::Parms);
   835 #ifdef ASSERT
   836           if (!(is_arraycopy ||
   837                 call->as_CallLeaf()->_name != NULL &&
   838                 (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre")  == 0 ||
   839                  strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 ))
   840           ) {
   841             call->dump();
   842             assert(false, "EA: unexpected CallLeaf");
   843           }
   844 #endif
   845           // Always process arraycopy's destination object since
   846           // we need to add all possible edges to references in
   847           // source object.
   848           if (arg_esc >= PointsToNode::ArgEscape &&
   849               !arg_is_arraycopy_dest) {
   850             continue;
   851           }
   852           set_escape_state(arg_ptn, PointsToNode::ArgEscape);
   853           if (arg_is_arraycopy_dest) {
   854             Node* src = call->in(TypeFunc::Parms);
   855             if (src->is_AddP()) {
   856               src = get_addp_base(src);
   857             }
   858             PointsToNode* src_ptn = ptnode_adr(src->_idx);
   859             assert(src_ptn != NULL, "should be registered");
   860             if (arg_ptn != src_ptn) {
   861               // Special arraycopy edge:
   862               // A destination object's field can't have the source object
   863               // as base since objects escape states are not related.
   864               // Only escape state of destination object's fields affects
   865               // escape state of fields in source object.
   866               add_arraycopy(call, PointsToNode::ArgEscape, src_ptn, arg_ptn);
   867             }
   868           }
   869         }
   870       }
   871       break;
   872     }
   873     case Op_CallStaticJava: {
   874       // For a static call, we know exactly what method is being called.
   875       // Use bytecode estimator to record the call's escape affects
   876 #ifdef ASSERT
   877       const char* name = call->as_CallStaticJava()->_name;
   878       assert((name == NULL || strcmp(name, "uncommon_trap") != 0), "normal calls only");
   879 #endif
   880       ciMethod* meth = call->as_CallJava()->method();
   881       BCEscapeAnalyzer* call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
   882       // fall-through if not a Java method or no analyzer information
   883       if (call_analyzer != NULL) {
   884         PointsToNode* call_ptn = ptnode_adr(call->_idx);
   885         const TypeTuple* d = call->tf()->domain();
   886         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   887           const Type* at = d->field_at(i);
   888           int k = i - TypeFunc::Parms;
   889           Node* arg = call->in(i);
   890           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
   891           if (at->isa_ptr() != NULL &&
   892               call_analyzer->is_arg_returned(k)) {
   893             // The call returns arguments.
   894             if (call_ptn != NULL) { // Is call's result used?
   895               assert(call_ptn->is_LocalVar(), "node should be registered");
   896               assert(arg_ptn != NULL, "node should be registered");
   897               add_edge(call_ptn, arg_ptn);
   898             }
   899           }
   900           if (at->isa_oopptr() != NULL &&
   901               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
   902             if (!call_analyzer->is_arg_stack(k)) {
   903               // The argument global escapes
   904               set_escape_state(arg_ptn, PointsToNode::GlobalEscape);
   905             } else {
   906               set_escape_state(arg_ptn, PointsToNode::ArgEscape);
   907               if (!call_analyzer->is_arg_local(k)) {
   908                 // The argument itself doesn't escape, but any fields might
   909                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape);
   910               }
   911             }
   912           }
   913         }
   914         if (call_ptn != NULL && call_ptn->is_LocalVar()) {
   915           // The call returns arguments.
   916           assert(call_ptn->edge_count() > 0, "sanity");
   917           if (!call_analyzer->is_return_local()) {
   918             // Returns also unknown object.
   919             add_edge(call_ptn, phantom_obj);
   920           }
   921         }
   922         break;
   923       }
   924     }
   925     default: {
   926       // Fall-through here if not a Java method or no analyzer information
   927       // or some other type of call, assume the worst case: all arguments
   928       // globally escape.
   929       const TypeTuple* d = call->tf()->domain();
   930       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
   931         const Type* at = d->field_at(i);
   932         if (at->isa_oopptr() != NULL) {
   933           Node* arg = call->in(i);
   934           if (arg->is_AddP()) {
   935             arg = get_addp_base(arg);
   936           }
   937           assert(ptnode_adr(arg->_idx) != NULL, "should be defined already");
   938           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape);
   939         }
   940       }
   941     }
   942   }
   943 }
   946 // Finish Graph construction.
   947 bool ConnectionGraph::complete_connection_graph(
   948                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
   949                          GrowableArray<JavaObjectNode*>& non_escaped_worklist,
   950                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
   951                          GrowableArray<FieldNode*>&      oop_fields_worklist) {
   952   // Normally only 1-3 passes needed to build Connection Graph depending
   953   // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
   954   // Set limit to 20 to catch situation when something did go wrong and
   955   // bailout Escape Analysis.
   956   // Also limit build time to 30 sec (60 in debug VM).
   957 #define CG_BUILD_ITER_LIMIT 20
   958 #ifdef ASSERT
   959 #define CG_BUILD_TIME_LIMIT 60.0
   960 #else
   961 #define CG_BUILD_TIME_LIMIT 30.0
   962 #endif
   964   // Propagate GlobalEscape and ArgEscape escape states and check that
   965   // we still have non-escaping objects. The method pushs on _worklist
   966   // Field nodes which reference phantom_object.
   967   if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
   968     return false; // Nothing to do.
   969   }
   970   // Now propagate references to all JavaObject nodes.
   971   int java_objects_length = java_objects_worklist.length();
   972   elapsedTimer time;
   973   int new_edges = 1;
   974   int iterations = 0;
   975   do {
   976     while ((new_edges > 0) &&
   977           (iterations++   < CG_BUILD_ITER_LIMIT) &&
   978           (time.seconds() < CG_BUILD_TIME_LIMIT)) {
   979       time.start();
   980       new_edges = 0;
   981       // Propagate references to phantom_object for nodes pushed on _worklist
   982       // by find_non_escaped_objects() and find_field_value().
   983       new_edges += add_java_object_edges(phantom_obj, false);
   984       for (int next = 0; next < java_objects_length; ++next) {
   985         JavaObjectNode* ptn = java_objects_worklist.at(next);
   986         new_edges += add_java_object_edges(ptn, true);
   987       }
   988       if (new_edges > 0) {
   989         // Update escape states on each iteration if graph was updated.
   990         if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
   991           return false; // Nothing to do.
   992         }
   993       }
   994       time.stop();
   995     }
   996     if ((iterations     < CG_BUILD_ITER_LIMIT) &&
   997         (time.seconds() < CG_BUILD_TIME_LIMIT)) {
   998       time.start();
   999       // Find fields which have unknown value.
  1000       int fields_length = oop_fields_worklist.length();
  1001       for (int next = 0; next < fields_length; next++) {
  1002         FieldNode* field = oop_fields_worklist.at(next);
  1003         if (field->edge_count() == 0) {
  1004           new_edges += find_field_value(field);
  1005           // This code may added new edges to phantom_object.
  1006           // Need an other cycle to propagate references to phantom_object.
  1009       time.stop();
  1010     } else {
  1011       new_edges = 0; // Bailout
  1013   } while (new_edges > 0);
  1015   // Bailout if passed limits.
  1016   if ((iterations     >= CG_BUILD_ITER_LIMIT) ||
  1017       (time.seconds() >= CG_BUILD_TIME_LIMIT)) {
  1018     Compile* C = _compile;
  1019     if (C->log() != NULL) {
  1020       C->log()->begin_elem("connectionGraph_bailout reason='reached ");
  1021       C->log()->text("%s", (iterations >= CG_BUILD_ITER_LIMIT) ? "iterations" : "time");
  1022       C->log()->end_elem(" limit'");
  1024     assert(false, err_msg("infinite EA connection graph build (%f sec, %d iterations) with %d nodes and worklist size %d",
  1025            time.seconds(), iterations, nodes_size(), ptnodes_worklist.length()));
  1026     // Possible infinite build_connection_graph loop,
  1027     // bailout (no changes to ideal graph were made).
  1028     return false;
  1030 #ifdef ASSERT
  1031   if (Verbose && PrintEscapeAnalysis) {
  1032     tty->print_cr("EA: %d iterations to build connection graph with %d nodes and worklist size %d",
  1033                   iterations, nodes_size(), ptnodes_worklist.length());
  1035 #endif
  1037 #undef CG_BUILD_ITER_LIMIT
  1038 #undef CG_BUILD_TIME_LIMIT
  1040   // Find fields initialized by NULL for non-escaping Allocations.
  1041   int non_escaped_length = non_escaped_worklist.length();
  1042   for (int next = 0; next < non_escaped_length; next++) {
  1043     JavaObjectNode* ptn = non_escaped_worklist.at(next);
  1044     PointsToNode::EscapeState es = ptn->escape_state();
  1045     assert(es <= PointsToNode::ArgEscape, "sanity");
  1046     if (es == PointsToNode::NoEscape) {
  1047       if (find_init_values(ptn, null_obj, _igvn) > 0) {
  1048         // Adding references to NULL object does not change escape states
  1049         // since it does not escape. Also no fields are added to NULL object.
  1050         add_java_object_edges(null_obj, false);
  1053     Node* n = ptn->ideal_node();
  1054     if (n->is_Allocate()) {
  1055       // The object allocated by this Allocate node will never be
  1056       // seen by an other thread. Mark it so that when it is
  1057       // expanded no MemBarStoreStore is added.
  1058       InitializeNode* ini = n->as_Allocate()->initialization();
  1059       if (ini != NULL)
  1060         ini->set_does_not_escape();
  1063   return true; // Finished graph construction.
  1066 // Propagate GlobalEscape and ArgEscape escape states to all nodes
  1067 // and check that we still have non-escaping java objects.
  1068 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
  1069                                                GrowableArray<JavaObjectNode*>& non_escaped_worklist) {
  1070   GrowableArray<PointsToNode*> escape_worklist;
  1071   // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
  1072   int ptnodes_length = ptnodes_worklist.length();
  1073   for (int next = 0; next < ptnodes_length; ++next) {
  1074     PointsToNode* ptn = ptnodes_worklist.at(next);
  1075     if (ptn->escape_state() >= PointsToNode::ArgEscape ||
  1076         ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
  1077       escape_worklist.push(ptn);
  1080   // Set escape states to referenced nodes (edges list).
  1081   while (escape_worklist.length() > 0) {
  1082     PointsToNode* ptn = escape_worklist.pop();
  1083     PointsToNode::EscapeState es  = ptn->escape_state();
  1084     PointsToNode::EscapeState field_es = ptn->fields_escape_state();
  1085     if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
  1086         es >= PointsToNode::ArgEscape) {
  1087       // GlobalEscape or ArgEscape state of field means it has unknown value.
  1088       if (add_edge(ptn, phantom_obj)) {
  1089         // New edge was added
  1090         add_field_uses_to_worklist(ptn->as_Field());
  1093     for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1094       PointsToNode* e = i.get();
  1095       if (e->is_Arraycopy()) {
  1096         assert(ptn->arraycopy_dst(), "sanity");
  1097         // Propagate only fields escape state through arraycopy edge.
  1098         if (e->fields_escape_state() < field_es) {
  1099           set_fields_escape_state(e, field_es);
  1100           escape_worklist.push(e);
  1102       } else if (es >= field_es) {
  1103         // fields_escape_state is also set to 'es' if it is less than 'es'.
  1104         if (e->escape_state() < es) {
  1105           set_escape_state(e, es);
  1106           escape_worklist.push(e);
  1108       } else {
  1109         // Propagate field escape state.
  1110         bool es_changed = false;
  1111         if (e->fields_escape_state() < field_es) {
  1112           set_fields_escape_state(e, field_es);
  1113           es_changed = true;
  1115         if ((e->escape_state() < field_es) &&
  1116             e->is_Field() && ptn->is_JavaObject() &&
  1117             e->as_Field()->is_oop()) {
  1118           // Change escape state of referenced fileds.
  1119           set_escape_state(e, field_es);
  1120           es_changed = true;;
  1121         } else if (e->escape_state() < es) {
  1122           set_escape_state(e, es);
  1123           es_changed = true;;
  1125         if (es_changed) {
  1126           escape_worklist.push(e);
  1131   // Remove escaped objects from non_escaped list.
  1132   for (int next = non_escaped_worklist.length()-1; next >= 0 ; --next) {
  1133     JavaObjectNode* ptn = non_escaped_worklist.at(next);
  1134     if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
  1135       non_escaped_worklist.delete_at(next);
  1137     if (ptn->escape_state() == PointsToNode::NoEscape) {
  1138       // Find fields in non-escaped allocations which have unknown value.
  1139       find_init_values(ptn, phantom_obj, NULL);
  1142   return (non_escaped_worklist.length() > 0);
  1145 // Add all references to JavaObject node by walking over all uses.
  1146 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
  1147   int new_edges = 0;
  1148   if (populate_worklist) {
  1149     // Populate _worklist by uses of jobj's uses.
  1150     for (UseIterator i(jobj); i.has_next(); i.next()) {
  1151       PointsToNode* use = i.get();
  1152       if (use->is_Arraycopy())
  1153         continue;
  1154       add_uses_to_worklist(use);
  1155       if (use->is_Field() && use->as_Field()->is_oop()) {
  1156         // Put on worklist all field's uses (loads) and
  1157         // related field nodes (same base and offset).
  1158         add_field_uses_to_worklist(use->as_Field());
  1162   while(_worklist.length() > 0) {
  1163     PointsToNode* use = _worklist.pop();
  1164     if (PointsToNode::is_base_use(use)) {
  1165       // Add reference from jobj to field and from field to jobj (field's base).
  1166       use = PointsToNode::get_use_node(use)->as_Field();
  1167       if (add_base(use->as_Field(), jobj)) {
  1168         new_edges++;
  1170       continue;
  1172     assert(!use->is_JavaObject(), "sanity");
  1173     if (use->is_Arraycopy()) {
  1174       if (jobj == null_obj) // NULL object does not have field edges
  1175         continue;
  1176       // Added edge from Arraycopy node to arraycopy's source java object
  1177       if (add_edge(use, jobj)) {
  1178         jobj->set_arraycopy_src();
  1179         new_edges++;
  1181       // and stop here.
  1182       continue;
  1184     if (!add_edge(use, jobj))
  1185       continue; // No new edge added, there was such edge already.
  1186     new_edges++;
  1187     if (use->is_LocalVar()) {
  1188       add_uses_to_worklist(use);
  1189       if (use->arraycopy_dst()) {
  1190         for (EdgeIterator i(use); i.has_next(); i.next()) {
  1191           PointsToNode* e = i.get();
  1192           if (e->is_Arraycopy()) {
  1193             if (jobj == null_obj) // NULL object does not have field edges
  1194               continue;
  1195             // Add edge from arraycopy's destination java object to Arraycopy node.
  1196             if (add_edge(jobj, e)) {
  1197               new_edges++;
  1198               jobj->set_arraycopy_dst();
  1203     } else {
  1204       // Added new edge to stored in field values.
  1205       // Put on worklist all field's uses (loads) and
  1206       // related field nodes (same base and offset).
  1207       add_field_uses_to_worklist(use->as_Field());
  1210   return new_edges;
  1213 // Put on worklist all related field nodes.
  1214 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
  1215   assert(field->is_oop(), "sanity");
  1216   int offset = field->offset();
  1217   add_uses_to_worklist(field);
  1218   // Loop over all bases of this field and push on worklist Field nodes
  1219   // with the same offset and base (since they may reference the same field).
  1220   for (BaseIterator i(field); i.has_next(); i.next()) {
  1221     PointsToNode* base = i.get();
  1222     add_fields_to_worklist(field, base);
  1223     // Check if the base was source object of arraycopy and go over arraycopy's
  1224     // destination objects since values stored to a field of source object are
  1225     // accessable by uses (loads) of fields of destination objects.
  1226     if (base->arraycopy_src()) {
  1227       for (UseIterator j(base); j.has_next(); j.next()) {
  1228         PointsToNode* arycp = j.get();
  1229         if (arycp->is_Arraycopy()) {
  1230           for (UseIterator k(arycp); k.has_next(); k.next()) {
  1231             PointsToNode* abase = k.get();
  1232             if (abase->arraycopy_dst() && abase != base) {
  1233               // Look for the same arracopy reference.
  1234               add_fields_to_worklist(field, abase);
  1243 // Put on worklist all related field nodes.
  1244 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
  1245   int offset = field->offset();
  1246   if (base->is_LocalVar()) {
  1247     for (UseIterator j(base); j.has_next(); j.next()) {
  1248       PointsToNode* f = j.get();
  1249       if (PointsToNode::is_base_use(f)) { // Field
  1250         f = PointsToNode::get_use_node(f);
  1251         if (f == field || !f->as_Field()->is_oop())
  1252           continue;
  1253         int offs = f->as_Field()->offset();
  1254         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
  1255           add_to_worklist(f);
  1259   } else {
  1260     assert(base->is_JavaObject(), "sanity");
  1261     if (// Skip phantom_object since it is only used to indicate that
  1262         // this field's content globally escapes.
  1263         (base != phantom_obj) &&
  1264         // NULL object node does not have fields.
  1265         (base != null_obj)) {
  1266       for (EdgeIterator i(base); i.has_next(); i.next()) {
  1267         PointsToNode* f = i.get();
  1268         // Skip arraycopy edge since store to destination object field
  1269         // does not update value in source object field.
  1270         if (f->is_Arraycopy()) {
  1271           assert(base->arraycopy_dst(), "sanity");
  1272           continue;
  1274         if (f == field || !f->as_Field()->is_oop())
  1275           continue;
  1276         int offs = f->as_Field()->offset();
  1277         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
  1278           add_to_worklist(f);
  1285 // Find fields which have unknown value.
  1286 int ConnectionGraph::find_field_value(FieldNode* field) {
  1287   // Escaped fields should have init value already.
  1288   assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
  1289   int new_edges = 0;
  1290   for (BaseIterator i(field); i.has_next(); i.next()) {
  1291     PointsToNode* base = i.get();
  1292     if (base->is_JavaObject()) {
  1293       // Skip Allocate's fields which will be processed later.
  1294       if (base->ideal_node()->is_Allocate())
  1295         return 0;
  1296       assert(base == null_obj, "only NULL ptr base expected here");
  1299   if (add_edge(field, phantom_obj)) {
  1300     // New edge was added
  1301     new_edges++;
  1302     add_field_uses_to_worklist(field);
  1304   return new_edges;
  1307 // Find fields initializing values for allocations.
  1308 int ConnectionGraph::find_init_values(JavaObjectNode* pta, PointsToNode* init_val, PhaseTransform* phase) {
  1309   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
  1310   int new_edges = 0;
  1311   Node* alloc = pta->ideal_node();
  1312   if (init_val == phantom_obj) {
  1313     // Do nothing for Allocate nodes since its fields values are "known".
  1314     if (alloc->is_Allocate())
  1315       return 0;
  1316     assert(alloc->as_CallStaticJava(), "sanity");
  1317 #ifdef ASSERT
  1318     if (alloc->as_CallStaticJava()->method() == NULL) {
  1319       const char* name = alloc->as_CallStaticJava()->_name;
  1320       assert(strncmp(name, "_multianewarray", 15) == 0, "sanity");
  1322 #endif
  1323     // Non-escaped allocation returned from Java or runtime call have
  1324     // unknown values in fields.
  1325     for (EdgeIterator i(pta); i.has_next(); i.next()) {
  1326       PointsToNode* ptn = i.get();
  1327       if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
  1328         if (add_edge(ptn, phantom_obj)) {
  1329           // New edge was added
  1330           new_edges++;
  1331           add_field_uses_to_worklist(ptn->as_Field());
  1335     return new_edges;
  1337   assert(init_val == null_obj, "sanity");
  1338   // Do nothing for Call nodes since its fields values are unknown.
  1339   if (!alloc->is_Allocate())
  1340     return 0;
  1342   InitializeNode* ini = alloc->as_Allocate()->initialization();
  1343   Compile* C = _compile;
  1344   bool visited_bottom_offset = false;
  1345   GrowableArray<int> offsets_worklist;
  1347   // Check if an oop field's initializing value is recorded and add
  1348   // a corresponding NULL if field's value if it is not recorded.
  1349   // Connection Graph does not record a default initialization by NULL
  1350   // captured by Initialize node.
  1351   //
  1352   for (EdgeIterator i(pta); i.has_next(); i.next()) {
  1353     PointsToNode* ptn = i.get(); // Field (AddP)
  1354     if (!ptn->is_Field() || !ptn->as_Field()->is_oop())
  1355       continue; // Not oop field
  1356     int offset = ptn->as_Field()->offset();
  1357     if (offset == Type::OffsetBot) {
  1358       if (!visited_bottom_offset) {
  1359         // OffsetBot is used to reference array's element,
  1360         // always add reference to NULL to all Field nodes since we don't
  1361         // known which element is referenced.
  1362         if (add_edge(ptn, null_obj)) {
  1363           // New edge was added
  1364           new_edges++;
  1365           add_field_uses_to_worklist(ptn->as_Field());
  1366           visited_bottom_offset = true;
  1369     } else {
  1370       // Check only oop fields.
  1371       const Type* adr_type = ptn->ideal_node()->as_AddP()->bottom_type();
  1372       if (adr_type->isa_rawptr()) {
  1373 #ifdef ASSERT
  1374         // Raw pointers are used for initializing stores so skip it
  1375         // since it should be recorded already
  1376         Node* base = get_addp_base(ptn->ideal_node());
  1377         assert(adr_type->isa_rawptr() && base->is_Proj() &&
  1378                (base->in(0) == alloc),"unexpected pointer type");
  1379 #endif
  1380         continue;
  1382       if (!offsets_worklist.contains(offset)) {
  1383         offsets_worklist.append(offset);
  1384         Node* value = NULL;
  1385         if (ini != NULL) {
  1386           BasicType ft = UseCompressedOops ? T_NARROWOOP : T_OBJECT;
  1387           Node* store = ini->find_captured_store(offset, type2aelembytes(ft), phase);
  1388           if (store != NULL && store->is_Store()) {
  1389             value = store->in(MemNode::ValueIn);
  1390           } else {
  1391             // There could be initializing stores which follow allocation.
  1392             // For example, a volatile field store is not collected
  1393             // by Initialize node.
  1394             //
  1395             // Need to check for dependent loads to separate such stores from
  1396             // stores which follow loads. For now, add initial value NULL so
  1397             // that compare pointers optimization works correctly.
  1400         if (value == NULL) {
  1401           // A field's initializing value was not recorded. Add NULL.
  1402           if (add_edge(ptn, null_obj)) {
  1403             // New edge was added
  1404             new_edges++;
  1405             add_field_uses_to_worklist(ptn->as_Field());
  1411   return new_edges;
  1414 // Adjust scalar_replaceable state after Connection Graph is built.
  1415 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj) {
  1416   // Search for non-escaping objects which are not scalar replaceable
  1417   // and mark them to propagate the state to referenced objects.
  1419   // 1. An object is not scalar replaceable if the field into which it is
  1420   // stored has unknown offset (stored into unknown element of an array).
  1421   //
  1422   for (UseIterator i(jobj); i.has_next(); i.next()) {
  1423     PointsToNode* use = i.get();
  1424     assert(!use->is_Arraycopy(), "sanity");
  1425     if (use->is_Field()) {
  1426       FieldNode* field = use->as_Field();
  1427       assert(field->is_oop() && field->scalar_replaceable() &&
  1428              field->fields_escape_state() == PointsToNode::NoEscape, "sanity");
  1429       if (field->offset() == Type::OffsetBot) {
  1430         jobj->set_scalar_replaceable(false);
  1431         return;
  1434     assert(use->is_Field() || use->is_LocalVar(), "sanity");
  1435     // 2. An object is not scalar replaceable if it is merged with other objects.
  1436     for (EdgeIterator j(use); j.has_next(); j.next()) {
  1437       PointsToNode* ptn = j.get();
  1438       if (ptn->is_JavaObject() && ptn != jobj) {
  1439         // Mark all objects.
  1440         jobj->set_scalar_replaceable(false);
  1441          ptn->set_scalar_replaceable(false);
  1444     if (!jobj->scalar_replaceable()) {
  1445       return;
  1449   for (EdgeIterator j(jobj); j.has_next(); j.next()) {
  1450     // Non-escaping object node should point only to field nodes.
  1451     FieldNode* field = j.get()->as_Field();
  1452     int offset = field->as_Field()->offset();
  1454     // 3. An object is not scalar replaceable if it has a field with unknown
  1455     // offset (array's element is accessed in loop).
  1456     if (offset == Type::OffsetBot) {
  1457       jobj->set_scalar_replaceable(false);
  1458       return;
  1460     // 4. Currently an object is not scalar replaceable if a LoadStore node
  1461     // access its field since the field value is unknown after it.
  1462     //
  1463     Node* n = field->ideal_node();
  1464     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  1465       if (n->fast_out(i)->is_LoadStore()) {
  1466         jobj->set_scalar_replaceable(false);
  1467         return;
  1471     // 5. Or the address may point to more then one object. This may produce
  1472     // the false positive result (set not scalar replaceable)
  1473     // since the flow-insensitive escape analysis can't separate
  1474     // the case when stores overwrite the field's value from the case
  1475     // when stores happened on different control branches.
  1476     //
  1477     // Note: it will disable scalar replacement in some cases:
  1478     //
  1479     //    Point p[] = new Point[1];
  1480     //    p[0] = new Point(); // Will be not scalar replaced
  1481     //
  1482     // but it will save us from incorrect optimizations in next cases:
  1483     //
  1484     //    Point p[] = new Point[1];
  1485     //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
  1486     //
  1487     if (field->base_count() > 1) {
  1488       for (BaseIterator i(field); i.has_next(); i.next()) {
  1489         PointsToNode* base = i.get();
  1490         // Don't take into account LocalVar nodes which
  1491         // may point to only one object which should be also
  1492         // this field's base by now.
  1493         if (base->is_JavaObject() && base != jobj) {
  1494           // Mark all bases.
  1495           jobj->set_scalar_replaceable(false);
  1496           base->set_scalar_replaceable(false);
  1503 #ifdef ASSERT
  1504 void ConnectionGraph::verify_connection_graph(
  1505                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
  1506                          GrowableArray<JavaObjectNode*>& non_escaped_worklist,
  1507                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
  1508                          GrowableArray<Node*>& addp_worklist) {
  1509   // Verify that graph is complete - no new edges could be added.
  1510   int java_objects_length = java_objects_worklist.length();
  1511   int non_escaped_length  = non_escaped_worklist.length();
  1512   int new_edges = 0;
  1513   for (int next = 0; next < java_objects_length; ++next) {
  1514     JavaObjectNode* ptn = java_objects_worklist.at(next);
  1515     new_edges += add_java_object_edges(ptn, true);
  1517   assert(new_edges == 0, "graph was not complete");
  1518   // Verify that escape state is final.
  1519   int length = non_escaped_worklist.length();
  1520   find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist);
  1521   assert((non_escaped_length == non_escaped_worklist.length()) &&
  1522          (non_escaped_length == length) &&
  1523          (_worklist.length() == 0), "escape state was not final");
  1525   // Verify fields information.
  1526   int addp_length = addp_worklist.length();
  1527   for (int next = 0; next < addp_length; ++next ) {
  1528     Node* n = addp_worklist.at(next);
  1529     FieldNode* field = ptnode_adr(n->_idx)->as_Field();
  1530     if (field->is_oop()) {
  1531       // Verify that field has all bases
  1532       Node* base = get_addp_base(n);
  1533       PointsToNode* ptn = ptnode_adr(base->_idx);
  1534       if (ptn->is_JavaObject()) {
  1535         assert(field->has_base(ptn->as_JavaObject()), "sanity");
  1536       } else {
  1537         assert(ptn->is_LocalVar(), "sanity");
  1538         for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1539           PointsToNode* e = i.get();
  1540           if (e->is_JavaObject()) {
  1541             assert(field->has_base(e->as_JavaObject()), "sanity");
  1545       // Verify that all fields have initializing values.
  1546       if (field->edge_count() == 0) {
  1547         field->dump();
  1548         assert(field->edge_count() > 0, "sanity");
  1553 #endif
  1555 // Optimize ideal graph.
  1556 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
  1557                                            GrowableArray<Node*>& storestore_worklist) {
  1558   Compile* C = _compile;
  1559   PhaseIterGVN* igvn = _igvn;
  1560   if (EliminateLocks) {
  1561     // Mark locks before changing ideal graph.
  1562     int cnt = C->macro_count();
  1563     for( int i=0; i < cnt; i++ ) {
  1564       Node *n = C->macro_node(i);
  1565       if (n->is_AbstractLock()) { // Lock and Unlock nodes
  1566         AbstractLockNode* alock = n->as_AbstractLock();
  1567         if (!alock->is_non_esc_obj()) {
  1568           if (not_global_escape(alock->obj_node())) {
  1569             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
  1570             // The lock could be marked eliminated by lock coarsening
  1571             // code during first IGVN before EA. Replace coarsened flag
  1572             // to eliminate all associated locks/unlocks.
  1573             alock->set_non_esc_obj();
  1580   if (OptimizePtrCompare) {
  1581     // Add ConI(#CC_GT) and ConI(#CC_EQ).
  1582     _pcmp_neq = igvn->makecon(TypeInt::CC_GT);
  1583     _pcmp_eq = igvn->makecon(TypeInt::CC_EQ);
  1584     // Optimize objects compare.
  1585     while (ptr_cmp_worklist.length() != 0) {
  1586       Node *n = ptr_cmp_worklist.pop();
  1587       Node *res = optimize_ptr_compare(n);
  1588       if (res != NULL) {
  1589 #ifndef PRODUCT
  1590         if (PrintOptimizePtrCompare) {
  1591           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"));
  1592           if (Verbose) {
  1593             n->dump(1);
  1596 #endif
  1597         igvn->replace_node(n, res);
  1600     // cleanup
  1601     if (_pcmp_neq->outcnt() == 0)
  1602       igvn->hash_delete(_pcmp_neq);
  1603     if (_pcmp_eq->outcnt()  == 0)
  1604       igvn->hash_delete(_pcmp_eq);
  1607   // For MemBarStoreStore nodes added in library_call.cpp, check
  1608   // escape status of associated AllocateNode and optimize out
  1609   // MemBarStoreStore node if the allocated object never escapes.
  1610   while (storestore_worklist.length() != 0) {
  1611     Node *n = storestore_worklist.pop();
  1612     MemBarStoreStoreNode *storestore = n ->as_MemBarStoreStore();
  1613     Node *alloc = storestore->in(MemBarNode::Precedent)->in(0);
  1614     assert (alloc->is_Allocate(), "storestore should point to AllocateNode");
  1615     if (not_global_escape(alloc)) {
  1616       MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
  1617       mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
  1618       mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
  1619       igvn->register_new_node_with_optimizer(mb);
  1620       igvn->replace_node(storestore, mb);
  1625 // Optimize objects compare.
  1626 Node* ConnectionGraph::optimize_ptr_compare(Node* n) {
  1627   assert(OptimizePtrCompare, "sanity");
  1628   PointsToNode* ptn1 = ptnode_adr(n->in(1)->_idx);
  1629   PointsToNode* ptn2 = ptnode_adr(n->in(2)->_idx);
  1630   JavaObjectNode* jobj1 = unique_java_object(n->in(1));
  1631   JavaObjectNode* jobj2 = unique_java_object(n->in(2));
  1632   assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
  1633   assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
  1635   // Check simple cases first.
  1636   if (jobj1 != NULL) {
  1637     if (jobj1->escape_state() == PointsToNode::NoEscape) {
  1638       if (jobj1 == jobj2) {
  1639         // Comparing the same not escaping object.
  1640         return _pcmp_eq;
  1642       Node* obj = jobj1->ideal_node();
  1643       // Comparing not escaping allocation.
  1644       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
  1645           !ptn2->points_to(jobj1)) {
  1646         return _pcmp_neq; // This includes nullness check.
  1650   if (jobj2 != NULL) {
  1651     if (jobj2->escape_state() == PointsToNode::NoEscape) {
  1652       Node* obj = jobj2->ideal_node();
  1653       // Comparing not escaping allocation.
  1654       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
  1655           !ptn1->points_to(jobj2)) {
  1656         return _pcmp_neq; // This includes nullness check.
  1660   if (jobj1 != NULL && jobj1 != phantom_obj &&
  1661       jobj2 != NULL && jobj2 != phantom_obj &&
  1662       jobj1->ideal_node()->is_Con() &&
  1663       jobj2->ideal_node()->is_Con()) {
  1664     // Klass or String constants compare. Need to be careful with
  1665     // compressed pointers - compare types of ConN and ConP instead of nodes.
  1666     const Type* t1 = jobj1->ideal_node()->bottom_type()->make_ptr();
  1667     const Type* t2 = jobj2->ideal_node()->bottom_type()->make_ptr();
  1668     assert(t1 != NULL && t2 != NULL, "sanity");
  1669     if (t1->make_ptr() == t2->make_ptr()) {
  1670       return _pcmp_eq;
  1671     } else {
  1672       return _pcmp_neq;
  1675   if (ptn1->meet(ptn2)) {
  1676     return NULL; // Sets are not disjoint
  1679   // Sets are disjoint.
  1680   bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
  1681   bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
  1682   bool set1_has_null_ptr    = ptn1->points_to(null_obj);
  1683   bool set2_has_null_ptr    = ptn2->points_to(null_obj);
  1684   if (set1_has_unknown_ptr && set2_has_null_ptr ||
  1685       set2_has_unknown_ptr && set1_has_null_ptr) {
  1686     // Check nullness of unknown object.
  1687     return NULL;
  1690   // Disjointness by itself is not sufficient since
  1691   // alias analysis is not complete for escaped objects.
  1692   // Disjoint sets are definitely unrelated only when
  1693   // at least one set has only not escaping allocations.
  1694   if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
  1695     if (ptn1->non_escaping_allocation()) {
  1696       return _pcmp_neq;
  1699   if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
  1700     if (ptn2->non_escaping_allocation()) {
  1701       return _pcmp_neq;
  1704   return NULL;
  1707 // Connection Graph constuction functions.
  1709 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
  1710   PointsToNode* ptadr = _nodes.at(n->_idx);
  1711   if (ptadr != NULL) {
  1712     assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
  1713     return;
  1715   Compile* C = _compile;
  1716   ptadr = new (C->comp_arena()) LocalVarNode(C, n, es);
  1717   _nodes.at_put(n->_idx, ptadr);
  1720 void ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
  1721   PointsToNode* ptadr = _nodes.at(n->_idx);
  1722   if (ptadr != NULL) {
  1723     assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
  1724     return;
  1726   Compile* C = _compile;
  1727   ptadr = new (C->comp_arena()) JavaObjectNode(C, n, es);
  1728   _nodes.at_put(n->_idx, ptadr);
  1731 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
  1732   PointsToNode* ptadr = _nodes.at(n->_idx);
  1733   if (ptadr != NULL) {
  1734     assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
  1735     return;
  1737   Compile* C = _compile;
  1738   bool is_oop = is_oop_field(n, offset);
  1739   FieldNode* field = new (C->comp_arena()) FieldNode(C, n, es, offset, is_oop);
  1740   _nodes.at_put(n->_idx, field);
  1743 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
  1744                                     PointsToNode* src, PointsToNode* dst) {
  1745   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
  1746   assert((src != null_obj) && (dst != null_obj), "not for ConP NULL");
  1747   PointsToNode* ptadr = _nodes.at(n->_idx);
  1748   if (ptadr != NULL) {
  1749     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
  1750     return;
  1752   Compile* C = _compile;
  1753   ptadr = new (C->comp_arena()) ArraycopyNode(C, n, es);
  1754   _nodes.at_put(n->_idx, ptadr);
  1755   // Add edge from arraycopy node to source object.
  1756   (void)add_edge(ptadr, src);
  1757   src->set_arraycopy_src();
  1758   // Add edge from destination object to arraycopy node.
  1759   (void)add_edge(dst, ptadr);
  1760   dst->set_arraycopy_dst();
  1763 bool ConnectionGraph::is_oop_field(Node* n, int offset) {
  1764   const Type* adr_type = n->as_AddP()->bottom_type();
  1765   BasicType bt = T_INT;
  1766   if (offset == Type::OffsetBot) {
  1767     // Check only oop fields.
  1768     if (!adr_type->isa_aryptr() ||
  1769         (adr_type->isa_aryptr()->klass() == NULL) ||
  1770          adr_type->isa_aryptr()->klass()->is_obj_array_klass()) {
  1771       // OffsetBot is used to reference array's element. Ignore first AddP.
  1772       if (find_second_addp(n, n->in(AddPNode::Base)) == NULL) {
  1773         bt = T_OBJECT;
  1776   } else if (offset != oopDesc::klass_offset_in_bytes()) {
  1777     if (adr_type->isa_instptr()) {
  1778       ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
  1779       if (field != NULL) {
  1780         bt = field->layout_type();
  1781       } else {
  1782         // Ignore non field load (for example, klass load)
  1784     } else if (adr_type->isa_aryptr()) {
  1785       if (offset == arrayOopDesc::length_offset_in_bytes()) {
  1786         // Ignore array length load.
  1787       } else if (find_second_addp(n, n->in(AddPNode::Base)) != NULL) {
  1788         // Ignore first AddP.
  1789       } else {
  1790         const Type* elemtype = adr_type->isa_aryptr()->elem();
  1791         bt = elemtype->array_element_basic_type();
  1793     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
  1794       // Allocation initialization, ThreadLocal field access, unsafe access
  1795       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  1796         int opcode = n->fast_out(i)->Opcode();
  1797         if (opcode == Op_StoreP || opcode == Op_LoadP ||
  1798             opcode == Op_StoreN || opcode == Op_LoadN) {
  1799           bt = T_OBJECT;
  1804   return (bt == T_OBJECT || bt == T_NARROWOOP || bt == T_ARRAY);
  1807 // Returns unique pointed java object or NULL.
  1808 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) {
  1809   assert(!_collecting, "should not call when contructed graph");
  1810   // If the node was created after the escape computation we can't answer.
  1811   uint idx = n->_idx;
  1812   if (idx >= nodes_size()) {
  1813     return NULL;
  1815   PointsToNode* ptn = ptnode_adr(idx);
  1816   if (ptn->is_JavaObject()) {
  1817     return ptn->as_JavaObject();
  1819   assert(ptn->is_LocalVar(), "sanity");
  1820   // Check all java objects it points to.
  1821   JavaObjectNode* jobj = NULL;
  1822   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1823     PointsToNode* e = i.get();
  1824     if (e->is_JavaObject()) {
  1825       if (jobj == NULL) {
  1826         jobj = e->as_JavaObject();
  1827       } else if (jobj != e) {
  1828         return NULL;
  1832   return jobj;
  1835 // Return true if this node points only to non-escaping allocations.
  1836 bool PointsToNode::non_escaping_allocation() {
  1837   if (is_JavaObject()) {
  1838     Node* n = ideal_node();
  1839     if (n->is_Allocate() || n->is_CallStaticJava()) {
  1840       return (escape_state() == PointsToNode::NoEscape);
  1841     } else {
  1842       return false;
  1845   assert(is_LocalVar(), "sanity");
  1846   // Check all java objects it points to.
  1847   for (EdgeIterator i(this); i.has_next(); i.next()) {
  1848     PointsToNode* e = i.get();
  1849     if (e->is_JavaObject()) {
  1850       Node* n = e->ideal_node();
  1851       if ((e->escape_state() != PointsToNode::NoEscape) ||
  1852           !(n->is_Allocate() || n->is_CallStaticJava())) {
  1853         return false;
  1857   return true;
  1860 // Return true if we know the node does not escape globally.
  1861 bool ConnectionGraph::not_global_escape(Node *n) {
  1862   assert(!_collecting, "should not call during graph construction");
  1863   // If the node was created after the escape computation we can't answer.
  1864   uint idx = n->_idx;
  1865   if (idx >= nodes_size()) {
  1866     return false;
  1868   PointsToNode* ptn = ptnode_adr(idx);
  1869   PointsToNode::EscapeState es = ptn->escape_state();
  1870   // If we have already computed a value, return it.
  1871   if (es >= PointsToNode::GlobalEscape)
  1872     return false;
  1873   if (ptn->is_JavaObject()) {
  1874     return true; // (es < PointsToNode::GlobalEscape);
  1876   assert(ptn->is_LocalVar(), "sanity");
  1877   // Check all java objects it points to.
  1878   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
  1879     if (i.get()->escape_state() >= PointsToNode::GlobalEscape)
  1880       return false;
  1882   return true;
  1886 // Helper functions
  1888 // Return true if this node points to specified node or nodes it points to.
  1889 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
  1890   if (is_JavaObject()) {
  1891     return (this == ptn);
  1893   assert(is_LocalVar(), "sanity");
  1894   for (EdgeIterator i(this); i.has_next(); i.next()) {
  1895     if (i.get() == ptn)
  1896       return true;
  1898   return false;
  1901 // Return true if one node points to an other.
  1902 bool PointsToNode::meet(PointsToNode* ptn) {
  1903   if (this == ptn) {
  1904     return true;
  1905   } else if (ptn->is_JavaObject()) {
  1906     return this->points_to(ptn->as_JavaObject());
  1907   } else if (this->is_JavaObject()) {
  1908     return ptn->points_to(this->as_JavaObject());
  1910   assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
  1911   int ptn_count =  ptn->edge_count();
  1912   for (EdgeIterator i(this); i.has_next(); i.next()) {
  1913     PointsToNode* this_e = i.get();
  1914     for (int j = 0; j < ptn_count; j++) {
  1915       if (this_e == ptn->edge(j))
  1916         return true;
  1919   return false;
  1922 #ifdef ASSERT
  1923 // Return true if bases point to this java object.
  1924 bool FieldNode::has_base(JavaObjectNode* jobj) const {
  1925   for (BaseIterator i(this); i.has_next(); i.next()) {
  1926     if (i.get() == jobj)
  1927       return true;
  1929   return false;
  1931 #endif
  1933 int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
  1934   const Type *adr_type = phase->type(adr);
  1935   if (adr->is_AddP() && adr_type->isa_oopptr() == NULL &&
  1936       adr->in(AddPNode::Address)->is_Proj() &&
  1937       adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
  1938     // We are computing a raw address for a store captured by an Initialize
  1939     // compute an appropriate address type. AddP cases #3 and #5 (see below).
  1940     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
  1941     assert(offs != Type::OffsetBot ||
  1942            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
  1943            "offset must be a constant or it is initialization of array");
  1944     return offs;
  1946   const TypePtr *t_ptr = adr_type->isa_ptr();
  1947   assert(t_ptr != NULL, "must be a pointer type");
  1948   return t_ptr->offset();
  1951 Node* ConnectionGraph::get_addp_base(Node *addp) {
  1952   assert(addp->is_AddP(), "must be AddP");
  1953   //
  1954   // AddP cases for Base and Address inputs:
  1955   // case #1. Direct object's field reference:
  1956   //     Allocate
  1957   //       |
  1958   //     Proj #5 ( oop result )
  1959   //       |
  1960   //     CheckCastPP (cast to instance type)
  1961   //      | |
  1962   //     AddP  ( base == address )
  1963   //
  1964   // case #2. Indirect object's field reference:
  1965   //      Phi
  1966   //       |
  1967   //     CastPP (cast to instance type)
  1968   //      | |
  1969   //     AddP  ( base == address )
  1970   //
  1971   // case #3. Raw object's field reference for Initialize node:
  1972   //      Allocate
  1973   //        |
  1974   //      Proj #5 ( oop result )
  1975   //  top   |
  1976   //     \  |
  1977   //     AddP  ( base == top )
  1978   //
  1979   // case #4. Array's element reference:
  1980   //   {CheckCastPP | CastPP}
  1981   //     |  | |
  1982   //     |  AddP ( array's element offset )
  1983   //     |  |
  1984   //     AddP ( array's offset )
  1985   //
  1986   // case #5. Raw object's field reference for arraycopy stub call:
  1987   //          The inline_native_clone() case when the arraycopy stub is called
  1988   //          after the allocation before Initialize and CheckCastPP nodes.
  1989   //      Allocate
  1990   //        |
  1991   //      Proj #5 ( oop result )
  1992   //       | |
  1993   //       AddP  ( base == address )
  1994   //
  1995   // case #6. Constant Pool, ThreadLocal, CastX2P or
  1996   //          Raw object's field reference:
  1997   //      {ConP, ThreadLocal, CastX2P, raw Load}
  1998   //  top   |
  1999   //     \  |
  2000   //     AddP  ( base == top )
  2001   //
  2002   // case #7. Klass's field reference.
  2003   //      LoadKlass
  2004   //       | |
  2005   //       AddP  ( base == address )
  2006   //
  2007   // case #8. narrow Klass's field reference.
  2008   //      LoadNKlass
  2009   //       |
  2010   //      DecodeN
  2011   //       | |
  2012   //       AddP  ( base == address )
  2013   //
  2014   Node *base = addp->in(AddPNode::Base);
  2015   if (base->uncast()->is_top()) { // The AddP case #3 and #6.
  2016     base = addp->in(AddPNode::Address);
  2017     while (base->is_AddP()) {
  2018       // Case #6 (unsafe access) may have several chained AddP nodes.
  2019       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
  2020       base = base->in(AddPNode::Address);
  2022     Node* uncast_base = base->uncast();
  2023     int opcode = uncast_base->Opcode();
  2024     assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
  2025            opcode == Op_CastX2P || uncast_base->is_DecodeN() ||
  2026            (uncast_base->is_Mem() && uncast_base->bottom_type() == TypeRawPtr::NOTNULL) ||
  2027            (uncast_base->is_Proj() && uncast_base->in(0)->is_Allocate()), "sanity");
  2029   return base;
  2032 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
  2033   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
  2034   Node* addp2 = addp->raw_out(0);
  2035   if (addp->outcnt() == 1 && addp2->is_AddP() &&
  2036       addp2->in(AddPNode::Base) == n &&
  2037       addp2->in(AddPNode::Address) == addp) {
  2038     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
  2039     //
  2040     // Find array's offset to push it on worklist first and
  2041     // as result process an array's element offset first (pushed second)
  2042     // to avoid CastPP for the array's offset.
  2043     // Otherwise the inserted CastPP (LocalVar) will point to what
  2044     // the AddP (Field) points to. Which would be wrong since
  2045     // the algorithm expects the CastPP has the same point as
  2046     // as AddP's base CheckCastPP (LocalVar).
  2047     //
  2048     //    ArrayAllocation
  2049     //     |
  2050     //    CheckCastPP
  2051     //     |
  2052     //    memProj (from ArrayAllocation CheckCastPP)
  2053     //     |  ||
  2054     //     |  ||   Int (element index)
  2055     //     |  ||    |   ConI (log(element size))
  2056     //     |  ||    |   /
  2057     //     |  ||   LShift
  2058     //     |  ||  /
  2059     //     |  AddP (array's element offset)
  2060     //     |  |
  2061     //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
  2062     //     | / /
  2063     //     AddP (array's offset)
  2064     //      |
  2065     //     Load/Store (memory operation on array's element)
  2066     //
  2067     return addp2;
  2069   return NULL;
  2072 //
  2073 // Adjust the type and inputs of an AddP which computes the
  2074 // address of a field of an instance
  2075 //
  2076 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
  2077   PhaseGVN* igvn = _igvn;
  2078   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
  2079   assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
  2080   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
  2081   if (t == NULL) {
  2082     // We are computing a raw address for a store captured by an Initialize
  2083     // compute an appropriate address type (cases #3 and #5).
  2084     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
  2085     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
  2086     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
  2087     assert(offs != Type::OffsetBot, "offset must be a constant");
  2088     t = base_t->add_offset(offs)->is_oopptr();
  2090   int inst_id =  base_t->instance_id();
  2091   assert(!t->is_known_instance() || t->instance_id() == inst_id,
  2092                              "old type must be non-instance or match new type");
  2094   // The type 't' could be subclass of 'base_t'.
  2095   // As result t->offset() could be large then base_t's size and it will
  2096   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
  2097   // constructor verifies correctness of the offset.
  2098   //
  2099   // It could happened on subclass's branch (from the type profiling
  2100   // inlining) which was not eliminated during parsing since the exactness
  2101   // of the allocation type was not propagated to the subclass type check.
  2102   //
  2103   // Or the type 't' could be not related to 'base_t' at all.
  2104   // It could happened when CHA type is different from MDO type on a dead path
  2105   // (for example, from instanceof check) which is not collapsed during parsing.
  2106   //
  2107   // Do nothing for such AddP node and don't process its users since
  2108   // this code branch will go away.
  2109   //
  2110   if (!t->is_known_instance() &&
  2111       !base_t->klass()->is_subtype_of(t->klass())) {
  2112      return false; // bail out
  2114   const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
  2115   // Do NOT remove the next line: ensure a new alias index is allocated
  2116   // for the instance type. Note: C++ will not remove it since the call
  2117   // has side effect.
  2118   int alias_idx = _compile->get_alias_index(tinst);
  2119   igvn->set_type(addp, tinst);
  2120   // record the allocation in the node map
  2121   set_map(addp, get_map(base->_idx));
  2122   // Set addp's Base and Address to 'base'.
  2123   Node *abase = addp->in(AddPNode::Base);
  2124   Node *adr   = addp->in(AddPNode::Address);
  2125   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
  2126       adr->in(0)->_idx == (uint)inst_id) {
  2127     // Skip AddP cases #3 and #5.
  2128   } else {
  2129     assert(!abase->is_top(), "sanity"); // AddP case #3
  2130     if (abase != base) {
  2131       igvn->hash_delete(addp);
  2132       addp->set_req(AddPNode::Base, base);
  2133       if (abase == adr) {
  2134         addp->set_req(AddPNode::Address, base);
  2135       } else {
  2136         // AddP case #4 (adr is array's element offset AddP node)
  2137 #ifdef ASSERT
  2138         const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
  2139         assert(adr->is_AddP() && atype != NULL &&
  2140                atype->instance_id() == inst_id, "array's element offset should be processed first");
  2141 #endif
  2143       igvn->hash_insert(addp);
  2146   // Put on IGVN worklist since at least addp's type was changed above.
  2147   record_for_optimizer(addp);
  2148   return true;
  2151 //
  2152 // Create a new version of orig_phi if necessary. Returns either the newly
  2153 // created phi or an existing phi.  Sets create_new to indicate whether a new
  2154 // phi was created.  Cache the last newly created phi in the node map.
  2155 //
  2156 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, bool &new_created) {
  2157   Compile *C = _compile;
  2158   PhaseGVN* igvn = _igvn;
  2159   new_created = false;
  2160   int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
  2161   // nothing to do if orig_phi is bottom memory or matches alias_idx
  2162   if (phi_alias_idx == alias_idx) {
  2163     return orig_phi;
  2165   // Have we recently created a Phi for this alias index?
  2166   PhiNode *result = get_map_phi(orig_phi->_idx);
  2167   if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
  2168     return result;
  2170   // Previous check may fail when the same wide memory Phi was split into Phis
  2171   // for different memory slices. Search all Phis for this region.
  2172   if (result != NULL) {
  2173     Node* region = orig_phi->in(0);
  2174     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
  2175       Node* phi = region->fast_out(i);
  2176       if (phi->is_Phi() &&
  2177           C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
  2178         assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
  2179         return phi->as_Phi();
  2183   if ((int)C->unique() + 2*NodeLimitFudgeFactor > MaxNodeLimit) {
  2184     if (C->do_escape_analysis() == true && !C->failing()) {
  2185       // Retry compilation without escape analysis.
  2186       // If this is the first failure, the sentinel string will "stick"
  2187       // to the Compile object, and the C2Compiler will see it and retry.
  2188       C->record_failure(C2Compiler::retry_no_escape_analysis());
  2190     return NULL;
  2192   orig_phi_worklist.append_if_missing(orig_phi);
  2193   const TypePtr *atype = C->get_adr_type(alias_idx);
  2194   result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
  2195   C->copy_node_notes_to(result, orig_phi);
  2196   igvn->set_type(result, result->bottom_type());
  2197   record_for_optimizer(result);
  2198   set_map(orig_phi, result);
  2199   new_created = true;
  2200   return result;
  2203 //
  2204 // Return a new version of Memory Phi "orig_phi" with the inputs having the
  2205 // specified alias index.
  2206 //
  2207 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist) {
  2208   assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
  2209   Compile *C = _compile;
  2210   PhaseGVN* igvn = _igvn;
  2211   bool new_phi_created;
  2212   PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
  2213   if (!new_phi_created) {
  2214     return result;
  2216   GrowableArray<PhiNode *>  phi_list;
  2217   GrowableArray<uint>  cur_input;
  2218   PhiNode *phi = orig_phi;
  2219   uint idx = 1;
  2220   bool finished = false;
  2221   while(!finished) {
  2222     while (idx < phi->req()) {
  2223       Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist);
  2224       if (mem != NULL && mem->is_Phi()) {
  2225         PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
  2226         if (new_phi_created) {
  2227           // found an phi for which we created a new split, push current one on worklist and begin
  2228           // processing new one
  2229           phi_list.push(phi);
  2230           cur_input.push(idx);
  2231           phi = mem->as_Phi();
  2232           result = newphi;
  2233           idx = 1;
  2234           continue;
  2235         } else {
  2236           mem = newphi;
  2239       if (C->failing()) {
  2240         return NULL;
  2242       result->set_req(idx++, mem);
  2244 #ifdef ASSERT
  2245     // verify that the new Phi has an input for each input of the original
  2246     assert( phi->req() == result->req(), "must have same number of inputs.");
  2247     assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
  2248 #endif
  2249     // Check if all new phi's inputs have specified alias index.
  2250     // Otherwise use old phi.
  2251     for (uint i = 1; i < phi->req(); i++) {
  2252       Node* in = result->in(i);
  2253       assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
  2255     // we have finished processing a Phi, see if there are any more to do
  2256     finished = (phi_list.length() == 0 );
  2257     if (!finished) {
  2258       phi = phi_list.pop();
  2259       idx = cur_input.pop();
  2260       PhiNode *prev_result = get_map_phi(phi->_idx);
  2261       prev_result->set_req(idx++, result);
  2262       result = prev_result;
  2265   return result;
  2268 //
  2269 // The next methods are derived from methods in MemNode.
  2270 //
  2271 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
  2272   Node *mem = mmem;
  2273   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
  2274   // means an array I have not precisely typed yet.  Do not do any
  2275   // alias stuff with it any time soon.
  2276   if (toop->base() != Type::AnyPtr &&
  2277       !(toop->klass() != NULL &&
  2278         toop->klass()->is_java_lang_Object() &&
  2279         toop->offset() == Type::OffsetBot)) {
  2280     mem = mmem->memory_at(alias_idx);
  2281     // Update input if it is progress over what we have now
  2283   return mem;
  2286 //
  2287 // Move memory users to their memory slices.
  2288 //
  2289 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis) {
  2290   Compile* C = _compile;
  2291   PhaseGVN* igvn = _igvn;
  2292   const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
  2293   assert(tp != NULL, "ptr type");
  2294   int alias_idx = C->get_alias_index(tp);
  2295   int general_idx = C->get_general_index(alias_idx);
  2297   // Move users first
  2298   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2299     Node* use = n->fast_out(i);
  2300     if (use->is_MergeMem()) {
  2301       MergeMemNode* mmem = use->as_MergeMem();
  2302       assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
  2303       if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
  2304         continue; // Nothing to do
  2306       // Replace previous general reference to mem node.
  2307       uint orig_uniq = C->unique();
  2308       Node* m = find_inst_mem(n, general_idx, orig_phis);
  2309       assert(orig_uniq == C->unique(), "no new nodes");
  2310       mmem->set_memory_at(general_idx, m);
  2311       --imax;
  2312       --i;
  2313     } else if (use->is_MemBar()) {
  2314       assert(!use->is_Initialize(), "initializing stores should not be moved");
  2315       if (use->req() > MemBarNode::Precedent &&
  2316           use->in(MemBarNode::Precedent) == n) {
  2317         // Don't move related membars.
  2318         record_for_optimizer(use);
  2319         continue;
  2321       tp = use->as_MemBar()->adr_type()->isa_ptr();
  2322       if (tp != NULL && C->get_alias_index(tp) == alias_idx ||
  2323           alias_idx == general_idx) {
  2324         continue; // Nothing to do
  2326       // Move to general memory slice.
  2327       uint orig_uniq = C->unique();
  2328       Node* m = find_inst_mem(n, general_idx, orig_phis);
  2329       assert(orig_uniq == C->unique(), "no new nodes");
  2330       igvn->hash_delete(use);
  2331       imax -= use->replace_edge(n, m);
  2332       igvn->hash_insert(use);
  2333       record_for_optimizer(use);
  2334       --i;
  2335 #ifdef ASSERT
  2336     } else if (use->is_Mem()) {
  2337       if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
  2338         // Don't move related cardmark.
  2339         continue;
  2341       // Memory nodes should have new memory input.
  2342       tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
  2343       assert(tp != NULL, "ptr type");
  2344       int idx = C->get_alias_index(tp);
  2345       assert(get_map(use->_idx) != NULL || idx == alias_idx,
  2346              "Following memory nodes should have new memory input or be on the same memory slice");
  2347     } else if (use->is_Phi()) {
  2348       // Phi nodes should be split and moved already.
  2349       tp = use->as_Phi()->adr_type()->isa_ptr();
  2350       assert(tp != NULL, "ptr type");
  2351       int idx = C->get_alias_index(tp);
  2352       assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
  2353     } else {
  2354       use->dump();
  2355       assert(false, "should not be here");
  2356 #endif
  2361 //
  2362 // Search memory chain of "mem" to find a MemNode whose address
  2363 // is the specified alias index.
  2364 //
  2365 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis) {
  2366   if (orig_mem == NULL)
  2367     return orig_mem;
  2368   Compile* C = _compile;
  2369   PhaseGVN* igvn = _igvn;
  2370   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
  2371   bool is_instance = (toop != NULL) && toop->is_known_instance();
  2372   Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
  2373   Node *prev = NULL;
  2374   Node *result = orig_mem;
  2375   while (prev != result) {
  2376     prev = result;
  2377     if (result == start_mem)
  2378       break;  // hit one of our sentinels
  2379     if (result->is_Mem()) {
  2380       const Type *at = igvn->type(result->in(MemNode::Address));
  2381       if (at == Type::TOP)
  2382         break; // Dead
  2383       assert (at->isa_ptr() != NULL, "pointer type required.");
  2384       int idx = C->get_alias_index(at->is_ptr());
  2385       if (idx == alias_idx)
  2386         break; // Found
  2387       if (!is_instance && (at->isa_oopptr() == NULL ||
  2388                            !at->is_oopptr()->is_known_instance())) {
  2389         break; // Do not skip store to general memory slice.
  2391       result = result->in(MemNode::Memory);
  2393     if (!is_instance)
  2394       continue;  // don't search further for non-instance types
  2395     // skip over a call which does not affect this memory slice
  2396     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
  2397       Node *proj_in = result->in(0);
  2398       if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
  2399         break;  // hit one of our sentinels
  2400       } else if (proj_in->is_Call()) {
  2401         CallNode *call = proj_in->as_Call();
  2402         if (!call->may_modify(toop, igvn)) {
  2403           result = call->in(TypeFunc::Memory);
  2405       } else if (proj_in->is_Initialize()) {
  2406         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
  2407         // Stop if this is the initialization for the object instance which
  2408         // which contains this memory slice, otherwise skip over it.
  2409         if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
  2410           result = proj_in->in(TypeFunc::Memory);
  2412       } else if (proj_in->is_MemBar()) {
  2413         result = proj_in->in(TypeFunc::Memory);
  2415     } else if (result->is_MergeMem()) {
  2416       MergeMemNode *mmem = result->as_MergeMem();
  2417       result = step_through_mergemem(mmem, alias_idx, toop);
  2418       if (result == mmem->base_memory()) {
  2419         // Didn't find instance memory, search through general slice recursively.
  2420         result = mmem->memory_at(C->get_general_index(alias_idx));
  2421         result = find_inst_mem(result, alias_idx, orig_phis);
  2422         if (C->failing()) {
  2423           return NULL;
  2425         mmem->set_memory_at(alias_idx, result);
  2427     } else if (result->is_Phi() &&
  2428                C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
  2429       Node *un = result->as_Phi()->unique_input(igvn);
  2430       if (un != NULL) {
  2431         orig_phis.append_if_missing(result->as_Phi());
  2432         result = un;
  2433       } else {
  2434         break;
  2436     } else if (result->is_ClearArray()) {
  2437       if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
  2438         // Can not bypass initialization of the instance
  2439         // we are looking for.
  2440         break;
  2442       // Otherwise skip it (the call updated 'result' value).
  2443     } else if (result->Opcode() == Op_SCMemProj) {
  2444       assert(result->in(0)->is_LoadStore(), "sanity");
  2445       const Type *at = igvn->type(result->in(0)->in(MemNode::Address));
  2446       if (at != Type::TOP) {
  2447         assert (at->isa_ptr() != NULL, "pointer type required.");
  2448         int idx = C->get_alias_index(at->is_ptr());
  2449         assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
  2450         break;
  2452       result = result->in(0)->in(MemNode::Memory);
  2455   if (result->is_Phi()) {
  2456     PhiNode *mphi = result->as_Phi();
  2457     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
  2458     const TypePtr *t = mphi->adr_type();
  2459     if (!is_instance) {
  2460       // Push all non-instance Phis on the orig_phis worklist to update inputs
  2461       // during Phase 4 if needed.
  2462       orig_phis.append_if_missing(mphi);
  2463     } else if (C->get_alias_index(t) != alias_idx) {
  2464       // Create a new Phi with the specified alias index type.
  2465       result = split_memory_phi(mphi, alias_idx, orig_phis);
  2468   // the result is either MemNode, PhiNode, InitializeNode.
  2469   return result;
  2472 //
  2473 //  Convert the types of unescaped object to instance types where possible,
  2474 //  propagate the new type information through the graph, and update memory
  2475 //  edges and MergeMem inputs to reflect the new type.
  2476 //
  2477 //  We start with allocations (and calls which may be allocations)  on alloc_worklist.
  2478 //  The processing is done in 4 phases:
  2479 //
  2480 //  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
  2481 //            types for the CheckCastPP for allocations where possible.
  2482 //            Propagate the the new types through users as follows:
  2483 //               casts and Phi:  push users on alloc_worklist
  2484 //               AddP:  cast Base and Address inputs to the instance type
  2485 //                      push any AddP users on alloc_worklist and push any memnode
  2486 //                      users onto memnode_worklist.
  2487 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
  2488 //            search the Memory chain for a store with the appropriate type
  2489 //            address type.  If a Phi is found, create a new version with
  2490 //            the appropriate memory slices from each of the Phi inputs.
  2491 //            For stores, process the users as follows:
  2492 //               MemNode:  push on memnode_worklist
  2493 //               MergeMem: push on mergemem_worklist
  2494 //  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
  2495 //            moving the first node encountered of each  instance type to the
  2496 //            the input corresponding to its alias index.
  2497 //            appropriate memory slice.
  2498 //  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
  2499 //
  2500 // In the following example, the CheckCastPP nodes are the cast of allocation
  2501 // results and the allocation of node 29 is unescaped and eligible to be an
  2502 // instance type.
  2503 //
  2504 // We start with:
  2505 //
  2506 //     7 Parm #memory
  2507 //    10  ConI  "12"
  2508 //    19  CheckCastPP   "Foo"
  2509 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
  2510 //    29  CheckCastPP   "Foo"
  2511 //    30  AddP  _ 29 29 10  Foo+12  alias_index=4
  2512 //
  2513 //    40  StoreP  25   7  20   ... alias_index=4
  2514 //    50  StoreP  35  40  30   ... alias_index=4
  2515 //    60  StoreP  45  50  20   ... alias_index=4
  2516 //    70  LoadP    _  60  30   ... alias_index=4
  2517 //    80  Phi     75  50  60   Memory alias_index=4
  2518 //    90  LoadP    _  80  30   ... alias_index=4
  2519 //   100  LoadP    _  80  20   ... alias_index=4
  2520 //
  2521 //
  2522 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
  2523 // and creating a new alias index for node 30.  This gives:
  2524 //
  2525 //     7 Parm #memory
  2526 //    10  ConI  "12"
  2527 //    19  CheckCastPP   "Foo"
  2528 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
  2529 //    29  CheckCastPP   "Foo"  iid=24
  2530 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
  2531 //
  2532 //    40  StoreP  25   7  20   ... alias_index=4
  2533 //    50  StoreP  35  40  30   ... alias_index=6
  2534 //    60  StoreP  45  50  20   ... alias_index=4
  2535 //    70  LoadP    _  60  30   ... alias_index=6
  2536 //    80  Phi     75  50  60   Memory alias_index=4
  2537 //    90  LoadP    _  80  30   ... alias_index=6
  2538 //   100  LoadP    _  80  20   ... alias_index=4
  2539 //
  2540 // In phase 2, new memory inputs are computed for the loads and stores,
  2541 // And a new version of the phi is created.  In phase 4, the inputs to
  2542 // node 80 are updated and then the memory nodes are updated with the
  2543 // values computed in phase 2.  This results in:
  2544 //
  2545 //     7 Parm #memory
  2546 //    10  ConI  "12"
  2547 //    19  CheckCastPP   "Foo"
  2548 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
  2549 //    29  CheckCastPP   "Foo"  iid=24
  2550 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
  2551 //
  2552 //    40  StoreP  25  7   20   ... alias_index=4
  2553 //    50  StoreP  35  7   30   ... alias_index=6
  2554 //    60  StoreP  45  40  20   ... alias_index=4
  2555 //    70  LoadP    _  50  30   ... alias_index=6
  2556 //    80  Phi     75  40  60   Memory alias_index=4
  2557 //   120  Phi     75  50  50   Memory alias_index=6
  2558 //    90  LoadP    _ 120  30   ... alias_index=6
  2559 //   100  LoadP    _  80  20   ... alias_index=4
  2560 //
  2561 void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist) {
  2562   GrowableArray<Node *>  memnode_worklist;
  2563   GrowableArray<PhiNode *>  orig_phis;
  2564   PhaseIterGVN  *igvn = _igvn;
  2565   uint new_index_start = (uint) _compile->num_alias_types();
  2566   Arena* arena = Thread::current()->resource_area();
  2567   VectorSet visited(arena);
  2568   ideal_nodes.clear(); // Reset for use with set_map/get_map.
  2569   uint unique_old = _compile->unique();
  2571   //  Phase 1:  Process possible allocations from alloc_worklist.
  2572   //  Create instance types for the CheckCastPP for allocations where possible.
  2573   //
  2574   // (Note: don't forget to change the order of the second AddP node on
  2575   //  the alloc_worklist if the order of the worklist processing is changed,
  2576   //  see the comment in find_second_addp().)
  2577   //
  2578   while (alloc_worklist.length() != 0) {
  2579     Node *n = alloc_worklist.pop();
  2580     uint ni = n->_idx;
  2581     if (n->is_Call()) {
  2582       CallNode *alloc = n->as_Call();
  2583       // copy escape information to call node
  2584       PointsToNode* ptn = ptnode_adr(alloc->_idx);
  2585       PointsToNode::EscapeState es = ptn->escape_state();
  2586       // We have an allocation or call which returns a Java object,
  2587       // see if it is unescaped.
  2588       if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable())
  2589         continue;
  2590       // Find CheckCastPP for the allocate or for the return value of a call
  2591       n = alloc->result_cast();
  2592       if (n == NULL) {            // No uses except Initialize node
  2593         if (alloc->is_Allocate()) {
  2594           // Set the scalar_replaceable flag for allocation
  2595           // so it could be eliminated if it has no uses.
  2596           alloc->as_Allocate()->_is_scalar_replaceable = true;
  2598         continue;
  2600       if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
  2601         assert(!alloc->is_Allocate(), "allocation should have unique type");
  2602         continue;
  2605       // The inline code for Object.clone() casts the allocation result to
  2606       // java.lang.Object and then to the actual type of the allocated
  2607       // object. Detect this case and use the second cast.
  2608       // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
  2609       // the allocation result is cast to java.lang.Object and then
  2610       // to the actual Array type.
  2611       if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
  2612           && (alloc->is_AllocateArray() ||
  2613               igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) {
  2614         Node *cast2 = NULL;
  2615         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2616           Node *use = n->fast_out(i);
  2617           if (use->is_CheckCastPP()) {
  2618             cast2 = use;
  2619             break;
  2622         if (cast2 != NULL) {
  2623           n = cast2;
  2624         } else {
  2625           // Non-scalar replaceable if the allocation type is unknown statically
  2626           // (reflection allocation), the object can't be restored during
  2627           // deoptimization without precise type.
  2628           continue;
  2631       if (alloc->is_Allocate()) {
  2632         // Set the scalar_replaceable flag for allocation
  2633         // so it could be eliminated.
  2634         alloc->as_Allocate()->_is_scalar_replaceable = true;
  2636       set_escape_state(ptnode_adr(n->_idx), es); // CheckCastPP escape state
  2637       // in order for an object to be scalar-replaceable, it must be:
  2638       //   - a direct allocation (not a call returning an object)
  2639       //   - non-escaping
  2640       //   - eligible to be a unique type
  2641       //   - not determined to be ineligible by escape analysis
  2642       set_map(alloc, n);
  2643       set_map(n, alloc);
  2644       const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
  2645       if (t == NULL)
  2646         continue;  // not a TypeOopPtr
  2647       const TypeOopPtr* tinst = t->cast_to_exactness(true)->is_oopptr()->cast_to_instance_id(ni);
  2648       igvn->hash_delete(n);
  2649       igvn->set_type(n,  tinst);
  2650       n->raise_bottom_type(tinst);
  2651       igvn->hash_insert(n);
  2652       record_for_optimizer(n);
  2653       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
  2655         // First, put on the worklist all Field edges from Connection Graph
  2656         // which is more accurate then putting immediate users from Ideal Graph.
  2657         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
  2658           PointsToNode* tgt = e.get();
  2659           Node* use = tgt->ideal_node();
  2660           assert(tgt->is_Field() && use->is_AddP(),
  2661                  "only AddP nodes are Field edges in CG");
  2662           if (use->outcnt() > 0) { // Don't process dead nodes
  2663             Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
  2664             if (addp2 != NULL) {
  2665               assert(alloc->is_AllocateArray(),"array allocation was expected");
  2666               alloc_worklist.append_if_missing(addp2);
  2668             alloc_worklist.append_if_missing(use);
  2672         // An allocation may have an Initialize which has raw stores. Scan
  2673         // the users of the raw allocation result and push AddP users
  2674         // on alloc_worklist.
  2675         Node *raw_result = alloc->proj_out(TypeFunc::Parms);
  2676         assert (raw_result != NULL, "must have an allocation result");
  2677         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
  2678           Node *use = raw_result->fast_out(i);
  2679           if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
  2680             Node* addp2 = find_second_addp(use, raw_result);
  2681             if (addp2 != NULL) {
  2682               assert(alloc->is_AllocateArray(),"array allocation was expected");
  2683               alloc_worklist.append_if_missing(addp2);
  2685             alloc_worklist.append_if_missing(use);
  2686           } else if (use->is_MemBar()) {
  2687             memnode_worklist.append_if_missing(use);
  2691     } else if (n->is_AddP()) {
  2692       JavaObjectNode* jobj = unique_java_object(get_addp_base(n));
  2693       if (jobj == NULL || jobj == phantom_obj) {
  2694 #ifdef ASSERT
  2695         ptnode_adr(get_addp_base(n)->_idx)->dump();
  2696         ptnode_adr(n->_idx)->dump();
  2697         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
  2698 #endif
  2699         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
  2700         return;
  2702       Node *base = get_map(jobj->idx());  // CheckCastPP node
  2703       if (!split_AddP(n, base)) continue; // wrong type from dead path
  2704     } else if (n->is_Phi() ||
  2705                n->is_CheckCastPP() ||
  2706                n->is_EncodeP() ||
  2707                n->is_DecodeN() ||
  2708                (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
  2709       if (visited.test_set(n->_idx)) {
  2710         assert(n->is_Phi(), "loops only through Phi's");
  2711         continue;  // already processed
  2713       JavaObjectNode* jobj = unique_java_object(n);
  2714       if (jobj == NULL || jobj == phantom_obj) {
  2715 #ifdef ASSERT
  2716         ptnode_adr(n->_idx)->dump();
  2717         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
  2718 #endif
  2719         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
  2720         return;
  2721       } else {
  2722         Node *val = get_map(jobj->idx());   // CheckCastPP node
  2723         TypeNode *tn = n->as_Type();
  2724         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
  2725         assert(tinst != NULL && tinst->is_known_instance() &&
  2726                tinst->instance_id() == jobj->idx() , "instance type expected.");
  2728         const Type *tn_type = igvn->type(tn);
  2729         const TypeOopPtr *tn_t;
  2730         if (tn_type->isa_narrowoop()) {
  2731           tn_t = tn_type->make_ptr()->isa_oopptr();
  2732         } else {
  2733           tn_t = tn_type->isa_oopptr();
  2735         if (tn_t != NULL && tinst->klass()->is_subtype_of(tn_t->klass())) {
  2736           if (tn_type->isa_narrowoop()) {
  2737             tn_type = tinst->make_narrowoop();
  2738           } else {
  2739             tn_type = tinst;
  2741           igvn->hash_delete(tn);
  2742           igvn->set_type(tn, tn_type);
  2743           tn->set_type(tn_type);
  2744           igvn->hash_insert(tn);
  2745           record_for_optimizer(n);
  2746         } else {
  2747           assert(tn_type == TypePtr::NULL_PTR ||
  2748                  tn_t != NULL && !tinst->klass()->is_subtype_of(tn_t->klass()),
  2749                  "unexpected type");
  2750           continue; // Skip dead path with different type
  2753     } else {
  2754       debug_only(n->dump();)
  2755       assert(false, "EA: unexpected node");
  2756       continue;
  2758     // push allocation's users on appropriate worklist
  2759     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2760       Node *use = n->fast_out(i);
  2761       if(use->is_Mem() && use->in(MemNode::Address) == n) {
  2762         // Load/store to instance's field
  2763         memnode_worklist.append_if_missing(use);
  2764       } else if (use->is_MemBar()) {
  2765         memnode_worklist.append_if_missing(use);
  2766       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
  2767         Node* addp2 = find_second_addp(use, n);
  2768         if (addp2 != NULL) {
  2769           alloc_worklist.append_if_missing(addp2);
  2771         alloc_worklist.append_if_missing(use);
  2772       } else if (use->is_Phi() ||
  2773                  use->is_CheckCastPP() ||
  2774                  use->is_EncodeP() ||
  2775                  use->is_DecodeN() ||
  2776                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
  2777         alloc_worklist.append_if_missing(use);
  2778 #ifdef ASSERT
  2779       } else if (use->is_Mem()) {
  2780         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
  2781       } else if (use->is_MergeMem()) {
  2782         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
  2783       } else if (use->is_SafePoint()) {
  2784         // Look for MergeMem nodes for calls which reference unique allocation
  2785         // (through CheckCastPP nodes) even for debug info.
  2786         Node* m = use->in(TypeFunc::Memory);
  2787         if (m->is_MergeMem()) {
  2788           assert(_mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
  2790       } else {
  2791         uint op = use->Opcode();
  2792         if (!(op == Op_CmpP || op == Op_Conv2B ||
  2793               op == Op_CastP2X || op == Op_StoreCM ||
  2794               op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
  2795               op == Op_StrEquals || op == Op_StrIndexOf)) {
  2796           n->dump();
  2797           use->dump();
  2798           assert(false, "EA: missing allocation reference path");
  2800 #endif
  2805   // New alias types were created in split_AddP().
  2806   uint new_index_end = (uint) _compile->num_alias_types();
  2807   assert(unique_old == _compile->unique(), "there should be no new ideal nodes after Phase 1");
  2809   //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
  2810   //            compute new values for Memory inputs  (the Memory inputs are not
  2811   //            actually updated until phase 4.)
  2812   if (memnode_worklist.length() == 0)
  2813     return;  // nothing to do
  2814   while (memnode_worklist.length() != 0) {
  2815     Node *n = memnode_worklist.pop();
  2816     if (visited.test_set(n->_idx))
  2817       continue;
  2818     if (n->is_Phi() || n->is_ClearArray()) {
  2819       // we don't need to do anything, but the users must be pushed
  2820     } else if (n->is_MemBar()) { // Initialize, MemBar nodes
  2821       // we don't need to do anything, but the users must be pushed
  2822       n = n->as_MemBar()->proj_out(TypeFunc::Memory);
  2823       if (n == NULL)
  2824         continue;
  2825     } else {
  2826       assert(n->is_Mem(), "memory node required.");
  2827       Node *addr = n->in(MemNode::Address);
  2828       const Type *addr_t = igvn->type(addr);
  2829       if (addr_t == Type::TOP)
  2830         continue;
  2831       assert (addr_t->isa_ptr() != NULL, "pointer type required.");
  2832       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
  2833       assert ((uint)alias_idx < new_index_end, "wrong alias index");
  2834       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
  2835       if (_compile->failing()) {
  2836         return;
  2838       if (mem != n->in(MemNode::Memory)) {
  2839         // We delay the memory edge update since we need old one in
  2840         // MergeMem code below when instances memory slices are separated.
  2841         set_map(n, mem);
  2843       if (n->is_Load()) {
  2844         continue;  // don't push users
  2845       } else if (n->is_LoadStore()) {
  2846         // get the memory projection
  2847         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2848           Node *use = n->fast_out(i);
  2849           if (use->Opcode() == Op_SCMemProj) {
  2850             n = use;
  2851             break;
  2854         assert(n->Opcode() == Op_SCMemProj, "memory projection required");
  2857     // push user on appropriate worklist
  2858     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  2859       Node *use = n->fast_out(i);
  2860       if (use->is_Phi() || use->is_ClearArray()) {
  2861         memnode_worklist.append_if_missing(use);
  2862       } else if(use->is_Mem() && use->in(MemNode::Memory) == n) {
  2863         if (use->Opcode() == Op_StoreCM) // Ignore cardmark stores
  2864           continue;
  2865         memnode_worklist.append_if_missing(use);
  2866       } else if (use->is_MemBar()) {
  2867         memnode_worklist.append_if_missing(use);
  2868 #ifdef ASSERT
  2869       } else if(use->is_Mem()) {
  2870         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
  2871       } else if (use->is_MergeMem()) {
  2872         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
  2873       } else {
  2874         uint op = use->Opcode();
  2875         if (!(op == Op_StoreCM ||
  2876               (op == Op_CallLeaf && use->as_CallLeaf()->_name != NULL &&
  2877                strcmp(use->as_CallLeaf()->_name, "g1_wb_pre") == 0) ||
  2878               op == Op_AryEq || op == Op_StrComp ||
  2879               op == Op_StrEquals || op == Op_StrIndexOf)) {
  2880           n->dump();
  2881           use->dump();
  2882           assert(false, "EA: missing memory path");
  2884 #endif
  2889   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
  2890   //            Walk each memory slice moving the first node encountered of each
  2891   //            instance type to the the input corresponding to its alias index.
  2892   uint length = _mergemem_worklist.length();
  2893   for( uint next = 0; next < length; ++next ) {
  2894     MergeMemNode* nmm = _mergemem_worklist.at(next);
  2895     assert(!visited.test_set(nmm->_idx), "should not be visited before");
  2896     // Note: we don't want to use MergeMemStream here because we only want to
  2897     // scan inputs which exist at the start, not ones we add during processing.
  2898     // Note 2: MergeMem may already contains instance memory slices added
  2899     // during find_inst_mem() call when memory nodes were processed above.
  2900     igvn->hash_delete(nmm);
  2901     uint nslices = nmm->req();
  2902     for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
  2903       Node* mem = nmm->in(i);
  2904       Node* cur = NULL;
  2905       if (mem == NULL || mem->is_top())
  2906         continue;
  2907       // First, update mergemem by moving memory nodes to corresponding slices
  2908       // if their type became more precise since this mergemem was created.
  2909       while (mem->is_Mem()) {
  2910         const Type *at = igvn->type(mem->in(MemNode::Address));
  2911         if (at != Type::TOP) {
  2912           assert (at->isa_ptr() != NULL, "pointer type required.");
  2913           uint idx = (uint)_compile->get_alias_index(at->is_ptr());
  2914           if (idx == i) {
  2915             if (cur == NULL)
  2916               cur = mem;
  2917           } else {
  2918             if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
  2919               nmm->set_memory_at(idx, mem);
  2923         mem = mem->in(MemNode::Memory);
  2925       nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
  2926       // Find any instance of the current type if we haven't encountered
  2927       // already a memory slice of the instance along the memory chain.
  2928       for (uint ni = new_index_start; ni < new_index_end; ni++) {
  2929         if((uint)_compile->get_general_index(ni) == i) {
  2930           Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
  2931           if (nmm->is_empty_memory(m)) {
  2932             Node* result = find_inst_mem(mem, ni, orig_phis);
  2933             if (_compile->failing()) {
  2934               return;
  2936             nmm->set_memory_at(ni, result);
  2941     // Find the rest of instances values
  2942     for (uint ni = new_index_start; ni < new_index_end; ni++) {
  2943       const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
  2944       Node* result = step_through_mergemem(nmm, ni, tinst);
  2945       if (result == nmm->base_memory()) {
  2946         // Didn't find instance memory, search through general slice recursively.
  2947         result = nmm->memory_at(_compile->get_general_index(ni));
  2948         result = find_inst_mem(result, ni, orig_phis);
  2949         if (_compile->failing()) {
  2950           return;
  2952         nmm->set_memory_at(ni, result);
  2955     igvn->hash_insert(nmm);
  2956     record_for_optimizer(nmm);
  2959   //  Phase 4:  Update the inputs of non-instance memory Phis and
  2960   //            the Memory input of memnodes
  2961   // First update the inputs of any non-instance Phi's from
  2962   // which we split out an instance Phi.  Note we don't have
  2963   // to recursively process Phi's encounted on the input memory
  2964   // chains as is done in split_memory_phi() since they  will
  2965   // also be processed here.
  2966   for (int j = 0; j < orig_phis.length(); j++) {
  2967     PhiNode *phi = orig_phis.at(j);
  2968     int alias_idx = _compile->get_alias_index(phi->adr_type());
  2969     igvn->hash_delete(phi);
  2970     for (uint i = 1; i < phi->req(); i++) {
  2971       Node *mem = phi->in(i);
  2972       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
  2973       if (_compile->failing()) {
  2974         return;
  2976       if (mem != new_mem) {
  2977         phi->set_req(i, new_mem);
  2980     igvn->hash_insert(phi);
  2981     record_for_optimizer(phi);
  2984   // Update the memory inputs of MemNodes with the value we computed
  2985   // in Phase 2 and move stores memory users to corresponding memory slices.
  2986   // Disable memory split verification code until the fix for 6984348.
  2987   // Currently it produces false negative results since it does not cover all cases.
  2988 #if 0 // ifdef ASSERT
  2989   visited.Reset();
  2990   Node_Stack old_mems(arena, _compile->unique() >> 2);
  2991 #endif
  2992   for (uint i = 0; i < ideal_nodes.size(); i++) {
  2993     Node*    n = ideal_nodes.at(i);
  2994     Node* nmem = get_map(n->_idx);
  2995     assert(nmem != NULL, "sanity");
  2996     if (n->is_Mem()) {
  2997 #if 0 // ifdef ASSERT
  2998       Node* old_mem = n->in(MemNode::Memory);
  2999       if (!visited.test_set(old_mem->_idx)) {
  3000         old_mems.push(old_mem, old_mem->outcnt());
  3002 #endif
  3003       assert(n->in(MemNode::Memory) != nmem, "sanity");
  3004       if (!n->is_Load()) {
  3005         // Move memory users of a store first.
  3006         move_inst_mem(n, orig_phis);
  3008       // Now update memory input
  3009       igvn->hash_delete(n);
  3010       n->set_req(MemNode::Memory, nmem);
  3011       igvn->hash_insert(n);
  3012       record_for_optimizer(n);
  3013     } else {
  3014       assert(n->is_Allocate() || n->is_CheckCastPP() ||
  3015              n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
  3018 #if 0 // ifdef ASSERT
  3019   // Verify that memory was split correctly
  3020   while (old_mems.is_nonempty()) {
  3021     Node* old_mem = old_mems.node();
  3022     uint  old_cnt = old_mems.index();
  3023     old_mems.pop();
  3024     assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
  3026 #endif
  3029 #ifndef PRODUCT
  3030 static const char *node_type_names[] = {
  3031   "UnknownType",
  3032   "JavaObject",
  3033   "LocalVar",
  3034   "Field",
  3035   "Arraycopy"
  3036 };
  3038 static const char *esc_names[] = {
  3039   "UnknownEscape",
  3040   "NoEscape",
  3041   "ArgEscape",
  3042   "GlobalEscape"
  3043 };
  3045 void PointsToNode::dump(bool print_state) const {
  3046   NodeType nt = node_type();
  3047   tty->print("%s ", node_type_names[(int) nt]);
  3048   if (print_state) {
  3049     EscapeState es = escape_state();
  3050     EscapeState fields_es = fields_escape_state();
  3051     tty->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
  3052     if (nt == PointsToNode::JavaObject && !this->scalar_replaceable())
  3053       tty->print("NSR");
  3055   if (is_Field()) {
  3056     FieldNode* f = (FieldNode*)this;
  3057     tty->print("(");
  3058     for (BaseIterator i(f); i.has_next(); i.next()) {
  3059       PointsToNode* b = i.get();
  3060       tty->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
  3062     tty->print(" )");
  3064   tty->print("[");
  3065   for (EdgeIterator i(this); i.has_next(); i.next()) {
  3066     PointsToNode* e = i.get();
  3067     tty->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
  3069   tty->print(" [");
  3070   for (UseIterator i(this); i.has_next(); i.next()) {
  3071     PointsToNode* u = i.get();
  3072     bool is_base = false;
  3073     if (PointsToNode::is_base_use(u)) {
  3074       is_base = true;
  3075       u = PointsToNode::get_use_node(u)->as_Field();
  3077     tty->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
  3079   tty->print(" ]]  ");
  3080   if (_node == NULL)
  3081     tty->print_cr("<null>");
  3082   else
  3083     _node->dump();
  3086 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
  3087   bool first = true;
  3088   int ptnodes_length = ptnodes_worklist.length();
  3089   for (int i = 0; i < ptnodes_length; i++) {
  3090     PointsToNode *ptn = ptnodes_worklist.at(i);
  3091     if (ptn == NULL || !ptn->is_JavaObject())
  3092       continue;
  3093     PointsToNode::EscapeState es = ptn->escape_state();
  3094     if (ptn->ideal_node()->is_Allocate() && (es == PointsToNode::NoEscape || Verbose)) {
  3095       if (first) {
  3096         tty->cr();
  3097         tty->print("======== Connection graph for ");
  3098         _compile->method()->print_short_name();
  3099         tty->cr();
  3100         first = false;
  3102       ptn->dump();
  3103       // Print all locals and fields which reference this allocation
  3104       for (UseIterator j(ptn); j.has_next(); j.next()) {
  3105         PointsToNode* use = j.get();
  3106         if (use->is_LocalVar()) {
  3107           use->dump(Verbose);
  3108         } else if (Verbose) {
  3109           use->dump();
  3112       tty->cr();
  3116 #endif

mercurial